xref: /linux-6.15/kernel/workqueue.c (revision e563d0a7)
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 
59*e563d0a7STejun 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 */
78*e563d0a7STejun Heo };
79db7bccf4STejun Heo 
80*e563d0a7STejun 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,
91*e563d0a7STejun Heo };
92db7bccf4STejun Heo 
93*e563d0a7STejun 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  *
1502e109a28STejun Heo  * MD: wq_mayday_lock protected.
151cd2440d6SPetr Mladek  *
152cd2440d6SPetr Mladek  * WD: Used internally by the watchdog.
1534690c4abSTejun Heo  */
1544690c4abSTejun Heo 
1552eaebdb3STejun Heo /* struct worker is defined in workqueue_internal.h */
156c34056a3STejun Heo 
157bd7bdd43STejun Heo struct worker_pool {
158a9b8a985SSebastian Andrzej Siewior 	raw_spinlock_t		lock;		/* the pool lock */
159d84ff051STejun Heo 	int			cpu;		/* I: the associated cpu */
160f3f90ad4STejun Heo 	int			node;		/* I: the associated node ID */
1619daf9e67STejun Heo 	int			id;		/* I: pool ID */
162bc8b50c2STejun Heo 	unsigned int		flags;		/* L: flags */
163bd7bdd43STejun Heo 
16482607adcSTejun Heo 	unsigned long		watchdog_ts;	/* L: watchdog timestamp */
165cd2440d6SPetr Mladek 	bool			cpu_stall;	/* WD: stalled cpu bound pool */
16682607adcSTejun Heo 
167bc35f7efSLai Jiangshan 	/*
168bc35f7efSLai Jiangshan 	 * The counter is incremented in a process context on the associated CPU
169bc35f7efSLai Jiangshan 	 * w/ preemption disabled, and decremented or reset in the same context
170bc35f7efSLai Jiangshan 	 * but w/ pool->lock held. The readers grab pool->lock and are
171bc35f7efSLai Jiangshan 	 * guaranteed to see if the counter reached zero.
172bc35f7efSLai Jiangshan 	 */
173bc35f7efSLai Jiangshan 	int			nr_running;
17484f91c62SLai Jiangshan 
175bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
176ea1abd61SLai Jiangshan 
1775826cc8fSLai Jiangshan 	int			nr_workers;	/* L: total number of workers */
1785826cc8fSLai Jiangshan 	int			nr_idle;	/* L: currently idle workers */
179bd7bdd43STejun Heo 
1802c1f1a91SLai Jiangshan 	struct list_head	idle_list;	/* L: list of idle workers */
181bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
1823f959aa3SValentin Schneider 	struct work_struct      idle_cull_work; /* L: worker idle cleanup */
1833f959aa3SValentin Schneider 
184bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	  /* L: SOS timer for workers */
185bd7bdd43STejun Heo 
186c5aa87bbSTejun Heo 	/* a workers is either on busy_hash or idle_list, or the manager */
187c9e7cf27STejun Heo 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
188c9e7cf27STejun Heo 						/* L: hash of busy workers */
189c9e7cf27STejun Heo 
1902607d7a6STejun Heo 	struct worker		*manager;	/* L: purely informational */
19192f9c5c4SLai Jiangshan 	struct list_head	workers;	/* A: attached workers */
192e02b9312SValentin Schneider 	struct list_head        dying_workers;  /* A: workers about to die */
19360f5a4bcSLai Jiangshan 	struct completion	*detach_completion; /* all workers detached */
194e19e397aSTejun Heo 
1957cda9aaeSLai Jiangshan 	struct ida		worker_ida;	/* worker IDs for task name */
196e19e397aSTejun Heo 
1977a4e344cSTejun Heo 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
19868e13a67SLai Jiangshan 	struct hlist_node	hash_node;	/* PL: unbound_pool_hash node */
19968e13a67SLai Jiangshan 	int			refcnt;		/* PL: refcnt for unbound pools */
2007a4e344cSTejun Heo 
201e19e397aSTejun Heo 	/*
20224acfb71SThomas Gleixner 	 * Destruction of pool is RCU protected to allow dereferences
20329c91e99STejun Heo 	 * from get_work_pool().
20429c91e99STejun Heo 	 */
20529c91e99STejun Heo 	struct rcu_head		rcu;
20684f91c62SLai Jiangshan };
2078b03ae3cSTejun Heo 
2088b03ae3cSTejun Heo /*
209725e8ec5STejun Heo  * Per-pool_workqueue statistics. These can be monitored using
210725e8ec5STejun Heo  * tools/workqueue/wq_monitor.py.
211725e8ec5STejun Heo  */
212725e8ec5STejun Heo enum pool_workqueue_stats {
213725e8ec5STejun Heo 	PWQ_STAT_STARTED,	/* work items started execution */
214725e8ec5STejun Heo 	PWQ_STAT_COMPLETED,	/* work items completed execution */
2158a1dd1e5STejun Heo 	PWQ_STAT_CPU_TIME,	/* total CPU time consumed */
216616db877STejun Heo 	PWQ_STAT_CPU_INTENSIVE,	/* wq_cpu_intensive_thresh_us violations */
217725e8ec5STejun Heo 	PWQ_STAT_CM_WAKEUP,	/* concurrency-management worker wakeups */
2188639ecebSTejun Heo 	PWQ_STAT_REPATRIATED,	/* unbound workers brought back into scope */
219725e8ec5STejun Heo 	PWQ_STAT_MAYDAY,	/* maydays to rescuer */
220725e8ec5STejun Heo 	PWQ_STAT_RESCUED,	/* linked work items executed by rescuer */
221725e8ec5STejun Heo 
222725e8ec5STejun Heo 	PWQ_NR_STATS,
223725e8ec5STejun Heo };
224725e8ec5STejun Heo 
225725e8ec5STejun Heo /*
226112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
227112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
228112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
229112202d9STejun Heo  * number of flag bits.
2301da177e4SLinus Torvalds  */
231112202d9STejun Heo struct pool_workqueue {
232bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
2334690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
23473f53c4aSTejun Heo 	int			work_color;	/* L: current color */
23573f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
2368864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
23773f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
23873f53c4aSTejun Heo 						/* L: nr of in_flight works */
239018f3a13SLai Jiangshan 
240018f3a13SLai Jiangshan 	/*
241018f3a13SLai Jiangshan 	 * nr_active management and WORK_STRUCT_INACTIVE:
242018f3a13SLai Jiangshan 	 *
243018f3a13SLai Jiangshan 	 * When pwq->nr_active >= max_active, new work item is queued to
244018f3a13SLai Jiangshan 	 * pwq->inactive_works instead of pool->worklist and marked with
245018f3a13SLai Jiangshan 	 * WORK_STRUCT_INACTIVE.
246018f3a13SLai Jiangshan 	 *
247018f3a13SLai Jiangshan 	 * All work items marked with WORK_STRUCT_INACTIVE do not participate
248018f3a13SLai Jiangshan 	 * in pwq->nr_active and all work items in pwq->inactive_works are
249018f3a13SLai Jiangshan 	 * marked with WORK_STRUCT_INACTIVE.  But not all WORK_STRUCT_INACTIVE
250018f3a13SLai Jiangshan 	 * work items are in pwq->inactive_works.  Some of them are ready to
251018f3a13SLai Jiangshan 	 * run in pool->worklist or worker->scheduled.  Those work itmes are
252018f3a13SLai Jiangshan 	 * only struct wq_barrier which is used for flush_work() and should
253018f3a13SLai Jiangshan 	 * not participate in pwq->nr_active.  For non-barrier work item, it
254018f3a13SLai Jiangshan 	 * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
255018f3a13SLai Jiangshan 	 */
2561e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
257a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
258f97a4a1aSLai Jiangshan 	struct list_head	inactive_works;	/* L: inactive works */
2593c25a55dSLai Jiangshan 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
2602e109a28STejun Heo 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
2618864b4e5STejun Heo 
262725e8ec5STejun Heo 	u64			stats[PWQ_NR_STATS];
263725e8ec5STejun Heo 
2648864b4e5STejun Heo 	/*
265967b494eSTejun Heo 	 * Release of unbound pwq is punted to a kthread_worker. See put_pwq()
266687a9aa5STejun Heo 	 * and pwq_release_workfn() for details. pool_workqueue itself is also
267687a9aa5STejun Heo 	 * RCU protected so that the first pwq can be determined without
268967b494eSTejun Heo 	 * grabbing wq->mutex.
2698864b4e5STejun Heo 	 */
270687a9aa5STejun Heo 	struct kthread_work	release_work;
2718864b4e5STejun Heo 	struct rcu_head		rcu;
272e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2731da177e4SLinus Torvalds 
2741da177e4SLinus Torvalds /*
27573f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
27673f53c4aSTejun Heo  */
27773f53c4aSTejun Heo struct wq_flusher {
2783c25a55dSLai Jiangshan 	struct list_head	list;		/* WQ: list of flushers */
2793c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: flush color waiting for */
28073f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
28173f53c4aSTejun Heo };
2821da177e4SLinus Torvalds 
283226223abSTejun Heo struct wq_device;
284226223abSTejun Heo 
28573f53c4aSTejun Heo /*
286c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
287c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
2881da177e4SLinus Torvalds  */
2891da177e4SLinus Torvalds struct workqueue_struct {
2903c25a55dSLai Jiangshan 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
291e2dca7adSTejun Heo 	struct list_head	list;		/* PR: list of all workqueues */
29273f53c4aSTejun Heo 
2933c25a55dSLai Jiangshan 	struct mutex		mutex;		/* protects this wq */
2943c25a55dSLai Jiangshan 	int			work_color;	/* WQ: current work color */
2953c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: current flush color */
296112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
2973c25a55dSLai Jiangshan 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
2983c25a55dSLai Jiangshan 	struct list_head	flusher_queue;	/* WQ: flush waiters */
2993c25a55dSLai Jiangshan 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
30073f53c4aSTejun Heo 
3012e109a28STejun Heo 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
30230ae2fc0STejun Heo 	struct worker		*rescuer;	/* MD: rescue worker */
303e22bee78STejun Heo 
30487fc741eSLai Jiangshan 	int			nr_drainers;	/* WQ: drain in progress */
305a357fc03SLai Jiangshan 	int			saved_max_active; /* WQ: saved pwq max_active */
306226223abSTejun Heo 
3075b95e1afSLai Jiangshan 	struct workqueue_attrs	*unbound_attrs;	/* PW: only for unbound wqs */
3085b95e1afSLai Jiangshan 	struct pool_workqueue	*dfl_pwq;	/* PW: only for unbound wqs */
3096029a918STejun Heo 
310226223abSTejun Heo #ifdef CONFIG_SYSFS
311226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
312226223abSTejun Heo #endif
3134e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
314669de8bdSBart Van Assche 	char			*lock_name;
315669de8bdSBart Van Assche 	struct lock_class_key	key;
3164e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
3174e6045f1SJohannes Berg #endif
318ecf6881fSTejun Heo 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
3192728fd2fSTejun Heo 
320e2dca7adSTejun Heo 	/*
32124acfb71SThomas Gleixner 	 * Destruction of workqueue_struct is RCU protected to allow walking
32224acfb71SThomas Gleixner 	 * the workqueues list without grabbing wq_pool_mutex.
323e2dca7adSTejun Heo 	 * This is used to dump all workqueues from sysrq.
324e2dca7adSTejun Heo 	 */
325e2dca7adSTejun Heo 	struct rcu_head		rcu;
326e2dca7adSTejun Heo 
3272728fd2fSTejun Heo 	/* hot fields used during command issue, aligned to cacheline */
3282728fd2fSTejun Heo 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
329636b927eSTejun Heo 	struct pool_workqueue __percpu __rcu **cpu_pwq; /* I: per-cpu pwqs */
3301da177e4SLinus Torvalds };
3311da177e4SLinus Torvalds 
332e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
333e904e6c2STejun Heo 
33484193c07STejun Heo /*
33584193c07STejun Heo  * Each pod type describes how CPUs should be grouped for unbound workqueues.
33684193c07STejun Heo  * See the comment above workqueue_attrs->affn_scope.
33784193c07STejun Heo  */
33884193c07STejun Heo struct wq_pod_type {
33984193c07STejun Heo 	int			nr_pods;	/* number of pods */
34084193c07STejun Heo 	cpumask_var_t		*pod_cpus;	/* pod -> cpus */
34184193c07STejun Heo 	int			*pod_node;	/* pod -> node */
34284193c07STejun Heo 	int			*cpu_pod;	/* cpu -> pod */
34384193c07STejun Heo };
34484193c07STejun Heo 
34584193c07STejun Heo static struct wq_pod_type wq_pod_types[WQ_AFFN_NR_TYPES];
346523a301eSTejun Heo static enum wq_affn_scope wq_affn_dfl = WQ_AFFN_CACHE;
34763c5484eSTejun Heo 
34863c5484eSTejun Heo static const char *wq_affn_names[WQ_AFFN_NR_TYPES] = {
349523a301eSTejun Heo 	[WQ_AFFN_DFL]			= "default",
35063c5484eSTejun Heo 	[WQ_AFFN_CPU]			= "cpu",
35163c5484eSTejun Heo 	[WQ_AFFN_SMT]			= "smt",
35263c5484eSTejun Heo 	[WQ_AFFN_CACHE]			= "cache",
35363c5484eSTejun Heo 	[WQ_AFFN_NUMA]			= "numa",
35463c5484eSTejun Heo 	[WQ_AFFN_SYSTEM]		= "system",
35563c5484eSTejun Heo };
356bce90380STejun Heo 
357616db877STejun Heo /*
358616db877STejun Heo  * Per-cpu work items which run for longer than the following threshold are
359616db877STejun Heo  * automatically considered CPU intensive and excluded from concurrency
360616db877STejun Heo  * management to prevent them from noticeably delaying other per-cpu work items.
361aa6fde93STejun Heo  * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
362aa6fde93STejun Heo  * The actual value is initialized in wq_cpu_intensive_thresh_init().
363616db877STejun Heo  */
364aa6fde93STejun Heo static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
365616db877STejun Heo module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
366616db877STejun Heo 
367cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
368552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
369cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
370cee22a15SViresh Kumar 
371863b710bSTejun Heo static bool wq_online;			/* can kworkers be created yet? */
3723347fa09STejun Heo 
373fef59c9cSTejun Heo /* buf for wq_update_unbound_pod_attrs(), protected by CPU hotplug exclusion */
374fef59c9cSTejun Heo static struct workqueue_attrs *wq_update_pod_attrs_buf;
3754c16bd32STejun Heo 
37668e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
3771258fae7STejun Heo static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
378a9b8a985SSebastian Andrzej Siewior static DEFINE_RAW_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
379d8bb65abSSebastian Andrzej Siewior /* wait for manager to go away */
380d8bb65abSSebastian Andrzej Siewior static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
3815bcab335STejun Heo 
382e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
38368e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
3847d19c5ceSTejun Heo 
38599c621efSLai Jiangshan /* PL&A: allowable cpus for unbound wqs and work items */
386ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
387ef557180SMike Galbraith 
388fe28f631SWaiman Long /* PL: user requested unbound cpumask via sysfs */
389fe28f631SWaiman Long static cpumask_var_t wq_requested_unbound_cpumask;
390fe28f631SWaiman Long 
391fe28f631SWaiman Long /* PL: isolated cpumask to be excluded from unbound cpumask */
392fe28f631SWaiman Long static cpumask_var_t wq_isolated_cpumask;
393fe28f631SWaiman Long 
394ace3c549Stiozhang /* for further constrain wq_unbound_cpumask by cmdline parameter*/
395ace3c549Stiozhang static struct cpumask wq_cmdline_cpumask __initdata;
396ace3c549Stiozhang 
397ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
398ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
399b05a7928SFrederic Weisbecker 
400f303fccbSTejun Heo /*
401f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
402f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
403f303fccbSTejun Heo  * to uncover usages which depend on it.
404f303fccbSTejun Heo  */
405f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
406f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
407f303fccbSTejun Heo #else
408f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
409f303fccbSTejun Heo #endif
410f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
411f303fccbSTejun Heo 
4127d19c5ceSTejun Heo /* the per-cpu worker pools */
41325528213SPeter Zijlstra static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
4147d19c5ceSTejun Heo 
41568e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
4167d19c5ceSTejun Heo 
41768e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
41829c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
41929c91e99STejun Heo 
420c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
42129c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
42229c91e99STejun Heo 
4238a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
4248a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
4258a2b7538STejun Heo 
426967b494eSTejun Heo /*
427967b494eSTejun Heo  * I: kthread_worker to release pwq's. pwq release needs to be bounced to a
428967b494eSTejun Heo  * process context while holding a pool lock. Bounce to a dedicated kthread
429967b494eSTejun Heo  * worker to avoid A-A deadlocks.
430967b494eSTejun Heo  */
43168279f9cSAlexey Dobriyan static struct kthread_worker *pwq_release_worker __ro_after_init;
432967b494eSTejun Heo 
43368279f9cSAlexey Dobriyan struct workqueue_struct *system_wq __ro_after_init;
434ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
43568279f9cSAlexey Dobriyan struct workqueue_struct *system_highpri_wq __ro_after_init;
4361aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
43768279f9cSAlexey Dobriyan struct workqueue_struct *system_long_wq __ro_after_init;
438d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
43968279f9cSAlexey Dobriyan struct workqueue_struct *system_unbound_wq __ro_after_init;
440f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
44168279f9cSAlexey Dobriyan struct workqueue_struct *system_freezable_wq __ro_after_init;
44224d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
44368279f9cSAlexey Dobriyan struct workqueue_struct *system_power_efficient_wq __ro_after_init;
4440668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
44568279f9cSAlexey Dobriyan struct workqueue_struct *system_freezable_power_efficient_wq __ro_after_init;
4460668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
447d320c038STejun Heo 
4487d19c5ceSTejun Heo static int worker_thread(void *__worker);
4496ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
450c29eb853STejun Heo static void show_pwq(struct pool_workqueue *pwq);
45155df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool);
4527d19c5ceSTejun Heo 
45397bd2347STejun Heo #define CREATE_TRACE_POINTS
45497bd2347STejun Heo #include <trace/events/workqueue.h>
45597bd2347STejun Heo 
45668e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
45724acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
458f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
45924acfb71SThomas Gleixner 			 "RCU or wq_pool_mutex should be held")
4605bcab335STejun Heo 
4615b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
46224acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
463f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
464f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
46524acfb71SThomas Gleixner 			 "RCU, wq->mutex or wq_pool_mutex should be held")
4665b95e1afSLai Jiangshan 
467f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
468f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
469f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
4707a62c2c8STejun Heo 	     (pool)++)
4714ce62e9eSTejun Heo 
47249e3cf44STejun Heo /**
47317116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
47417116969STejun Heo  * @pool: iteration cursor
475611c92a0STejun Heo  * @pi: integer used for iteration
476fa1b54e6STejun Heo  *
47724acfb71SThomas Gleixner  * This must be called either with wq_pool_mutex held or RCU read
47868e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
47968e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
480fa1b54e6STejun Heo  *
481fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
482fa1b54e6STejun Heo  * ignored.
48317116969STejun Heo  */
484611c92a0STejun Heo #define for_each_pool(pool, pi)						\
485611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
48668e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
487fa1b54e6STejun Heo 		else
48817116969STejun Heo 
48917116969STejun Heo /**
490822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
491822d8405STejun Heo  * @worker: iteration cursor
492822d8405STejun Heo  * @pool: worker_pool to iterate workers of
493822d8405STejun Heo  *
4941258fae7STejun Heo  * This must be called with wq_pool_attach_mutex.
495822d8405STejun Heo  *
496822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
497822d8405STejun Heo  * ignored.
498822d8405STejun Heo  */
499da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
500da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
5011258fae7STejun Heo 		if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
502822d8405STejun Heo 		else
503822d8405STejun Heo 
504822d8405STejun Heo /**
50549e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
50649e3cf44STejun Heo  * @pwq: iteration cursor
50749e3cf44STejun Heo  * @wq: the target workqueue
50876af4d93STejun Heo  *
50924acfb71SThomas Gleixner  * This must be called either with wq->mutex held or RCU read locked.
510794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
511794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
51276af4d93STejun Heo  *
51376af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
51476af4d93STejun Heo  * ignored.
51549e3cf44STejun Heo  */
51649e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
51749e9d1a9SSebastian Andrzej Siewior 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node,		\
5185a644662SJoel Fernandes (Google) 				 lockdep_is_held(&(wq->mutex)))
519f3421797STejun Heo 
520dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
521dc186ad7SThomas Gleixner 
522f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr;
523dc186ad7SThomas Gleixner 
52499777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
52599777288SStanislaw Gruszka {
52699777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
52799777288SStanislaw Gruszka }
52899777288SStanislaw Gruszka 
529b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
530b9fdac7fSDu, Changbin {
531b9fdac7fSDu, Changbin 	struct work_struct *work = addr;
532b9fdac7fSDu, Changbin 
533b9fdac7fSDu, Changbin 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
534b9fdac7fSDu, Changbin }
535b9fdac7fSDu, Changbin 
536dc186ad7SThomas Gleixner /*
537dc186ad7SThomas Gleixner  * fixup_init is called when:
538dc186ad7SThomas Gleixner  * - an active object is initialized
539dc186ad7SThomas Gleixner  */
54002a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
541dc186ad7SThomas Gleixner {
542dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
543dc186ad7SThomas Gleixner 
544dc186ad7SThomas Gleixner 	switch (state) {
545dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
546dc186ad7SThomas Gleixner 		cancel_work_sync(work);
547dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
54802a982a6SDu, Changbin 		return true;
549dc186ad7SThomas Gleixner 	default:
55002a982a6SDu, Changbin 		return false;
551dc186ad7SThomas Gleixner 	}
552dc186ad7SThomas Gleixner }
553dc186ad7SThomas Gleixner 
554dc186ad7SThomas Gleixner /*
555dc186ad7SThomas Gleixner  * fixup_free is called when:
556dc186ad7SThomas Gleixner  * - an active object is freed
557dc186ad7SThomas Gleixner  */
55802a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
559dc186ad7SThomas Gleixner {
560dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
561dc186ad7SThomas Gleixner 
562dc186ad7SThomas Gleixner 	switch (state) {
563dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
564dc186ad7SThomas Gleixner 		cancel_work_sync(work);
565dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
56602a982a6SDu, Changbin 		return true;
567dc186ad7SThomas Gleixner 	default:
56802a982a6SDu, Changbin 		return false;
569dc186ad7SThomas Gleixner 	}
570dc186ad7SThomas Gleixner }
571dc186ad7SThomas Gleixner 
572f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr = {
573dc186ad7SThomas Gleixner 	.name		= "work_struct",
57499777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
575b9fdac7fSDu, Changbin 	.is_static_object = work_is_static_object,
576dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
577dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
578dc186ad7SThomas Gleixner };
579dc186ad7SThomas Gleixner 
580dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
581dc186ad7SThomas Gleixner {
582dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
583dc186ad7SThomas Gleixner }
584dc186ad7SThomas Gleixner 
585dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
586dc186ad7SThomas Gleixner {
587dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
588dc186ad7SThomas Gleixner }
589dc186ad7SThomas Gleixner 
590dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
591dc186ad7SThomas Gleixner {
592dc186ad7SThomas Gleixner 	if (onstack)
593dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
594dc186ad7SThomas Gleixner 	else
595dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
596dc186ad7SThomas Gleixner }
597dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
598dc186ad7SThomas Gleixner 
599dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
600dc186ad7SThomas Gleixner {
601dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
602dc186ad7SThomas Gleixner }
603dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
604dc186ad7SThomas Gleixner 
605ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
606ea2e64f2SThomas Gleixner {
607ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
608ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
609ea2e64f2SThomas Gleixner }
610ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
611ea2e64f2SThomas Gleixner 
612dc186ad7SThomas Gleixner #else
613dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
614dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
615dc186ad7SThomas Gleixner #endif
616dc186ad7SThomas Gleixner 
6174e8b22bdSLi Bin /**
61867dc8325SCai Huoqing  * worker_pool_assign_id - allocate ID and assign it to @pool
6194e8b22bdSLi Bin  * @pool: the pool pointer of interest
6204e8b22bdSLi Bin  *
6214e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
6224e8b22bdSLi Bin  * successfully, -errno on failure.
6234e8b22bdSLi Bin  */
6249daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
6259daf9e67STejun Heo {
6269daf9e67STejun Heo 	int ret;
6279daf9e67STejun Heo 
62868e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
6295bcab335STejun Heo 
6304e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
6314e8b22bdSLi Bin 			GFP_KERNEL);
632229641a6STejun Heo 	if (ret >= 0) {
633e68035fbSTejun Heo 		pool->id = ret;
634229641a6STejun Heo 		return 0;
635229641a6STejun Heo 	}
6369daf9e67STejun Heo 	return ret;
6379daf9e67STejun Heo }
6389daf9e67STejun Heo 
63973f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
64073f53c4aSTejun Heo {
64173f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
64273f53c4aSTejun Heo }
64373f53c4aSTejun Heo 
644c4560c2cSLai Jiangshan static int get_work_color(unsigned long work_data)
64573f53c4aSTejun Heo {
646c4560c2cSLai Jiangshan 	return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
64773f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
64873f53c4aSTejun Heo }
64973f53c4aSTejun Heo 
65073f53c4aSTejun Heo static int work_next_color(int color)
65173f53c4aSTejun Heo {
65273f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
653a848e3b6SOleg Nesterov }
654a848e3b6SOleg Nesterov 
6554594bf15SDavid Howells /*
656112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
657112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
6587c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
6597a22ad75STejun Heo  *
660112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
661112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
662bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
663bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
6647a22ad75STejun Heo  *
665112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6667c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
667112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
6687c3eed5cSTejun Heo  * available only while the work item is queued.
669bbb68dfaSTejun Heo  *
670bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
671bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
672bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
673bbb68dfaSTejun Heo  * try to steal the PENDING bit.
6744594bf15SDavid Howells  */
6757a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6767a22ad75STejun Heo 				 unsigned long flags)
6777a22ad75STejun Heo {
6786183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
6797a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
6807a22ad75STejun Heo }
6817a22ad75STejun Heo 
682112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6834690c4abSTejun Heo 			 unsigned long extra_flags)
684365970a1SDavid Howells {
685112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
686112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
687365970a1SDavid Howells }
688365970a1SDavid Howells 
6894468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6904468a00fSLai Jiangshan 					   int pool_id)
6914468a00fSLai Jiangshan {
6924468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6934468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6944468a00fSLai Jiangshan }
6954468a00fSLai Jiangshan 
6967c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6977c3eed5cSTejun Heo 					    int pool_id)
6984d707b9fSOleg Nesterov {
69923657bb1STejun Heo 	/*
70023657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
70123657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
70223657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
70323657bb1STejun Heo 	 * owner.
70423657bb1STejun Heo 	 */
70523657bb1STejun Heo 	smp_wmb();
7067c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
707346c09f8SRoman Pen 	/*
708346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
709346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
710346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
7118bdc6201SLiu Song 	 * reordering can lead to a missed execution on attempt to queue
712346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
713346c09f8SRoman Pen 	 *
714346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
715346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
716346c09f8SRoman Pen 	 *
717346c09f8SRoman Pen 	 * 1  STORE event_indicated
718346c09f8SRoman Pen 	 * 2  queue_work_on() {
719346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
720346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
721346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
722346c09f8SRoman Pen 	 * 6                                 smp_mb()
723346c09f8SRoman Pen 	 * 7                               work->current_func() {
724346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
725346c09f8SRoman Pen 	 *				   }
726346c09f8SRoman Pen 	 *
727346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
728346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
729346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
730346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
731346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
732346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
733346c09f8SRoman Pen 	 * before actual STORE.
734346c09f8SRoman Pen 	 */
735346c09f8SRoman Pen 	smp_mb();
7364d707b9fSOleg Nesterov }
7374d707b9fSOleg Nesterov 
7387a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
739365970a1SDavid Howells {
7407c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
7417c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
7427a22ad75STejun Heo }
7437a22ad75STejun Heo 
744afa4bb77SLinus Torvalds static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
745afa4bb77SLinus Torvalds {
746afa4bb77SLinus Torvalds 	return (struct pool_workqueue *)(data & WORK_STRUCT_WQ_DATA_MASK);
747afa4bb77SLinus Torvalds }
748afa4bb77SLinus Torvalds 
749112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
7507a22ad75STejun Heo {
751e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7527a22ad75STejun Heo 
753112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
754afa4bb77SLinus Torvalds 		return work_struct_pwq(data);
755e120153dSTejun Heo 	else
756e120153dSTejun Heo 		return NULL;
7577a22ad75STejun Heo }
7587a22ad75STejun Heo 
7597c3eed5cSTejun Heo /**
7607c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
7617c3eed5cSTejun Heo  * @work: the work item of interest
7627c3eed5cSTejun Heo  *
76368e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
76424acfb71SThomas Gleixner  * access under RCU read lock.  As such, this function should be
76524acfb71SThomas Gleixner  * called under wq_pool_mutex or inside of a rcu_read_lock() region.
766fa1b54e6STejun Heo  *
767fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
768fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
769fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
770fa1b54e6STejun Heo  * returned pool is and stays online.
771d185af30SYacine Belkadi  *
772d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
7737c3eed5cSTejun Heo  */
7747c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
7757a22ad75STejun Heo {
776e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7777c3eed5cSTejun Heo 	int pool_id;
7787a22ad75STejun Heo 
77968e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
780fa1b54e6STejun Heo 
781112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
782afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool;
7837a22ad75STejun Heo 
7847c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
7857c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
7867a22ad75STejun Heo 		return NULL;
7877a22ad75STejun Heo 
788fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
7897c3eed5cSTejun Heo }
7907c3eed5cSTejun Heo 
7917c3eed5cSTejun Heo /**
7927c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
7937c3eed5cSTejun Heo  * @work: the work item of interest
7947c3eed5cSTejun Heo  *
795d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
7967c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
7977c3eed5cSTejun Heo  */
7987c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
7997c3eed5cSTejun Heo {
80054d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
8017c3eed5cSTejun Heo 
802112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
803afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool->id;
80454d5b7d0SLai Jiangshan 
80554d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
8067c3eed5cSTejun Heo }
8077c3eed5cSTejun Heo 
808bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
809bbb68dfaSTejun Heo {
8107c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
811bbb68dfaSTejun Heo 
8127c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
8137c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
814bbb68dfaSTejun Heo }
815bbb68dfaSTejun Heo 
816bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
817bbb68dfaSTejun Heo {
818bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
819bbb68dfaSTejun Heo 
820112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
821bbb68dfaSTejun Heo }
822bbb68dfaSTejun Heo 
823e22bee78STejun Heo /*
8243270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
8253270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
826d565ed63STejun Heo  * they're being called with pool->lock held.
827e22bee78STejun Heo  */
828e22bee78STejun Heo 
829e22bee78STejun Heo /*
830e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
831e22bee78STejun Heo  * running workers.
832974271c4STejun Heo  *
833974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
834706026c2STejun Heo  * function will always return %true for unbound pools as long as the
835974271c4STejun Heo  * worklist isn't empty.
836e22bee78STejun Heo  */
83763d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
838e22bee78STejun Heo {
8390219a352STejun Heo 	return !list_empty(&pool->worklist) && !pool->nr_running;
840e22bee78STejun Heo }
841e22bee78STejun Heo 
842e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
84363d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
844e22bee78STejun Heo {
84563d95a91STejun Heo 	return pool->nr_idle;
846e22bee78STejun Heo }
847e22bee78STejun Heo 
848e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
84963d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
850e22bee78STejun Heo {
851bc35f7efSLai Jiangshan 	return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
852e22bee78STejun Heo }
853e22bee78STejun Heo 
854e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
85563d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
856e22bee78STejun Heo {
85763d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
858e22bee78STejun Heo }
859e22bee78STejun Heo 
860e22bee78STejun Heo /* Do we have too many workers and should some go away? */
86163d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
862e22bee78STejun Heo {
863692b4825STejun Heo 	bool managing = pool->flags & POOL_MANAGER_ACTIVE;
86463d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
86563d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
866e22bee78STejun Heo 
867e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
868e22bee78STejun Heo }
869e22bee78STejun Heo 
8704690c4abSTejun Heo /**
871e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
872cb444766STejun Heo  * @worker: self
873d302f017STejun Heo  * @flags: flags to set
874d302f017STejun Heo  *
875228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
876d302f017STejun Heo  */
877228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
878d302f017STejun Heo {
879bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
880e22bee78STejun Heo 
881bc8b50c2STejun Heo 	lockdep_assert_held(&pool->lock);
882cb444766STejun Heo 
883228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
884e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
885e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
886bc35f7efSLai Jiangshan 		pool->nr_running--;
887e22bee78STejun Heo 	}
888e22bee78STejun Heo 
889d302f017STejun Heo 	worker->flags |= flags;
890d302f017STejun Heo }
891d302f017STejun Heo 
892d302f017STejun Heo /**
893e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
894cb444766STejun Heo  * @worker: self
895d302f017STejun Heo  * @flags: flags to clear
896d302f017STejun Heo  *
897e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
898d302f017STejun Heo  */
899d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
900d302f017STejun Heo {
90163d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
902e22bee78STejun Heo 	unsigned int oflags = worker->flags;
903e22bee78STejun Heo 
904bc8b50c2STejun Heo 	lockdep_assert_held(&pool->lock);
905cb444766STejun Heo 
906d302f017STejun Heo 	worker->flags &= ~flags;
907e22bee78STejun Heo 
90842c025f3STejun Heo 	/*
90942c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
91042c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
91142c025f3STejun Heo 	 * of multiple flags, not a single flag.
91242c025f3STejun Heo 	 */
913e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
914e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
915bc35f7efSLai Jiangshan 			pool->nr_running++;
916d302f017STejun Heo }
917d302f017STejun Heo 
918797e8345STejun Heo /* Return the first idle worker.  Called with pool->lock held. */
919797e8345STejun Heo static struct worker *first_idle_worker(struct worker_pool *pool)
920797e8345STejun Heo {
921797e8345STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
922797e8345STejun Heo 		return NULL;
923797e8345STejun Heo 
924797e8345STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
925797e8345STejun Heo }
926797e8345STejun Heo 
927797e8345STejun Heo /**
928797e8345STejun Heo  * worker_enter_idle - enter idle state
929797e8345STejun Heo  * @worker: worker which is entering idle state
930797e8345STejun Heo  *
931797e8345STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
932797e8345STejun Heo  * necessary.
933797e8345STejun Heo  *
934797e8345STejun Heo  * LOCKING:
935797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
936797e8345STejun Heo  */
937797e8345STejun Heo static void worker_enter_idle(struct worker *worker)
938797e8345STejun Heo {
939797e8345STejun Heo 	struct worker_pool *pool = worker->pool;
940797e8345STejun Heo 
941797e8345STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
942797e8345STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
943797e8345STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
944797e8345STejun Heo 		return;
945797e8345STejun Heo 
946797e8345STejun Heo 	/* can't use worker_set_flags(), also called from create_worker() */
947797e8345STejun Heo 	worker->flags |= WORKER_IDLE;
948797e8345STejun Heo 	pool->nr_idle++;
949797e8345STejun Heo 	worker->last_active = jiffies;
950797e8345STejun Heo 
951797e8345STejun Heo 	/* idle_list is LIFO */
952797e8345STejun Heo 	list_add(&worker->entry, &pool->idle_list);
953797e8345STejun Heo 
954797e8345STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
955797e8345STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
956797e8345STejun Heo 
957797e8345STejun Heo 	/* Sanity check nr_running. */
958797e8345STejun Heo 	WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
959797e8345STejun Heo }
960797e8345STejun Heo 
961797e8345STejun Heo /**
962797e8345STejun Heo  * worker_leave_idle - leave idle state
963797e8345STejun Heo  * @worker: worker which is leaving idle state
964797e8345STejun Heo  *
965797e8345STejun Heo  * @worker is leaving idle state.  Update stats.
966797e8345STejun Heo  *
967797e8345STejun Heo  * LOCKING:
968797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
969797e8345STejun Heo  */
970797e8345STejun Heo static void worker_leave_idle(struct worker *worker)
971797e8345STejun Heo {
972797e8345STejun Heo 	struct worker_pool *pool = worker->pool;
973797e8345STejun Heo 
974797e8345STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
975797e8345STejun Heo 		return;
976797e8345STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
977797e8345STejun Heo 	pool->nr_idle--;
978797e8345STejun Heo 	list_del_init(&worker->entry);
979797e8345STejun Heo }
980797e8345STejun Heo 
981797e8345STejun Heo /**
982797e8345STejun Heo  * find_worker_executing_work - find worker which is executing a work
983797e8345STejun Heo  * @pool: pool of interest
984797e8345STejun Heo  * @work: work to find worker for
985797e8345STejun Heo  *
986797e8345STejun Heo  * Find a worker which is executing @work on @pool by searching
987797e8345STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
988797e8345STejun Heo  * to match, its current execution should match the address of @work and
989797e8345STejun Heo  * its work function.  This is to avoid unwanted dependency between
990797e8345STejun Heo  * unrelated work executions through a work item being recycled while still
991797e8345STejun Heo  * being executed.
992797e8345STejun Heo  *
993797e8345STejun Heo  * This is a bit tricky.  A work item may be freed once its execution
994797e8345STejun Heo  * starts and nothing prevents the freed area from being recycled for
995797e8345STejun Heo  * another work item.  If the same work item address ends up being reused
996797e8345STejun Heo  * before the original execution finishes, workqueue will identify the
997797e8345STejun Heo  * recycled work item as currently executing and make it wait until the
998797e8345STejun Heo  * current execution finishes, introducing an unwanted dependency.
999797e8345STejun Heo  *
1000797e8345STejun Heo  * This function checks the work item address and work function to avoid
1001797e8345STejun Heo  * false positives.  Note that this isn't complete as one may construct a
1002797e8345STejun Heo  * work function which can introduce dependency onto itself through a
1003797e8345STejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
1004797e8345STejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
1005797e8345STejun Heo  * actually occurs, it should be easy to locate the culprit work function.
1006797e8345STejun Heo  *
1007797e8345STejun Heo  * CONTEXT:
1008797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1009797e8345STejun Heo  *
1010797e8345STejun Heo  * Return:
1011797e8345STejun Heo  * Pointer to worker which is executing @work if found, %NULL
1012797e8345STejun Heo  * otherwise.
1013797e8345STejun Heo  */
1014797e8345STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
1015797e8345STejun Heo 						 struct work_struct *work)
1016797e8345STejun Heo {
1017797e8345STejun Heo 	struct worker *worker;
1018797e8345STejun Heo 
1019797e8345STejun Heo 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1020797e8345STejun Heo 			       (unsigned long)work)
1021797e8345STejun Heo 		if (worker->current_work == work &&
1022797e8345STejun Heo 		    worker->current_func == work->func)
1023797e8345STejun Heo 			return worker;
1024797e8345STejun Heo 
1025797e8345STejun Heo 	return NULL;
1026797e8345STejun Heo }
1027797e8345STejun Heo 
1028797e8345STejun Heo /**
1029797e8345STejun Heo  * move_linked_works - move linked works to a list
1030797e8345STejun Heo  * @work: start of series of works to be scheduled
1031797e8345STejun Heo  * @head: target list to append @work to
1032797e8345STejun Heo  * @nextp: out parameter for nested worklist walking
1033797e8345STejun Heo  *
1034873eaca6STejun Heo  * Schedule linked works starting from @work to @head. Work series to be
1035873eaca6STejun Heo  * scheduled starts at @work and includes any consecutive work with
1036873eaca6STejun Heo  * WORK_STRUCT_LINKED set in its predecessor. See assign_work() for details on
1037873eaca6STejun Heo  * @nextp.
1038797e8345STejun Heo  *
1039797e8345STejun Heo  * CONTEXT:
1040797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1041797e8345STejun Heo  */
1042797e8345STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1043797e8345STejun Heo 			      struct work_struct **nextp)
1044797e8345STejun Heo {
1045797e8345STejun Heo 	struct work_struct *n;
1046797e8345STejun Heo 
1047797e8345STejun Heo 	/*
1048797e8345STejun Heo 	 * Linked worklist will always end before the end of the list,
1049797e8345STejun Heo 	 * use NULL for list head.
1050797e8345STejun Heo 	 */
1051797e8345STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1052797e8345STejun Heo 		list_move_tail(&work->entry, head);
1053797e8345STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1054797e8345STejun Heo 			break;
1055797e8345STejun Heo 	}
1056797e8345STejun Heo 
1057797e8345STejun Heo 	/*
1058797e8345STejun Heo 	 * If we're already inside safe list traversal and have moved
1059797e8345STejun Heo 	 * multiple works to the scheduled queue, the next position
1060797e8345STejun Heo 	 * needs to be updated.
1061797e8345STejun Heo 	 */
1062797e8345STejun Heo 	if (nextp)
1063797e8345STejun Heo 		*nextp = n;
1064797e8345STejun Heo }
1065797e8345STejun Heo 
1066797e8345STejun Heo /**
1067873eaca6STejun Heo  * assign_work - assign a work item and its linked work items to a worker
1068873eaca6STejun Heo  * @work: work to assign
1069873eaca6STejun Heo  * @worker: worker to assign to
1070873eaca6STejun Heo  * @nextp: out parameter for nested worklist walking
1071873eaca6STejun Heo  *
1072873eaca6STejun Heo  * Assign @work and its linked work items to @worker. If @work is already being
1073873eaca6STejun Heo  * executed by another worker in the same pool, it'll be punted there.
1074873eaca6STejun Heo  *
1075873eaca6STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of the last
1076873eaca6STejun Heo  * scheduled work. This allows assign_work() to be nested inside
1077873eaca6STejun Heo  * list_for_each_entry_safe().
1078873eaca6STejun Heo  *
1079873eaca6STejun Heo  * Returns %true if @work was successfully assigned to @worker. %false if @work
1080873eaca6STejun Heo  * was punted to another worker already executing it.
1081873eaca6STejun Heo  */
1082873eaca6STejun Heo static bool assign_work(struct work_struct *work, struct worker *worker,
1083873eaca6STejun Heo 			struct work_struct **nextp)
1084873eaca6STejun Heo {
1085873eaca6STejun Heo 	struct worker_pool *pool = worker->pool;
1086873eaca6STejun Heo 	struct worker *collision;
1087873eaca6STejun Heo 
1088873eaca6STejun Heo 	lockdep_assert_held(&pool->lock);
1089873eaca6STejun Heo 
1090873eaca6STejun Heo 	/*
1091873eaca6STejun Heo 	 * A single work shouldn't be executed concurrently by multiple workers.
1092873eaca6STejun Heo 	 * __queue_work() ensures that @work doesn't jump to a different pool
1093873eaca6STejun Heo 	 * while still running in the previous pool. Here, we should ensure that
1094873eaca6STejun Heo 	 * @work is not executed concurrently by multiple workers from the same
1095873eaca6STejun Heo 	 * pool. Check whether anyone is already processing the work. If so,
1096873eaca6STejun Heo 	 * defer the work to the currently executing one.
1097873eaca6STejun Heo 	 */
1098873eaca6STejun Heo 	collision = find_worker_executing_work(pool, work);
1099873eaca6STejun Heo 	if (unlikely(collision)) {
1100873eaca6STejun Heo 		move_linked_works(work, &collision->scheduled, nextp);
1101873eaca6STejun Heo 		return false;
1102873eaca6STejun Heo 	}
1103873eaca6STejun Heo 
1104873eaca6STejun Heo 	move_linked_works(work, &worker->scheduled, nextp);
1105873eaca6STejun Heo 	return true;
1106873eaca6STejun Heo }
1107873eaca6STejun Heo 
1108873eaca6STejun Heo /**
11090219a352STejun Heo  * kick_pool - wake up an idle worker if necessary
11100219a352STejun Heo  * @pool: pool to kick
1111797e8345STejun Heo  *
11120219a352STejun Heo  * @pool may have pending work items. Wake up worker if necessary. Returns
11130219a352STejun Heo  * whether a worker was woken up.
1114797e8345STejun Heo  */
11150219a352STejun Heo static bool kick_pool(struct worker_pool *pool)
1116797e8345STejun Heo {
1117797e8345STejun Heo 	struct worker *worker = first_idle_worker(pool);
11188639ecebSTejun Heo 	struct task_struct *p;
1119797e8345STejun Heo 
11200219a352STejun Heo 	lockdep_assert_held(&pool->lock);
11210219a352STejun Heo 
11220219a352STejun Heo 	if (!need_more_worker(pool) || !worker)
11230219a352STejun Heo 		return false;
11240219a352STejun Heo 
11258639ecebSTejun Heo 	p = worker->task;
11268639ecebSTejun Heo 
11278639ecebSTejun Heo #ifdef CONFIG_SMP
11288639ecebSTejun Heo 	/*
11298639ecebSTejun Heo 	 * Idle @worker is about to execute @work and waking up provides an
11308639ecebSTejun Heo 	 * opportunity to migrate @worker at a lower cost by setting the task's
11318639ecebSTejun Heo 	 * wake_cpu field. Let's see if we want to move @worker to improve
11328639ecebSTejun Heo 	 * execution locality.
11338639ecebSTejun Heo 	 *
11348639ecebSTejun Heo 	 * We're waking the worker that went idle the latest and there's some
11358639ecebSTejun Heo 	 * chance that @worker is marked idle but hasn't gone off CPU yet. If
11368639ecebSTejun Heo 	 * so, setting the wake_cpu won't do anything. As this is a best-effort
11378639ecebSTejun Heo 	 * optimization and the race window is narrow, let's leave as-is for
11388639ecebSTejun Heo 	 * now. If this becomes pronounced, we can skip over workers which are
11398639ecebSTejun Heo 	 * still on cpu when picking an idle worker.
11408639ecebSTejun Heo 	 *
11418639ecebSTejun Heo 	 * If @pool has non-strict affinity, @worker might have ended up outside
11428639ecebSTejun Heo 	 * its affinity scope. Repatriate.
11438639ecebSTejun Heo 	 */
11448639ecebSTejun Heo 	if (!pool->attrs->affn_strict &&
11458639ecebSTejun Heo 	    !cpumask_test_cpu(p->wake_cpu, pool->attrs->__pod_cpumask)) {
11468639ecebSTejun Heo 		struct work_struct *work = list_first_entry(&pool->worklist,
11478639ecebSTejun Heo 						struct work_struct, entry);
11488639ecebSTejun Heo 		p->wake_cpu = cpumask_any_distribute(pool->attrs->__pod_cpumask);
11498639ecebSTejun Heo 		get_work_pwq(work)->stats[PWQ_STAT_REPATRIATED]++;
11508639ecebSTejun Heo 	}
11518639ecebSTejun Heo #endif
11528639ecebSTejun Heo 	wake_up_process(p);
11530219a352STejun Heo 	return true;
1154797e8345STejun Heo }
1155797e8345STejun Heo 
115663638450STejun Heo #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
115763638450STejun Heo 
115863638450STejun Heo /*
115963638450STejun Heo  * Concurrency-managed per-cpu work items that hog CPU for longer than
116063638450STejun Heo  * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
116163638450STejun Heo  * which prevents them from stalling other concurrency-managed work items. If a
116263638450STejun Heo  * work function keeps triggering this mechanism, it's likely that the work item
116363638450STejun Heo  * should be using an unbound workqueue instead.
116463638450STejun Heo  *
116563638450STejun Heo  * wq_cpu_intensive_report() tracks work functions which trigger such conditions
116663638450STejun Heo  * and report them so that they can be examined and converted to use unbound
116763638450STejun Heo  * workqueues as appropriate. To avoid flooding the console, each violating work
116863638450STejun Heo  * function is tracked and reported with exponential backoff.
116963638450STejun Heo  */
117063638450STejun Heo #define WCI_MAX_ENTS 128
117163638450STejun Heo 
117263638450STejun Heo struct wci_ent {
117363638450STejun Heo 	work_func_t		func;
117463638450STejun Heo 	atomic64_t		cnt;
117563638450STejun Heo 	struct hlist_node	hash_node;
117663638450STejun Heo };
117763638450STejun Heo 
117863638450STejun Heo static struct wci_ent wci_ents[WCI_MAX_ENTS];
117963638450STejun Heo static int wci_nr_ents;
118063638450STejun Heo static DEFINE_RAW_SPINLOCK(wci_lock);
118163638450STejun Heo static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
118263638450STejun Heo 
118363638450STejun Heo static struct wci_ent *wci_find_ent(work_func_t func)
118463638450STejun Heo {
118563638450STejun Heo 	struct wci_ent *ent;
118663638450STejun Heo 
118763638450STejun Heo 	hash_for_each_possible_rcu(wci_hash, ent, hash_node,
118863638450STejun Heo 				   (unsigned long)func) {
118963638450STejun Heo 		if (ent->func == func)
119063638450STejun Heo 			return ent;
119163638450STejun Heo 	}
119263638450STejun Heo 	return NULL;
119363638450STejun Heo }
119463638450STejun Heo 
119563638450STejun Heo static void wq_cpu_intensive_report(work_func_t func)
119663638450STejun Heo {
119763638450STejun Heo 	struct wci_ent *ent;
119863638450STejun Heo 
119963638450STejun Heo restart:
120063638450STejun Heo 	ent = wci_find_ent(func);
120163638450STejun Heo 	if (ent) {
120263638450STejun Heo 		u64 cnt;
120363638450STejun Heo 
120463638450STejun Heo 		/*
120563638450STejun Heo 		 * Start reporting from the fourth time and back off
120663638450STejun Heo 		 * exponentially.
120763638450STejun Heo 		 */
120863638450STejun Heo 		cnt = atomic64_inc_return_relaxed(&ent->cnt);
120963638450STejun Heo 		if (cnt >= 4 && is_power_of_2(cnt))
121063638450STejun Heo 			printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
121163638450STejun Heo 					ent->func, wq_cpu_intensive_thresh_us,
121263638450STejun Heo 					atomic64_read(&ent->cnt));
121363638450STejun Heo 		return;
121463638450STejun Heo 	}
121563638450STejun Heo 
121663638450STejun Heo 	/*
121763638450STejun Heo 	 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
121863638450STejun Heo 	 * is exhausted, something went really wrong and we probably made enough
121963638450STejun Heo 	 * noise already.
122063638450STejun Heo 	 */
122163638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS)
122263638450STejun Heo 		return;
122363638450STejun Heo 
122463638450STejun Heo 	raw_spin_lock(&wci_lock);
122563638450STejun Heo 
122663638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS) {
122763638450STejun Heo 		raw_spin_unlock(&wci_lock);
122863638450STejun Heo 		return;
122963638450STejun Heo 	}
123063638450STejun Heo 
123163638450STejun Heo 	if (wci_find_ent(func)) {
123263638450STejun Heo 		raw_spin_unlock(&wci_lock);
123363638450STejun Heo 		goto restart;
123463638450STejun Heo 	}
123563638450STejun Heo 
123663638450STejun Heo 	ent = &wci_ents[wci_nr_ents++];
123763638450STejun Heo 	ent->func = func;
123863638450STejun Heo 	atomic64_set(&ent->cnt, 1);
123963638450STejun Heo 	hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
124063638450STejun Heo 
124163638450STejun Heo 	raw_spin_unlock(&wci_lock);
124263638450STejun Heo }
124363638450STejun Heo 
124463638450STejun Heo #else	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
124563638450STejun Heo static void wq_cpu_intensive_report(work_func_t func) {}
124663638450STejun Heo #endif	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
124763638450STejun Heo 
1248c54d5046STejun Heo /**
12491da177e4SLinus Torvalds  * wq_worker_running - a worker is running again
12501da177e4SLinus Torvalds  * @task: task waking up
12511da177e4SLinus Torvalds  *
12521da177e4SLinus Torvalds  * This function is called when a worker returns from schedule()
12531da177e4SLinus Torvalds  */
12541da177e4SLinus Torvalds void wq_worker_running(struct task_struct *task)
12551da177e4SLinus Torvalds {
12561da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
12571da177e4SLinus Torvalds 
1258c8f6219bSZqiang 	if (!READ_ONCE(worker->sleeping))
12591da177e4SLinus Torvalds 		return;
12601da177e4SLinus Torvalds 
12611da177e4SLinus Torvalds 	/*
12621da177e4SLinus Torvalds 	 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
12631da177e4SLinus Torvalds 	 * and the nr_running increment below, we may ruin the nr_running reset
12641da177e4SLinus Torvalds 	 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
12651da177e4SLinus Torvalds 	 * pool. Protect against such race.
12661da177e4SLinus Torvalds 	 */
12671da177e4SLinus Torvalds 	preempt_disable();
12681da177e4SLinus Torvalds 	if (!(worker->flags & WORKER_NOT_RUNNING))
12691da177e4SLinus Torvalds 		worker->pool->nr_running++;
12701da177e4SLinus Torvalds 	preempt_enable();
1271616db877STejun Heo 
1272616db877STejun Heo 	/*
1273616db877STejun Heo 	 * CPU intensive auto-detection cares about how long a work item hogged
1274616db877STejun Heo 	 * CPU without sleeping. Reset the starting timestamp on wakeup.
1275616db877STejun Heo 	 */
1276616db877STejun Heo 	worker->current_at = worker->task->se.sum_exec_runtime;
1277616db877STejun Heo 
1278c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 0);
12791da177e4SLinus Torvalds }
12801da177e4SLinus Torvalds 
12811da177e4SLinus Torvalds /**
12821da177e4SLinus Torvalds  * wq_worker_sleeping - a worker is going to sleep
12831da177e4SLinus Torvalds  * @task: task going to sleep
12841da177e4SLinus Torvalds  *
12851da177e4SLinus Torvalds  * This function is called from schedule() when a busy worker is
12861da177e4SLinus Torvalds  * going to sleep.
12871da177e4SLinus Torvalds  */
12881da177e4SLinus Torvalds void wq_worker_sleeping(struct task_struct *task)
12891da177e4SLinus Torvalds {
12901da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
12911da177e4SLinus Torvalds 	struct worker_pool *pool;
12921da177e4SLinus Torvalds 
12931da177e4SLinus Torvalds 	/*
12941da177e4SLinus Torvalds 	 * Rescuers, which may not have all the fields set up like normal
12951da177e4SLinus Torvalds 	 * workers, also reach here, let's not access anything before
12961da177e4SLinus Torvalds 	 * checking NOT_RUNNING.
12971da177e4SLinus Torvalds 	 */
12981da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING)
12991da177e4SLinus Torvalds 		return;
13001da177e4SLinus Torvalds 
13011da177e4SLinus Torvalds 	pool = worker->pool;
13021da177e4SLinus Torvalds 
13031da177e4SLinus Torvalds 	/* Return if preempted before wq_worker_running() was reached */
1304c8f6219bSZqiang 	if (READ_ONCE(worker->sleeping))
13051da177e4SLinus Torvalds 		return;
13061da177e4SLinus Torvalds 
1307c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 1);
13081da177e4SLinus Torvalds 	raw_spin_lock_irq(&pool->lock);
13091da177e4SLinus Torvalds 
13101da177e4SLinus Torvalds 	/*
13111da177e4SLinus Torvalds 	 * Recheck in case unbind_workers() preempted us. We don't
13121da177e4SLinus Torvalds 	 * want to decrement nr_running after the worker is unbound
13131da177e4SLinus Torvalds 	 * and nr_running has been reset.
13141da177e4SLinus Torvalds 	 */
13151da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING) {
13161da177e4SLinus Torvalds 		raw_spin_unlock_irq(&pool->lock);
13171da177e4SLinus Torvalds 		return;
13181da177e4SLinus Torvalds 	}
13191da177e4SLinus Torvalds 
13201da177e4SLinus Torvalds 	pool->nr_running--;
13210219a352STejun Heo 	if (kick_pool(pool))
1322725e8ec5STejun Heo 		worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
13230219a352STejun Heo 
13241da177e4SLinus Torvalds 	raw_spin_unlock_irq(&pool->lock);
13251da177e4SLinus Torvalds }
13261da177e4SLinus Torvalds 
13271da177e4SLinus Torvalds /**
1328616db877STejun Heo  * wq_worker_tick - a scheduler tick occurred while a kworker is running
1329616db877STejun Heo  * @task: task currently running
1330616db877STejun Heo  *
1331616db877STejun Heo  * Called from scheduler_tick(). We're in the IRQ context and the current
1332616db877STejun Heo  * worker's fields which follow the 'K' locking rule can be accessed safely.
1333616db877STejun Heo  */
1334616db877STejun Heo void wq_worker_tick(struct task_struct *task)
1335616db877STejun Heo {
1336616db877STejun Heo 	struct worker *worker = kthread_data(task);
1337616db877STejun Heo 	struct pool_workqueue *pwq = worker->current_pwq;
1338616db877STejun Heo 	struct worker_pool *pool = worker->pool;
1339616db877STejun Heo 
1340616db877STejun Heo 	if (!pwq)
1341616db877STejun Heo 		return;
1342616db877STejun Heo 
13438a1dd1e5STejun Heo 	pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
13448a1dd1e5STejun Heo 
134518c8ae81SZqiang 	if (!wq_cpu_intensive_thresh_us)
134618c8ae81SZqiang 		return;
134718c8ae81SZqiang 
1348616db877STejun Heo 	/*
1349616db877STejun Heo 	 * If the current worker is concurrency managed and hogged the CPU for
1350616db877STejun Heo 	 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1351616db877STejun Heo 	 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1352c8f6219bSZqiang 	 *
1353c8f6219bSZqiang 	 * Set @worker->sleeping means that @worker is in the process of
1354c8f6219bSZqiang 	 * switching out voluntarily and won't be contributing to
1355c8f6219bSZqiang 	 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1356c8f6219bSZqiang 	 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1357c8f6219bSZqiang 	 * double decrements. The task is releasing the CPU anyway. Let's skip.
1358c8f6219bSZqiang 	 * We probably want to make this prettier in the future.
1359616db877STejun Heo 	 */
1360c8f6219bSZqiang 	if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1361616db877STejun Heo 	    worker->task->se.sum_exec_runtime - worker->current_at <
1362616db877STejun Heo 	    wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1363616db877STejun Heo 		return;
1364616db877STejun Heo 
1365616db877STejun Heo 	raw_spin_lock(&pool->lock);
1366616db877STejun Heo 
1367616db877STejun Heo 	worker_set_flags(worker, WORKER_CPU_INTENSIVE);
136863638450STejun Heo 	wq_cpu_intensive_report(worker->current_func);
1369616db877STejun Heo 	pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1370616db877STejun Heo 
13710219a352STejun Heo 	if (kick_pool(pool))
1372616db877STejun Heo 		pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1373616db877STejun Heo 
1374616db877STejun Heo 	raw_spin_unlock(&pool->lock);
1375616db877STejun Heo }
1376616db877STejun Heo 
1377616db877STejun Heo /**
13781da177e4SLinus Torvalds  * wq_worker_last_func - retrieve worker's last work function
13791da177e4SLinus Torvalds  * @task: Task to retrieve last work function of.
13801da177e4SLinus Torvalds  *
13811da177e4SLinus Torvalds  * Determine the last function a worker executed. This is called from
13821da177e4SLinus Torvalds  * the scheduler to get a worker's last known identity.
13831da177e4SLinus Torvalds  *
13841da177e4SLinus Torvalds  * CONTEXT:
13859b41ea72SAndrew Morton  * raw_spin_lock_irq(rq->lock)
13861da177e4SLinus Torvalds  *
13871da177e4SLinus Torvalds  * This function is called during schedule() when a kworker is going
1388f756d5e2SNathan Lynch  * to sleep. It's used by psi to identify aggregation workers during
1389f756d5e2SNathan Lynch  * dequeuing, to allow periodic aggregation to shut-off when that
13901da177e4SLinus Torvalds  * worker is the last task in the system or cgroup to go to sleep.
13911da177e4SLinus Torvalds  *
13921da177e4SLinus Torvalds  * As this function doesn't involve any workqueue-related locking, it
13931da177e4SLinus Torvalds  * only returns stable values when called from inside the scheduler's
13941da177e4SLinus Torvalds  * queuing and dequeuing paths, when @task, which must be a kworker,
13951da177e4SLinus Torvalds  * is guaranteed to not be processing any works.
1396365970a1SDavid Howells  *
1397365970a1SDavid Howells  * Return:
1398365970a1SDavid Howells  * The last work function %current executed as a worker, NULL if it
1399365970a1SDavid Howells  * hasn't executed any work yet.
1400365970a1SDavid Howells  */
1401365970a1SDavid Howells work_func_t wq_worker_last_func(struct task_struct *task)
1402365970a1SDavid Howells {
1403365970a1SDavid Howells 	struct worker *worker = kthread_data(task);
1404365970a1SDavid Howells 
1405365970a1SDavid Howells 	return worker->last_func;
1406365970a1SDavid Howells }
1407365970a1SDavid Howells 
1408d302f017STejun Heo /**
14098864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
14108864b4e5STejun Heo  * @pwq: pool_workqueue to get
14118864b4e5STejun Heo  *
14128864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
14138864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
14148864b4e5STejun Heo  */
14158864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
14168864b4e5STejun Heo {
14178864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
14188864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
14198864b4e5STejun Heo 	pwq->refcnt++;
14208864b4e5STejun Heo }
14218864b4e5STejun Heo 
14228864b4e5STejun Heo /**
14238864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
14248864b4e5STejun Heo  * @pwq: pool_workqueue to put
14258864b4e5STejun Heo  *
14268864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
14278864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
14288864b4e5STejun Heo  */
14298864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
14308864b4e5STejun Heo {
14318864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
14328864b4e5STejun Heo 	if (likely(--pwq->refcnt))
14338864b4e5STejun Heo 		return;
14348864b4e5STejun Heo 	/*
1435967b494eSTejun Heo 	 * @pwq can't be released under pool->lock, bounce to a dedicated
1436967b494eSTejun Heo 	 * kthread_worker to avoid A-A deadlocks.
14378864b4e5STejun Heo 	 */
1438687a9aa5STejun Heo 	kthread_queue_work(pwq_release_worker, &pwq->release_work);
14398864b4e5STejun Heo }
14408864b4e5STejun Heo 
1441dce90d47STejun Heo /**
1442dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1443dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1444dce90d47STejun Heo  *
1445dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1446dce90d47STejun Heo  */
1447dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1448dce90d47STejun Heo {
1449dce90d47STejun Heo 	if (pwq) {
1450dce90d47STejun Heo 		/*
145124acfb71SThomas Gleixner 		 * As both pwqs and pools are RCU protected, the
1452dce90d47STejun Heo 		 * following lock operations are safe.
1453dce90d47STejun Heo 		 */
1454a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
1455dce90d47STejun Heo 		put_pwq(pwq);
1456a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
1457dce90d47STejun Heo 	}
1458dce90d47STejun Heo }
1459dce90d47STejun Heo 
1460f97a4a1aSLai Jiangshan static void pwq_activate_inactive_work(struct work_struct *work)
1461bf4ede01STejun Heo {
1462112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1463bf4ede01STejun Heo 
1464bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
146582607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
146682607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1467112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
1468f97a4a1aSLai Jiangshan 	__clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work));
1469112202d9STejun Heo 	pwq->nr_active++;
1470bf4ede01STejun Heo }
1471bf4ede01STejun Heo 
1472f97a4a1aSLai Jiangshan static void pwq_activate_first_inactive(struct pool_workqueue *pwq)
14733aa62497SLai Jiangshan {
1474f97a4a1aSLai Jiangshan 	struct work_struct *work = list_first_entry(&pwq->inactive_works,
14753aa62497SLai Jiangshan 						    struct work_struct, entry);
14763aa62497SLai Jiangshan 
1477f97a4a1aSLai Jiangshan 	pwq_activate_inactive_work(work);
14783aa62497SLai Jiangshan }
14793aa62497SLai Jiangshan 
1480bf4ede01STejun Heo /**
1481112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1482112202d9STejun Heo  * @pwq: pwq of interest
1483c4560c2cSLai Jiangshan  * @work_data: work_data of work which left the queue
1484bf4ede01STejun Heo  *
1485bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1486112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1487bf4ede01STejun Heo  *
1488bf4ede01STejun Heo  * CONTEXT:
1489a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1490bf4ede01STejun Heo  */
1491c4560c2cSLai Jiangshan static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1492bf4ede01STejun Heo {
1493c4560c2cSLai Jiangshan 	int color = get_work_color(work_data);
1494c4560c2cSLai Jiangshan 
1495018f3a13SLai Jiangshan 	if (!(work_data & WORK_STRUCT_INACTIVE)) {
1496112202d9STejun Heo 		pwq->nr_active--;
1497f97a4a1aSLai Jiangshan 		if (!list_empty(&pwq->inactive_works)) {
1498f97a4a1aSLai Jiangshan 			/* one down, submit an inactive one */
1499112202d9STejun Heo 			if (pwq->nr_active < pwq->max_active)
1500f97a4a1aSLai Jiangshan 				pwq_activate_first_inactive(pwq);
1501bf4ede01STejun Heo 		}
1502018f3a13SLai Jiangshan 	}
1503018f3a13SLai Jiangshan 
1504018f3a13SLai Jiangshan 	pwq->nr_in_flight[color]--;
1505bf4ede01STejun Heo 
1506bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1507112202d9STejun Heo 	if (likely(pwq->flush_color != color))
15088864b4e5STejun Heo 		goto out_put;
1509bf4ede01STejun Heo 
1510bf4ede01STejun Heo 	/* are there still in-flight works? */
1511112202d9STejun Heo 	if (pwq->nr_in_flight[color])
15128864b4e5STejun Heo 		goto out_put;
1513bf4ede01STejun Heo 
1514112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1515112202d9STejun Heo 	pwq->flush_color = -1;
1516bf4ede01STejun Heo 
1517bf4ede01STejun Heo 	/*
1518112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1519bf4ede01STejun Heo 	 * will handle the rest.
1520bf4ede01STejun Heo 	 */
1521112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1522112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
15238864b4e5STejun Heo out_put:
15248864b4e5STejun Heo 	put_pwq(pwq);
1525bf4ede01STejun Heo }
1526bf4ede01STejun Heo 
152736e227d2STejun Heo /**
1528bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
152936e227d2STejun Heo  * @work: work item to steal
153036e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1531bbb68dfaSTejun Heo  * @flags: place to store irq state
153236e227d2STejun Heo  *
153336e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1534d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
153536e227d2STejun Heo  *
1536d185af30SYacine Belkadi  * Return:
15373eb6b31bSMauro Carvalho Chehab  *
15383eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
153936e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
154036e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
154136e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1542bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1543bbb68dfaSTejun Heo  *		for arbitrarily long
15443eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
154536e227d2STejun Heo  *
1546d185af30SYacine Belkadi  * Note:
1547bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1548e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1549e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1550e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1551bbb68dfaSTejun Heo  *
1552bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1553bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1554bbb68dfaSTejun Heo  *
1555e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1556bf4ede01STejun Heo  */
1557bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1558bbb68dfaSTejun Heo 			       unsigned long *flags)
1559bf4ede01STejun Heo {
1560d565ed63STejun Heo 	struct worker_pool *pool;
1561112202d9STejun Heo 	struct pool_workqueue *pwq;
1562bf4ede01STejun Heo 
1563bbb68dfaSTejun Heo 	local_irq_save(*flags);
1564bbb68dfaSTejun Heo 
156536e227d2STejun Heo 	/* try to steal the timer if it exists */
156636e227d2STejun Heo 	if (is_dwork) {
156736e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
156836e227d2STejun Heo 
1569e0aecdd8STejun Heo 		/*
1570e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1571e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1572e0aecdd8STejun Heo 		 * running on the local CPU.
1573e0aecdd8STejun Heo 		 */
157436e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
157536e227d2STejun Heo 			return 1;
157636e227d2STejun Heo 	}
157736e227d2STejun Heo 
157836e227d2STejun Heo 	/* try to claim PENDING the normal way */
1579bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1580bf4ede01STejun Heo 		return 0;
1581bf4ede01STejun Heo 
158224acfb71SThomas Gleixner 	rcu_read_lock();
1583bf4ede01STejun Heo 	/*
1584bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1585bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1586bf4ede01STejun Heo 	 */
1587d565ed63STejun Heo 	pool = get_work_pool(work);
1588d565ed63STejun Heo 	if (!pool)
1589bbb68dfaSTejun Heo 		goto fail;
1590bf4ede01STejun Heo 
1591a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&pool->lock);
1592bf4ede01STejun Heo 	/*
1593112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1594112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1595112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1596112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1597112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
15980b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1599bf4ede01STejun Heo 	 */
1600112202d9STejun Heo 	pwq = get_work_pwq(work);
1601112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1602bf4ede01STejun Heo 		debug_work_deactivate(work);
16033aa62497SLai Jiangshan 
16043aa62497SLai Jiangshan 		/*
1605018f3a13SLai Jiangshan 		 * A cancelable inactive work item must be in the
1606018f3a13SLai Jiangshan 		 * pwq->inactive_works since a queued barrier can't be
1607018f3a13SLai Jiangshan 		 * canceled (see the comments in insert_wq_barrier()).
1608018f3a13SLai Jiangshan 		 *
1609f97a4a1aSLai Jiangshan 		 * An inactive work item cannot be grabbed directly because
1610d812796eSLai Jiangshan 		 * it might have linked barrier work items which, if left
1611f97a4a1aSLai Jiangshan 		 * on the inactive_works list, will confuse pwq->nr_active
161216062836STejun Heo 		 * management later on and cause stall.  Make sure the work
161316062836STejun Heo 		 * item is activated before grabbing.
16143aa62497SLai Jiangshan 		 */
1615f97a4a1aSLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_INACTIVE)
1616f97a4a1aSLai Jiangshan 			pwq_activate_inactive_work(work);
16173aa62497SLai Jiangshan 
1618bf4ede01STejun Heo 		list_del_init(&work->entry);
1619c4560c2cSLai Jiangshan 		pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
162036e227d2STejun Heo 
1621112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
16224468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
16234468a00fSLai Jiangshan 
1624a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock(&pool->lock);
162524acfb71SThomas Gleixner 		rcu_read_unlock();
162636e227d2STejun Heo 		return 1;
1627bf4ede01STejun Heo 	}
1628a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pool->lock);
1629bbb68dfaSTejun Heo fail:
163024acfb71SThomas Gleixner 	rcu_read_unlock();
1631bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1632bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1633bbb68dfaSTejun Heo 		return -ENOENT;
1634bbb68dfaSTejun Heo 	cpu_relax();
163536e227d2STejun Heo 	return -EAGAIN;
1636bf4ede01STejun Heo }
1637bf4ede01STejun Heo 
1638bf4ede01STejun Heo /**
1639706026c2STejun Heo  * insert_work - insert a work into a pool
1640112202d9STejun Heo  * @pwq: pwq @work belongs to
16414690c4abSTejun Heo  * @work: work to insert
16424690c4abSTejun Heo  * @head: insertion point
16434690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
16444690c4abSTejun Heo  *
1645112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1646706026c2STejun Heo  * work_struct flags.
16474690c4abSTejun Heo  *
16484690c4abSTejun Heo  * CONTEXT:
1649a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1650365970a1SDavid Howells  */
1651112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1652112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1653b89deed3SOleg Nesterov {
1654fe089f87STejun Heo 	debug_work_activate(work);
1655e1d8aa9fSFrederic Weisbecker 
1656e89a85d6SWalter Wu 	/* record the work call stack in order to print it in KASAN reports */
1657f70da745SMarco Elver 	kasan_record_aux_stack_noalloc(work);
1658e89a85d6SWalter Wu 
16594690c4abSTejun Heo 	/* we own @work, set data and link */
1660112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
16611a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
16628864b4e5STejun Heo 	get_pwq(pwq);
1663b89deed3SOleg Nesterov }
1664b89deed3SOleg Nesterov 
1665c8efcc25STejun Heo /*
1666c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
16678d03ecfeSTejun Heo  * same workqueue.
1668c8efcc25STejun Heo  */
1669c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1670c8efcc25STejun Heo {
1671c8efcc25STejun Heo 	struct worker *worker;
1672c8efcc25STejun Heo 
16738d03ecfeSTejun Heo 	worker = current_wq_worker();
1674c8efcc25STejun Heo 	/*
1675bf393fd4SBart Van Assche 	 * Return %true iff I'm a worker executing a work item on @wq.  If
16768d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1677c8efcc25STejun Heo 	 */
1678112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1679c8efcc25STejun Heo }
1680c8efcc25STejun Heo 
1681ef557180SMike Galbraith /*
1682ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
1683ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
1684ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
1685ef557180SMike Galbraith  */
1686ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1687ef557180SMike Galbraith {
1688ef557180SMike Galbraith 	int new_cpu;
1689ef557180SMike Galbraith 
1690f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
1691ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1692ef557180SMike Galbraith 			return cpu;
1693a8ec5880SAmmar Faizi 	} else {
1694a8ec5880SAmmar Faizi 		pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
1695f303fccbSTejun Heo 	}
1696f303fccbSTejun Heo 
1697ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
1698ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1699ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
1700ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1701ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
1702ef557180SMike Galbraith 			return cpu;
1703ef557180SMike Galbraith 	}
1704ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
1705ef557180SMike Galbraith 
1706ef557180SMike Galbraith 	return new_cpu;
1707ef557180SMike Galbraith }
1708ef557180SMike Galbraith 
1709d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
17101da177e4SLinus Torvalds 			 struct work_struct *work)
17111da177e4SLinus Torvalds {
1712112202d9STejun Heo 	struct pool_workqueue *pwq;
1713fe089f87STejun Heo 	struct worker_pool *last_pool, *pool;
17148a2e8e5dSTejun Heo 	unsigned int work_flags;
1715b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
17168930cabaSTejun Heo 
17178930cabaSTejun Heo 	/*
17188930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
17198930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
17208930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
17218930cabaSTejun Heo 	 * happen with IRQ disabled.
17228930cabaSTejun Heo 	 */
17238e8eb730SFrederic Weisbecker 	lockdep_assert_irqs_disabled();
17241da177e4SLinus Torvalds 
17251e19ffc6STejun Heo 
172633e3f0a3SRichard Clark 	/*
172733e3f0a3SRichard Clark 	 * For a draining wq, only works from the same workqueue are
172833e3f0a3SRichard Clark 	 * allowed. The __WQ_DESTROYING helps to spot the issue that
172933e3f0a3SRichard Clark 	 * queues a new work item to a wq after destroy_workqueue(wq).
173033e3f0a3SRichard Clark 	 */
173133e3f0a3SRichard Clark 	if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
173233e3f0a3SRichard Clark 		     WARN_ON_ONCE(!is_chained_work(wq))))
1733e41e704bSTejun Heo 		return;
173424acfb71SThomas Gleixner 	rcu_read_lock();
17359e8cd2f5STejun Heo retry:
1736aa202f1fSHillf Danton 	/* pwq which will be used unless @work is executing elsewhere */
1737636b927eSTejun Heo 	if (req_cpu == WORK_CPU_UNBOUND) {
1738636b927eSTejun Heo 		if (wq->flags & WQ_UNBOUND)
1739ef557180SMike Galbraith 			cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1740636b927eSTejun Heo 		else
1741aa202f1fSHillf Danton 			cpu = raw_smp_processor_id();
1742aa202f1fSHillf Danton 	}
1743f3421797STejun Heo 
1744636b927eSTejun Heo 	pwq = rcu_dereference(*per_cpu_ptr(wq->cpu_pwq, cpu));
1745fe089f87STejun Heo 	pool = pwq->pool;
1746fe089f87STejun Heo 
174718aa9effSTejun Heo 	/*
1748c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1749c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1750c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
175118aa9effSTejun Heo 	 */
1752c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1753fe089f87STejun Heo 	if (last_pool && last_pool != pool) {
175418aa9effSTejun Heo 		struct worker *worker;
175518aa9effSTejun Heo 
1756a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&last_pool->lock);
175718aa9effSTejun Heo 
1758c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
175918aa9effSTejun Heo 
1760112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1761c9178087STejun Heo 			pwq = worker->current_pwq;
1762fe089f87STejun Heo 			pool = pwq->pool;
1763fe089f87STejun Heo 			WARN_ON_ONCE(pool != last_pool);
17648594fadeSLai Jiangshan 		} else {
176518aa9effSTejun Heo 			/* meh... not running there, queue here */
1766a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&last_pool->lock);
1767fe089f87STejun Heo 			raw_spin_lock(&pool->lock);
176818aa9effSTejun Heo 		}
17698930cabaSTejun Heo 	} else {
1770fe089f87STejun Heo 		raw_spin_lock(&pool->lock);
17718930cabaSTejun Heo 	}
1772502ca9d8STejun Heo 
17739e8cd2f5STejun Heo 	/*
1774636b927eSTejun Heo 	 * pwq is determined and locked. For unbound pools, we could have raced
1775636b927eSTejun Heo 	 * with pwq release and it could already be dead. If its refcnt is zero,
1776636b927eSTejun Heo 	 * repeat pwq selection. Note that unbound pwqs never die without
1777636b927eSTejun Heo 	 * another pwq replacing it in cpu_pwq or while work items are executing
1778636b927eSTejun Heo 	 * on it, so the retrying is guaranteed to make forward-progress.
17799e8cd2f5STejun Heo 	 */
17809e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
17819e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
1782fe089f87STejun Heo 			raw_spin_unlock(&pool->lock);
17839e8cd2f5STejun Heo 			cpu_relax();
17849e8cd2f5STejun Heo 			goto retry;
17859e8cd2f5STejun Heo 		}
17869e8cd2f5STejun Heo 		/* oops */
17879e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
17889e8cd2f5STejun Heo 			  wq->name, cpu);
17899e8cd2f5STejun Heo 	}
17909e8cd2f5STejun Heo 
1791112202d9STejun Heo 	/* pwq determined, queue */
1792112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1793502ca9d8STejun Heo 
179424acfb71SThomas Gleixner 	if (WARN_ON(!list_empty(&work->entry)))
179524acfb71SThomas Gleixner 		goto out;
17961e19ffc6STejun Heo 
1797112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1798112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
17991e19ffc6STejun Heo 
1800112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1801fe089f87STejun Heo 		if (list_empty(&pool->worklist))
1802fe089f87STejun Heo 			pool->watchdog_ts = jiffies;
1803fe089f87STejun Heo 
1804cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1805112202d9STejun Heo 		pwq->nr_active++;
1806fe089f87STejun Heo 		insert_work(pwq, work, &pool->worklist, work_flags);
18070219a352STejun Heo 		kick_pool(pool);
18088a2e8e5dSTejun Heo 	} else {
1809f97a4a1aSLai Jiangshan 		work_flags |= WORK_STRUCT_INACTIVE;
1810fe089f87STejun Heo 		insert_work(pwq, work, &pwq->inactive_works, work_flags);
18118a2e8e5dSTejun Heo 	}
18121e19ffc6STejun Heo 
181324acfb71SThomas Gleixner out:
1814fe089f87STejun Heo 	raw_spin_unlock(&pool->lock);
181524acfb71SThomas Gleixner 	rcu_read_unlock();
18161da177e4SLinus Torvalds }
18171da177e4SLinus Torvalds 
18180fcb78c2SRolf Eike Beer /**
1819c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1820c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1821c1a220e7SZhang Rui  * @wq: workqueue to use
1822c1a220e7SZhang Rui  * @work: work to queue
1823c1a220e7SZhang Rui  *
1824c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1825443378f0SPaul E. McKenney  * can't go away.  Callers that fail to ensure that the specified
1826443378f0SPaul E. McKenney  * CPU cannot go away will execute on a randomly chosen CPU.
1827854f5cc5SPaul E. McKenney  * But note well that callers specifying a CPU that never has been
1828854f5cc5SPaul E. McKenney  * online will get a splat.
1829d185af30SYacine Belkadi  *
1830d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
1831c1a220e7SZhang Rui  */
1832d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1833d4283e93STejun Heo 		   struct work_struct *work)
1834c1a220e7SZhang Rui {
1835d4283e93STejun Heo 	bool ret = false;
18368930cabaSTejun Heo 	unsigned long flags;
18378930cabaSTejun Heo 
18388930cabaSTejun Heo 	local_irq_save(flags);
1839c1a220e7SZhang Rui 
184022df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
18414690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1842d4283e93STejun Heo 		ret = true;
1843c1a220e7SZhang Rui 	}
18448930cabaSTejun Heo 
18458930cabaSTejun Heo 	local_irq_restore(flags);
1846c1a220e7SZhang Rui 	return ret;
1847c1a220e7SZhang Rui }
1848ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1849c1a220e7SZhang Rui 
18508204e0c1SAlexander Duyck /**
1851fef59c9cSTejun Heo  * select_numa_node_cpu - Select a CPU based on NUMA node
18528204e0c1SAlexander Duyck  * @node: NUMA node ID that we want to select a CPU from
18538204e0c1SAlexander Duyck  *
18548204e0c1SAlexander Duyck  * This function will attempt to find a "random" cpu available on a given
18558204e0c1SAlexander Duyck  * node. If there are no CPUs available on the given node it will return
18568204e0c1SAlexander Duyck  * WORK_CPU_UNBOUND indicating that we should just schedule to any
18578204e0c1SAlexander Duyck  * available CPU if we need to schedule this work.
18588204e0c1SAlexander Duyck  */
1859fef59c9cSTejun Heo static int select_numa_node_cpu(int node)
18608204e0c1SAlexander Duyck {
18618204e0c1SAlexander Duyck 	int cpu;
18628204e0c1SAlexander Duyck 
18638204e0c1SAlexander Duyck 	/* Delay binding to CPU if node is not valid or online */
18648204e0c1SAlexander Duyck 	if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
18658204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
18668204e0c1SAlexander Duyck 
18678204e0c1SAlexander Duyck 	/* Use local node/cpu if we are already there */
18688204e0c1SAlexander Duyck 	cpu = raw_smp_processor_id();
18698204e0c1SAlexander Duyck 	if (node == cpu_to_node(cpu))
18708204e0c1SAlexander Duyck 		return cpu;
18718204e0c1SAlexander Duyck 
18728204e0c1SAlexander Duyck 	/* Use "random" otherwise know as "first" online CPU of node */
18738204e0c1SAlexander Duyck 	cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
18748204e0c1SAlexander Duyck 
18758204e0c1SAlexander Duyck 	/* If CPU is valid return that, otherwise just defer */
18768204e0c1SAlexander Duyck 	return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
18778204e0c1SAlexander Duyck }
18788204e0c1SAlexander Duyck 
18798204e0c1SAlexander Duyck /**
18808204e0c1SAlexander Duyck  * queue_work_node - queue work on a "random" cpu for a given NUMA node
18818204e0c1SAlexander Duyck  * @node: NUMA node that we are targeting the work for
18828204e0c1SAlexander Duyck  * @wq: workqueue to use
18838204e0c1SAlexander Duyck  * @work: work to queue
18848204e0c1SAlexander Duyck  *
18858204e0c1SAlexander Duyck  * We queue the work to a "random" CPU within a given NUMA node. The basic
18868204e0c1SAlexander Duyck  * idea here is to provide a way to somehow associate work with a given
18878204e0c1SAlexander Duyck  * NUMA node.
18888204e0c1SAlexander Duyck  *
18898204e0c1SAlexander Duyck  * This function will only make a best effort attempt at getting this onto
18908204e0c1SAlexander Duyck  * the right NUMA node. If no node is requested or the requested node is
18918204e0c1SAlexander Duyck  * offline then we just fall back to standard queue_work behavior.
18928204e0c1SAlexander Duyck  *
18938204e0c1SAlexander Duyck  * Currently the "random" CPU ends up being the first available CPU in the
18948204e0c1SAlexander Duyck  * intersection of cpu_online_mask and the cpumask of the node, unless we
18958204e0c1SAlexander Duyck  * are running on the node. In that case we just use the current CPU.
18968204e0c1SAlexander Duyck  *
18978204e0c1SAlexander Duyck  * Return: %false if @work was already on a queue, %true otherwise.
18988204e0c1SAlexander Duyck  */
18998204e0c1SAlexander Duyck bool queue_work_node(int node, struct workqueue_struct *wq,
19008204e0c1SAlexander Duyck 		     struct work_struct *work)
19018204e0c1SAlexander Duyck {
19028204e0c1SAlexander Duyck 	unsigned long flags;
19038204e0c1SAlexander Duyck 	bool ret = false;
19048204e0c1SAlexander Duyck 
19058204e0c1SAlexander Duyck 	/*
19068204e0c1SAlexander Duyck 	 * This current implementation is specific to unbound workqueues.
19078204e0c1SAlexander Duyck 	 * Specifically we only return the first available CPU for a given
19088204e0c1SAlexander Duyck 	 * node instead of cycling through individual CPUs within the node.
19098204e0c1SAlexander Duyck 	 *
19108204e0c1SAlexander Duyck 	 * If this is used with a per-cpu workqueue then the logic in
19118204e0c1SAlexander Duyck 	 * workqueue_select_cpu_near would need to be updated to allow for
19128204e0c1SAlexander Duyck 	 * some round robin type logic.
19138204e0c1SAlexander Duyck 	 */
19148204e0c1SAlexander Duyck 	WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
19158204e0c1SAlexander Duyck 
19168204e0c1SAlexander Duyck 	local_irq_save(flags);
19178204e0c1SAlexander Duyck 
19188204e0c1SAlexander Duyck 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1919fef59c9cSTejun Heo 		int cpu = select_numa_node_cpu(node);
19208204e0c1SAlexander Duyck 
19218204e0c1SAlexander Duyck 		__queue_work(cpu, wq, work);
19228204e0c1SAlexander Duyck 		ret = true;
19238204e0c1SAlexander Duyck 	}
19248204e0c1SAlexander Duyck 
19258204e0c1SAlexander Duyck 	local_irq_restore(flags);
19268204e0c1SAlexander Duyck 	return ret;
19278204e0c1SAlexander Duyck }
19288204e0c1SAlexander Duyck EXPORT_SYMBOL_GPL(queue_work_node);
19298204e0c1SAlexander Duyck 
19308c20feb6SKees Cook void delayed_work_timer_fn(struct timer_list *t)
19311da177e4SLinus Torvalds {
19328c20feb6SKees Cook 	struct delayed_work *dwork = from_timer(dwork, t, timer);
19331da177e4SLinus Torvalds 
1934e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
193560c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
19361da177e4SLinus Torvalds }
19371438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
19381da177e4SLinus Torvalds 
19397beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
194052bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
19411da177e4SLinus Torvalds {
19427beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
19437beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
19441da177e4SLinus Torvalds 
1945637fdbaeSTejun Heo 	WARN_ON_ONCE(!wq);
19464b243563SSami Tolvanen 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
1947fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1948fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
19497beb2edfSTejun Heo 
19508852aac2STejun Heo 	/*
19518852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
19528852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
19538852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
19548852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
19558852aac2STejun Heo 	 */
19568852aac2STejun Heo 	if (!delay) {
19578852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
19588852aac2STejun Heo 		return;
19598852aac2STejun Heo 	}
19608852aac2STejun Heo 
196160c057bcSLai Jiangshan 	dwork->wq = wq;
19621265057fSTejun Heo 	dwork->cpu = cpu;
19637beb2edfSTejun Heo 	timer->expires = jiffies + delay;
19647beb2edfSTejun Heo 
1965041bd12eSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
19667beb2edfSTejun Heo 		add_timer_on(timer, cpu);
1967041bd12eSTejun Heo 	else
1968041bd12eSTejun Heo 		add_timer(timer);
19697beb2edfSTejun Heo }
19701da177e4SLinus Torvalds 
19710fcb78c2SRolf Eike Beer /**
19720fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
19730fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
19740fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1975af9997e4SRandy Dunlap  * @dwork: work to queue
19760fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
19770fcb78c2SRolf Eike Beer  *
1978d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
1979715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1980715f1300STejun Heo  * execution.
19810fcb78c2SRolf Eike Beer  */
1982d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
198352bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
19847a6bc1cdSVenkatesh Pallipadi {
198552bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1986d4283e93STejun Heo 	bool ret = false;
19878930cabaSTejun Heo 	unsigned long flags;
19888930cabaSTejun Heo 
19898930cabaSTejun Heo 	/* read the comment in __queue_work() */
19908930cabaSTejun Heo 	local_irq_save(flags);
19917a6bc1cdSVenkatesh Pallipadi 
199222df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
19937beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1994d4283e93STejun Heo 		ret = true;
19957a6bc1cdSVenkatesh Pallipadi 	}
19968930cabaSTejun Heo 
19978930cabaSTejun Heo 	local_irq_restore(flags);
19987a6bc1cdSVenkatesh Pallipadi 	return ret;
19997a6bc1cdSVenkatesh Pallipadi }
2000ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
20011da177e4SLinus Torvalds 
2002c8e55f36STejun Heo /**
20038376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
20048376fe22STejun Heo  * @cpu: CPU number to execute work on
20058376fe22STejun Heo  * @wq: workqueue to use
20068376fe22STejun Heo  * @dwork: work to queue
20078376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
20088376fe22STejun Heo  *
20098376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
20108376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
20118376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
20128376fe22STejun Heo  * current state.
20138376fe22STejun Heo  *
2014d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
20158376fe22STejun Heo  * pending and its timer was modified.
20168376fe22STejun Heo  *
2017e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
20188376fe22STejun Heo  * See try_to_grab_pending() for details.
20198376fe22STejun Heo  */
20208376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
20218376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
20228376fe22STejun Heo {
20238376fe22STejun Heo 	unsigned long flags;
20248376fe22STejun Heo 	int ret;
20258376fe22STejun Heo 
20268376fe22STejun Heo 	do {
20278376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
20288376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
20298376fe22STejun Heo 
20308376fe22STejun Heo 	if (likely(ret >= 0)) {
20318376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
20328376fe22STejun Heo 		local_irq_restore(flags);
20338376fe22STejun Heo 	}
20348376fe22STejun Heo 
20358376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
20368376fe22STejun Heo 	return ret;
20378376fe22STejun Heo }
20388376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
20398376fe22STejun Heo 
204005f0fe6bSTejun Heo static void rcu_work_rcufn(struct rcu_head *rcu)
204105f0fe6bSTejun Heo {
204205f0fe6bSTejun Heo 	struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
204305f0fe6bSTejun Heo 
204405f0fe6bSTejun Heo 	/* read the comment in __queue_work() */
204505f0fe6bSTejun Heo 	local_irq_disable();
204605f0fe6bSTejun Heo 	__queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
204705f0fe6bSTejun Heo 	local_irq_enable();
204805f0fe6bSTejun Heo }
204905f0fe6bSTejun Heo 
205005f0fe6bSTejun Heo /**
205105f0fe6bSTejun Heo  * queue_rcu_work - queue work after a RCU grace period
205205f0fe6bSTejun Heo  * @wq: workqueue to use
205305f0fe6bSTejun Heo  * @rwork: work to queue
205405f0fe6bSTejun Heo  *
205505f0fe6bSTejun Heo  * Return: %false if @rwork was already pending, %true otherwise.  Note
205605f0fe6bSTejun Heo  * that a full RCU grace period is guaranteed only after a %true return.
2057bf393fd4SBart Van Assche  * While @rwork is guaranteed to be executed after a %false return, the
205805f0fe6bSTejun Heo  * execution may happen before a full RCU grace period has passed.
205905f0fe6bSTejun Heo  */
206005f0fe6bSTejun Heo bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
206105f0fe6bSTejun Heo {
206205f0fe6bSTejun Heo 	struct work_struct *work = &rwork->work;
206305f0fe6bSTejun Heo 
206405f0fe6bSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
206505f0fe6bSTejun Heo 		rwork->wq = wq;
2066a7e30c0eSUladzislau Rezki 		call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
206705f0fe6bSTejun Heo 		return true;
206805f0fe6bSTejun Heo 	}
206905f0fe6bSTejun Heo 
207005f0fe6bSTejun Heo 	return false;
207105f0fe6bSTejun Heo }
207205f0fe6bSTejun Heo EXPORT_SYMBOL(queue_rcu_work);
207305f0fe6bSTejun Heo 
2074f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
2075c34056a3STejun Heo {
2076c34056a3STejun Heo 	struct worker *worker;
2077c34056a3STejun Heo 
2078f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
2079c8e55f36STejun Heo 	if (worker) {
2080c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
2081affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
2082da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
2083e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
2084e22bee78STejun Heo 		worker->flags = WORKER_PREP;
2085c8e55f36STejun Heo 	}
2086c34056a3STejun Heo 	return worker;
2087c34056a3STejun Heo }
2088c34056a3STejun Heo 
20899546b29eSTejun Heo static cpumask_t *pool_allowed_cpus(struct worker_pool *pool)
20909546b29eSTejun Heo {
20918639ecebSTejun Heo 	if (pool->cpu < 0 && pool->attrs->affn_strict)
20929546b29eSTejun Heo 		return pool->attrs->__pod_cpumask;
20938639ecebSTejun Heo 	else
20948639ecebSTejun Heo 		return pool->attrs->cpumask;
20959546b29eSTejun Heo }
20969546b29eSTejun Heo 
2097c34056a3STejun Heo /**
20984736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
20994736cbf7SLai Jiangshan  * @worker: worker to be attached
21004736cbf7SLai Jiangshan  * @pool: the target pool
21014736cbf7SLai Jiangshan  *
21024736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
21034736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
21044736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
21054736cbf7SLai Jiangshan  */
21064736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
21074736cbf7SLai Jiangshan 				   struct worker_pool *pool)
21084736cbf7SLai Jiangshan {
21091258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
21104736cbf7SLai Jiangshan 
21114736cbf7SLai Jiangshan 	/*
21121258fae7STejun Heo 	 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
21131258fae7STejun Heo 	 * stable across this function.  See the comments above the flag
21141258fae7STejun Heo 	 * definition for details.
21154736cbf7SLai Jiangshan 	 */
21164736cbf7SLai Jiangshan 	if (pool->flags & POOL_DISASSOCIATED)
21174736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
21185c25b5ffSPeter Zijlstra 	else
21195c25b5ffSPeter Zijlstra 		kthread_set_per_cpu(worker->task, pool->cpu);
21204736cbf7SLai Jiangshan 
2121640f17c8SPeter Zijlstra 	if (worker->rescue_wq)
21229546b29eSTejun Heo 		set_cpus_allowed_ptr(worker->task, pool_allowed_cpus(pool));
2123640f17c8SPeter Zijlstra 
21244736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
2125a2d812a2STejun Heo 	worker->pool = pool;
21264736cbf7SLai Jiangshan 
21271258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
21284736cbf7SLai Jiangshan }
21294736cbf7SLai Jiangshan 
21304736cbf7SLai Jiangshan /**
213160f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
213260f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
213360f5a4bcSLai Jiangshan  *
21344736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
21354736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
21364736cbf7SLai Jiangshan  * other reference to the pool.
213760f5a4bcSLai Jiangshan  */
2138a2d812a2STejun Heo static void worker_detach_from_pool(struct worker *worker)
213960f5a4bcSLai Jiangshan {
2140a2d812a2STejun Heo 	struct worker_pool *pool = worker->pool;
214160f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
214260f5a4bcSLai Jiangshan 
21431258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2144a2d812a2STejun Heo 
21455c25b5ffSPeter Zijlstra 	kthread_set_per_cpu(worker->task, -1);
2146da028469SLai Jiangshan 	list_del(&worker->node);
2147a2d812a2STejun Heo 	worker->pool = NULL;
2148a2d812a2STejun Heo 
2149e02b9312SValentin Schneider 	if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
215060f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
21511258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
215260f5a4bcSLai Jiangshan 
2153b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
2154b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2155b62c0751SLai Jiangshan 
215660f5a4bcSLai Jiangshan 	if (detach_completion)
215760f5a4bcSLai Jiangshan 		complete(detach_completion);
215860f5a4bcSLai Jiangshan }
215960f5a4bcSLai Jiangshan 
216060f5a4bcSLai Jiangshan /**
2161c34056a3STejun Heo  * create_worker - create a new workqueue worker
216263d95a91STejun Heo  * @pool: pool the new worker will belong to
2163c34056a3STejun Heo  *
2164051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
2165c34056a3STejun Heo  *
2166c34056a3STejun Heo  * CONTEXT:
2167c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
2168c34056a3STejun Heo  *
2169d185af30SYacine Belkadi  * Return:
2170c34056a3STejun Heo  * Pointer to the newly created worker.
2171c34056a3STejun Heo  */
2172bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
2173c34056a3STejun Heo {
2174e441b56fSZhen Lei 	struct worker *worker;
2175e441b56fSZhen Lei 	int id;
21765d9c7a1eSLucy Mielke 	char id_buf[23];
2177c34056a3STejun Heo 
21787cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
2179e441b56fSZhen Lei 	id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
21803f0ea0b8SPetr Mladek 	if (id < 0) {
21813f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
21823f0ea0b8SPetr Mladek 			    ERR_PTR(id));
2183e441b56fSZhen Lei 		return NULL;
21843f0ea0b8SPetr Mladek 	}
2185c34056a3STejun Heo 
2186f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
21873f0ea0b8SPetr Mladek 	if (!worker) {
21883f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker\n");
2189c34056a3STejun Heo 		goto fail;
21903f0ea0b8SPetr Mladek 	}
2191c34056a3STejun Heo 
2192c34056a3STejun Heo 	worker->id = id;
2193c34056a3STejun Heo 
219429c91e99STejun Heo 	if (pool->cpu >= 0)
2195e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
2196e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
2197f3421797STejun Heo 	else
2198e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
2199e3c916a4STejun Heo 
2200f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
2201e3c916a4STejun Heo 					      "kworker/%s", id_buf);
22023f0ea0b8SPetr Mladek 	if (IS_ERR(worker->task)) {
220360f54038SPetr Mladek 		if (PTR_ERR(worker->task) == -EINTR) {
220460f54038SPetr Mladek 			pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n",
220560f54038SPetr Mladek 			       id_buf);
220660f54038SPetr Mladek 		} else {
22073f0ea0b8SPetr Mladek 			pr_err_once("workqueue: Failed to create a worker thread: %pe",
22083f0ea0b8SPetr Mladek 				    worker->task);
220960f54038SPetr Mladek 		}
2210c34056a3STejun Heo 		goto fail;
22113f0ea0b8SPetr Mladek 	}
2212c34056a3STejun Heo 
221391151228SOleg Nesterov 	set_user_nice(worker->task, pool->attrs->nice);
22149546b29eSTejun Heo 	kthread_bind_mask(worker->task, pool_allowed_cpus(pool));
221591151228SOleg Nesterov 
2216da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
22174736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
2218822d8405STejun Heo 
2219051e1850SLai Jiangshan 	/* start the newly created worker */
2220a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
22210219a352STejun Heo 
2222051e1850SLai Jiangshan 	worker->pool->nr_workers++;
2223051e1850SLai Jiangshan 	worker_enter_idle(worker);
22240219a352STejun Heo 
22250219a352STejun Heo 	/*
22260219a352STejun Heo 	 * @worker is waiting on a completion in kthread() and will trigger hung
22276a229b0eSTejun Heo 	 * check if not woken up soon. As kick_pool() is noop if @pool is empty,
22286a229b0eSTejun Heo 	 * wake it up explicitly.
22290219a352STejun Heo 	 */
2230051e1850SLai Jiangshan 	wake_up_process(worker->task);
22310219a352STejun Heo 
2232a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2233051e1850SLai Jiangshan 
2234c34056a3STejun Heo 	return worker;
2235822d8405STejun Heo 
2236c34056a3STejun Heo fail:
2237e441b56fSZhen Lei 	ida_free(&pool->worker_ida, id);
2238c34056a3STejun Heo 	kfree(worker);
2239c34056a3STejun Heo 	return NULL;
2240c34056a3STejun Heo }
2241c34056a3STejun Heo 
2242793777bcSValentin Schneider static void unbind_worker(struct worker *worker)
2243793777bcSValentin Schneider {
2244793777bcSValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2245793777bcSValentin Schneider 
2246793777bcSValentin Schneider 	kthread_set_per_cpu(worker->task, -1);
2247793777bcSValentin Schneider 	if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2248793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2249793777bcSValentin Schneider 	else
2250793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2251793777bcSValentin Schneider }
2252793777bcSValentin Schneider 
2253e02b9312SValentin Schneider static void wake_dying_workers(struct list_head *cull_list)
2254e02b9312SValentin Schneider {
2255e02b9312SValentin Schneider 	struct worker *worker, *tmp;
2256e02b9312SValentin Schneider 
2257e02b9312SValentin Schneider 	list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2258e02b9312SValentin Schneider 		list_del_init(&worker->entry);
2259e02b9312SValentin Schneider 		unbind_worker(worker);
2260e02b9312SValentin Schneider 		/*
2261e02b9312SValentin Schneider 		 * If the worker was somehow already running, then it had to be
2262e02b9312SValentin Schneider 		 * in pool->idle_list when set_worker_dying() happened or we
2263e02b9312SValentin Schneider 		 * wouldn't have gotten here.
2264c34056a3STejun Heo 		 *
2265e02b9312SValentin Schneider 		 * Thus, the worker must either have observed the WORKER_DIE
2266e02b9312SValentin Schneider 		 * flag, or have set its state to TASK_IDLE. Either way, the
2267e02b9312SValentin Schneider 		 * below will be observed by the worker and is safe to do
2268e02b9312SValentin Schneider 		 * outside of pool->lock.
2269e02b9312SValentin Schneider 		 */
2270e02b9312SValentin Schneider 		wake_up_process(worker->task);
2271e02b9312SValentin Schneider 	}
2272e02b9312SValentin Schneider }
2273e02b9312SValentin Schneider 
2274e02b9312SValentin Schneider /**
2275e02b9312SValentin Schneider  * set_worker_dying - Tag a worker for destruction
2276e02b9312SValentin Schneider  * @worker: worker to be destroyed
2277e02b9312SValentin Schneider  * @list: transfer worker away from its pool->idle_list and into list
2278e02b9312SValentin Schneider  *
2279e02b9312SValentin Schneider  * Tag @worker for destruction and adjust @pool stats accordingly.  The worker
2280e02b9312SValentin Schneider  * should be idle.
2281c8e55f36STejun Heo  *
2282c8e55f36STejun Heo  * CONTEXT:
2283a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
2284c34056a3STejun Heo  */
2285e02b9312SValentin Schneider static void set_worker_dying(struct worker *worker, struct list_head *list)
2286c34056a3STejun Heo {
2287bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2288c34056a3STejun Heo 
2289cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
2290e02b9312SValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2291cd549687STejun Heo 
2292c34056a3STejun Heo 	/* sanity check frenzy */
22936183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
229473eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
229573eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
22966183c009STejun Heo 		return;
2297c34056a3STejun Heo 
2298bd7bdd43STejun Heo 	pool->nr_workers--;
2299bd7bdd43STejun Heo 	pool->nr_idle--;
2300c8e55f36STejun Heo 
2301cb444766STejun Heo 	worker->flags |= WORKER_DIE;
2302e02b9312SValentin Schneider 
2303e02b9312SValentin Schneider 	list_move(&worker->entry, list);
2304e02b9312SValentin Schneider 	list_move(&worker->node, &pool->dying_workers);
2305c34056a3STejun Heo }
2306c34056a3STejun Heo 
23073f959aa3SValentin Schneider /**
23083f959aa3SValentin Schneider  * idle_worker_timeout - check if some idle workers can now be deleted.
23093f959aa3SValentin Schneider  * @t: The pool's idle_timer that just expired
23103f959aa3SValentin Schneider  *
23113f959aa3SValentin Schneider  * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
23123f959aa3SValentin Schneider  * worker_leave_idle(), as a worker flicking between idle and active while its
23133f959aa3SValentin Schneider  * pool is at the too_many_workers() tipping point would cause too much timer
23143f959aa3SValentin Schneider  * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
23153f959aa3SValentin Schneider  * it expire and re-evaluate things from there.
23163f959aa3SValentin Schneider  */
231732a6c723SKees Cook static void idle_worker_timeout(struct timer_list *t)
2318e22bee78STejun Heo {
231932a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, idle_timer);
23203f959aa3SValentin Schneider 	bool do_cull = false;
23213f959aa3SValentin Schneider 
23223f959aa3SValentin Schneider 	if (work_pending(&pool->idle_cull_work))
23233f959aa3SValentin Schneider 		return;
23243f959aa3SValentin Schneider 
23253f959aa3SValentin Schneider 	raw_spin_lock_irq(&pool->lock);
23263f959aa3SValentin Schneider 
23273f959aa3SValentin Schneider 	if (too_many_workers(pool)) {
23283f959aa3SValentin Schneider 		struct worker *worker;
23293f959aa3SValentin Schneider 		unsigned long expires;
23303f959aa3SValentin Schneider 
23313f959aa3SValentin Schneider 		/* idle_list is kept in LIFO order, check the last one */
23323f959aa3SValentin Schneider 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
23333f959aa3SValentin Schneider 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
23343f959aa3SValentin Schneider 		do_cull = !time_before(jiffies, expires);
23353f959aa3SValentin Schneider 
23363f959aa3SValentin Schneider 		if (!do_cull)
23373f959aa3SValentin Schneider 			mod_timer(&pool->idle_timer, expires);
23383f959aa3SValentin Schneider 	}
23393f959aa3SValentin Schneider 	raw_spin_unlock_irq(&pool->lock);
23403f959aa3SValentin Schneider 
23413f959aa3SValentin Schneider 	if (do_cull)
23423f959aa3SValentin Schneider 		queue_work(system_unbound_wq, &pool->idle_cull_work);
23433f959aa3SValentin Schneider }
23443f959aa3SValentin Schneider 
23453f959aa3SValentin Schneider /**
23463f959aa3SValentin Schneider  * idle_cull_fn - cull workers that have been idle for too long.
23473f959aa3SValentin Schneider  * @work: the pool's work for handling these idle workers
23483f959aa3SValentin Schneider  *
23493f959aa3SValentin Schneider  * This goes through a pool's idle workers and gets rid of those that have been
23503f959aa3SValentin Schneider  * idle for at least IDLE_WORKER_TIMEOUT seconds.
2351e02b9312SValentin Schneider  *
2352e02b9312SValentin Schneider  * We don't want to disturb isolated CPUs because of a pcpu kworker being
2353e02b9312SValentin Schneider  * culled, so this also resets worker affinity. This requires a sleepable
2354e02b9312SValentin Schneider  * context, hence the split between timer callback and work item.
23553f959aa3SValentin Schneider  */
23563f959aa3SValentin Schneider static void idle_cull_fn(struct work_struct *work)
23573f959aa3SValentin Schneider {
23583f959aa3SValentin Schneider 	struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
23599680540cSYang Yingliang 	LIST_HEAD(cull_list);
2360e22bee78STejun Heo 
2361e02b9312SValentin Schneider 	/*
2362e02b9312SValentin Schneider 	 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2363e02b9312SValentin Schneider 	 * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2364e02b9312SValentin Schneider 	 * path. This is required as a previously-preempted worker could run after
2365e02b9312SValentin Schneider 	 * set_worker_dying() has happened but before wake_dying_workers() did.
2366e02b9312SValentin Schneider 	 */
2367e02b9312SValentin Schneider 	mutex_lock(&wq_pool_attach_mutex);
2368a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2369e22bee78STejun Heo 
23703347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
2371e22bee78STejun Heo 		struct worker *worker;
2372e22bee78STejun Heo 		unsigned long expires;
2373e22bee78STejun Heo 
237463d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
2375e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2376e22bee78STejun Heo 
23773347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
237863d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
23793347fc9fSLai Jiangshan 			break;
2380e22bee78STejun Heo 		}
23813347fc9fSLai Jiangshan 
2382e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
2383e22bee78STejun Heo 	}
2384e22bee78STejun Heo 
2385a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2386e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
2387e02b9312SValentin Schneider 	mutex_unlock(&wq_pool_attach_mutex);
2388e22bee78STejun Heo }
2389e22bee78STejun Heo 
2390493a1724STejun Heo static void send_mayday(struct work_struct *work)
2391e22bee78STejun Heo {
2392112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2393112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
2394493a1724STejun Heo 
23952e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
2396e22bee78STejun Heo 
2397493008a8STejun Heo 	if (!wq->rescuer)
2398493a1724STejun Heo 		return;
2399e22bee78STejun Heo 
2400e22bee78STejun Heo 	/* mayday mayday mayday */
2401493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
240277668c8bSLai Jiangshan 		/*
240377668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
240477668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
240577668c8bSLai Jiangshan 		 * rescuer is done with it.
240677668c8bSLai Jiangshan 		 */
240777668c8bSLai Jiangshan 		get_pwq(pwq);
2408493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
2409e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
2410725e8ec5STejun Heo 		pwq->stats[PWQ_STAT_MAYDAY]++;
2411493a1724STejun Heo 	}
2412e22bee78STejun Heo }
2413e22bee78STejun Heo 
241432a6c723SKees Cook static void pool_mayday_timeout(struct timer_list *t)
2415e22bee78STejun Heo {
241632a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2417e22bee78STejun Heo 	struct work_struct *work;
2418e22bee78STejun Heo 
2419a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2420a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&wq_mayday_lock);		/* for wq->maydays */
2421e22bee78STejun Heo 
242263d95a91STejun Heo 	if (need_to_create_worker(pool)) {
2423e22bee78STejun Heo 		/*
2424e22bee78STejun Heo 		 * We've been trying to create a new worker but
2425e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
2426e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
2427e22bee78STejun Heo 		 * rescuers.
2428e22bee78STejun Heo 		 */
242963d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
2430e22bee78STejun Heo 			send_mayday(work);
2431e22bee78STejun Heo 	}
2432e22bee78STejun Heo 
2433a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&wq_mayday_lock);
2434a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2435e22bee78STejun Heo 
243663d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2437e22bee78STejun Heo }
2438e22bee78STejun Heo 
2439e22bee78STejun Heo /**
2440e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
244163d95a91STejun Heo  * @pool: pool to create a new worker for
2442e22bee78STejun Heo  *
244363d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
2444e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
2445e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
244663d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
2447e22bee78STejun Heo  * possible allocation deadlock.
2448e22bee78STejun Heo  *
2449c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
2450c5aa87bbSTejun Heo  * may_start_working() %true.
2451e22bee78STejun Heo  *
2452e22bee78STejun Heo  * LOCKING:
2453a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2454e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
2455e22bee78STejun Heo  * manager.
2456e22bee78STejun Heo  */
245729187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
2458d565ed63STejun Heo __releases(&pool->lock)
2459d565ed63STejun Heo __acquires(&pool->lock)
2460e22bee78STejun Heo {
2461e22bee78STejun Heo restart:
2462a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
24639f9c2364STejun Heo 
2464e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
246563d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2466e22bee78STejun Heo 
2467e22bee78STejun Heo 	while (true) {
2468051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
2469e22bee78STejun Heo 			break;
2470e22bee78STejun Heo 
2471e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
24729f9c2364STejun Heo 
247363d95a91STejun Heo 		if (!need_to_create_worker(pool))
2474e22bee78STejun Heo 			break;
2475e22bee78STejun Heo 	}
2476e22bee78STejun Heo 
247763d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
2478a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2479051e1850SLai Jiangshan 	/*
2480051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
2481051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
2482051e1850SLai Jiangshan 	 * already become busy.
2483051e1850SLai Jiangshan 	 */
248463d95a91STejun Heo 	if (need_to_create_worker(pool))
2485e22bee78STejun Heo 		goto restart;
2486e22bee78STejun Heo }
2487e22bee78STejun Heo 
2488e22bee78STejun Heo /**
2489e22bee78STejun Heo  * manage_workers - manage worker pool
2490e22bee78STejun Heo  * @worker: self
2491e22bee78STejun Heo  *
2492706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
2493e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2494706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2495e22bee78STejun Heo  *
2496e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2497e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2498e22bee78STejun Heo  * and may_start_working() is true.
2499e22bee78STejun Heo  *
2500e22bee78STejun Heo  * CONTEXT:
2501a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2502e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2503e22bee78STejun Heo  *
2504d185af30SYacine Belkadi  * Return:
250529187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
250629187a9eSTejun Heo  * start processing works, %true if management function was performed and
250729187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
250829187a9eSTejun Heo  * no longer be true.
2509e22bee78STejun Heo  */
2510e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2511e22bee78STejun Heo {
251263d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2513e22bee78STejun Heo 
2514692b4825STejun Heo 	if (pool->flags & POOL_MANAGER_ACTIVE)
251529187a9eSTejun Heo 		return false;
2516692b4825STejun Heo 
2517692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
25182607d7a6STejun Heo 	pool->manager = worker;
2519e22bee78STejun Heo 
252029187a9eSTejun Heo 	maybe_create_worker(pool);
2521e22bee78STejun Heo 
25222607d7a6STejun Heo 	pool->manager = NULL;
2523692b4825STejun Heo 	pool->flags &= ~POOL_MANAGER_ACTIVE;
2524d8bb65abSSebastian Andrzej Siewior 	rcuwait_wake_up(&manager_wait);
252529187a9eSTejun Heo 	return true;
2526e22bee78STejun Heo }
2527e22bee78STejun Heo 
2528a62428c0STejun Heo /**
2529a62428c0STejun Heo  * process_one_work - process single work
2530c34056a3STejun Heo  * @worker: self
2531a62428c0STejun Heo  * @work: work to process
2532a62428c0STejun Heo  *
2533a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2534a62428c0STejun Heo  * process a single work including synchronization against and
2535a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2536a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2537a62428c0STejun Heo  * call this function to process a work.
2538a62428c0STejun Heo  *
2539a62428c0STejun Heo  * CONTEXT:
2540a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
2541a62428c0STejun Heo  */
2542c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2543d565ed63STejun Heo __releases(&pool->lock)
2544d565ed63STejun Heo __acquires(&pool->lock)
25451da177e4SLinus Torvalds {
2546112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2547bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2548c4560c2cSLai Jiangshan 	unsigned long work_data;
25494e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
25504e6045f1SJohannes Berg 	/*
2551a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2552a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2553a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2554a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2555a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
25564e6045f1SJohannes Berg 	 */
25574d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
25584d82a1deSPeter Zijlstra 
25594d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
25604e6045f1SJohannes Berg #endif
2561807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
256285327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2563ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
256425511a47STejun Heo 
25658930cabaSTejun Heo 	/* claim and dequeue */
2566dc186ad7SThomas Gleixner 	debug_work_deactivate(work);
2567c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2568c34056a3STejun Heo 	worker->current_work = work;
2569a2c1c57bSTejun Heo 	worker->current_func = work->func;
2570112202d9STejun Heo 	worker->current_pwq = pwq;
2571616db877STejun Heo 	worker->current_at = worker->task->se.sum_exec_runtime;
2572c4560c2cSLai Jiangshan 	work_data = *work_data_bits(work);
2573d812796eSLai Jiangshan 	worker->current_color = get_work_color(work_data);
25747a22ad75STejun Heo 
25758bf89593STejun Heo 	/*
25768bf89593STejun Heo 	 * Record wq name for cmdline and debug reporting, may get
25778bf89593STejun Heo 	 * overridden through set_worker_desc().
25788bf89593STejun Heo 	 */
25798bf89593STejun Heo 	strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
25808bf89593STejun Heo 
2581a62428c0STejun Heo 	list_del_init(&work->entry);
2582a62428c0STejun Heo 
2583649027d7STejun Heo 	/*
2584228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
2585228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
2586228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
2587228f1d00SLai Jiangshan 	 * execution of the pending work items.
2588fb0e7bebSTejun Heo 	 */
2589616db877STejun Heo 	if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
2590228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2591fb0e7bebSTejun Heo 
2592974271c4STejun Heo 	/*
25930219a352STejun Heo 	 * Kick @pool if necessary. It's always noop for per-cpu worker pools
25940219a352STejun Heo 	 * since nr_running would always be >= 1 at this point. This is used to
25950219a352STejun Heo 	 * chain execution of the pending work items for WORKER_NOT_RUNNING
25960219a352STejun Heo 	 * workers such as the UNBOUND and CPU_INTENSIVE ones.
2597974271c4STejun Heo 	 */
25980219a352STejun Heo 	kick_pool(pool);
2599974271c4STejun Heo 
26008930cabaSTejun Heo 	/*
26017c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2602d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
260323657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
260423657bb1STejun Heo 	 * disabled.
26058930cabaSTejun Heo 	 */
26067c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
26071da177e4SLinus Torvalds 
2608fe48ba7dSMirsad Goran Todorovac 	pwq->stats[PWQ_STAT_STARTED]++;
2609a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2610365970a1SDavid Howells 
2611a1d14934SPeter Zijlstra 	lock_map_acquire(&pwq->wq->lockdep_map);
26123295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2613e6f3faa7SPeter Zijlstra 	/*
2614f52be570SPeter Zijlstra 	 * Strictly speaking we should mark the invariant state without holding
2615f52be570SPeter Zijlstra 	 * any locks, that is, before these two lock_map_acquire()'s.
2616e6f3faa7SPeter Zijlstra 	 *
2617e6f3faa7SPeter Zijlstra 	 * However, that would result in:
2618e6f3faa7SPeter Zijlstra 	 *
2619e6f3faa7SPeter Zijlstra 	 *   A(W1)
2620e6f3faa7SPeter Zijlstra 	 *   WFC(C)
2621e6f3faa7SPeter Zijlstra 	 *		A(W1)
2622e6f3faa7SPeter Zijlstra 	 *		C(C)
2623e6f3faa7SPeter Zijlstra 	 *
2624e6f3faa7SPeter Zijlstra 	 * Which would create W1->C->W1 dependencies, even though there is no
2625e6f3faa7SPeter Zijlstra 	 * actual deadlock possible. There are two solutions, using a
2626e6f3faa7SPeter Zijlstra 	 * read-recursive acquire on the work(queue) 'locks', but this will then
2627f52be570SPeter Zijlstra 	 * hit the lockdep limitation on recursive locks, or simply discard
2628e6f3faa7SPeter Zijlstra 	 * these locks.
2629e6f3faa7SPeter Zijlstra 	 *
2630e6f3faa7SPeter Zijlstra 	 * AFAICT there is no possible deadlock scenario between the
2631e6f3faa7SPeter Zijlstra 	 * flush_work() and complete() primitives (except for single-threaded
2632e6f3faa7SPeter Zijlstra 	 * workqueues), so hiding them isn't a problem.
2633e6f3faa7SPeter Zijlstra 	 */
2634f52be570SPeter Zijlstra 	lockdep_invariant_state(true);
2635e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2636a2c1c57bSTejun Heo 	worker->current_func(work);
2637e36c886aSArjan van de Ven 	/*
2638e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2639e36c886aSArjan van de Ven 	 * point will only record its address.
2640e36c886aSArjan van de Ven 	 */
26411c5da0ecSDaniel Jordan 	trace_workqueue_execute_end(work, worker->current_func);
2642725e8ec5STejun Heo 	pwq->stats[PWQ_STAT_COMPLETED]++;
26433295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2644112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
26451da177e4SLinus Torvalds 
26461a65a6d1SXuewen Yan 	if (unlikely(in_atomic() || lockdep_depth(current) > 0 ||
26471a65a6d1SXuewen Yan 		     rcu_preempt_depth() > 0)) {
26481a65a6d1SXuewen Yan 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d/%d\n"
2649d75f773cSSakari Ailus 		       "     last function: %ps\n",
26501a65a6d1SXuewen Yan 		       current->comm, preempt_count(), rcu_preempt_depth(),
26511a65a6d1SXuewen Yan 		       task_pid_nr(current), worker->current_func);
2652d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2653d5abe669SPeter Zijlstra 		dump_stack();
2654d5abe669SPeter Zijlstra 	}
2655d5abe669SPeter Zijlstra 
2656b22ce278STejun Heo 	/*
2657025f50f3SSebastian Andrzej Siewior 	 * The following prevents a kworker from hogging CPU on !PREEMPTION
2658b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
2659b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
2660b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
2661789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
2662789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
2663b22ce278STejun Heo 	 */
2664a7e6425eSPaul E. McKenney 	cond_resched();
2665b22ce278STejun Heo 
2666a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2667a62428c0STejun Heo 
2668616db877STejun Heo 	/*
2669616db877STejun Heo 	 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
2670616db877STejun Heo 	 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
2671616db877STejun Heo 	 * wq_cpu_intensive_thresh_us. Clear it.
2672616db877STejun Heo 	 */
2673fb0e7bebSTejun Heo 	worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2674fb0e7bebSTejun Heo 
26751b69ac6bSJohannes Weiner 	/* tag the worker for identification in schedule() */
26761b69ac6bSJohannes Weiner 	worker->last_func = worker->current_func;
26771b69ac6bSJohannes Weiner 
2678a62428c0STejun Heo 	/* we're done with it, release */
267942f8570fSSasha Levin 	hash_del(&worker->hentry);
2680c34056a3STejun Heo 	worker->current_work = NULL;
2681a2c1c57bSTejun Heo 	worker->current_func = NULL;
2682112202d9STejun Heo 	worker->current_pwq = NULL;
2683d812796eSLai Jiangshan 	worker->current_color = INT_MAX;
2684c4560c2cSLai Jiangshan 	pwq_dec_nr_in_flight(pwq, work_data);
26851da177e4SLinus Torvalds }
26861da177e4SLinus Torvalds 
2687affee4b2STejun Heo /**
2688affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2689affee4b2STejun Heo  * @worker: self
2690affee4b2STejun Heo  *
2691affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2692affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2693affee4b2STejun Heo  * fetches a work from the top and executes it.
2694affee4b2STejun Heo  *
2695affee4b2STejun Heo  * CONTEXT:
2696a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2697affee4b2STejun Heo  * multiple times.
2698affee4b2STejun Heo  */
2699affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
27001da177e4SLinus Torvalds {
2701c0ab017dSTejun Heo 	struct work_struct *work;
2702c0ab017dSTejun Heo 	bool first = true;
2703c0ab017dSTejun Heo 
2704c0ab017dSTejun Heo 	while ((work = list_first_entry_or_null(&worker->scheduled,
2705c0ab017dSTejun Heo 						struct work_struct, entry))) {
2706c0ab017dSTejun Heo 		if (first) {
2707c0ab017dSTejun Heo 			worker->pool->watchdog_ts = jiffies;
2708c0ab017dSTejun Heo 			first = false;
2709c0ab017dSTejun Heo 		}
2710c34056a3STejun Heo 		process_one_work(worker, work);
2711a62428c0STejun Heo 	}
27121da177e4SLinus Torvalds }
27131da177e4SLinus Torvalds 
2714197f6accSTejun Heo static void set_pf_worker(bool val)
2715197f6accSTejun Heo {
2716197f6accSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2717197f6accSTejun Heo 	if (val)
2718197f6accSTejun Heo 		current->flags |= PF_WQ_WORKER;
2719197f6accSTejun Heo 	else
2720197f6accSTejun Heo 		current->flags &= ~PF_WQ_WORKER;
2721197f6accSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
2722197f6accSTejun Heo }
2723197f6accSTejun Heo 
27244690c4abSTejun Heo /**
27254690c4abSTejun Heo  * worker_thread - the worker thread function
2726c34056a3STejun Heo  * @__worker: self
27274690c4abSTejun Heo  *
2728c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2729c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2730c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2731c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2732c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
2733d185af30SYacine Belkadi  *
2734d185af30SYacine Belkadi  * Return: 0
27354690c4abSTejun Heo  */
2736c34056a3STejun Heo static int worker_thread(void *__worker)
27371da177e4SLinus Torvalds {
2738c34056a3STejun Heo 	struct worker *worker = __worker;
2739bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
27401da177e4SLinus Torvalds 
2741e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2742197f6accSTejun Heo 	set_pf_worker(true);
2743c8e55f36STejun Heo woke_up:
2744a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2745affee4b2STejun Heo 
2746a9ab775bSTejun Heo 	/* am I supposed to die? */
2747a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2748a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
2749197f6accSTejun Heo 		set_pf_worker(false);
275060f5a4bcSLai Jiangshan 
275160f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
2752e441b56fSZhen Lei 		ida_free(&pool->worker_ida, worker->id);
2753a2d812a2STejun Heo 		worker_detach_from_pool(worker);
2754e02b9312SValentin Schneider 		WARN_ON_ONCE(!list_empty(&worker->entry));
275560f5a4bcSLai Jiangshan 		kfree(worker);
2756c8e55f36STejun Heo 		return 0;
2757c8e55f36STejun Heo 	}
2758c8e55f36STejun Heo 
2759c8e55f36STejun Heo 	worker_leave_idle(worker);
2760db7bccf4STejun Heo recheck:
2761e22bee78STejun Heo 	/* no more worker necessary? */
276263d95a91STejun Heo 	if (!need_more_worker(pool))
2763e22bee78STejun Heo 		goto sleep;
2764e22bee78STejun Heo 
2765e22bee78STejun Heo 	/* do we need to manage? */
276663d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2767e22bee78STejun Heo 		goto recheck;
2768e22bee78STejun Heo 
2769c8e55f36STejun Heo 	/*
2770c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2771c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2772c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2773c8e55f36STejun Heo 	 */
27746183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2775c8e55f36STejun Heo 
2776e22bee78STejun Heo 	/*
2777a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2778a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2779a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2780a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2781a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2782e22bee78STejun Heo 	 */
2783a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2784e22bee78STejun Heo 
2785e22bee78STejun Heo 	do {
2786affee4b2STejun Heo 		struct work_struct *work =
2787bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2788affee4b2STejun Heo 					 struct work_struct, entry);
2789affee4b2STejun Heo 
2790873eaca6STejun Heo 		if (assign_work(work, worker, NULL))
2791affee4b2STejun Heo 			process_scheduled_works(worker);
279263d95a91STejun Heo 	} while (keep_working(pool));
2793affee4b2STejun Heo 
2794228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
2795d313dd85STejun Heo sleep:
2796c8e55f36STejun Heo 	/*
2797d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2798d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2799d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2800d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2801d565ed63STejun Heo 	 * event.
2802c8e55f36STejun Heo 	 */
2803c8e55f36STejun Heo 	worker_enter_idle(worker);
2804c5a94a61SPeter Zijlstra 	__set_current_state(TASK_IDLE);
2805a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
28061da177e4SLinus Torvalds 	schedule();
2807c8e55f36STejun Heo 	goto woke_up;
28081da177e4SLinus Torvalds }
28091da177e4SLinus Torvalds 
2810e22bee78STejun Heo /**
2811e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2812111c225aSTejun Heo  * @__rescuer: self
2813e22bee78STejun Heo  *
2814e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2815493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2816e22bee78STejun Heo  *
2817706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2818e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2819e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2820e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2821e22bee78STejun Heo  * the problem rescuer solves.
2822e22bee78STejun Heo  *
2823706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2824706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2825e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2826e22bee78STejun Heo  *
2827e22bee78STejun Heo  * This should happen rarely.
2828d185af30SYacine Belkadi  *
2829d185af30SYacine Belkadi  * Return: 0
2830e22bee78STejun Heo  */
2831111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2832e22bee78STejun Heo {
2833111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2834111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
28354d595b86SLai Jiangshan 	bool should_stop;
2836e22bee78STejun Heo 
2837e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2838111c225aSTejun Heo 
2839111c225aSTejun Heo 	/*
2840111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2841111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2842111c225aSTejun Heo 	 */
2843197f6accSTejun Heo 	set_pf_worker(true);
2844e22bee78STejun Heo repeat:
2845c5a94a61SPeter Zijlstra 	set_current_state(TASK_IDLE);
28461da177e4SLinus Torvalds 
28474d595b86SLai Jiangshan 	/*
28484d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
28494d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
28504d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
28514d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
28524d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
28534d595b86SLai Jiangshan 	 * list is always empty on exit.
28544d595b86SLai Jiangshan 	 */
28554d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
28561da177e4SLinus Torvalds 
2857493a1724STejun Heo 	/* see whether any pwq is asking for help */
2858a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq_mayday_lock);
2859493a1724STejun Heo 
2860493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2861493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2862493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2863112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2864e22bee78STejun Heo 		struct work_struct *work, *n;
2865e22bee78STejun Heo 
2866e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2867493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2868493a1724STejun Heo 
2869a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
2870e22bee78STejun Heo 
287151697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
287251697d39SLai Jiangshan 
2873a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
2874e22bee78STejun Heo 
2875e22bee78STejun Heo 		/*
2876e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2877e22bee78STejun Heo 		 * process'em.
2878e22bee78STejun Heo 		 */
2879873eaca6STejun Heo 		WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
288082607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
2881873eaca6STejun Heo 			if (get_work_pwq(work) == pwq &&
2882873eaca6STejun Heo 			    assign_work(work, rescuer, &n))
2883725e8ec5STejun Heo 				pwq->stats[PWQ_STAT_RESCUED]++;
288482607adcSTejun Heo 		}
2885e22bee78STejun Heo 
2886873eaca6STejun Heo 		if (!list_empty(&rescuer->scheduled)) {
2887e22bee78STejun Heo 			process_scheduled_works(rescuer);
28887576958aSTejun Heo 
28897576958aSTejun Heo 			/*
2890008847f6SNeilBrown 			 * The above execution of rescued work items could
2891008847f6SNeilBrown 			 * have created more to rescue through
2892f97a4a1aSLai Jiangshan 			 * pwq_activate_first_inactive() or chained
2893008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
2894008847f6SNeilBrown 			 * that such back-to-back work items, which may be
2895008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
2896008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
2897008847f6SNeilBrown 			 */
28984f3f4cf3SLai Jiangshan 			if (pwq->nr_active && need_to_create_worker(pool)) {
2899a9b8a985SSebastian Andrzej Siewior 				raw_spin_lock(&wq_mayday_lock);
2900e66b39afSTejun Heo 				/*
2901e66b39afSTejun Heo 				 * Queue iff we aren't racing destruction
2902e66b39afSTejun Heo 				 * and somebody else hasn't queued it already.
2903e66b39afSTejun Heo 				 */
2904e66b39afSTejun Heo 				if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2905008847f6SNeilBrown 					get_pwq(pwq);
2906e66b39afSTejun Heo 					list_add_tail(&pwq->mayday_node, &wq->maydays);
2907e66b39afSTejun Heo 				}
2908a9b8a985SSebastian Andrzej Siewior 				raw_spin_unlock(&wq_mayday_lock);
2909008847f6SNeilBrown 			}
2910008847f6SNeilBrown 		}
2911008847f6SNeilBrown 
2912008847f6SNeilBrown 		/*
291377668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
291413b1d625SLai Jiangshan 		 * go away while we're still attached to it.
291577668c8bSLai Jiangshan 		 */
291677668c8bSLai Jiangshan 		put_pwq(pwq);
291777668c8bSLai Jiangshan 
291877668c8bSLai Jiangshan 		/*
29190219a352STejun Heo 		 * Leave this pool. Notify regular workers; otherwise, we end up
29200219a352STejun Heo 		 * with 0 concurrency and stalling the execution.
29217576958aSTejun Heo 		 */
29220219a352STejun Heo 		kick_pool(pool);
29237576958aSTejun Heo 
2924a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
292513b1d625SLai Jiangshan 
2926a2d812a2STejun Heo 		worker_detach_from_pool(rescuer);
292713b1d625SLai Jiangshan 
2928a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
29291da177e4SLinus Torvalds 	}
29301da177e4SLinus Torvalds 
2931a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq_mayday_lock);
2932493a1724STejun Heo 
29334d595b86SLai Jiangshan 	if (should_stop) {
29344d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
2935197f6accSTejun Heo 		set_pf_worker(false);
29364d595b86SLai Jiangshan 		return 0;
29374d595b86SLai Jiangshan 	}
29384d595b86SLai Jiangshan 
2939111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2940111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2941e22bee78STejun Heo 	schedule();
2942e22bee78STejun Heo 	goto repeat;
29431da177e4SLinus Torvalds }
29441da177e4SLinus Torvalds 
2945fca839c0STejun Heo /**
2946fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
2947fca839c0STejun Heo  * @target_wq: workqueue being flushed
2948fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
2949fca839c0STejun Heo  *
2950fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
2951fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2952fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
2953fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2954fca839c0STejun Heo  * a deadlock.
2955fca839c0STejun Heo  */
2956fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
2957fca839c0STejun Heo 				   struct work_struct *target_work)
2958fca839c0STejun Heo {
2959fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
2960fca839c0STejun Heo 	struct worker *worker;
2961fca839c0STejun Heo 
2962fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
2963fca839c0STejun Heo 		return;
2964fca839c0STejun Heo 
2965fca839c0STejun Heo 	worker = current_wq_worker();
2966fca839c0STejun Heo 
2967fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
2968d75f773cSSakari Ailus 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
2969fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
297023d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
297123d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2972d75f773cSSakari Ailus 		  "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
2973fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
2974fca839c0STejun Heo 		  target_wq->name, target_func);
2975fca839c0STejun Heo }
2976fca839c0STejun Heo 
2977fc2e4d70SOleg Nesterov struct wq_barrier {
2978fc2e4d70SOleg Nesterov 	struct work_struct	work;
2979fc2e4d70SOleg Nesterov 	struct completion	done;
29802607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
2981fc2e4d70SOleg Nesterov };
2982fc2e4d70SOleg Nesterov 
2983fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2984fc2e4d70SOleg Nesterov {
2985fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2986fc2e4d70SOleg Nesterov 	complete(&barr->done);
2987fc2e4d70SOleg Nesterov }
2988fc2e4d70SOleg Nesterov 
29894690c4abSTejun Heo /**
29904690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2991112202d9STejun Heo  * @pwq: pwq to insert barrier into
29924690c4abSTejun Heo  * @barr: wq_barrier to insert
2993affee4b2STejun Heo  * @target: target work to attach @barr to
2994affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
29954690c4abSTejun Heo  *
2996affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2997affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2998affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2999affee4b2STejun Heo  * cpu.
3000affee4b2STejun Heo  *
3001affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
3002affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
3003affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
3004affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
3005affee4b2STejun Heo  * after a work with LINKED flag set.
3006affee4b2STejun Heo  *
3007affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
3008112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
30094690c4abSTejun Heo  *
30104690c4abSTejun Heo  * CONTEXT:
3011a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
30124690c4abSTejun Heo  */
3013112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
3014affee4b2STejun Heo 			      struct wq_barrier *barr,
3015affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
3016fc2e4d70SOleg Nesterov {
3017d812796eSLai Jiangshan 	unsigned int work_flags = 0;
3018d812796eSLai Jiangshan 	unsigned int work_color;
3019affee4b2STejun Heo 	struct list_head *head;
3020affee4b2STejun Heo 
3021dc186ad7SThomas Gleixner 	/*
3022d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
3023dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
3024dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
3025dc186ad7SThomas Gleixner 	 * might deadlock.
3026dc186ad7SThomas Gleixner 	 */
3027ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
302822df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
302952fa5bc5SBoqun Feng 
3030fd1a5b04SByungchul Park 	init_completion_map(&barr->done, &target->lockdep_map);
3031fd1a5b04SByungchul Park 
30322607d7a6STejun Heo 	barr->task = current;
303383c22520SOleg Nesterov 
3034018f3a13SLai Jiangshan 	/* The barrier work item does not participate in pwq->nr_active. */
3035018f3a13SLai Jiangshan 	work_flags |= WORK_STRUCT_INACTIVE;
3036018f3a13SLai Jiangshan 
3037affee4b2STejun Heo 	/*
3038affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
3039affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
3040affee4b2STejun Heo 	 */
3041d812796eSLai Jiangshan 	if (worker) {
3042affee4b2STejun Heo 		head = worker->scheduled.next;
3043d812796eSLai Jiangshan 		work_color = worker->current_color;
3044d812796eSLai Jiangshan 	} else {
3045affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
3046affee4b2STejun Heo 
3047affee4b2STejun Heo 		head = target->entry.next;
3048affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
3049d21cece0SLai Jiangshan 		work_flags |= *bits & WORK_STRUCT_LINKED;
3050d812796eSLai Jiangshan 		work_color = get_work_color(*bits);
3051affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
3052affee4b2STejun Heo 	}
3053affee4b2STejun Heo 
3054d812796eSLai Jiangshan 	pwq->nr_in_flight[work_color]++;
3055d812796eSLai Jiangshan 	work_flags |= work_color_to_flags(work_color);
3056d812796eSLai Jiangshan 
3057d21cece0SLai Jiangshan 	insert_work(pwq, &barr->work, head, work_flags);
3058fc2e4d70SOleg Nesterov }
3059fc2e4d70SOleg Nesterov 
306073f53c4aSTejun Heo /**
3061112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
306273f53c4aSTejun Heo  * @wq: workqueue being flushed
306373f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
306473f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
306573f53c4aSTejun Heo  *
3066112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
306773f53c4aSTejun Heo  *
3068112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
3069112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
3070112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
3071112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
3072112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
307373f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
307473f53c4aSTejun Heo  *
307573f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
307673f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
307773f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
307873f53c4aSTejun Heo  * is returned.
307973f53c4aSTejun Heo  *
3080112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
308173f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
308273f53c4aSTejun Heo  * advanced to @work_color.
308373f53c4aSTejun Heo  *
308473f53c4aSTejun Heo  * CONTEXT:
30853c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
308673f53c4aSTejun Heo  *
3087d185af30SYacine Belkadi  * Return:
308873f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
308973f53c4aSTejun Heo  * otherwise.
309073f53c4aSTejun Heo  */
3091112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
309273f53c4aSTejun Heo 				      int flush_color, int work_color)
30931da177e4SLinus Torvalds {
309473f53c4aSTejun Heo 	bool wait = false;
309549e3cf44STejun Heo 	struct pool_workqueue *pwq;
30961da177e4SLinus Torvalds 
309773f53c4aSTejun Heo 	if (flush_color >= 0) {
30986183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
3099112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
3100dc186ad7SThomas Gleixner 	}
310114441960SOleg Nesterov 
310249e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3103112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
31041da177e4SLinus Torvalds 
3105a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
310673f53c4aSTejun Heo 
310773f53c4aSTejun Heo 		if (flush_color >= 0) {
31086183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
310973f53c4aSTejun Heo 
3110112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
3111112202d9STejun Heo 				pwq->flush_color = flush_color;
3112112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
311373f53c4aSTejun Heo 				wait = true;
31141da177e4SLinus Torvalds 			}
311573f53c4aSTejun Heo 		}
311673f53c4aSTejun Heo 
311773f53c4aSTejun Heo 		if (work_color >= 0) {
31186183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
3119112202d9STejun Heo 			pwq->work_color = work_color;
312073f53c4aSTejun Heo 		}
312173f53c4aSTejun Heo 
3122a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
31231da177e4SLinus Torvalds 	}
31241da177e4SLinus Torvalds 
3125112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
312673f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
312773f53c4aSTejun Heo 
312873f53c4aSTejun Heo 	return wait;
312983c22520SOleg Nesterov }
31301da177e4SLinus Torvalds 
31310fcb78c2SRolf Eike Beer /**
3132c4f135d6STetsuo Handa  * __flush_workqueue - ensure that any scheduled work has run to completion.
31330fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
31341da177e4SLinus Torvalds  *
3135c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
3136c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
31371da177e4SLinus Torvalds  */
3138c4f135d6STetsuo Handa void __flush_workqueue(struct workqueue_struct *wq)
31391da177e4SLinus Torvalds {
314073f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
314173f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
314273f53c4aSTejun Heo 		.flush_color = -1,
3143fd1a5b04SByungchul Park 		.done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
314473f53c4aSTejun Heo 	};
314573f53c4aSTejun Heo 	int next_color;
3146b1f4ec17SOleg Nesterov 
31473347fa09STejun Heo 	if (WARN_ON(!wq_online))
31483347fa09STejun Heo 		return;
31493347fa09STejun Heo 
315087915adcSJohannes Berg 	lock_map_acquire(&wq->lockdep_map);
315187915adcSJohannes Berg 	lock_map_release(&wq->lockdep_map);
315287915adcSJohannes Berg 
31533c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
315473f53c4aSTejun Heo 
315573f53c4aSTejun Heo 	/*
315673f53c4aSTejun Heo 	 * Start-to-wait phase
315773f53c4aSTejun Heo 	 */
315873f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
315973f53c4aSTejun Heo 
316073f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
316173f53c4aSTejun Heo 		/*
316273f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
316373f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
316473f53c4aSTejun Heo 		 * by one.
316573f53c4aSTejun Heo 		 */
31666183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
316773f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
316873f53c4aSTejun Heo 		wq->work_color = next_color;
316973f53c4aSTejun Heo 
317073f53c4aSTejun Heo 		if (!wq->first_flusher) {
317173f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
31726183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
317373f53c4aSTejun Heo 
317473f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
317573f53c4aSTejun Heo 
3176112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
317773f53c4aSTejun Heo 						       wq->work_color)) {
317873f53c4aSTejun Heo 				/* nothing to flush, done */
317973f53c4aSTejun Heo 				wq->flush_color = next_color;
318073f53c4aSTejun Heo 				wq->first_flusher = NULL;
318173f53c4aSTejun Heo 				goto out_unlock;
318273f53c4aSTejun Heo 			}
318373f53c4aSTejun Heo 		} else {
318473f53c4aSTejun Heo 			/* wait in queue */
31856183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
318673f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
3187112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
318873f53c4aSTejun Heo 		}
318973f53c4aSTejun Heo 	} else {
319073f53c4aSTejun Heo 		/*
319173f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
319273f53c4aSTejun Heo 		 * The next flush completion will assign us
319373f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
319473f53c4aSTejun Heo 		 */
319573f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
319673f53c4aSTejun Heo 	}
319773f53c4aSTejun Heo 
3198fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
3199fca839c0STejun Heo 
32003c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
320173f53c4aSTejun Heo 
320273f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
320373f53c4aSTejun Heo 
320473f53c4aSTejun Heo 	/*
320573f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
320673f53c4aSTejun Heo 	 *
320773f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
320873f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
320973f53c4aSTejun Heo 	 */
321000d5d15bSChris Wilson 	if (READ_ONCE(wq->first_flusher) != &this_flusher)
321173f53c4aSTejun Heo 		return;
321273f53c4aSTejun Heo 
32133c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
321473f53c4aSTejun Heo 
32154ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
32164ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
32174ce48b37STejun Heo 		goto out_unlock;
32184ce48b37STejun Heo 
321900d5d15bSChris Wilson 	WRITE_ONCE(wq->first_flusher, NULL);
322073f53c4aSTejun Heo 
32216183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
32226183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
322373f53c4aSTejun Heo 
322473f53c4aSTejun Heo 	while (true) {
322573f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
322673f53c4aSTejun Heo 
322773f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
322873f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
322973f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
323073f53c4aSTejun Heo 				break;
323173f53c4aSTejun Heo 			list_del_init(&next->list);
323273f53c4aSTejun Heo 			complete(&next->done);
323373f53c4aSTejun Heo 		}
323473f53c4aSTejun Heo 
32356183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
323673f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
323773f53c4aSTejun Heo 
323873f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
323973f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
324073f53c4aSTejun Heo 
324173f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
324273f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
324373f53c4aSTejun Heo 			/*
324473f53c4aSTejun Heo 			 * Assign the same color to all overflowed
324573f53c4aSTejun Heo 			 * flushers, advance work_color and append to
324673f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
324773f53c4aSTejun Heo 			 * phase for these overflowed flushers.
324873f53c4aSTejun Heo 			 */
324973f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
325073f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
325173f53c4aSTejun Heo 
325273f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
325373f53c4aSTejun Heo 
325473f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
325573f53c4aSTejun Heo 					      &wq->flusher_queue);
3256112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
325773f53c4aSTejun Heo 		}
325873f53c4aSTejun Heo 
325973f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
32606183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
326173f53c4aSTejun Heo 			break;
326273f53c4aSTejun Heo 		}
326373f53c4aSTejun Heo 
326473f53c4aSTejun Heo 		/*
326573f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
3266112202d9STejun Heo 		 * the new first flusher and arm pwqs.
326773f53c4aSTejun Heo 		 */
32686183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
32696183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
327073f53c4aSTejun Heo 
327173f53c4aSTejun Heo 		list_del_init(&next->list);
327273f53c4aSTejun Heo 		wq->first_flusher = next;
327373f53c4aSTejun Heo 
3274112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
327573f53c4aSTejun Heo 			break;
327673f53c4aSTejun Heo 
327773f53c4aSTejun Heo 		/*
327873f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
327973f53c4aSTejun Heo 		 * flusher and repeat cascading.
328073f53c4aSTejun Heo 		 */
328173f53c4aSTejun Heo 		wq->first_flusher = NULL;
328273f53c4aSTejun Heo 	}
328373f53c4aSTejun Heo 
328473f53c4aSTejun Heo out_unlock:
32853c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
32861da177e4SLinus Torvalds }
3287c4f135d6STetsuo Handa EXPORT_SYMBOL(__flush_workqueue);
32881da177e4SLinus Torvalds 
32899c5a2ba7STejun Heo /**
32909c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
32919c5a2ba7STejun Heo  * @wq: workqueue to drain
32929c5a2ba7STejun Heo  *
32939c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
32949c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
32959c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
3296b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
32979c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
32989c5a2ba7STejun Heo  * takes too long.
32999c5a2ba7STejun Heo  */
33009c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
33019c5a2ba7STejun Heo {
33029c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
330349e3cf44STejun Heo 	struct pool_workqueue *pwq;
33049c5a2ba7STejun Heo 
33059c5a2ba7STejun Heo 	/*
33069c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
33079c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
3308618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
33099c5a2ba7STejun Heo 	 */
331087fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
33119c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
3312618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
331387fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
33149c5a2ba7STejun Heo reflush:
3315c4f135d6STetsuo Handa 	__flush_workqueue(wq);
33169c5a2ba7STejun Heo 
3317b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
331876af4d93STejun Heo 
331949e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3320fa2563e4SThomas Tuttle 		bool drained;
33219c5a2ba7STejun Heo 
3322a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
3323f97a4a1aSLai Jiangshan 		drained = !pwq->nr_active && list_empty(&pwq->inactive_works);
3324a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
3325fa2563e4SThomas Tuttle 
3326fa2563e4SThomas Tuttle 		if (drained)
33279c5a2ba7STejun Heo 			continue;
33289c5a2ba7STejun Heo 
33299c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
33309c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
3331e9ad2eb3SStephen Zhang 			pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3332e9ad2eb3SStephen Zhang 				wq->name, __func__, flush_cnt);
333376af4d93STejun Heo 
3334b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
33359c5a2ba7STejun Heo 		goto reflush;
33369c5a2ba7STejun Heo 	}
33379c5a2ba7STejun Heo 
33389c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
3339618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
334087fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
33419c5a2ba7STejun Heo }
33429c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
33439c5a2ba7STejun Heo 
3344d6e89786SJohannes Berg static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3345d6e89786SJohannes Berg 			     bool from_cancel)
3346baf59022STejun Heo {
3347baf59022STejun Heo 	struct worker *worker = NULL;
3348c9e7cf27STejun Heo 	struct worker_pool *pool;
3349112202d9STejun Heo 	struct pool_workqueue *pwq;
3350baf59022STejun Heo 
3351baf59022STejun Heo 	might_sleep();
3352baf59022STejun Heo 
335324acfb71SThomas Gleixner 	rcu_read_lock();
3354fa1b54e6STejun Heo 	pool = get_work_pool(work);
3355fa1b54e6STejun Heo 	if (!pool) {
335624acfb71SThomas Gleixner 		rcu_read_unlock();
3357fa1b54e6STejun Heo 		return false;
3358fa1b54e6STejun Heo 	}
3359fa1b54e6STejun Heo 
3360a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
33610b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
3362112202d9STejun Heo 	pwq = get_work_pwq(work);
3363112202d9STejun Heo 	if (pwq) {
3364112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
3365baf59022STejun Heo 			goto already_gone;
3366606a5020STejun Heo 	} else {
3367c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
3368baf59022STejun Heo 		if (!worker)
3369baf59022STejun Heo 			goto already_gone;
3370112202d9STejun Heo 		pwq = worker->current_pwq;
3371606a5020STejun Heo 	}
3372baf59022STejun Heo 
3373fca839c0STejun Heo 	check_flush_dependency(pwq->wq, work);
3374fca839c0STejun Heo 
3375112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
3376a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
3377baf59022STejun Heo 
3378e159489bSTejun Heo 	/*
3379a1d14934SPeter Zijlstra 	 * Force a lock recursion deadlock when using flush_work() inside a
3380a1d14934SPeter Zijlstra 	 * single-threaded or rescuer equipped workqueue.
3381a1d14934SPeter Zijlstra 	 *
3382a1d14934SPeter Zijlstra 	 * For single threaded workqueues the deadlock happens when the work
3383a1d14934SPeter Zijlstra 	 * is after the work issuing the flush_work(). For rescuer equipped
3384a1d14934SPeter Zijlstra 	 * workqueues the deadlock happens when the rescuer stalls, blocking
3385a1d14934SPeter Zijlstra 	 * forward progress.
3386e159489bSTejun Heo 	 */
3387d6e89786SJohannes Berg 	if (!from_cancel &&
3388d6e89786SJohannes Berg 	    (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
3389112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
3390112202d9STejun Heo 		lock_map_release(&pwq->wq->lockdep_map);
3391a1d14934SPeter Zijlstra 	}
339224acfb71SThomas Gleixner 	rcu_read_unlock();
3393baf59022STejun Heo 	return true;
3394baf59022STejun Heo already_gone:
3395a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
339624acfb71SThomas Gleixner 	rcu_read_unlock();
3397baf59022STejun Heo 	return false;
3398baf59022STejun Heo }
3399baf59022STejun Heo 
3400d6e89786SJohannes Berg static bool __flush_work(struct work_struct *work, bool from_cancel)
3401d6e89786SJohannes Berg {
3402d6e89786SJohannes Berg 	struct wq_barrier barr;
3403d6e89786SJohannes Berg 
3404d6e89786SJohannes Berg 	if (WARN_ON(!wq_online))
3405d6e89786SJohannes Berg 		return false;
3406d6e89786SJohannes Berg 
34074d43d395STetsuo Handa 	if (WARN_ON(!work->func))
34084d43d395STetsuo Handa 		return false;
34094d43d395STetsuo Handa 
341087915adcSJohannes Berg 	lock_map_acquire(&work->lockdep_map);
341187915adcSJohannes Berg 	lock_map_release(&work->lockdep_map);
341287915adcSJohannes Berg 
3413d6e89786SJohannes Berg 	if (start_flush_work(work, &barr, from_cancel)) {
3414d6e89786SJohannes Berg 		wait_for_completion(&barr.done);
3415d6e89786SJohannes Berg 		destroy_work_on_stack(&barr.work);
3416d6e89786SJohannes Berg 		return true;
3417d6e89786SJohannes Berg 	} else {
3418d6e89786SJohannes Berg 		return false;
3419d6e89786SJohannes Berg 	}
3420d6e89786SJohannes Berg }
3421d6e89786SJohannes Berg 
3422db700897SOleg Nesterov /**
3423401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
3424401a8d04STejun Heo  * @work: the work to flush
3425db700897SOleg Nesterov  *
3426606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
3427606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
3428401a8d04STejun Heo  *
3429d185af30SYacine Belkadi  * Return:
3430401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3431401a8d04STejun Heo  * %false if it was already idle.
3432db700897SOleg Nesterov  */
3433401a8d04STejun Heo bool flush_work(struct work_struct *work)
3434db700897SOleg Nesterov {
3435d6e89786SJohannes Berg 	return __flush_work(work, false);
3436606a5020STejun Heo }
3437db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
3438db700897SOleg Nesterov 
34398603e1b3STejun Heo struct cwt_wait {
3440ac6424b9SIngo Molnar 	wait_queue_entry_t		wait;
34418603e1b3STejun Heo 	struct work_struct	*work;
34428603e1b3STejun Heo };
34438603e1b3STejun Heo 
3444ac6424b9SIngo Molnar static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
34458603e1b3STejun Heo {
34468603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
34478603e1b3STejun Heo 
34488603e1b3STejun Heo 	if (cwait->work != key)
34498603e1b3STejun Heo 		return 0;
34508603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
34518603e1b3STejun Heo }
34528603e1b3STejun Heo 
345336e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3454401a8d04STejun Heo {
34558603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3456bbb68dfaSTejun Heo 	unsigned long flags;
34571f1f642eSOleg Nesterov 	int ret;
34581f1f642eSOleg Nesterov 
34591f1f642eSOleg Nesterov 	do {
3460bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
3461bbb68dfaSTejun Heo 		/*
34628603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
34638603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
34648603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
34658603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
34668603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
34678603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
34688603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
34698603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
34708603e1b3STejun Heo 		 * we're hogging the CPU.
34718603e1b3STejun Heo 		 *
34728603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
34738603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
34748603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
34758603e1b3STejun Heo 		 * wait and wakeup.
3476bbb68dfaSTejun Heo 		 */
34778603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
34788603e1b3STejun Heo 			struct cwt_wait cwait;
34798603e1b3STejun Heo 
34808603e1b3STejun Heo 			init_wait(&cwait.wait);
34818603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
34828603e1b3STejun Heo 			cwait.work = work;
34838603e1b3STejun Heo 
34848603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
34858603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
34868603e1b3STejun Heo 			if (work_is_canceling(work))
34878603e1b3STejun Heo 				schedule();
34888603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
34898603e1b3STejun Heo 		}
34901f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
34911f1f642eSOleg Nesterov 
3492bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
3493bbb68dfaSTejun Heo 	mark_work_canceling(work);
3494bbb68dfaSTejun Heo 	local_irq_restore(flags);
3495bbb68dfaSTejun Heo 
34963347fa09STejun Heo 	/*
34973347fa09STejun Heo 	 * This allows canceling during early boot.  We know that @work
34983347fa09STejun Heo 	 * isn't executing.
34993347fa09STejun Heo 	 */
35003347fa09STejun Heo 	if (wq_online)
3501d6e89786SJohannes Berg 		__flush_work(work, true);
35023347fa09STejun Heo 
35037a22ad75STejun Heo 	clear_work_data(work);
35048603e1b3STejun Heo 
35058603e1b3STejun Heo 	/*
35068603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
35078603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
35088603e1b3STejun Heo 	 * visible there.
35098603e1b3STejun Heo 	 */
35108603e1b3STejun Heo 	smp_mb();
35118603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
35128603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
35138603e1b3STejun Heo 
35141f1f642eSOleg Nesterov 	return ret;
35151f1f642eSOleg Nesterov }
35161f1f642eSOleg Nesterov 
35176e84d644SOleg Nesterov /**
3518401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
3519401a8d04STejun Heo  * @work: the work to cancel
35206e84d644SOleg Nesterov  *
3521401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
3522401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
3523401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
3524401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
35251f1f642eSOleg Nesterov  *
3526401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
3527401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
35286e84d644SOleg Nesterov  *
3529401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
35306e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
3531401a8d04STejun Heo  *
3532d185af30SYacine Belkadi  * Return:
3533401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
35346e84d644SOleg Nesterov  */
3535401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
35366e84d644SOleg Nesterov {
353736e227d2STejun Heo 	return __cancel_work_timer(work, false);
3538b89deed3SOleg Nesterov }
353928e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
3540b89deed3SOleg Nesterov 
35416e84d644SOleg Nesterov /**
3542401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
3543401a8d04STejun Heo  * @dwork: the delayed work to flush
35446e84d644SOleg Nesterov  *
3545401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
3546401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
3547401a8d04STejun Heo  * considers the last queueing instance of @dwork.
35481f1f642eSOleg Nesterov  *
3549d185af30SYacine Belkadi  * Return:
3550401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3551401a8d04STejun Heo  * %false if it was already idle.
35526e84d644SOleg Nesterov  */
3553401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
3554401a8d04STejun Heo {
35558930cabaSTejun Heo 	local_irq_disable();
3556401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
355760c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
35588930cabaSTejun Heo 	local_irq_enable();
3559401a8d04STejun Heo 	return flush_work(&dwork->work);
3560401a8d04STejun Heo }
3561401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3562401a8d04STejun Heo 
356305f0fe6bSTejun Heo /**
356405f0fe6bSTejun Heo  * flush_rcu_work - wait for a rwork to finish executing the last queueing
356505f0fe6bSTejun Heo  * @rwork: the rcu work to flush
356605f0fe6bSTejun Heo  *
356705f0fe6bSTejun Heo  * Return:
356805f0fe6bSTejun Heo  * %true if flush_rcu_work() waited for the work to finish execution,
356905f0fe6bSTejun Heo  * %false if it was already idle.
357005f0fe6bSTejun Heo  */
357105f0fe6bSTejun Heo bool flush_rcu_work(struct rcu_work *rwork)
357205f0fe6bSTejun Heo {
357305f0fe6bSTejun Heo 	if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
357405f0fe6bSTejun Heo 		rcu_barrier();
357505f0fe6bSTejun Heo 		flush_work(&rwork->work);
357605f0fe6bSTejun Heo 		return true;
357705f0fe6bSTejun Heo 	} else {
357805f0fe6bSTejun Heo 		return flush_work(&rwork->work);
357905f0fe6bSTejun Heo 	}
358005f0fe6bSTejun Heo }
358105f0fe6bSTejun Heo EXPORT_SYMBOL(flush_rcu_work);
358205f0fe6bSTejun Heo 
3583f72b8792SJens Axboe static bool __cancel_work(struct work_struct *work, bool is_dwork)
3584f72b8792SJens Axboe {
3585f72b8792SJens Axboe 	unsigned long flags;
3586f72b8792SJens Axboe 	int ret;
3587f72b8792SJens Axboe 
3588f72b8792SJens Axboe 	do {
3589f72b8792SJens Axboe 		ret = try_to_grab_pending(work, is_dwork, &flags);
3590f72b8792SJens Axboe 	} while (unlikely(ret == -EAGAIN));
3591f72b8792SJens Axboe 
3592f72b8792SJens Axboe 	if (unlikely(ret < 0))
3593f72b8792SJens Axboe 		return false;
3594f72b8792SJens Axboe 
3595f72b8792SJens Axboe 	set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3596f72b8792SJens Axboe 	local_irq_restore(flags);
3597f72b8792SJens Axboe 	return ret;
3598f72b8792SJens Axboe }
3599f72b8792SJens Axboe 
360073b4b532SAndrey Grodzovsky /*
360173b4b532SAndrey Grodzovsky  * See cancel_delayed_work()
360273b4b532SAndrey Grodzovsky  */
360373b4b532SAndrey Grodzovsky bool cancel_work(struct work_struct *work)
360473b4b532SAndrey Grodzovsky {
360573b4b532SAndrey Grodzovsky 	return __cancel_work(work, false);
360673b4b532SAndrey Grodzovsky }
360773b4b532SAndrey Grodzovsky EXPORT_SYMBOL(cancel_work);
360873b4b532SAndrey Grodzovsky 
3609401a8d04STejun Heo /**
361057b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
361157b30ae7STejun Heo  * @dwork: delayed_work to cancel
361209383498STejun Heo  *
3613d185af30SYacine Belkadi  * Kill off a pending delayed_work.
3614d185af30SYacine Belkadi  *
3615d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
3616d185af30SYacine Belkadi  * pending.
3617d185af30SYacine Belkadi  *
3618d185af30SYacine Belkadi  * Note:
3619d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
3620d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
3621d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
362209383498STejun Heo  *
362357b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
362409383498STejun Heo  */
362557b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
362609383498STejun Heo {
3627f72b8792SJens Axboe 	return __cancel_work(&dwork->work, true);
362809383498STejun Heo }
362957b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
363009383498STejun Heo 
363109383498STejun Heo /**
3632401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3633401a8d04STejun Heo  * @dwork: the delayed work cancel
3634401a8d04STejun Heo  *
3635401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
3636401a8d04STejun Heo  *
3637d185af30SYacine Belkadi  * Return:
3638401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
3639401a8d04STejun Heo  */
3640401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
36416e84d644SOleg Nesterov {
364236e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
36436e84d644SOleg Nesterov }
3644f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
36451da177e4SLinus Torvalds 
36460fcb78c2SRolf Eike Beer /**
364731ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3648b6136773SAndrew Morton  * @func: the function to call
3649b6136773SAndrew Morton  *
365031ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
365131ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3652b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
365331ddd871STejun Heo  *
3654d185af30SYacine Belkadi  * Return:
365531ddd871STejun Heo  * 0 on success, -errno on failure.
3656b6136773SAndrew Morton  */
365765f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
365815316ba8SChristoph Lameter {
365915316ba8SChristoph Lameter 	int cpu;
366038f51568SNamhyung Kim 	struct work_struct __percpu *works;
366115316ba8SChristoph Lameter 
3662b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3663b6136773SAndrew Morton 	if (!works)
366415316ba8SChristoph Lameter 		return -ENOMEM;
3665b6136773SAndrew Morton 
3666ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
366793981800STejun Heo 
366815316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
36699bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
36709bfb1839SIngo Molnar 
36719bfb1839SIngo Molnar 		INIT_WORK(work, func);
36728de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
367315316ba8SChristoph Lameter 	}
367493981800STejun Heo 
367593981800STejun Heo 	for_each_online_cpu(cpu)
36768616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
367793981800STejun Heo 
3678ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
3679b6136773SAndrew Morton 	free_percpu(works);
368015316ba8SChristoph Lameter 	return 0;
368115316ba8SChristoph Lameter }
368215316ba8SChristoph Lameter 
3683eef6a7d5SAlan Stern /**
36841fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
36851fa44ecaSJames Bottomley  * @fn:		the function to execute
36861fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
36871fa44ecaSJames Bottomley  *		be available when the work executes)
36881fa44ecaSJames Bottomley  *
36891fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
36901fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
36911fa44ecaSJames Bottomley  *
3692d185af30SYacine Belkadi  * Return:	0 - function was executed
36931fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
36941fa44ecaSJames Bottomley  */
369565f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
36961fa44ecaSJames Bottomley {
36971fa44ecaSJames Bottomley 	if (!in_interrupt()) {
369865f27f38SDavid Howells 		fn(&ew->work);
36991fa44ecaSJames Bottomley 		return 0;
37001fa44ecaSJames Bottomley 	}
37011fa44ecaSJames Bottomley 
370265f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
37031fa44ecaSJames Bottomley 	schedule_work(&ew->work);
37041fa44ecaSJames Bottomley 
37051fa44ecaSJames Bottomley 	return 1;
37061fa44ecaSJames Bottomley }
37071fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
37081fa44ecaSJames Bottomley 
37097a4e344cSTejun Heo /**
37107a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
37117a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
37127a4e344cSTejun Heo  *
37137a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
37147a4e344cSTejun Heo  */
3715513c98d0SDaniel Jordan void free_workqueue_attrs(struct workqueue_attrs *attrs)
37167a4e344cSTejun Heo {
37177a4e344cSTejun Heo 	if (attrs) {
37187a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
37199546b29eSTejun Heo 		free_cpumask_var(attrs->__pod_cpumask);
37207a4e344cSTejun Heo 		kfree(attrs);
37217a4e344cSTejun Heo 	}
37227a4e344cSTejun Heo }
37237a4e344cSTejun Heo 
37247a4e344cSTejun Heo /**
37257a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
37267a4e344cSTejun Heo  *
37277a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3728d185af30SYacine Belkadi  * return it.
3729d185af30SYacine Belkadi  *
3730d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
37317a4e344cSTejun Heo  */
3732513c98d0SDaniel Jordan struct workqueue_attrs *alloc_workqueue_attrs(void)
37337a4e344cSTejun Heo {
37347a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
37357a4e344cSTejun Heo 
3736be69d00dSThomas Gleixner 	attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
37377a4e344cSTejun Heo 	if (!attrs)
37387a4e344cSTejun Heo 		goto fail;
3739be69d00dSThomas Gleixner 	if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
37407a4e344cSTejun Heo 		goto fail;
37419546b29eSTejun Heo 	if (!alloc_cpumask_var(&attrs->__pod_cpumask, GFP_KERNEL))
37429546b29eSTejun Heo 		goto fail;
37437a4e344cSTejun Heo 
374413e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
3745523a301eSTejun Heo 	attrs->affn_scope = WQ_AFFN_DFL;
37467a4e344cSTejun Heo 	return attrs;
37477a4e344cSTejun Heo fail:
37487a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
37497a4e344cSTejun Heo 	return NULL;
37507a4e344cSTejun Heo }
37517a4e344cSTejun Heo 
375229c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
375329c91e99STejun Heo 				 const struct workqueue_attrs *from)
375429c91e99STejun Heo {
375529c91e99STejun Heo 	to->nice = from->nice;
375629c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
37579546b29eSTejun Heo 	cpumask_copy(to->__pod_cpumask, from->__pod_cpumask);
37588639ecebSTejun Heo 	to->affn_strict = from->affn_strict;
375984193c07STejun Heo 
37602865a8fbSShaohua Li 	/*
376184193c07STejun Heo 	 * Unlike hash and equality test, copying shouldn't ignore wq-only
376284193c07STejun Heo 	 * fields as copying is used for both pool and wq attrs. Instead,
376384193c07STejun Heo 	 * get_unbound_pool() explicitly clears the fields.
37642865a8fbSShaohua Li 	 */
376584193c07STejun Heo 	to->affn_scope = from->affn_scope;
3766af73f5c9STejun Heo 	to->ordered = from->ordered;
376729c91e99STejun Heo }
376829c91e99STejun Heo 
37695de7a03cSTejun Heo /*
37705de7a03cSTejun Heo  * Some attrs fields are workqueue-only. Clear them for worker_pool's. See the
37715de7a03cSTejun Heo  * comments in 'struct workqueue_attrs' definition.
37725de7a03cSTejun Heo  */
37735de7a03cSTejun Heo static void wqattrs_clear_for_pool(struct workqueue_attrs *attrs)
37745de7a03cSTejun Heo {
377584193c07STejun Heo 	attrs->affn_scope = WQ_AFFN_NR_TYPES;
37765de7a03cSTejun Heo 	attrs->ordered = false;
37775de7a03cSTejun Heo }
37785de7a03cSTejun Heo 
377929c91e99STejun Heo /* hash value of the content of @attr */
378029c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
378129c91e99STejun Heo {
378229c91e99STejun Heo 	u32 hash = 0;
378329c91e99STejun Heo 
378429c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
378513e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
378613e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
37879546b29eSTejun Heo 	hash = jhash(cpumask_bits(attrs->__pod_cpumask),
37889546b29eSTejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
37898639ecebSTejun Heo 	hash = jhash_1word(attrs->affn_strict, hash);
379029c91e99STejun Heo 	return hash;
379129c91e99STejun Heo }
379229c91e99STejun Heo 
379329c91e99STejun Heo /* content equality test */
379429c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
379529c91e99STejun Heo 			  const struct workqueue_attrs *b)
379629c91e99STejun Heo {
379729c91e99STejun Heo 	if (a->nice != b->nice)
379829c91e99STejun Heo 		return false;
379929c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
380029c91e99STejun Heo 		return false;
38019546b29eSTejun Heo 	if (!cpumask_equal(a->__pod_cpumask, b->__pod_cpumask))
38029546b29eSTejun Heo 		return false;
38038639ecebSTejun Heo 	if (a->affn_strict != b->affn_strict)
38048639ecebSTejun Heo 		return false;
380529c91e99STejun Heo 	return true;
380629c91e99STejun Heo }
380729c91e99STejun Heo 
38080f36ee24STejun Heo /* Update @attrs with actually available CPUs */
38090f36ee24STejun Heo static void wqattrs_actualize_cpumask(struct workqueue_attrs *attrs,
38100f36ee24STejun Heo 				      const cpumask_t *unbound_cpumask)
38110f36ee24STejun Heo {
38120f36ee24STejun Heo 	/*
38130f36ee24STejun Heo 	 * Calculate the effective CPU mask of @attrs given @unbound_cpumask. If
38140f36ee24STejun Heo 	 * @attrs->cpumask doesn't overlap with @unbound_cpumask, we fallback to
38150f36ee24STejun Heo 	 * @unbound_cpumask.
38160f36ee24STejun Heo 	 */
38170f36ee24STejun Heo 	cpumask_and(attrs->cpumask, attrs->cpumask, unbound_cpumask);
38180f36ee24STejun Heo 	if (unlikely(cpumask_empty(attrs->cpumask)))
38190f36ee24STejun Heo 		cpumask_copy(attrs->cpumask, unbound_cpumask);
38200f36ee24STejun Heo }
38210f36ee24STejun Heo 
382284193c07STejun Heo /* find wq_pod_type to use for @attrs */
382384193c07STejun Heo static const struct wq_pod_type *
382484193c07STejun Heo wqattrs_pod_type(const struct workqueue_attrs *attrs)
382584193c07STejun Heo {
3826523a301eSTejun Heo 	enum wq_affn_scope scope;
3827523a301eSTejun Heo 	struct wq_pod_type *pt;
3828523a301eSTejun Heo 
3829523a301eSTejun Heo 	/* to synchronize access to wq_affn_dfl */
3830523a301eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3831523a301eSTejun Heo 
3832523a301eSTejun Heo 	if (attrs->affn_scope == WQ_AFFN_DFL)
3833523a301eSTejun Heo 		scope = wq_affn_dfl;
3834523a301eSTejun Heo 	else
3835523a301eSTejun Heo 		scope = attrs->affn_scope;
3836523a301eSTejun Heo 
3837523a301eSTejun Heo 	pt = &wq_pod_types[scope];
383884193c07STejun Heo 
383984193c07STejun Heo 	if (!WARN_ON_ONCE(attrs->affn_scope == WQ_AFFN_NR_TYPES) &&
384084193c07STejun Heo 	    likely(pt->nr_pods))
384184193c07STejun Heo 		return pt;
384284193c07STejun Heo 
384384193c07STejun Heo 	/*
384484193c07STejun Heo 	 * Before workqueue_init_topology(), only SYSTEM is available which is
384584193c07STejun Heo 	 * initialized in workqueue_init_early().
384684193c07STejun Heo 	 */
384784193c07STejun Heo 	pt = &wq_pod_types[WQ_AFFN_SYSTEM];
384884193c07STejun Heo 	BUG_ON(!pt->nr_pods);
384984193c07STejun Heo 	return pt;
385084193c07STejun Heo }
385184193c07STejun Heo 
38527a4e344cSTejun Heo /**
38537a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
38547a4e344cSTejun Heo  * @pool: worker_pool to initialize
38557a4e344cSTejun Heo  *
3856402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3857d185af30SYacine Belkadi  *
3858d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
385929c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
386029c91e99STejun Heo  * on @pool safely to release it.
38617a4e344cSTejun Heo  */
38627a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
38634e1a1f9aSTejun Heo {
3864a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_init(&pool->lock);
386529c91e99STejun Heo 	pool->id = -1;
386629c91e99STejun Heo 	pool->cpu = -1;
3867f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
38684e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
386982607adcSTejun Heo 	pool->watchdog_ts = jiffies;
38704e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
38714e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
38724e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
38734e1a1f9aSTejun Heo 
387432a6c723SKees Cook 	timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
38753f959aa3SValentin Schneider 	INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
38764e1a1f9aSTejun Heo 
387732a6c723SKees Cook 	timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
38784e1a1f9aSTejun Heo 
3879da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
3880e02b9312SValentin Schneider 	INIT_LIST_HEAD(&pool->dying_workers);
38817a4e344cSTejun Heo 
38827cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
388329c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
388429c91e99STejun Heo 	pool->refcnt = 1;
388529c91e99STejun Heo 
388629c91e99STejun Heo 	/* shouldn't fail above this point */
3887be69d00dSThomas Gleixner 	pool->attrs = alloc_workqueue_attrs();
38887a4e344cSTejun Heo 	if (!pool->attrs)
38897a4e344cSTejun Heo 		return -ENOMEM;
38905de7a03cSTejun Heo 
38915de7a03cSTejun Heo 	wqattrs_clear_for_pool(pool->attrs);
38925de7a03cSTejun Heo 
38937a4e344cSTejun Heo 	return 0;
38944e1a1f9aSTejun Heo }
38954e1a1f9aSTejun Heo 
3896669de8bdSBart Van Assche #ifdef CONFIG_LOCKDEP
3897669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3898669de8bdSBart Van Assche {
3899669de8bdSBart Van Assche 	char *lock_name;
3900669de8bdSBart Van Assche 
3901669de8bdSBart Van Assche 	lockdep_register_key(&wq->key);
3902669de8bdSBart Van Assche 	lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3903669de8bdSBart Van Assche 	if (!lock_name)
3904669de8bdSBart Van Assche 		lock_name = wq->name;
390569a106c0SQian Cai 
390669a106c0SQian Cai 	wq->lock_name = lock_name;
3907669de8bdSBart Van Assche 	lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3908669de8bdSBart Van Assche }
3909669de8bdSBart Van Assche 
3910669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3911669de8bdSBart Van Assche {
3912669de8bdSBart Van Assche 	lockdep_unregister_key(&wq->key);
3913669de8bdSBart Van Assche }
3914669de8bdSBart Van Assche 
3915669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3916669de8bdSBart Van Assche {
3917669de8bdSBart Van Assche 	if (wq->lock_name != wq->name)
3918669de8bdSBart Van Assche 		kfree(wq->lock_name);
3919669de8bdSBart Van Assche }
3920669de8bdSBart Van Assche #else
3921669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3922669de8bdSBart Van Assche {
3923669de8bdSBart Van Assche }
3924669de8bdSBart Van Assche 
3925669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3926669de8bdSBart Van Assche {
3927669de8bdSBart Van Assche }
3928669de8bdSBart Van Assche 
3929669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3930669de8bdSBart Van Assche {
3931669de8bdSBart Van Assche }
3932669de8bdSBart Van Assche #endif
3933669de8bdSBart Van Assche 
3934e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
3935e2dca7adSTejun Heo {
3936e2dca7adSTejun Heo 	struct workqueue_struct *wq =
3937e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
3938e2dca7adSTejun Heo 
3939669de8bdSBart Van Assche 	wq_free_lockdep(wq);
3940ee1ceef7STejun Heo 	free_percpu(wq->cpu_pwq);
3941e2dca7adSTejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
3942e2dca7adSTejun Heo 	kfree(wq);
3943e2dca7adSTejun Heo }
3944e2dca7adSTejun Heo 
394529c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
394629c91e99STejun Heo {
394729c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
394829c91e99STejun Heo 
39497cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
395029c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
395129c91e99STejun Heo 	kfree(pool);
395229c91e99STejun Heo }
395329c91e99STejun Heo 
395429c91e99STejun Heo /**
395529c91e99STejun Heo  * put_unbound_pool - put a worker_pool
395629c91e99STejun Heo  * @pool: worker_pool to put
395729c91e99STejun Heo  *
395824acfb71SThomas Gleixner  * Put @pool.  If its refcnt reaches zero, it gets destroyed in RCU
3959c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3960c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3961c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
3962a892caccSTejun Heo  *
3963a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
396429c91e99STejun Heo  */
396529c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
396629c91e99STejun Heo {
396760f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
396829c91e99STejun Heo 	struct worker *worker;
39699680540cSYang Yingliang 	LIST_HEAD(cull_list);
3970e02b9312SValentin Schneider 
3971a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3972a892caccSTejun Heo 
3973a892caccSTejun Heo 	if (--pool->refcnt)
397429c91e99STejun Heo 		return;
397529c91e99STejun Heo 
397629c91e99STejun Heo 	/* sanity checks */
397761d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
3978a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
397929c91e99STejun Heo 		return;
398029c91e99STejun Heo 
398129c91e99STejun Heo 	/* release id and unhash */
398229c91e99STejun Heo 	if (pool->id >= 0)
398329c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
398429c91e99STejun Heo 	hash_del(&pool->hash_node);
398529c91e99STejun Heo 
3986c5aa87bbSTejun Heo 	/*
3987692b4825STejun Heo 	 * Become the manager and destroy all workers.  This prevents
3988692b4825STejun Heo 	 * @pool's workers from blocking on attach_mutex.  We're the last
3989692b4825STejun Heo 	 * manager and @pool gets freed with the flag set.
39909ab03be4SValentin Schneider 	 *
39919ab03be4SValentin Schneider 	 * Having a concurrent manager is quite unlikely to happen as we can
39929ab03be4SValentin Schneider 	 * only get here with
39939ab03be4SValentin Schneider 	 *   pwq->refcnt == pool->refcnt == 0
39949ab03be4SValentin Schneider 	 * which implies no work queued to the pool, which implies no worker can
39959ab03be4SValentin Schneider 	 * become the manager. However a worker could have taken the role of
39969ab03be4SValentin Schneider 	 * manager before the refcnts dropped to 0, since maybe_create_worker()
39979ab03be4SValentin Schneider 	 * drops pool->lock
3998c5aa87bbSTejun Heo 	 */
39999ab03be4SValentin Schneider 	while (true) {
40009ab03be4SValentin Schneider 		rcuwait_wait_event(&manager_wait,
40019ab03be4SValentin Schneider 				   !(pool->flags & POOL_MANAGER_ACTIVE),
4002d8bb65abSSebastian Andrzej Siewior 				   TASK_UNINTERRUPTIBLE);
4003e02b9312SValentin Schneider 
4004e02b9312SValentin Schneider 		mutex_lock(&wq_pool_attach_mutex);
40059ab03be4SValentin Schneider 		raw_spin_lock_irq(&pool->lock);
40069ab03be4SValentin Schneider 		if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
4007692b4825STejun Heo 			pool->flags |= POOL_MANAGER_ACTIVE;
40089ab03be4SValentin Schneider 			break;
40099ab03be4SValentin Schneider 		}
40109ab03be4SValentin Schneider 		raw_spin_unlock_irq(&pool->lock);
4011e02b9312SValentin Schneider 		mutex_unlock(&wq_pool_attach_mutex);
40129ab03be4SValentin Schneider 	}
4013692b4825STejun Heo 
40141037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
4015e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
401629c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
4017a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
401860f5a4bcSLai Jiangshan 
4019e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
4020e02b9312SValentin Schneider 
4021e02b9312SValentin Schneider 	if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
402260f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
40231258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
402460f5a4bcSLai Jiangshan 
402560f5a4bcSLai Jiangshan 	if (pool->detach_completion)
402660f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
402760f5a4bcSLai Jiangshan 
402829c91e99STejun Heo 	/* shut down the timers */
402929c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
40303f959aa3SValentin Schneider 	cancel_work_sync(&pool->idle_cull_work);
403129c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
403229c91e99STejun Heo 
403324acfb71SThomas Gleixner 	/* RCU protected to allow dereferences from get_work_pool() */
403425b00775SPaul E. McKenney 	call_rcu(&pool->rcu, rcu_free_pool);
403529c91e99STejun Heo }
403629c91e99STejun Heo 
403729c91e99STejun Heo /**
403829c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
403929c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
404029c91e99STejun Heo  *
404129c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
404229c91e99STejun Heo  * reference count and return it.  If there already is a matching
404329c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
4044d185af30SYacine Belkadi  * create a new one.
4045a892caccSTejun Heo  *
4046a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
4047d185af30SYacine Belkadi  *
4048d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
4049d185af30SYacine Belkadi  * On failure, %NULL.
405029c91e99STejun Heo  */
405129c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
405229c91e99STejun Heo {
405384193c07STejun Heo 	struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_NUMA];
405429c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
405529c91e99STejun Heo 	struct worker_pool *pool;
405684193c07STejun Heo 	int pod, node = NUMA_NO_NODE;
405729c91e99STejun Heo 
4058a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
405929c91e99STejun Heo 
406029c91e99STejun Heo 	/* do we already have a matching pool? */
406129c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
406229c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
406329c91e99STejun Heo 			pool->refcnt++;
40643fb1823cSLai Jiangshan 			return pool;
406529c91e99STejun Heo 		}
406629c91e99STejun Heo 	}
406729c91e99STejun Heo 
40689546b29eSTejun Heo 	/* If __pod_cpumask is contained inside a NUMA pod, that's our node */
406984193c07STejun Heo 	for (pod = 0; pod < pt->nr_pods; pod++) {
40709546b29eSTejun Heo 		if (cpumask_subset(attrs->__pod_cpumask, pt->pod_cpus[pod])) {
407184193c07STejun Heo 			node = pt->pod_node[pod];
4072e2273584SXunlei Pang 			break;
4073e2273584SXunlei Pang 		}
4074e2273584SXunlei Pang 	}
4075e2273584SXunlei Pang 
407629c91e99STejun Heo 	/* nope, create a new one */
407784193c07STejun Heo 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, node);
407829c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
407929c91e99STejun Heo 		goto fail;
408029c91e99STejun Heo 
408184193c07STejun Heo 	pool->node = node;
40825de7a03cSTejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
40835de7a03cSTejun Heo 	wqattrs_clear_for_pool(pool->attrs);
40842865a8fbSShaohua Li 
408529c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
408629c91e99STejun Heo 		goto fail;
408729c91e99STejun Heo 
408829c91e99STejun Heo 	/* create and start the initial worker */
40893347fa09STejun Heo 	if (wq_online && !create_worker(pool))
409029c91e99STejun Heo 		goto fail;
409129c91e99STejun Heo 
409229c91e99STejun Heo 	/* install */
409329c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
40943fb1823cSLai Jiangshan 
409529c91e99STejun Heo 	return pool;
409629c91e99STejun Heo fail:
409729c91e99STejun Heo 	if (pool)
409829c91e99STejun Heo 		put_unbound_pool(pool);
409929c91e99STejun Heo 	return NULL;
410029c91e99STejun Heo }
410129c91e99STejun Heo 
41028864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
41038864b4e5STejun Heo {
41048864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
41058864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
41068864b4e5STejun Heo }
41078864b4e5STejun Heo 
41088864b4e5STejun Heo /*
4109967b494eSTejun Heo  * Scheduled on pwq_release_worker by put_pwq() when an unbound pwq hits zero
4110967b494eSTejun Heo  * refcnt and needs to be destroyed.
41118864b4e5STejun Heo  */
4112687a9aa5STejun Heo static void pwq_release_workfn(struct kthread_work *work)
41138864b4e5STejun Heo {
41148864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
4115687a9aa5STejun Heo 						  release_work);
41168864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
41178864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
4118b42b0bddSYang Yingliang 	bool is_last = false;
41198864b4e5STejun Heo 
4120b42b0bddSYang Yingliang 	/*
4121687a9aa5STejun Heo 	 * When @pwq is not linked, it doesn't hold any reference to the
4122b42b0bddSYang Yingliang 	 * @wq, and @wq is invalid to access.
4123b42b0bddSYang Yingliang 	 */
4124b42b0bddSYang Yingliang 	if (!list_empty(&pwq->pwqs_node)) {
41253c25a55dSLai Jiangshan 		mutex_lock(&wq->mutex);
41268864b4e5STejun Heo 		list_del_rcu(&pwq->pwqs_node);
4127bc0caf09STejun Heo 		is_last = list_empty(&wq->pwqs);
41283c25a55dSLai Jiangshan 		mutex_unlock(&wq->mutex);
4129b42b0bddSYang Yingliang 	}
41308864b4e5STejun Heo 
4131687a9aa5STejun Heo 	if (wq->flags & WQ_UNBOUND) {
4132a892caccSTejun Heo 		mutex_lock(&wq_pool_mutex);
41338864b4e5STejun Heo 		put_unbound_pool(pool);
4134a892caccSTejun Heo 		mutex_unlock(&wq_pool_mutex);
4135687a9aa5STejun Heo 	}
4136a892caccSTejun Heo 
413725b00775SPaul E. McKenney 	call_rcu(&pwq->rcu, rcu_free_pwq);
41388864b4e5STejun Heo 
41398864b4e5STejun Heo 	/*
41408864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
4141e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
41428864b4e5STejun Heo 	 */
4143669de8bdSBart Van Assche 	if (is_last) {
4144669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
414525b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
41466029a918STejun Heo 	}
4147669de8bdSBart Van Assche }
41488864b4e5STejun Heo 
41490fbd95aaSTejun Heo /**
4150699ce097STejun Heo  * pwq_adjust_max_active - update a pwq's max_active to the current setting
41510fbd95aaSTejun Heo  * @pwq: target pool_workqueue
41520fbd95aaSTejun Heo  *
4153699ce097STejun Heo  * If @pwq isn't freezing, set @pwq->max_active to the associated
4154f97a4a1aSLai Jiangshan  * workqueue's saved_max_active and activate inactive work items
4155699ce097STejun Heo  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
41560fbd95aaSTejun Heo  */
4157699ce097STejun Heo static void pwq_adjust_max_active(struct pool_workqueue *pwq)
41580fbd95aaSTejun Heo {
4159699ce097STejun Heo 	struct workqueue_struct *wq = pwq->wq;
4160699ce097STejun Heo 	bool freezable = wq->flags & WQ_FREEZABLE;
41613347fa09STejun Heo 	unsigned long flags;
4162699ce097STejun Heo 
4163699ce097STejun Heo 	/* for @wq->saved_max_active */
4164a357fc03SLai Jiangshan 	lockdep_assert_held(&wq->mutex);
4165699ce097STejun Heo 
4166699ce097STejun Heo 	/* fast exit for non-freezable wqs */
4167699ce097STejun Heo 	if (!freezable && pwq->max_active == wq->saved_max_active)
4168699ce097STejun Heo 		return;
4169699ce097STejun Heo 
41703347fa09STejun Heo 	/* this function can be called during early boot w/ irq disabled */
4171a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pwq->pool->lock, flags);
4172699ce097STejun Heo 
417374b414eaSLai Jiangshan 	/*
417474b414eaSLai Jiangshan 	 * During [un]freezing, the caller is responsible for ensuring that
417574b414eaSLai Jiangshan 	 * this function is called at least once after @workqueue_freezing
417674b414eaSLai Jiangshan 	 * is updated and visible.
417774b414eaSLai Jiangshan 	 */
417874b414eaSLai Jiangshan 	if (!freezable || !workqueue_freezing) {
4179699ce097STejun Heo 		pwq->max_active = wq->saved_max_active;
41800fbd95aaSTejun Heo 
4181f97a4a1aSLai Jiangshan 		while (!list_empty(&pwq->inactive_works) &&
41820219a352STejun Heo 		       pwq->nr_active < pwq->max_active)
4183f97a4a1aSLai Jiangshan 			pwq_activate_first_inactive(pwq);
4184951a078aSLai Jiangshan 
41850219a352STejun Heo 		kick_pool(pwq->pool);
4186699ce097STejun Heo 	} else {
4187699ce097STejun Heo 		pwq->max_active = 0;
4188699ce097STejun Heo 	}
4189699ce097STejun Heo 
4190a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
41910fbd95aaSTejun Heo }
41920fbd95aaSTejun Heo 
419367dc8325SCai Huoqing /* initialize newly allocated @pwq which is associated with @wq and @pool */
4194f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
4195f147f29eSTejun Heo 		     struct worker_pool *pool)
4196d2c1d404STejun Heo {
4197d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
4198d2c1d404STejun Heo 
4199e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
4200e50aba9aSTejun Heo 
4201d2c1d404STejun Heo 	pwq->pool = pool;
4202d2c1d404STejun Heo 	pwq->wq = wq;
4203d2c1d404STejun Heo 	pwq->flush_color = -1;
42048864b4e5STejun Heo 	pwq->refcnt = 1;
4205f97a4a1aSLai Jiangshan 	INIT_LIST_HEAD(&pwq->inactive_works);
42061befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
4207d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
4208687a9aa5STejun Heo 	kthread_init_work(&pwq->release_work, pwq_release_workfn);
4209f147f29eSTejun Heo }
4210d2c1d404STejun Heo 
4211f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
42121befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
4213f147f29eSTejun Heo {
4214f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
4215f147f29eSTejun Heo 
4216f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
421775ccf595STejun Heo 
42181befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
42191befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
42201befcf30STejun Heo 		return;
42211befcf30STejun Heo 
422229b1cb41SLai Jiangshan 	/* set the matching work_color */
422375ccf595STejun Heo 	pwq->work_color = wq->work_color;
4224983ca25eSTejun Heo 
4225983ca25eSTejun Heo 	/* sync max_active to the current setting */
4226983ca25eSTejun Heo 	pwq_adjust_max_active(pwq);
4227983ca25eSTejun Heo 
4228983ca25eSTejun Heo 	/* link in @pwq */
42299e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
4230df2d5ae4STejun Heo }
42316029a918STejun Heo 
4232f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
4233f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
4234f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
4235f147f29eSTejun Heo {
4236f147f29eSTejun Heo 	struct worker_pool *pool;
4237f147f29eSTejun Heo 	struct pool_workqueue *pwq;
4238f147f29eSTejun Heo 
4239f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
4240f147f29eSTejun Heo 
4241f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
4242f147f29eSTejun Heo 	if (!pool)
4243f147f29eSTejun Heo 		return NULL;
4244f147f29eSTejun Heo 
4245e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
4246f147f29eSTejun Heo 	if (!pwq) {
4247f147f29eSTejun Heo 		put_unbound_pool(pool);
4248f147f29eSTejun Heo 		return NULL;
4249f147f29eSTejun Heo 	}
4250f147f29eSTejun Heo 
4251f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
4252f147f29eSTejun Heo 	return pwq;
4253d2c1d404STejun Heo }
4254d2c1d404STejun Heo 
42554c16bd32STejun Heo /**
4256fef59c9cSTejun Heo  * wq_calc_pod_cpumask - calculate a wq_attrs' cpumask for a pod
4257042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
425884193c07STejun Heo  * @cpu: the target CPU
42594c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
42604c16bd32STejun Heo  *
4261fef59c9cSTejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @pod. If
4262fef59c9cSTejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during calculation.
42639546b29eSTejun Heo  * The result is stored in @attrs->__pod_cpumask.
42644c16bd32STejun Heo  *
4265fef59c9cSTejun Heo  * If pod affinity is not enabled, @attrs->cpumask is always used. If enabled
4266fef59c9cSTejun Heo  * and @pod has online CPUs requested by @attrs, the returned cpumask is the
4267fef59c9cSTejun Heo  * intersection of the possible CPUs of @pod and @attrs->cpumask.
42684c16bd32STejun Heo  *
4269fef59c9cSTejun Heo  * The caller is responsible for ensuring that the cpumask of @pod stays stable.
42704c16bd32STejun Heo  */
42719546b29eSTejun Heo static void wq_calc_pod_cpumask(struct workqueue_attrs *attrs, int cpu,
42729546b29eSTejun Heo 				int cpu_going_down)
42734c16bd32STejun Heo {
427484193c07STejun Heo 	const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
427584193c07STejun Heo 	int pod = pt->cpu_pod[cpu];
42764c16bd32STejun Heo 
4277fef59c9cSTejun Heo 	/* does @pod have any online CPUs @attrs wants? */
42789546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, pt->pod_cpus[pod], attrs->cpumask);
42799546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, attrs->__pod_cpumask, cpu_online_mask);
42804c16bd32STejun Heo 	if (cpu_going_down >= 0)
42819546b29eSTejun Heo 		cpumask_clear_cpu(cpu_going_down, attrs->__pod_cpumask);
42824c16bd32STejun Heo 
42839546b29eSTejun Heo 	if (cpumask_empty(attrs->__pod_cpumask)) {
42849546b29eSTejun Heo 		cpumask_copy(attrs->__pod_cpumask, attrs->cpumask);
428584193c07STejun Heo 		return;
428684193c07STejun Heo 	}
42874c16bd32STejun Heo 
4288fef59c9cSTejun Heo 	/* yeap, return possible CPUs in @pod that @attrs wants */
42899546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, attrs->cpumask, pt->pod_cpus[pod]);
42901ad0f0a7SMichael Bringmann 
42919546b29eSTejun Heo 	if (cpumask_empty(attrs->__pod_cpumask))
42921ad0f0a7SMichael Bringmann 		pr_warn_once("WARNING: workqueue cpumask: online intersect > "
42931ad0f0a7SMichael Bringmann 				"possible intersect\n");
42944c16bd32STejun Heo }
42954c16bd32STejun Heo 
4296636b927eSTejun Heo /* install @pwq into @wq's cpu_pwq and return the old pwq */
4297636b927eSTejun Heo static struct pool_workqueue *install_unbound_pwq(struct workqueue_struct *wq,
4298636b927eSTejun Heo 					int cpu, struct pool_workqueue *pwq)
42991befcf30STejun Heo {
43001befcf30STejun Heo 	struct pool_workqueue *old_pwq;
43011befcf30STejun Heo 
43025b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
43031befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
43041befcf30STejun Heo 
43051befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
43061befcf30STejun Heo 	link_pwq(pwq);
43071befcf30STejun Heo 
4308636b927eSTejun Heo 	old_pwq = rcu_access_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu));
4309636b927eSTejun Heo 	rcu_assign_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu), pwq);
43101befcf30STejun Heo 	return old_pwq;
43111befcf30STejun Heo }
43121befcf30STejun Heo 
43132d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
43142d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
43152d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
43162d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
4317042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
43182d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
43192d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
43202d5f0764SLai Jiangshan };
43212d5f0764SLai Jiangshan 
43222d5f0764SLai Jiangshan /* free the resources after success or abort */
43232d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
43242d5f0764SLai Jiangshan {
43252d5f0764SLai Jiangshan 	if (ctx) {
4326636b927eSTejun Heo 		int cpu;
43272d5f0764SLai Jiangshan 
4328636b927eSTejun Heo 		for_each_possible_cpu(cpu)
4329636b927eSTejun Heo 			put_pwq_unlocked(ctx->pwq_tbl[cpu]);
43302d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
43312d5f0764SLai Jiangshan 
43322d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
43332d5f0764SLai Jiangshan 
43342d5f0764SLai Jiangshan 		kfree(ctx);
43352d5f0764SLai Jiangshan 	}
43362d5f0764SLai Jiangshan }
43372d5f0764SLai Jiangshan 
43382d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
43392d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
43402d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
434199c621efSLai Jiangshan 		      const struct workqueue_attrs *attrs,
434299c621efSLai Jiangshan 		      const cpumask_var_t unbound_cpumask)
43432d5f0764SLai Jiangshan {
43442d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
43459546b29eSTejun Heo 	struct workqueue_attrs *new_attrs;
4346636b927eSTejun Heo 	int cpu;
43472d5f0764SLai Jiangshan 
43482d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
43492d5f0764SLai Jiangshan 
435084193c07STejun Heo 	if (WARN_ON(attrs->affn_scope < 0 ||
435184193c07STejun Heo 		    attrs->affn_scope >= WQ_AFFN_NR_TYPES))
435284193c07STejun Heo 		return ERR_PTR(-EINVAL);
435384193c07STejun Heo 
4354636b927eSTejun Heo 	ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_cpu_ids), GFP_KERNEL);
43552d5f0764SLai Jiangshan 
4356be69d00dSThomas Gleixner 	new_attrs = alloc_workqueue_attrs();
43579546b29eSTejun Heo 	if (!ctx || !new_attrs)
43582d5f0764SLai Jiangshan 		goto out_free;
43592d5f0764SLai Jiangshan 
4360042f7df1SLai Jiangshan 	/*
43612d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
43622d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
43632d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
43642d5f0764SLai Jiangshan 	 */
43650f36ee24STejun Heo 	copy_workqueue_attrs(new_attrs, attrs);
43660f36ee24STejun Heo 	wqattrs_actualize_cpumask(new_attrs, unbound_cpumask);
43679546b29eSTejun Heo 	cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
43682d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
43692d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
43702d5f0764SLai Jiangshan 		goto out_free;
43712d5f0764SLai Jiangshan 
4372636b927eSTejun Heo 	for_each_possible_cpu(cpu) {
4373af73f5c9STejun Heo 		if (new_attrs->ordered) {
43742d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
4375636b927eSTejun Heo 			ctx->pwq_tbl[cpu] = ctx->dfl_pwq;
4376636b927eSTejun Heo 		} else {
43779546b29eSTejun Heo 			wq_calc_pod_cpumask(new_attrs, cpu, -1);
43789546b29eSTejun Heo 			ctx->pwq_tbl[cpu] = alloc_unbound_pwq(wq, new_attrs);
4379636b927eSTejun Heo 			if (!ctx->pwq_tbl[cpu])
4380636b927eSTejun Heo 				goto out_free;
43812d5f0764SLai Jiangshan 		}
43822d5f0764SLai Jiangshan 	}
43832d5f0764SLai Jiangshan 
4384042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
4385042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
4386042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
43879546b29eSTejun Heo 	cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
43882d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
4389042f7df1SLai Jiangshan 
43902d5f0764SLai Jiangshan 	ctx->wq = wq;
43912d5f0764SLai Jiangshan 	return ctx;
43922d5f0764SLai Jiangshan 
43932d5f0764SLai Jiangshan out_free:
43942d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
43952d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
439684193c07STejun Heo 	return ERR_PTR(-ENOMEM);
43972d5f0764SLai Jiangshan }
43982d5f0764SLai Jiangshan 
43992d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
44002d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
44012d5f0764SLai Jiangshan {
4402636b927eSTejun Heo 	int cpu;
44032d5f0764SLai Jiangshan 
44042d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
44052d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
44062d5f0764SLai Jiangshan 
44072d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
44082d5f0764SLai Jiangshan 
44092d5f0764SLai Jiangshan 	/* save the previous pwq and install the new one */
4410636b927eSTejun Heo 	for_each_possible_cpu(cpu)
4411636b927eSTejun Heo 		ctx->pwq_tbl[cpu] = install_unbound_pwq(ctx->wq, cpu,
4412636b927eSTejun Heo 							ctx->pwq_tbl[cpu]);
44132d5f0764SLai Jiangshan 
44142d5f0764SLai Jiangshan 	/* @dfl_pwq might not have been used, ensure it's linked */
44152d5f0764SLai Jiangshan 	link_pwq(ctx->dfl_pwq);
44162d5f0764SLai Jiangshan 	swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
44172d5f0764SLai Jiangshan 
44182d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
44192d5f0764SLai Jiangshan }
44202d5f0764SLai Jiangshan 
4421a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4422a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
4423a0111cf6SLai Jiangshan {
4424a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
4425a0111cf6SLai Jiangshan 
4426a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
4427a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4428a0111cf6SLai Jiangshan 		return -EINVAL;
4429a0111cf6SLai Jiangshan 
4430a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
44310a94efb5STejun Heo 	if (!list_empty(&wq->pwqs)) {
44320a94efb5STejun Heo 		if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4433a0111cf6SLai Jiangshan 			return -EINVAL;
4434a0111cf6SLai Jiangshan 
44350a94efb5STejun Heo 		wq->flags &= ~__WQ_ORDERED;
44360a94efb5STejun Heo 	}
44370a94efb5STejun Heo 
443899c621efSLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
443984193c07STejun Heo 	if (IS_ERR(ctx))
444084193c07STejun Heo 		return PTR_ERR(ctx);
4441a0111cf6SLai Jiangshan 
4442a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
4443a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
4444a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
4445a0111cf6SLai Jiangshan 
44466201171eSwanghaibin 	return 0;
4447a0111cf6SLai Jiangshan }
4448a0111cf6SLai Jiangshan 
44499e8cd2f5STejun Heo /**
44509e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
44519e8cd2f5STejun Heo  * @wq: the target workqueue
44529e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
44539e8cd2f5STejun Heo  *
4454fef59c9cSTejun Heo  * Apply @attrs to an unbound workqueue @wq. Unless disabled, this function maps
4455fef59c9cSTejun Heo  * a separate pwq to each CPU pod with possibles CPUs in @attrs->cpumask so that
4456fef59c9cSTejun Heo  * work items are affine to the pod it was issued on. Older pwqs are released as
4457fef59c9cSTejun Heo  * in-flight work items finish. Note that a work item which repeatedly requeues
4458fef59c9cSTejun Heo  * itself back-to-back will stay on its current pwq.
44599e8cd2f5STejun Heo  *
4460d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
4461d185af30SYacine Belkadi  *
4462ffd8bea8SSebastian Andrzej Siewior  * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
4463509b3204SDaniel Jordan  *
4464d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
44659e8cd2f5STejun Heo  */
4466513c98d0SDaniel Jordan int apply_workqueue_attrs(struct workqueue_struct *wq,
44679e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
44689e8cd2f5STejun Heo {
4469a0111cf6SLai Jiangshan 	int ret;
44709e8cd2f5STejun Heo 
4471509b3204SDaniel Jordan 	lockdep_assert_cpus_held();
4472509b3204SDaniel Jordan 
4473509b3204SDaniel Jordan 	mutex_lock(&wq_pool_mutex);
4474a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
4475509b3204SDaniel Jordan 	mutex_unlock(&wq_pool_mutex);
44762d5f0764SLai Jiangshan 
44772d5f0764SLai Jiangshan 	return ret;
44789e8cd2f5STejun Heo }
44799e8cd2f5STejun Heo 
44804c16bd32STejun Heo /**
4481fef59c9cSTejun Heo  * wq_update_pod - update pod affinity of a wq for CPU hot[un]plug
44824c16bd32STejun Heo  * @wq: the target workqueue
44834cbfd3deSTejun Heo  * @cpu: the CPU to update pool association for
44844cbfd3deSTejun Heo  * @hotplug_cpu: the CPU coming up or going down
44854c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
44864c16bd32STejun Heo  *
44874c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
4488fef59c9cSTejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update pod affinity of
44894c16bd32STejun Heo  * @wq accordingly.
44904c16bd32STejun Heo  *
44914c16bd32STejun Heo  *
4492fef59c9cSTejun Heo  * If pod affinity can't be adjusted due to memory allocation failure, it falls
4493fef59c9cSTejun Heo  * back to @wq->dfl_pwq which may not be optimal but is always correct.
4494fef59c9cSTejun Heo  *
4495fef59c9cSTejun Heo  * Note that when the last allowed CPU of a pod goes offline for a workqueue
4496fef59c9cSTejun Heo  * with a cpumask spanning multiple pods, the workers which were already
4497fef59c9cSTejun Heo  * executing the work items for the workqueue will lose their CPU affinity and
4498fef59c9cSTejun Heo  * may execute on any CPU. This is similar to how per-cpu workqueues behave on
4499fef59c9cSTejun Heo  * CPU_DOWN. If a workqueue user wants strict affinity, it's the user's
4500fef59c9cSTejun Heo  * responsibility to flush the work item from CPU_DOWN_PREPARE.
45014c16bd32STejun Heo  */
4502fef59c9cSTejun Heo static void wq_update_pod(struct workqueue_struct *wq, int cpu,
45034cbfd3deSTejun Heo 			  int hotplug_cpu, bool online)
45044c16bd32STejun Heo {
45054cbfd3deSTejun Heo 	int off_cpu = online ? -1 : hotplug_cpu;
45064c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
45074c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
45084c16bd32STejun Heo 
45094c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
45104c16bd32STejun Heo 
451184193c07STejun Heo 	if (!(wq->flags & WQ_UNBOUND) || wq->unbound_attrs->ordered)
45124c16bd32STejun Heo 		return;
45134c16bd32STejun Heo 
45144c16bd32STejun Heo 	/*
45154c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
45164c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
45174c16bd32STejun Heo 	 * CPU hotplug exclusion.
45184c16bd32STejun Heo 	 */
4519fef59c9cSTejun Heo 	target_attrs = wq_update_pod_attrs_buf;
45204c16bd32STejun Heo 
45214c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
45220f36ee24STejun Heo 	wqattrs_actualize_cpumask(target_attrs, wq_unbound_cpumask);
45234c16bd32STejun Heo 
4524636b927eSTejun Heo 	/* nothing to do if the target cpumask matches the current pwq */
45259546b29eSTejun Heo 	wq_calc_pod_cpumask(target_attrs, cpu, off_cpu);
4526636b927eSTejun Heo 	pwq = rcu_dereference_protected(*per_cpu_ptr(wq->cpu_pwq, cpu),
4527636b927eSTejun Heo 					lockdep_is_held(&wq_pool_mutex));
45289546b29eSTejun Heo 	if (wqattrs_equal(target_attrs, pwq->pool->attrs))
4529f7142ed4SLai Jiangshan 		return;
45304c16bd32STejun Heo 
45314c16bd32STejun Heo 	/* create a new pwq */
45324c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
45334c16bd32STejun Heo 	if (!pwq) {
4534fef59c9cSTejun Heo 		pr_warn("workqueue: allocation failed while updating CPU pod affinity of \"%s\"\n",
45354c16bd32STejun Heo 			wq->name);
453677f300b1SDaeseok Youn 		goto use_dfl_pwq;
45374c16bd32STejun Heo 	}
45384c16bd32STejun Heo 
4539f7142ed4SLai Jiangshan 	/* Install the new pwq. */
45404c16bd32STejun Heo 	mutex_lock(&wq->mutex);
4541636b927eSTejun Heo 	old_pwq = install_unbound_pwq(wq, cpu, pwq);
45424c16bd32STejun Heo 	goto out_unlock;
45434c16bd32STejun Heo 
45444c16bd32STejun Heo use_dfl_pwq:
4545f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
4546a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
45474c16bd32STejun Heo 	get_pwq(wq->dfl_pwq);
4548a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
4549636b927eSTejun Heo 	old_pwq = install_unbound_pwq(wq, cpu, wq->dfl_pwq);
45504c16bd32STejun Heo out_unlock:
45514c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
45524c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
45534c16bd32STejun Heo }
45544c16bd32STejun Heo 
455530cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
45561da177e4SLinus Torvalds {
455749e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
45588a2b7538STejun Heo 	int cpu, ret;
4559e1d8aa9fSFrederic Weisbecker 
4560687a9aa5STejun Heo 	wq->cpu_pwq = alloc_percpu(struct pool_workqueue *);
4561ee1ceef7STejun Heo 	if (!wq->cpu_pwq)
4562687a9aa5STejun Heo 		goto enomem;
456330cdf249STejun Heo 
4564636b927eSTejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
456530cdf249STejun Heo 		for_each_possible_cpu(cpu) {
4566687a9aa5STejun Heo 			struct pool_workqueue **pwq_p =
4567ee1ceef7STejun Heo 				per_cpu_ptr(wq->cpu_pwq, cpu);
4568687a9aa5STejun Heo 			struct worker_pool *pool =
4569687a9aa5STejun Heo 				&(per_cpu_ptr(cpu_worker_pools, cpu)[highpri]);
457030cdf249STejun Heo 
4571687a9aa5STejun Heo 			*pwq_p = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL,
4572687a9aa5STejun Heo 						       pool->node);
4573687a9aa5STejun Heo 			if (!*pwq_p)
4574687a9aa5STejun Heo 				goto enomem;
4575687a9aa5STejun Heo 
4576687a9aa5STejun Heo 			init_pwq(*pwq_p, wq, pool);
4577f147f29eSTejun Heo 
4578f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
4579687a9aa5STejun Heo 			link_pwq(*pwq_p);
4580f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
458130cdf249STejun Heo 		}
458230cdf249STejun Heo 		return 0;
4583509b3204SDaniel Jordan 	}
4584509b3204SDaniel Jordan 
4585ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4586509b3204SDaniel Jordan 	if (wq->flags & __WQ_ORDERED) {
45878a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
45888a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
45898a2b7538STejun Heo 		WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
45908a2b7538STejun Heo 			      wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
45918a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
45929e8cd2f5STejun Heo 	} else {
4593509b3204SDaniel Jordan 		ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
45949e8cd2f5STejun Heo 	}
4595ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4596509b3204SDaniel Jordan 
459764344553SZqiang 	/* for unbound pwq, flush the pwq_release_worker ensures that the
459864344553SZqiang 	 * pwq_release_workfn() completes before calling kfree(wq).
459964344553SZqiang 	 */
460064344553SZqiang 	if (ret)
460164344553SZqiang 		kthread_flush_worker(pwq_release_worker);
460264344553SZqiang 
4603509b3204SDaniel Jordan 	return ret;
4604687a9aa5STejun Heo 
4605687a9aa5STejun Heo enomem:
4606687a9aa5STejun Heo 	if (wq->cpu_pwq) {
46077b42f401SZqiang 		for_each_possible_cpu(cpu) {
46087b42f401SZqiang 			struct pool_workqueue *pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
46097b42f401SZqiang 
46107b42f401SZqiang 			if (pwq)
46117b42f401SZqiang 				kmem_cache_free(pwq_cache, pwq);
46127b42f401SZqiang 		}
4613687a9aa5STejun Heo 		free_percpu(wq->cpu_pwq);
4614687a9aa5STejun Heo 		wq->cpu_pwq = NULL;
4615687a9aa5STejun Heo 	}
4616687a9aa5STejun Heo 	return -ENOMEM;
46170f900049STejun Heo }
46180f900049STejun Heo 
4619f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
4620f3421797STejun Heo 			       const char *name)
4621b71ab8c2STejun Heo {
4622636b927eSTejun Heo 	if (max_active < 1 || max_active > WQ_MAX_ACTIVE)
4623044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4624636b927eSTejun Heo 			max_active, name, 1, WQ_MAX_ACTIVE);
4625b71ab8c2STejun Heo 
4626636b927eSTejun Heo 	return clamp_val(max_active, 1, WQ_MAX_ACTIVE);
4627b71ab8c2STejun Heo }
4628b71ab8c2STejun Heo 
4629983c7515STejun Heo /*
4630983c7515STejun Heo  * Workqueues which may be used during memory reclaim should have a rescuer
4631983c7515STejun Heo  * to guarantee forward progress.
4632983c7515STejun Heo  */
4633983c7515STejun Heo static int init_rescuer(struct workqueue_struct *wq)
4634983c7515STejun Heo {
4635983c7515STejun Heo 	struct worker *rescuer;
4636b92b36eaSDan Carpenter 	int ret;
4637983c7515STejun Heo 
4638983c7515STejun Heo 	if (!(wq->flags & WQ_MEM_RECLAIM))
4639983c7515STejun Heo 		return 0;
4640983c7515STejun Heo 
4641983c7515STejun Heo 	rescuer = alloc_worker(NUMA_NO_NODE);
46424c0736a7SPetr Mladek 	if (!rescuer) {
46434c0736a7SPetr Mladek 		pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
46444c0736a7SPetr Mladek 		       wq->name);
4645983c7515STejun Heo 		return -ENOMEM;
46464c0736a7SPetr Mladek 	}
4647983c7515STejun Heo 
4648983c7515STejun Heo 	rescuer->rescue_wq = wq;
4649b6a46f72SAaron Tomlin 	rescuer->task = kthread_create(rescuer_thread, rescuer, "kworker/R-%s", wq->name);
4650f187b697SSean Fu 	if (IS_ERR(rescuer->task)) {
4651b92b36eaSDan Carpenter 		ret = PTR_ERR(rescuer->task);
46524c0736a7SPetr Mladek 		pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
46534c0736a7SPetr Mladek 		       wq->name, ERR_PTR(ret));
4654983c7515STejun Heo 		kfree(rescuer);
4655b92b36eaSDan Carpenter 		return ret;
4656983c7515STejun Heo 	}
4657983c7515STejun Heo 
4658983c7515STejun Heo 	wq->rescuer = rescuer;
465985f0ab43SJuri Lelli 	if (wq->flags & WQ_UNBOUND)
466085f0ab43SJuri Lelli 		kthread_bind_mask(rescuer->task, wq->unbound_attrs->cpumask);
466185f0ab43SJuri Lelli 	else
4662983c7515STejun Heo 		kthread_bind_mask(rescuer->task, cpu_possible_mask);
4663983c7515STejun Heo 	wake_up_process(rescuer->task);
4664983c7515STejun Heo 
4665983c7515STejun Heo 	return 0;
4666983c7515STejun Heo }
4667983c7515STejun Heo 
4668a2775bbcSMathieu Malaterre __printf(1, 4)
4669669de8bdSBart Van Assche struct workqueue_struct *alloc_workqueue(const char *fmt,
467097e37d7bSTejun Heo 					 unsigned int flags,
4671669de8bdSBart Van Assche 					 int max_active, ...)
46723af24433SOleg Nesterov {
4673ecf6881fSTejun Heo 	va_list args;
46743af24433SOleg Nesterov 	struct workqueue_struct *wq;
467549e3cf44STejun Heo 	struct pool_workqueue *pwq;
467631c89007SAudra Mitchell 	int len;
4677b196be89STejun Heo 
46785c0338c6STejun Heo 	/*
4679fef59c9cSTejun Heo 	 * Unbound && max_active == 1 used to imply ordered, which is no longer
4680fef59c9cSTejun Heo 	 * the case on many machines due to per-pod pools. While
46815c0338c6STejun Heo 	 * alloc_ordered_workqueue() is the right way to create an ordered
4682fef59c9cSTejun Heo 	 * workqueue, keep the previous behavior to avoid subtle breakages.
46835c0338c6STejun Heo 	 */
46845c0338c6STejun Heo 	if ((flags & WQ_UNBOUND) && max_active == 1)
46855c0338c6STejun Heo 		flags |= __WQ_ORDERED;
46865c0338c6STejun Heo 
4687cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
4688cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4689cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
4690cee22a15SViresh Kumar 
4691ecf6881fSTejun Heo 	/* allocate wq and format name */
4692636b927eSTejun Heo 	wq = kzalloc(sizeof(*wq), GFP_KERNEL);
4693b196be89STejun Heo 	if (!wq)
4694d2c1d404STejun Heo 		return NULL;
4695b196be89STejun Heo 
46966029a918STejun Heo 	if (flags & WQ_UNBOUND) {
4697be69d00dSThomas Gleixner 		wq->unbound_attrs = alloc_workqueue_attrs();
46986029a918STejun Heo 		if (!wq->unbound_attrs)
46996029a918STejun Heo 			goto err_free_wq;
47006029a918STejun Heo 	}
47016029a918STejun Heo 
4702669de8bdSBart Van Assche 	va_start(args, max_active);
470331c89007SAudra Mitchell 	len = vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4704b196be89STejun Heo 	va_end(args);
47053af24433SOleg Nesterov 
470631c89007SAudra Mitchell 	if (len >= WQ_NAME_LEN)
470731c89007SAudra Mitchell 		pr_warn_once("workqueue: name exceeds WQ_NAME_LEN. Truncating to: %s\n", wq->name);
470831c89007SAudra Mitchell 
4709d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
4710b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
47113af24433SOleg Nesterov 
4712b196be89STejun Heo 	/* init wq */
471397e37d7bSTejun Heo 	wq->flags = flags;
4714a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
47153c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
4716112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
471730cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
471873f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
471973f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
4720493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
47213af24433SOleg Nesterov 
4722669de8bdSBart Van Assche 	wq_init_lockdep(wq);
4723cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
47243af24433SOleg Nesterov 
472530cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
472682efcab3SBart Van Assche 		goto err_unreg_lockdep;
47271537663fSTejun Heo 
472840c17f75STejun Heo 	if (wq_online && init_rescuer(wq) < 0)
4729d2c1d404STejun Heo 		goto err_destroy;
4730e22bee78STejun Heo 
4731226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4732226223abSTejun Heo 		goto err_destroy;
4733226223abSTejun Heo 
47346af8bf3dSOleg Nesterov 	/*
473568e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
473668e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
473768e13a67SLai Jiangshan 	 * list.
47386af8bf3dSOleg Nesterov 	 */
473968e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4740a0a1a5fdSTejun Heo 
4741a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
474249e3cf44STejun Heo 	for_each_pwq(pwq, wq)
4743699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4744a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4745a0a1a5fdSTejun Heo 
4746e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
4747a0a1a5fdSTejun Heo 
474868e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
47493af24433SOleg Nesterov 
47503af24433SOleg Nesterov 	return wq;
4751d2c1d404STejun Heo 
475282efcab3SBart Van Assche err_unreg_lockdep:
4753009bb421SBart Van Assche 	wq_unregister_lockdep(wq);
4754009bb421SBart Van Assche 	wq_free_lockdep(wq);
475582efcab3SBart Van Assche err_free_wq:
47566029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
47574690c4abSTejun Heo 	kfree(wq);
4758d2c1d404STejun Heo 	return NULL;
4759d2c1d404STejun Heo err_destroy:
4760d2c1d404STejun Heo 	destroy_workqueue(wq);
47614690c4abSTejun Heo 	return NULL;
47621da177e4SLinus Torvalds }
4763669de8bdSBart Van Assche EXPORT_SYMBOL_GPL(alloc_workqueue);
47641da177e4SLinus Torvalds 
4765c29eb853STejun Heo static bool pwq_busy(struct pool_workqueue *pwq)
4766c29eb853STejun Heo {
4767c29eb853STejun Heo 	int i;
4768c29eb853STejun Heo 
4769c29eb853STejun Heo 	for (i = 0; i < WORK_NR_COLORS; i++)
4770c29eb853STejun Heo 		if (pwq->nr_in_flight[i])
4771c29eb853STejun Heo 			return true;
4772c29eb853STejun Heo 
4773c29eb853STejun Heo 	if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4774c29eb853STejun Heo 		return true;
4775f97a4a1aSLai Jiangshan 	if (pwq->nr_active || !list_empty(&pwq->inactive_works))
4776c29eb853STejun Heo 		return true;
4777c29eb853STejun Heo 
4778c29eb853STejun Heo 	return false;
4779c29eb853STejun Heo }
4780c29eb853STejun Heo 
47813af24433SOleg Nesterov /**
47823af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
47833af24433SOleg Nesterov  * @wq: target workqueue
47843af24433SOleg Nesterov  *
47853af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
47863af24433SOleg Nesterov  */
47873af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
47883af24433SOleg Nesterov {
478949e3cf44STejun Heo 	struct pool_workqueue *pwq;
4790636b927eSTejun Heo 	int cpu;
47913af24433SOleg Nesterov 
4792def98c84STejun Heo 	/*
4793def98c84STejun Heo 	 * Remove it from sysfs first so that sanity check failure doesn't
4794def98c84STejun Heo 	 * lead to sysfs name conflicts.
4795def98c84STejun Heo 	 */
4796def98c84STejun Heo 	workqueue_sysfs_unregister(wq);
4797def98c84STejun Heo 
479833e3f0a3SRichard Clark 	/* mark the workqueue destruction is in progress */
479933e3f0a3SRichard Clark 	mutex_lock(&wq->mutex);
480033e3f0a3SRichard Clark 	wq->flags |= __WQ_DESTROYING;
480133e3f0a3SRichard Clark 	mutex_unlock(&wq->mutex);
480233e3f0a3SRichard Clark 
48039c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
48049c5a2ba7STejun Heo 	drain_workqueue(wq);
4805c8efcc25STejun Heo 
4806def98c84STejun Heo 	/* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4807def98c84STejun Heo 	if (wq->rescuer) {
4808def98c84STejun Heo 		struct worker *rescuer = wq->rescuer;
4809def98c84STejun Heo 
4810def98c84STejun Heo 		/* this prevents new queueing */
4811a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
4812def98c84STejun Heo 		wq->rescuer = NULL;
4813a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
4814def98c84STejun Heo 
4815def98c84STejun Heo 		/* rescuer will empty maydays list before exiting */
4816def98c84STejun Heo 		kthread_stop(rescuer->task);
48178efe1223STejun Heo 		kfree(rescuer);
4818def98c84STejun Heo 	}
4819def98c84STejun Heo 
4820c29eb853STejun Heo 	/*
4821c29eb853STejun Heo 	 * Sanity checks - grab all the locks so that we wait for all
4822c29eb853STejun Heo 	 * in-flight operations which may do put_pwq().
4823c29eb853STejun Heo 	 */
4824c29eb853STejun Heo 	mutex_lock(&wq_pool_mutex);
4825b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
482649e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
4827a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
4828c29eb853STejun Heo 		if (WARN_ON(pwq_busy(pwq))) {
48291d9a6159SKefeng Wang 			pr_warn("%s: %s has the following busy pwq\n",
4830e66b39afSTejun Heo 				__func__, wq->name);
4831c29eb853STejun Heo 			show_pwq(pwq);
4832a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pwq->pool->lock);
4833b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
4834c29eb853STejun Heo 			mutex_unlock(&wq_pool_mutex);
483555df0933SImran Khan 			show_one_workqueue(wq);
48366183c009STejun Heo 			return;
483776af4d93STejun Heo 		}
4838a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
483976af4d93STejun Heo 	}
4840b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
48416183c009STejun Heo 
4842a0a1a5fdSTejun Heo 	/*
4843a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
4844a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
4845a0a1a5fdSTejun Heo 	 */
4846e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
484768e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
48483af24433SOleg Nesterov 
48498864b4e5STejun Heo 	/*
4850636b927eSTejun Heo 	 * We're the sole accessor of @wq. Directly access cpu_pwq and dfl_pwq
4851636b927eSTejun Heo 	 * to put the base refs. @wq will be auto-destroyed from the last
4852636b927eSTejun Heo 	 * pwq_put. RCU read lock prevents @wq from going away from under us.
48538864b4e5STejun Heo 	 */
4854636b927eSTejun Heo 	rcu_read_lock();
4855636b927eSTejun Heo 
4856636b927eSTejun Heo 	for_each_possible_cpu(cpu) {
4857636b927eSTejun Heo 		pwq = rcu_access_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu));
4858636b927eSTejun Heo 		RCU_INIT_POINTER(*per_cpu_ptr(wq->cpu_pwq, cpu), NULL);
48594c16bd32STejun Heo 		put_pwq_unlocked(pwq);
48604c16bd32STejun Heo 	}
48614c16bd32STejun Heo 
4862636b927eSTejun Heo 	put_pwq_unlocked(wq->dfl_pwq);
48634c16bd32STejun Heo 	wq->dfl_pwq = NULL;
4864636b927eSTejun Heo 
4865636b927eSTejun Heo 	rcu_read_unlock();
48663af24433SOleg Nesterov }
48673af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
48683af24433SOleg Nesterov 
4869dcd989cbSTejun Heo /**
4870dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
4871dcd989cbSTejun Heo  * @wq: target workqueue
4872dcd989cbSTejun Heo  * @max_active: new max_active value.
4873dcd989cbSTejun Heo  *
4874dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
4875dcd989cbSTejun Heo  *
4876dcd989cbSTejun Heo  * CONTEXT:
4877dcd989cbSTejun Heo  * Don't call from IRQ context.
4878dcd989cbSTejun Heo  */
4879dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4880dcd989cbSTejun Heo {
488149e3cf44STejun Heo 	struct pool_workqueue *pwq;
4882dcd989cbSTejun Heo 
48838719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
48840a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
48858719dceaSTejun Heo 		return;
48868719dceaSTejun Heo 
4887f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4888dcd989cbSTejun Heo 
4889a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4890dcd989cbSTejun Heo 
48910a94efb5STejun Heo 	wq->flags &= ~__WQ_ORDERED;
4892dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4893dcd989cbSTejun Heo 
4894699ce097STejun Heo 	for_each_pwq(pwq, wq)
4895699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4896dcd989cbSTejun Heo 
4897a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4898dcd989cbSTejun Heo }
4899dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4900dcd989cbSTejun Heo 
4901dcd989cbSTejun Heo /**
490227d4ee03SLukas Wunner  * current_work - retrieve %current task's work struct
490327d4ee03SLukas Wunner  *
490427d4ee03SLukas Wunner  * Determine if %current task is a workqueue worker and what it's working on.
490527d4ee03SLukas Wunner  * Useful to find out the context that the %current task is running in.
490627d4ee03SLukas Wunner  *
490727d4ee03SLukas Wunner  * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
490827d4ee03SLukas Wunner  */
490927d4ee03SLukas Wunner struct work_struct *current_work(void)
491027d4ee03SLukas Wunner {
491127d4ee03SLukas Wunner 	struct worker *worker = current_wq_worker();
491227d4ee03SLukas Wunner 
491327d4ee03SLukas Wunner 	return worker ? worker->current_work : NULL;
491427d4ee03SLukas Wunner }
491527d4ee03SLukas Wunner EXPORT_SYMBOL(current_work);
491627d4ee03SLukas Wunner 
491727d4ee03SLukas Wunner /**
4918e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4919e6267616STejun Heo  *
4920e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4921e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4922d185af30SYacine Belkadi  *
4923d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
4924e6267616STejun Heo  */
4925e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4926e6267616STejun Heo {
4927e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4928e6267616STejun Heo 
49296a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
4930e6267616STejun Heo }
4931e6267616STejun Heo 
4932e6267616STejun Heo /**
4933dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4934dcd989cbSTejun Heo  * @cpu: CPU in question
4935dcd989cbSTejun Heo  * @wq: target workqueue
4936dcd989cbSTejun Heo  *
4937dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4938dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4939dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4940dcd989cbSTejun Heo  *
4941d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4942636b927eSTejun Heo  *
4943636b927eSTejun Heo  * With the exception of ordered workqueues, all workqueues have per-cpu
4944636b927eSTejun Heo  * pool_workqueues, each with its own congested state. A workqueue being
4945636b927eSTejun Heo  * congested on one CPU doesn't mean that the workqueue is contested on any
4946636b927eSTejun Heo  * other CPUs.
4947d3251859STejun Heo  *
4948d185af30SYacine Belkadi  * Return:
4949dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4950dcd989cbSTejun Heo  */
4951d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4952dcd989cbSTejun Heo {
49537fb98ea7STejun Heo 	struct pool_workqueue *pwq;
495476af4d93STejun Heo 	bool ret;
495576af4d93STejun Heo 
495624acfb71SThomas Gleixner 	rcu_read_lock();
495724acfb71SThomas Gleixner 	preempt_disable();
49587fb98ea7STejun Heo 
4959d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
4960d3251859STejun Heo 		cpu = smp_processor_id();
4961d3251859STejun Heo 
4962687a9aa5STejun Heo 	pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
4963f97a4a1aSLai Jiangshan 	ret = !list_empty(&pwq->inactive_works);
4964636b927eSTejun Heo 
496524acfb71SThomas Gleixner 	preempt_enable();
496624acfb71SThomas Gleixner 	rcu_read_unlock();
496776af4d93STejun Heo 
496876af4d93STejun Heo 	return ret;
4969dcd989cbSTejun Heo }
4970dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4971dcd989cbSTejun Heo 
4972dcd989cbSTejun Heo /**
4973dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4974dcd989cbSTejun Heo  * @work: the work to be tested
4975dcd989cbSTejun Heo  *
4976dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4977dcd989cbSTejun Heo  * synchronization around this function and the test result is
4978dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4979dcd989cbSTejun Heo  *
4980d185af30SYacine Belkadi  * Return:
4981dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
4982dcd989cbSTejun Heo  */
4983dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4984dcd989cbSTejun Heo {
4985fa1b54e6STejun Heo 	struct worker_pool *pool;
4986dcd989cbSTejun Heo 	unsigned long flags;
4987dcd989cbSTejun Heo 	unsigned int ret = 0;
4988dcd989cbSTejun Heo 
4989dcd989cbSTejun Heo 	if (work_pending(work))
4990dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
4991038366c5SLai Jiangshan 
499224acfb71SThomas Gleixner 	rcu_read_lock();
4993fa1b54e6STejun Heo 	pool = get_work_pool(work);
4994038366c5SLai Jiangshan 	if (pool) {
4995a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pool->lock, flags);
4996c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
4997dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
4998a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pool->lock, flags);
4999038366c5SLai Jiangshan 	}
500024acfb71SThomas Gleixner 	rcu_read_unlock();
5001dcd989cbSTejun Heo 
5002dcd989cbSTejun Heo 	return ret;
5003dcd989cbSTejun Heo }
5004dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
5005dcd989cbSTejun Heo 
50063d1cb205STejun Heo /**
50073d1cb205STejun Heo  * set_worker_desc - set description for the current work item
50083d1cb205STejun Heo  * @fmt: printf-style format string
50093d1cb205STejun Heo  * @...: arguments for the format string
50103d1cb205STejun Heo  *
50113d1cb205STejun Heo  * This function can be called by a running work function to describe what
50123d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
50133d1cb205STejun Heo  * information will be printed out together to help debugging.  The
50143d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
50153d1cb205STejun Heo  */
50163d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
50173d1cb205STejun Heo {
50183d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
50193d1cb205STejun Heo 	va_list args;
50203d1cb205STejun Heo 
50213d1cb205STejun Heo 	if (worker) {
50223d1cb205STejun Heo 		va_start(args, fmt);
50233d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
50243d1cb205STejun Heo 		va_end(args);
50253d1cb205STejun Heo 	}
50263d1cb205STejun Heo }
50275c750d58SSteffen Maier EXPORT_SYMBOL_GPL(set_worker_desc);
50283d1cb205STejun Heo 
50293d1cb205STejun Heo /**
50303d1cb205STejun Heo  * print_worker_info - print out worker information and description
50313d1cb205STejun Heo  * @log_lvl: the log level to use when printing
50323d1cb205STejun Heo  * @task: target task
50333d1cb205STejun Heo  *
50343d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
50353d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
50363d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
50373d1cb205STejun Heo  *
50383d1cb205STejun Heo  * This function can be safely called on any task as long as the
50393d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
50403d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
50413d1cb205STejun Heo  */
50423d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
50433d1cb205STejun Heo {
50443d1cb205STejun Heo 	work_func_t *fn = NULL;
50453d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
50463d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
50473d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
50483d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
50493d1cb205STejun Heo 	struct worker *worker;
50503d1cb205STejun Heo 
50513d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
50523d1cb205STejun Heo 		return;
50533d1cb205STejun Heo 
50543d1cb205STejun Heo 	/*
50553d1cb205STejun Heo 	 * This function is called without any synchronization and @task
50563d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
50573d1cb205STejun Heo 	 */
5058e700591aSPetr Mladek 	worker = kthread_probe_data(task);
50593d1cb205STejun Heo 
50603d1cb205STejun Heo 	/*
50618bf89593STejun Heo 	 * Carefully copy the associated workqueue's workfn, name and desc.
50628bf89593STejun Heo 	 * Keep the original last '\0' in case the original is garbage.
50633d1cb205STejun Heo 	 */
5064fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
5065fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
5066fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
5067fe557319SChristoph Hellwig 	copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
5068fe557319SChristoph Hellwig 	copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
50693d1cb205STejun Heo 
50703d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
5071d75f773cSSakari Ailus 		printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
50728bf89593STejun Heo 		if (strcmp(name, desc))
50733d1cb205STejun Heo 			pr_cont(" (%s)", desc);
50743d1cb205STejun Heo 		pr_cont("\n");
50753d1cb205STejun Heo 	}
50763d1cb205STejun Heo }
50773d1cb205STejun Heo 
50783494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
50793494fc30STejun Heo {
50803494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
50813494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
50823494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
50833494fc30STejun Heo 	pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
50843494fc30STejun Heo }
50853494fc30STejun Heo 
5086c76feb0dSPaul E. McKenney struct pr_cont_work_struct {
5087c76feb0dSPaul E. McKenney 	bool comma;
5088c76feb0dSPaul E. McKenney 	work_func_t func;
5089c76feb0dSPaul E. McKenney 	long ctr;
5090c76feb0dSPaul E. McKenney };
5091c76feb0dSPaul E. McKenney 
5092c76feb0dSPaul E. McKenney static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
5093c76feb0dSPaul E. McKenney {
5094c76feb0dSPaul E. McKenney 	if (!pcwsp->ctr)
5095c76feb0dSPaul E. McKenney 		goto out_record;
5096c76feb0dSPaul E. McKenney 	if (func == pcwsp->func) {
5097c76feb0dSPaul E. McKenney 		pcwsp->ctr++;
5098c76feb0dSPaul E. McKenney 		return;
5099c76feb0dSPaul E. McKenney 	}
5100c76feb0dSPaul E. McKenney 	if (pcwsp->ctr == 1)
5101c76feb0dSPaul E. McKenney 		pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
5102c76feb0dSPaul E. McKenney 	else
5103c76feb0dSPaul E. McKenney 		pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
5104c76feb0dSPaul E. McKenney 	pcwsp->ctr = 0;
5105c76feb0dSPaul E. McKenney out_record:
5106c76feb0dSPaul E. McKenney 	if ((long)func == -1L)
5107c76feb0dSPaul E. McKenney 		return;
5108c76feb0dSPaul E. McKenney 	pcwsp->comma = comma;
5109c76feb0dSPaul E. McKenney 	pcwsp->func = func;
5110c76feb0dSPaul E. McKenney 	pcwsp->ctr = 1;
5111c76feb0dSPaul E. McKenney }
5112c76feb0dSPaul E. McKenney 
5113c76feb0dSPaul E. McKenney static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
51143494fc30STejun Heo {
51153494fc30STejun Heo 	if (work->func == wq_barrier_func) {
51163494fc30STejun Heo 		struct wq_barrier *barr;
51173494fc30STejun Heo 
51183494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
51193494fc30STejun Heo 
5120c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
51213494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
51223494fc30STejun Heo 			task_pid_nr(barr->task));
51233494fc30STejun Heo 	} else {
5124c76feb0dSPaul E. McKenney 		if (!comma)
5125c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5126c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, work->func, pcwsp);
51273494fc30STejun Heo 	}
51283494fc30STejun Heo }
51293494fc30STejun Heo 
51303494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
51313494fc30STejun Heo {
5132c76feb0dSPaul E. McKenney 	struct pr_cont_work_struct pcws = { .ctr = 0, };
51333494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
51343494fc30STejun Heo 	struct work_struct *work;
51353494fc30STejun Heo 	struct worker *worker;
51363494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
51373494fc30STejun Heo 	int bkt;
51383494fc30STejun Heo 
51393494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
51403494fc30STejun Heo 	pr_cont_pool_info(pool);
51413494fc30STejun Heo 
5142e66b39afSTejun Heo 	pr_cont(" active=%d/%d refcnt=%d%s\n",
5143e66b39afSTejun Heo 		pwq->nr_active, pwq->max_active, pwq->refcnt,
51443494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
51453494fc30STejun Heo 
51463494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
51473494fc30STejun Heo 		if (worker->current_pwq == pwq) {
51483494fc30STejun Heo 			has_in_flight = true;
51493494fc30STejun Heo 			break;
51503494fc30STejun Heo 		}
51513494fc30STejun Heo 	}
51523494fc30STejun Heo 	if (has_in_flight) {
51533494fc30STejun Heo 		bool comma = false;
51543494fc30STejun Heo 
51553494fc30STejun Heo 		pr_info("    in-flight:");
51563494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
51573494fc30STejun Heo 			if (worker->current_pwq != pwq)
51583494fc30STejun Heo 				continue;
51593494fc30STejun Heo 
5160d75f773cSSakari Ailus 			pr_cont("%s %d%s:%ps", comma ? "," : "",
51613494fc30STejun Heo 				task_pid_nr(worker->task),
516230ae2fc0STejun Heo 				worker->rescue_wq ? "(RESCUER)" : "",
51633494fc30STejun Heo 				worker->current_func);
51643494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
5165c76feb0dSPaul E. McKenney 				pr_cont_work(false, work, &pcws);
5166c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
51673494fc30STejun Heo 			comma = true;
51683494fc30STejun Heo 		}
51693494fc30STejun Heo 		pr_cont("\n");
51703494fc30STejun Heo 	}
51713494fc30STejun Heo 
51723494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
51733494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
51743494fc30STejun Heo 			has_pending = true;
51753494fc30STejun Heo 			break;
51763494fc30STejun Heo 		}
51773494fc30STejun Heo 	}
51783494fc30STejun Heo 	if (has_pending) {
51793494fc30STejun Heo 		bool comma = false;
51803494fc30STejun Heo 
51813494fc30STejun Heo 		pr_info("    pending:");
51823494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
51833494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
51843494fc30STejun Heo 				continue;
51853494fc30STejun Heo 
5186c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
51873494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
51883494fc30STejun Heo 		}
5189c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
51903494fc30STejun Heo 		pr_cont("\n");
51913494fc30STejun Heo 	}
51923494fc30STejun Heo 
5193f97a4a1aSLai Jiangshan 	if (!list_empty(&pwq->inactive_works)) {
51943494fc30STejun Heo 		bool comma = false;
51953494fc30STejun Heo 
5196f97a4a1aSLai Jiangshan 		pr_info("    inactive:");
5197f97a4a1aSLai Jiangshan 		list_for_each_entry(work, &pwq->inactive_works, entry) {
5198c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
51993494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
52003494fc30STejun Heo 		}
5201c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
52023494fc30STejun Heo 		pr_cont("\n");
52033494fc30STejun Heo 	}
52043494fc30STejun Heo }
52053494fc30STejun Heo 
52063494fc30STejun Heo /**
520755df0933SImran Khan  * show_one_workqueue - dump state of specified workqueue
520855df0933SImran Khan  * @wq: workqueue whose state will be printed
52093494fc30STejun Heo  */
521055df0933SImran Khan void show_one_workqueue(struct workqueue_struct *wq)
52113494fc30STejun Heo {
52123494fc30STejun Heo 	struct pool_workqueue *pwq;
52133494fc30STejun Heo 	bool idle = true;
521455df0933SImran Khan 	unsigned long flags;
52153494fc30STejun Heo 
52163494fc30STejun Heo 	for_each_pwq(pwq, wq) {
5217f97a4a1aSLai Jiangshan 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
52183494fc30STejun Heo 			idle = false;
52193494fc30STejun Heo 			break;
52203494fc30STejun Heo 		}
52213494fc30STejun Heo 	}
522255df0933SImran Khan 	if (idle) /* Nothing to print for idle workqueue */
522355df0933SImran Khan 		return;
52243494fc30STejun Heo 
52253494fc30STejun Heo 	pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
52263494fc30STejun Heo 
52273494fc30STejun Heo 	for_each_pwq(pwq, wq) {
5228a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pwq->pool->lock, flags);
522957116ce1SJohan Hovold 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
523057116ce1SJohan Hovold 			/*
523157116ce1SJohan Hovold 			 * Defer printing to avoid deadlocks in console
523257116ce1SJohan Hovold 			 * drivers that queue work while holding locks
523357116ce1SJohan Hovold 			 * also taken in their write paths.
523457116ce1SJohan Hovold 			 */
523557116ce1SJohan Hovold 			printk_deferred_enter();
52363494fc30STejun Heo 			show_pwq(pwq);
523757116ce1SJohan Hovold 			printk_deferred_exit();
523857116ce1SJohan Hovold 		}
5239a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
524062635ea8SSergey Senozhatsky 		/*
524162635ea8SSergey Senozhatsky 		 * We could be printing a lot from atomic context, e.g.
524255df0933SImran Khan 		 * sysrq-t -> show_all_workqueues(). Avoid triggering
524362635ea8SSergey Senozhatsky 		 * hard lockup.
524462635ea8SSergey Senozhatsky 		 */
524562635ea8SSergey Senozhatsky 		touch_nmi_watchdog();
52463494fc30STejun Heo 	}
524755df0933SImran Khan 
52483494fc30STejun Heo }
52493494fc30STejun Heo 
525055df0933SImran Khan /**
525155df0933SImran Khan  * show_one_worker_pool - dump state of specified worker pool
525255df0933SImran Khan  * @pool: worker pool whose state will be printed
525355df0933SImran Khan  */
525455df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool)
525555df0933SImran Khan {
52563494fc30STejun Heo 	struct worker *worker;
52573494fc30STejun Heo 	bool first = true;
525855df0933SImran Khan 	unsigned long flags;
5259335a42ebSPetr Mladek 	unsigned long hung = 0;
52603494fc30STejun Heo 
5261a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pool->lock, flags);
52623494fc30STejun Heo 	if (pool->nr_workers == pool->nr_idle)
52633494fc30STejun Heo 		goto next_pool;
5264335a42ebSPetr Mladek 
5265335a42ebSPetr Mladek 	/* How long the first pending work is waiting for a worker. */
5266335a42ebSPetr Mladek 	if (!list_empty(&pool->worklist))
5267335a42ebSPetr Mladek 		hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
5268335a42ebSPetr Mladek 
526957116ce1SJohan Hovold 	/*
527057116ce1SJohan Hovold 	 * Defer printing to avoid deadlocks in console drivers that
527157116ce1SJohan Hovold 	 * queue work while holding locks also taken in their write
527257116ce1SJohan Hovold 	 * paths.
527357116ce1SJohan Hovold 	 */
527457116ce1SJohan Hovold 	printk_deferred_enter();
52753494fc30STejun Heo 	pr_info("pool %d:", pool->id);
52763494fc30STejun Heo 	pr_cont_pool_info(pool);
5277335a42ebSPetr Mladek 	pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
52783494fc30STejun Heo 	if (pool->manager)
52793494fc30STejun Heo 		pr_cont(" manager: %d",
52803494fc30STejun Heo 			task_pid_nr(pool->manager->task));
52813494fc30STejun Heo 	list_for_each_entry(worker, &pool->idle_list, entry) {
52823494fc30STejun Heo 		pr_cont(" %s%d", first ? "idle: " : "",
52833494fc30STejun Heo 			task_pid_nr(worker->task));
52843494fc30STejun Heo 		first = false;
52853494fc30STejun Heo 	}
52863494fc30STejun Heo 	pr_cont("\n");
528757116ce1SJohan Hovold 	printk_deferred_exit();
52883494fc30STejun Heo next_pool:
5289a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pool->lock, flags);
529062635ea8SSergey Senozhatsky 	/*
529162635ea8SSergey Senozhatsky 	 * We could be printing a lot from atomic context, e.g.
529255df0933SImran Khan 	 * sysrq-t -> show_all_workqueues(). Avoid triggering
529362635ea8SSergey Senozhatsky 	 * hard lockup.
529462635ea8SSergey Senozhatsky 	 */
529562635ea8SSergey Senozhatsky 	touch_nmi_watchdog();
529655df0933SImran Khan 
52973494fc30STejun Heo }
52983494fc30STejun Heo 
529955df0933SImran Khan /**
530055df0933SImran Khan  * show_all_workqueues - dump workqueue state
530155df0933SImran Khan  *
5302704bc669SJungseung Lee  * Called from a sysrq handler and prints out all busy workqueues and pools.
530355df0933SImran Khan  */
530455df0933SImran Khan void show_all_workqueues(void)
530555df0933SImran Khan {
530655df0933SImran Khan 	struct workqueue_struct *wq;
530755df0933SImran Khan 	struct worker_pool *pool;
530855df0933SImran Khan 	int pi;
530955df0933SImran Khan 
531055df0933SImran Khan 	rcu_read_lock();
531155df0933SImran Khan 
531255df0933SImran Khan 	pr_info("Showing busy workqueues and worker pools:\n");
531355df0933SImran Khan 
531455df0933SImran Khan 	list_for_each_entry_rcu(wq, &workqueues, list)
531555df0933SImran Khan 		show_one_workqueue(wq);
531655df0933SImran Khan 
531755df0933SImran Khan 	for_each_pool(pool, pi)
531855df0933SImran Khan 		show_one_worker_pool(pool);
531955df0933SImran Khan 
532024acfb71SThomas Gleixner 	rcu_read_unlock();
53213494fc30STejun Heo }
53223494fc30STejun Heo 
5323704bc669SJungseung Lee /**
5324704bc669SJungseung Lee  * show_freezable_workqueues - dump freezable workqueue state
5325704bc669SJungseung Lee  *
5326704bc669SJungseung Lee  * Called from try_to_freeze_tasks() and prints out all freezable workqueues
5327704bc669SJungseung Lee  * still busy.
5328704bc669SJungseung Lee  */
5329704bc669SJungseung Lee void show_freezable_workqueues(void)
5330704bc669SJungseung Lee {
5331704bc669SJungseung Lee 	struct workqueue_struct *wq;
5332704bc669SJungseung Lee 
5333704bc669SJungseung Lee 	rcu_read_lock();
5334704bc669SJungseung Lee 
5335704bc669SJungseung Lee 	pr_info("Showing freezable workqueues that are still busy:\n");
5336704bc669SJungseung Lee 
5337704bc669SJungseung Lee 	list_for_each_entry_rcu(wq, &workqueues, list) {
5338704bc669SJungseung Lee 		if (!(wq->flags & WQ_FREEZABLE))
5339704bc669SJungseung Lee 			continue;
5340704bc669SJungseung Lee 		show_one_workqueue(wq);
5341704bc669SJungseung Lee 	}
5342704bc669SJungseung Lee 
5343704bc669SJungseung Lee 	rcu_read_unlock();
5344704bc669SJungseung Lee }
5345704bc669SJungseung Lee 
53466b59808bSTejun Heo /* used to show worker information through /proc/PID/{comm,stat,status} */
53476b59808bSTejun Heo void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
53486b59808bSTejun Heo {
53496b59808bSTejun Heo 	int off;
53506b59808bSTejun Heo 
53516b59808bSTejun Heo 	/* always show the actual comm */
53526b59808bSTejun Heo 	off = strscpy(buf, task->comm, size);
53536b59808bSTejun Heo 	if (off < 0)
53546b59808bSTejun Heo 		return;
53556b59808bSTejun Heo 
5356197f6accSTejun Heo 	/* stabilize PF_WQ_WORKER and worker pool association */
53576b59808bSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
53586b59808bSTejun Heo 
5359197f6accSTejun Heo 	if (task->flags & PF_WQ_WORKER) {
5360197f6accSTejun Heo 		struct worker *worker = kthread_data(task);
5361197f6accSTejun Heo 		struct worker_pool *pool = worker->pool;
53626b59808bSTejun Heo 
53636b59808bSTejun Heo 		if (pool) {
5364a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock_irq(&pool->lock);
53656b59808bSTejun Heo 			/*
5366197f6accSTejun Heo 			 * ->desc tracks information (wq name or
5367197f6accSTejun Heo 			 * set_worker_desc()) for the latest execution.  If
5368197f6accSTejun Heo 			 * current, prepend '+', otherwise '-'.
53696b59808bSTejun Heo 			 */
53706b59808bSTejun Heo 			if (worker->desc[0] != '\0') {
53716b59808bSTejun Heo 				if (worker->current_work)
53726b59808bSTejun Heo 					scnprintf(buf + off, size - off, "+%s",
53736b59808bSTejun Heo 						  worker->desc);
53746b59808bSTejun Heo 				else
53756b59808bSTejun Heo 					scnprintf(buf + off, size - off, "-%s",
53766b59808bSTejun Heo 						  worker->desc);
53776b59808bSTejun Heo 			}
5378a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pool->lock);
53796b59808bSTejun Heo 		}
5380197f6accSTejun Heo 	}
53816b59808bSTejun Heo 
53826b59808bSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
53836b59808bSTejun Heo }
53846b59808bSTejun Heo 
538566448bc2SMathieu Malaterre #ifdef CONFIG_SMP
538666448bc2SMathieu Malaterre 
5387db7bccf4STejun Heo /*
5388db7bccf4STejun Heo  * CPU hotplug.
5389db7bccf4STejun Heo  *
5390e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
5391112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
5392706026c2STejun Heo  * pool which make migrating pending and scheduled works very
5393e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
539494cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
5395e22bee78STejun Heo  * blocked draining impractical.
5396e22bee78STejun Heo  *
539724647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
5398628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
5399628c78e7STejun Heo  * cpu comes back online.
5400db7bccf4STejun Heo  */
5401db7bccf4STejun Heo 
5402e8b3f8dbSLai Jiangshan static void unbind_workers(int cpu)
5403db7bccf4STejun Heo {
54044ce62e9eSTejun Heo 	struct worker_pool *pool;
5405db7bccf4STejun Heo 	struct worker *worker;
5406db7bccf4STejun Heo 
5407f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
54081258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
5409a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
5410e22bee78STejun Heo 
5411f2d5a0eeSTejun Heo 		/*
541292f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
541394cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
541411b45b0bSLai Jiangshan 		 * must be on the cpu.  After this, they may become diasporas.
5415b4ac9384SLai Jiangshan 		 * And the preemption disabled section in their sched callbacks
5416b4ac9384SLai Jiangshan 		 * are guaranteed to see WORKER_UNBOUND since the code here
5417b4ac9384SLai Jiangshan 		 * is on the same cpu.
5418f2d5a0eeSTejun Heo 		 */
5419da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
5420403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
5421db7bccf4STejun Heo 
542224647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
5423f2d5a0eeSTejun Heo 
5424e22bee78STejun Heo 		/*
5425989442d7SLai Jiangshan 		 * The handling of nr_running in sched callbacks are disabled
5426989442d7SLai Jiangshan 		 * now.  Zap nr_running.  After this, nr_running stays zero and
5427989442d7SLai Jiangshan 		 * need_more_worker() and keep_working() are always true as
5428989442d7SLai Jiangshan 		 * long as the worklist is not empty.  This pool now behaves as
5429989442d7SLai Jiangshan 		 * an unbound (in terms of concurrency management) pool which
5430eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
5431e22bee78STejun Heo 		 */
5432bc35f7efSLai Jiangshan 		pool->nr_running = 0;
5433eb283428SLai Jiangshan 
5434eb283428SLai Jiangshan 		/*
5435eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
5436eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
5437eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
5438eb283428SLai Jiangshan 		 */
54390219a352STejun Heo 		kick_pool(pool);
5440989442d7SLai Jiangshan 
5441a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
5442989442d7SLai Jiangshan 
5443793777bcSValentin Schneider 		for_each_pool_worker(worker, pool)
5444793777bcSValentin Schneider 			unbind_worker(worker);
5445989442d7SLai Jiangshan 
5446989442d7SLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
5447eb283428SLai Jiangshan 	}
5448db7bccf4STejun Heo }
5449db7bccf4STejun Heo 
5450bd7c089eSTejun Heo /**
5451bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
5452bd7c089eSTejun Heo  * @pool: pool of interest
5453bd7c089eSTejun Heo  *
5454a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
5455bd7c089eSTejun Heo  */
5456bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
5457bd7c089eSTejun Heo {
5458a9ab775bSTejun Heo 	struct worker *worker;
5459bd7c089eSTejun Heo 
54601258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
5461bd7c089eSTejun Heo 
5462bd7c089eSTejun Heo 	/*
5463a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
5464a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
5465402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
5466a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
5467a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
5468bd7c089eSTejun Heo 	 */
5469c63a2e52SValentin Schneider 	for_each_pool_worker(worker, pool) {
5470c63a2e52SValentin Schneider 		kthread_set_per_cpu(worker->task, pool->cpu);
5471c63a2e52SValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
54729546b29eSTejun Heo 						  pool_allowed_cpus(pool)) < 0);
5473c63a2e52SValentin Schneider 	}
5474a9ab775bSTejun Heo 
5475a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
5476f7c17d26SWanpeng Li 
54773de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
5478a9ab775bSTejun Heo 
5479da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
5480a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
5481a9ab775bSTejun Heo 
5482a9ab775bSTejun Heo 		/*
5483a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
5484a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
5485a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5486a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
5487a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
5488a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
5489a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
5490a9ab775bSTejun Heo 		 *
5491c95491edSMark Rutland 		 * WRITE_ONCE() is necessary because @worker->flags may be
5492a9ab775bSTejun Heo 		 * tested without holding any lock in
54936d25be57SThomas Gleixner 		 * wq_worker_running().  Without it, NOT_RUNNING test may
5494a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
5495a9ab775bSTejun Heo 		 * management operations.
5496bd7c089eSTejun Heo 		 */
5497a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5498a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
5499a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
5500c95491edSMark Rutland 		WRITE_ONCE(worker->flags, worker_flags);
5501bd7c089eSTejun Heo 	}
5502a9ab775bSTejun Heo 
5503a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
5504bd7c089eSTejun Heo }
5505bd7c089eSTejun Heo 
55067dbc725eSTejun Heo /**
55077dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
55087dbc725eSTejun Heo  * @pool: unbound pool of interest
55097dbc725eSTejun Heo  * @cpu: the CPU which is coming up
55107dbc725eSTejun Heo  *
55117dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
55127dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
55137dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
55147dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
55157dbc725eSTejun Heo  */
55167dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
55177dbc725eSTejun Heo {
55187dbc725eSTejun Heo 	static cpumask_t cpumask;
55197dbc725eSTejun Heo 	struct worker *worker;
55207dbc725eSTejun Heo 
55211258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
55227dbc725eSTejun Heo 
55237dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
55247dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
55257dbc725eSTejun Heo 		return;
55267dbc725eSTejun Heo 
55277dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
55287dbc725eSTejun Heo 
55297dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
5530da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
5531d945b5e9SPeter Zijlstra 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
55327dbc725eSTejun Heo }
55337dbc725eSTejun Heo 
55347ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
55351da177e4SLinus Torvalds {
55364ce62e9eSTejun Heo 	struct worker_pool *pool;
55371da177e4SLinus Torvalds 
5538f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
55393ce63377STejun Heo 		if (pool->nr_workers)
55403ce63377STejun Heo 			continue;
5541051e1850SLai Jiangshan 		if (!create_worker(pool))
55427ee681b2SThomas Gleixner 			return -ENOMEM;
55433af24433SOleg Nesterov 	}
55447ee681b2SThomas Gleixner 	return 0;
55457ee681b2SThomas Gleixner }
55461da177e4SLinus Torvalds 
55477ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
55487ee681b2SThomas Gleixner {
55497ee681b2SThomas Gleixner 	struct worker_pool *pool;
55507ee681b2SThomas Gleixner 	struct workqueue_struct *wq;
55517ee681b2SThomas Gleixner 	int pi;
55527ee681b2SThomas Gleixner 
555368e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
55547dbc725eSTejun Heo 
55557dbc725eSTejun Heo 	for_each_pool(pool, pi) {
55561258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
555794cf58bbSTejun Heo 
5558f05b558dSLai Jiangshan 		if (pool->cpu == cpu)
555994cf58bbSTejun Heo 			rebind_workers(pool);
5560f05b558dSLai Jiangshan 		else if (pool->cpu < 0)
55617dbc725eSTejun Heo 			restore_unbound_workers_cpumask(pool, cpu);
556294cf58bbSTejun Heo 
55631258fae7STejun Heo 		mutex_unlock(&wq_pool_attach_mutex);
556494cf58bbSTejun Heo 	}
55657dbc725eSTejun Heo 
5566fef59c9cSTejun Heo 	/* update pod affinity of unbound workqueues */
55674cbfd3deSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
556884193c07STejun Heo 		struct workqueue_attrs *attrs = wq->unbound_attrs;
556984193c07STejun Heo 
557084193c07STejun Heo 		if (attrs) {
557184193c07STejun Heo 			const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
55724cbfd3deSTejun Heo 			int tcpu;
55734cbfd3deSTejun Heo 
557484193c07STejun Heo 			for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
5575fef59c9cSTejun Heo 				wq_update_pod(wq, tcpu, cpu, true);
55764cbfd3deSTejun Heo 		}
55774cbfd3deSTejun Heo 	}
55784c16bd32STejun Heo 
557968e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
55807ee681b2SThomas Gleixner 	return 0;
558165758202STejun Heo }
558265758202STejun Heo 
55837ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
558465758202STejun Heo {
55854c16bd32STejun Heo 	struct workqueue_struct *wq;
55868db25e78STejun Heo 
55874c16bd32STejun Heo 	/* unbinding per-cpu workers should happen on the local CPU */
5588e8b3f8dbSLai Jiangshan 	if (WARN_ON(cpu != smp_processor_id()))
5589e8b3f8dbSLai Jiangshan 		return -1;
5590e8b3f8dbSLai Jiangshan 
5591e8b3f8dbSLai Jiangshan 	unbind_workers(cpu);
55924c16bd32STejun Heo 
5593fef59c9cSTejun Heo 	/* update pod affinity of unbound workqueues */
55944c16bd32STejun Heo 	mutex_lock(&wq_pool_mutex);
55954cbfd3deSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
559684193c07STejun Heo 		struct workqueue_attrs *attrs = wq->unbound_attrs;
559784193c07STejun Heo 
559884193c07STejun Heo 		if (attrs) {
559984193c07STejun Heo 			const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
56004cbfd3deSTejun Heo 			int tcpu;
56014cbfd3deSTejun Heo 
560284193c07STejun Heo 			for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
5603fef59c9cSTejun Heo 				wq_update_pod(wq, tcpu, cpu, false);
56044cbfd3deSTejun Heo 		}
56054cbfd3deSTejun Heo 	}
56064c16bd32STejun Heo 	mutex_unlock(&wq_pool_mutex);
56074c16bd32STejun Heo 
56087ee681b2SThomas Gleixner 	return 0;
560965758202STejun Heo }
561065758202STejun Heo 
56112d3854a3SRusty Russell struct work_for_cpu {
5612ed48ece2STejun Heo 	struct work_struct work;
56132d3854a3SRusty Russell 	long (*fn)(void *);
56142d3854a3SRusty Russell 	void *arg;
56152d3854a3SRusty Russell 	long ret;
56162d3854a3SRusty Russell };
56172d3854a3SRusty Russell 
5618ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
56192d3854a3SRusty Russell {
5620ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5621ed48ece2STejun Heo 
56222d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
56232d3854a3SRusty Russell }
56242d3854a3SRusty Russell 
56252d3854a3SRusty Russell /**
5626265f3ed0SFrederic Weisbecker  * work_on_cpu_key - run a function in thread context on a particular cpu
56272d3854a3SRusty Russell  * @cpu: the cpu to run on
56282d3854a3SRusty Russell  * @fn: the function to run
56292d3854a3SRusty Russell  * @arg: the function arg
5630265f3ed0SFrederic Weisbecker  * @key: The lock class key for lock debugging purposes
56312d3854a3SRusty Russell  *
563231ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
56336b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
5634d185af30SYacine Belkadi  *
5635d185af30SYacine Belkadi  * Return: The value @fn returns.
56362d3854a3SRusty Russell  */
5637265f3ed0SFrederic Weisbecker long work_on_cpu_key(int cpu, long (*fn)(void *),
5638265f3ed0SFrederic Weisbecker 		     void *arg, struct lock_class_key *key)
56392d3854a3SRusty Russell {
5640ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
56412d3854a3SRusty Russell 
5642265f3ed0SFrederic Weisbecker 	INIT_WORK_ONSTACK_KEY(&wfc.work, work_for_cpu_fn, key);
5643ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
564412997d1aSBjorn Helgaas 	flush_work(&wfc.work);
5645440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
56462d3854a3SRusty Russell 	return wfc.ret;
56472d3854a3SRusty Russell }
5648265f3ed0SFrederic Weisbecker EXPORT_SYMBOL_GPL(work_on_cpu_key);
56490e8d6a93SThomas Gleixner 
56500e8d6a93SThomas Gleixner /**
5651265f3ed0SFrederic Weisbecker  * work_on_cpu_safe_key - run a function in thread context on a particular cpu
56520e8d6a93SThomas Gleixner  * @cpu: the cpu to run on
56530e8d6a93SThomas Gleixner  * @fn:  the function to run
56540e8d6a93SThomas Gleixner  * @arg: the function argument
5655265f3ed0SFrederic Weisbecker  * @key: The lock class key for lock debugging purposes
56560e8d6a93SThomas Gleixner  *
56570e8d6a93SThomas Gleixner  * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
56580e8d6a93SThomas Gleixner  * any locks which would prevent @fn from completing.
56590e8d6a93SThomas Gleixner  *
56600e8d6a93SThomas Gleixner  * Return: The value @fn returns.
56610e8d6a93SThomas Gleixner  */
5662265f3ed0SFrederic Weisbecker long work_on_cpu_safe_key(int cpu, long (*fn)(void *),
5663265f3ed0SFrederic Weisbecker 			  void *arg, struct lock_class_key *key)
56640e8d6a93SThomas Gleixner {
56650e8d6a93SThomas Gleixner 	long ret = -ENODEV;
56660e8d6a93SThomas Gleixner 
5667ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
56680e8d6a93SThomas Gleixner 	if (cpu_online(cpu))
5669265f3ed0SFrederic Weisbecker 		ret = work_on_cpu_key(cpu, fn, arg, key);
5670ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
56710e8d6a93SThomas Gleixner 	return ret;
56720e8d6a93SThomas Gleixner }
5673265f3ed0SFrederic Weisbecker EXPORT_SYMBOL_GPL(work_on_cpu_safe_key);
56742d3854a3SRusty Russell #endif /* CONFIG_SMP */
56752d3854a3SRusty Russell 
5676a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
5677e7577c50SRusty Russell 
5678a0a1a5fdSTejun Heo /**
5679a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
5680a0a1a5fdSTejun Heo  *
568158a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
5682f97a4a1aSLai Jiangshan  * workqueues will queue new works to their inactive_works list instead of
5683706026c2STejun Heo  * pool->worklist.
5684a0a1a5fdSTejun Heo  *
5685a0a1a5fdSTejun Heo  * CONTEXT:
5686a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5687a0a1a5fdSTejun Heo  */
5688a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
5689a0a1a5fdSTejun Heo {
569024b8a847STejun Heo 	struct workqueue_struct *wq;
569124b8a847STejun Heo 	struct pool_workqueue *pwq;
5692a0a1a5fdSTejun Heo 
569368e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5694a0a1a5fdSTejun Heo 
56956183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
5696a0a1a5fdSTejun Heo 	workqueue_freezing = true;
5697a0a1a5fdSTejun Heo 
569824b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5699a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5700699ce097STejun Heo 		for_each_pwq(pwq, wq)
5701699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5702a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
5703a1056305STejun Heo 	}
57045bcab335STejun Heo 
570568e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5706a0a1a5fdSTejun Heo }
5707a0a1a5fdSTejun Heo 
5708a0a1a5fdSTejun Heo /**
570958a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
5710a0a1a5fdSTejun Heo  *
5711a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
5712a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
5713a0a1a5fdSTejun Heo  *
5714a0a1a5fdSTejun Heo  * CONTEXT:
571568e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
5716a0a1a5fdSTejun Heo  *
5717d185af30SYacine Belkadi  * Return:
571858a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
571958a69cb4STejun Heo  * is complete.
5720a0a1a5fdSTejun Heo  */
5721a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
5722a0a1a5fdSTejun Heo {
5723a0a1a5fdSTejun Heo 	bool busy = false;
572424b8a847STejun Heo 	struct workqueue_struct *wq;
572524b8a847STejun Heo 	struct pool_workqueue *pwq;
5726a0a1a5fdSTejun Heo 
572768e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5728a0a1a5fdSTejun Heo 
57296183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
5730a0a1a5fdSTejun Heo 
573124b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
573224b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
573324b8a847STejun Heo 			continue;
5734a0a1a5fdSTejun Heo 		/*
5735a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
5736a0a1a5fdSTejun Heo 		 * to peek without lock.
5737a0a1a5fdSTejun Heo 		 */
573824acfb71SThomas Gleixner 		rcu_read_lock();
573924b8a847STejun Heo 		for_each_pwq(pwq, wq) {
57406183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
5741112202d9STejun Heo 			if (pwq->nr_active) {
5742a0a1a5fdSTejun Heo 				busy = true;
574324acfb71SThomas Gleixner 				rcu_read_unlock();
5744a0a1a5fdSTejun Heo 				goto out_unlock;
5745a0a1a5fdSTejun Heo 			}
5746a0a1a5fdSTejun Heo 		}
574724acfb71SThomas Gleixner 		rcu_read_unlock();
5748a0a1a5fdSTejun Heo 	}
5749a0a1a5fdSTejun Heo out_unlock:
575068e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5751a0a1a5fdSTejun Heo 	return busy;
5752a0a1a5fdSTejun Heo }
5753a0a1a5fdSTejun Heo 
5754a0a1a5fdSTejun Heo /**
5755a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
5756a0a1a5fdSTejun Heo  *
5757a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
5758706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
5759a0a1a5fdSTejun Heo  *
5760a0a1a5fdSTejun Heo  * CONTEXT:
5761a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5762a0a1a5fdSTejun Heo  */
5763a0a1a5fdSTejun Heo void thaw_workqueues(void)
5764a0a1a5fdSTejun Heo {
576524b8a847STejun Heo 	struct workqueue_struct *wq;
576624b8a847STejun Heo 	struct pool_workqueue *pwq;
5767a0a1a5fdSTejun Heo 
576868e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5769a0a1a5fdSTejun Heo 
5770a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
5771a0a1a5fdSTejun Heo 		goto out_unlock;
5772a0a1a5fdSTejun Heo 
577374b414eaSLai Jiangshan 	workqueue_freezing = false;
577424b8a847STejun Heo 
577524b8a847STejun Heo 	/* restore max_active and repopulate worklist */
577624b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5777a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5778699ce097STejun Heo 		for_each_pwq(pwq, wq)
5779699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5780a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
578124b8a847STejun Heo 	}
578224b8a847STejun Heo 
5783a0a1a5fdSTejun Heo out_unlock:
578468e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5785a0a1a5fdSTejun Heo }
5786a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
5787a0a1a5fdSTejun Heo 
578899c621efSLai Jiangshan static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
5789042f7df1SLai Jiangshan {
5790042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
5791042f7df1SLai Jiangshan 	int ret = 0;
5792042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
5793042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
5794042f7df1SLai Jiangshan 
5795042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5796042f7df1SLai Jiangshan 
5797042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
5798042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
5799042f7df1SLai Jiangshan 			continue;
5800ca10d851SWaiman Long 
5801042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
5802ca10d851SWaiman Long 		if (!list_empty(&wq->pwqs)) {
5803ca10d851SWaiman Long 			if (wq->flags & __WQ_ORDERED_EXPLICIT)
5804042f7df1SLai Jiangshan 				continue;
5805ca10d851SWaiman Long 			wq->flags &= ~__WQ_ORDERED;
5806ca10d851SWaiman Long 		}
5807042f7df1SLai Jiangshan 
580899c621efSLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
580984193c07STejun Heo 		if (IS_ERR(ctx)) {
581084193c07STejun Heo 			ret = PTR_ERR(ctx);
5811042f7df1SLai Jiangshan 			break;
5812042f7df1SLai Jiangshan 		}
5813042f7df1SLai Jiangshan 
5814042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
5815042f7df1SLai Jiangshan 	}
5816042f7df1SLai Jiangshan 
5817042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
5818042f7df1SLai Jiangshan 		if (!ret)
5819042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
5820042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
5821042f7df1SLai Jiangshan 	}
5822042f7df1SLai Jiangshan 
582399c621efSLai Jiangshan 	if (!ret) {
582499c621efSLai Jiangshan 		mutex_lock(&wq_pool_attach_mutex);
582599c621efSLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
582699c621efSLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
582799c621efSLai Jiangshan 	}
5828042f7df1SLai Jiangshan 	return ret;
5829042f7df1SLai Jiangshan }
5830042f7df1SLai Jiangshan 
5831042f7df1SLai Jiangshan /**
5832fe28f631SWaiman Long  * workqueue_unbound_exclude_cpumask - Exclude given CPUs from unbound cpumask
5833fe28f631SWaiman Long  * @exclude_cpumask: the cpumask to be excluded from wq_unbound_cpumask
5834fe28f631SWaiman Long  *
5835fe28f631SWaiman Long  * This function can be called from cpuset code to provide a set of isolated
5836fe28f631SWaiman Long  * CPUs that should be excluded from wq_unbound_cpumask. The caller must hold
5837fe28f631SWaiman Long  * either cpus_read_lock or cpus_write_lock.
5838fe28f631SWaiman Long  */
5839fe28f631SWaiman Long int workqueue_unbound_exclude_cpumask(cpumask_var_t exclude_cpumask)
5840fe28f631SWaiman Long {
5841fe28f631SWaiman Long 	cpumask_var_t cpumask;
5842fe28f631SWaiman Long 	int ret = 0;
5843fe28f631SWaiman Long 
5844fe28f631SWaiman Long 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5845fe28f631SWaiman Long 		return -ENOMEM;
5846fe28f631SWaiman Long 
5847fe28f631SWaiman Long 	lockdep_assert_cpus_held();
5848fe28f631SWaiman Long 	mutex_lock(&wq_pool_mutex);
5849fe28f631SWaiman Long 
5850fe28f631SWaiman Long 	/* Save the current isolated cpumask & export it via sysfs */
5851fe28f631SWaiman Long 	cpumask_copy(wq_isolated_cpumask, exclude_cpumask);
5852fe28f631SWaiman Long 
5853fe28f631SWaiman Long 	/*
5854fe28f631SWaiman Long 	 * If the operation fails, it will fall back to
5855fe28f631SWaiman Long 	 * wq_requested_unbound_cpumask which is initially set to
5856fe28f631SWaiman Long 	 * (HK_TYPE_WQ ∩ HK_TYPE_DOMAIN) house keeping mask and rewritten
5857fe28f631SWaiman Long 	 * by any subsequent write to workqueue/cpumask sysfs file.
5858fe28f631SWaiman Long 	 */
5859fe28f631SWaiman Long 	if (!cpumask_andnot(cpumask, wq_requested_unbound_cpumask, exclude_cpumask))
5860fe28f631SWaiman Long 		cpumask_copy(cpumask, wq_requested_unbound_cpumask);
5861fe28f631SWaiman Long 	if (!cpumask_equal(cpumask, wq_unbound_cpumask))
5862fe28f631SWaiman Long 		ret = workqueue_apply_unbound_cpumask(cpumask);
5863fe28f631SWaiman Long 
5864fe28f631SWaiman Long 	mutex_unlock(&wq_pool_mutex);
5865fe28f631SWaiman Long 	free_cpumask_var(cpumask);
5866fe28f631SWaiman Long 	return ret;
5867fe28f631SWaiman Long }
5868fe28f631SWaiman Long 
586963c5484eSTejun Heo static int parse_affn_scope(const char *val)
587063c5484eSTejun Heo {
587163c5484eSTejun Heo 	int i;
587263c5484eSTejun Heo 
587363c5484eSTejun Heo 	for (i = 0; i < ARRAY_SIZE(wq_affn_names); i++) {
587463c5484eSTejun Heo 		if (!strncasecmp(val, wq_affn_names[i], strlen(wq_affn_names[i])))
587563c5484eSTejun Heo 			return i;
587663c5484eSTejun Heo 	}
587763c5484eSTejun Heo 	return -EINVAL;
587863c5484eSTejun Heo }
587963c5484eSTejun Heo 
588063c5484eSTejun Heo static int wq_affn_dfl_set(const char *val, const struct kernel_param *kp)
588163c5484eSTejun Heo {
5882523a301eSTejun Heo 	struct workqueue_struct *wq;
5883523a301eSTejun Heo 	int affn, cpu;
588463c5484eSTejun Heo 
588563c5484eSTejun Heo 	affn = parse_affn_scope(val);
588663c5484eSTejun Heo 	if (affn < 0)
588763c5484eSTejun Heo 		return affn;
5888523a301eSTejun Heo 	if (affn == WQ_AFFN_DFL)
5889523a301eSTejun Heo 		return -EINVAL;
5890523a301eSTejun Heo 
5891523a301eSTejun Heo 	cpus_read_lock();
5892523a301eSTejun Heo 	mutex_lock(&wq_pool_mutex);
589363c5484eSTejun Heo 
589463c5484eSTejun Heo 	wq_affn_dfl = affn;
5895523a301eSTejun Heo 
5896523a301eSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5897523a301eSTejun Heo 		for_each_online_cpu(cpu) {
5898523a301eSTejun Heo 			wq_update_pod(wq, cpu, cpu, true);
5899523a301eSTejun Heo 		}
5900523a301eSTejun Heo 	}
5901523a301eSTejun Heo 
5902523a301eSTejun Heo 	mutex_unlock(&wq_pool_mutex);
5903523a301eSTejun Heo 	cpus_read_unlock();
5904523a301eSTejun Heo 
590563c5484eSTejun Heo 	return 0;
590663c5484eSTejun Heo }
590763c5484eSTejun Heo 
590863c5484eSTejun Heo static int wq_affn_dfl_get(char *buffer, const struct kernel_param *kp)
590963c5484eSTejun Heo {
591063c5484eSTejun Heo 	return scnprintf(buffer, PAGE_SIZE, "%s\n", wq_affn_names[wq_affn_dfl]);
591163c5484eSTejun Heo }
591263c5484eSTejun Heo 
591363c5484eSTejun Heo static const struct kernel_param_ops wq_affn_dfl_ops = {
591463c5484eSTejun Heo 	.set	= wq_affn_dfl_set,
591563c5484eSTejun Heo 	.get	= wq_affn_dfl_get,
591663c5484eSTejun Heo };
591763c5484eSTejun Heo 
591863c5484eSTejun Heo module_param_cb(default_affinity_scope, &wq_affn_dfl_ops, NULL, 0644);
591963c5484eSTejun Heo 
59206ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
59216ba94429SFrederic Weisbecker /*
59226ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
59236ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
59246ba94429SFrederic Weisbecker  * following attributes.
59256ba94429SFrederic Weisbecker  *
59266ba94429SFrederic Weisbecker  *  per_cpu		RO bool	: whether the workqueue is per-cpu or unbound
59276ba94429SFrederic Weisbecker  *  max_active		RW int	: maximum number of in-flight work items
59286ba94429SFrederic Weisbecker  *
59296ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
59306ba94429SFrederic Weisbecker  *
59316ba94429SFrederic Weisbecker  *  nice		RW int	: nice value of the workers
59326ba94429SFrederic Weisbecker  *  cpumask		RW mask	: bitmask of allowed CPUs for the workers
593363c5484eSTejun Heo  *  affinity_scope	RW str  : worker CPU affinity scope (cache, numa, none)
59348639ecebSTejun Heo  *  affinity_strict	RW bool : worker CPU affinity is strict
59356ba94429SFrederic Weisbecker  */
59366ba94429SFrederic Weisbecker struct wq_device {
59376ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
59386ba94429SFrederic Weisbecker 	struct device			dev;
59396ba94429SFrederic Weisbecker };
59406ba94429SFrederic Weisbecker 
59416ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
59426ba94429SFrederic Weisbecker {
59436ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
59446ba94429SFrederic Weisbecker 
59456ba94429SFrederic Weisbecker 	return wq_dev->wq;
59466ba94429SFrederic Weisbecker }
59476ba94429SFrederic Weisbecker 
59486ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
59496ba94429SFrederic Weisbecker 			    char *buf)
59506ba94429SFrederic Weisbecker {
59516ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
59526ba94429SFrederic Weisbecker 
59536ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
59546ba94429SFrederic Weisbecker }
59556ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
59566ba94429SFrederic Weisbecker 
59576ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
59586ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
59596ba94429SFrederic Weisbecker {
59606ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
59616ba94429SFrederic Weisbecker 
59626ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
59636ba94429SFrederic Weisbecker }
59646ba94429SFrederic Weisbecker 
59656ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
59666ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
59676ba94429SFrederic Weisbecker 				size_t count)
59686ba94429SFrederic Weisbecker {
59696ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
59706ba94429SFrederic Weisbecker 	int val;
59716ba94429SFrederic Weisbecker 
59726ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
59736ba94429SFrederic Weisbecker 		return -EINVAL;
59746ba94429SFrederic Weisbecker 
59756ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
59766ba94429SFrederic Weisbecker 	return count;
59776ba94429SFrederic Weisbecker }
59786ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
59796ba94429SFrederic Weisbecker 
59806ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
59816ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
59826ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
59836ba94429SFrederic Weisbecker 	NULL,
59846ba94429SFrederic Weisbecker };
59856ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
59866ba94429SFrederic Weisbecker 
598749277a5bSWaiman Long static void apply_wqattrs_lock(void)
598849277a5bSWaiman Long {
598949277a5bSWaiman Long 	/* CPUs should stay stable across pwq creations and installations */
599049277a5bSWaiman Long 	cpus_read_lock();
599149277a5bSWaiman Long 	mutex_lock(&wq_pool_mutex);
599249277a5bSWaiman Long }
599349277a5bSWaiman Long 
599449277a5bSWaiman Long static void apply_wqattrs_unlock(void)
599549277a5bSWaiman Long {
599649277a5bSWaiman Long 	mutex_unlock(&wq_pool_mutex);
599749277a5bSWaiman Long 	cpus_read_unlock();
599849277a5bSWaiman Long }
599949277a5bSWaiman Long 
60006ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
60016ba94429SFrederic Weisbecker 			    char *buf)
60026ba94429SFrederic Weisbecker {
60036ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
60046ba94429SFrederic Weisbecker 	int written;
60056ba94429SFrederic Weisbecker 
60066ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
60076ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
60086ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
60096ba94429SFrederic Weisbecker 
60106ba94429SFrederic Weisbecker 	return written;
60116ba94429SFrederic Weisbecker }
60126ba94429SFrederic Weisbecker 
60136ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
60146ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
60156ba94429SFrederic Weisbecker {
60166ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
60176ba94429SFrederic Weisbecker 
6018899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
6019899a94feSLai Jiangshan 
6020be69d00dSThomas Gleixner 	attrs = alloc_workqueue_attrs();
60216ba94429SFrederic Weisbecker 	if (!attrs)
60226ba94429SFrederic Weisbecker 		return NULL;
60236ba94429SFrederic Weisbecker 
60246ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
60256ba94429SFrederic Weisbecker 	return attrs;
60266ba94429SFrederic Weisbecker }
60276ba94429SFrederic Weisbecker 
60286ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
60296ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
60306ba94429SFrederic Weisbecker {
60316ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
60326ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
6033d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
6034d4d3e257SLai Jiangshan 
6035d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
60366ba94429SFrederic Weisbecker 
60376ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
60386ba94429SFrederic Weisbecker 	if (!attrs)
6039d4d3e257SLai Jiangshan 		goto out_unlock;
60406ba94429SFrederic Weisbecker 
60416ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
60426ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
6043d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
60446ba94429SFrederic Weisbecker 	else
60456ba94429SFrederic Weisbecker 		ret = -EINVAL;
60466ba94429SFrederic Weisbecker 
6047d4d3e257SLai Jiangshan out_unlock:
6048d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
60496ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
60506ba94429SFrederic Weisbecker 	return ret ?: count;
60516ba94429SFrederic Weisbecker }
60526ba94429SFrederic Weisbecker 
60536ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
60546ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
60556ba94429SFrederic Weisbecker {
60566ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
60576ba94429SFrederic Weisbecker 	int written;
60586ba94429SFrederic Weisbecker 
60596ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
60606ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
60616ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
60626ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
60636ba94429SFrederic Weisbecker 	return written;
60646ba94429SFrederic Weisbecker }
60656ba94429SFrederic Weisbecker 
60666ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
60676ba94429SFrederic Weisbecker 				struct device_attribute *attr,
60686ba94429SFrederic Weisbecker 				const char *buf, size_t count)
60696ba94429SFrederic Weisbecker {
60706ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
60716ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
6072d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
6073d4d3e257SLai Jiangshan 
6074d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
60756ba94429SFrederic Weisbecker 
60766ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
60776ba94429SFrederic Weisbecker 	if (!attrs)
6078d4d3e257SLai Jiangshan 		goto out_unlock;
60796ba94429SFrederic Weisbecker 
60806ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
60816ba94429SFrederic Weisbecker 	if (!ret)
6082d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
60836ba94429SFrederic Weisbecker 
6084d4d3e257SLai Jiangshan out_unlock:
6085d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
60866ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
60876ba94429SFrederic Weisbecker 	return ret ?: count;
60886ba94429SFrederic Weisbecker }
60896ba94429SFrederic Weisbecker 
609063c5484eSTejun Heo static ssize_t wq_affn_scope_show(struct device *dev,
609163c5484eSTejun Heo 				  struct device_attribute *attr, char *buf)
609263c5484eSTejun Heo {
609363c5484eSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
609463c5484eSTejun Heo 	int written;
609563c5484eSTejun Heo 
609663c5484eSTejun Heo 	mutex_lock(&wq->mutex);
6097523a301eSTejun Heo 	if (wq->unbound_attrs->affn_scope == WQ_AFFN_DFL)
6098523a301eSTejun Heo 		written = scnprintf(buf, PAGE_SIZE, "%s (%s)\n",
6099523a301eSTejun Heo 				    wq_affn_names[WQ_AFFN_DFL],
6100523a301eSTejun Heo 				    wq_affn_names[wq_affn_dfl]);
6101523a301eSTejun Heo 	else
610263c5484eSTejun Heo 		written = scnprintf(buf, PAGE_SIZE, "%s\n",
610363c5484eSTejun Heo 				    wq_affn_names[wq->unbound_attrs->affn_scope]);
610463c5484eSTejun Heo 	mutex_unlock(&wq->mutex);
610563c5484eSTejun Heo 
610663c5484eSTejun Heo 	return written;
610763c5484eSTejun Heo }
610863c5484eSTejun Heo 
610963c5484eSTejun Heo static ssize_t wq_affn_scope_store(struct device *dev,
611063c5484eSTejun Heo 				   struct device_attribute *attr,
611163c5484eSTejun Heo 				   const char *buf, size_t count)
611263c5484eSTejun Heo {
611363c5484eSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
611463c5484eSTejun Heo 	struct workqueue_attrs *attrs;
611563c5484eSTejun Heo 	int affn, ret = -ENOMEM;
611663c5484eSTejun Heo 
611763c5484eSTejun Heo 	affn = parse_affn_scope(buf);
611863c5484eSTejun Heo 	if (affn < 0)
611963c5484eSTejun Heo 		return affn;
612063c5484eSTejun Heo 
612163c5484eSTejun Heo 	apply_wqattrs_lock();
612263c5484eSTejun Heo 	attrs = wq_sysfs_prep_attrs(wq);
612363c5484eSTejun Heo 	if (attrs) {
612463c5484eSTejun Heo 		attrs->affn_scope = affn;
612563c5484eSTejun Heo 		ret = apply_workqueue_attrs_locked(wq, attrs);
612663c5484eSTejun Heo 	}
612763c5484eSTejun Heo 	apply_wqattrs_unlock();
612863c5484eSTejun Heo 	free_workqueue_attrs(attrs);
612963c5484eSTejun Heo 	return ret ?: count;
613063c5484eSTejun Heo }
613163c5484eSTejun Heo 
61328639ecebSTejun Heo static ssize_t wq_affinity_strict_show(struct device *dev,
61338639ecebSTejun Heo 				       struct device_attribute *attr, char *buf)
61348639ecebSTejun Heo {
61358639ecebSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
61368639ecebSTejun Heo 
61378639ecebSTejun Heo 	return scnprintf(buf, PAGE_SIZE, "%d\n",
61388639ecebSTejun Heo 			 wq->unbound_attrs->affn_strict);
61398639ecebSTejun Heo }
61408639ecebSTejun Heo 
61418639ecebSTejun Heo static ssize_t wq_affinity_strict_store(struct device *dev,
61428639ecebSTejun Heo 					struct device_attribute *attr,
61438639ecebSTejun Heo 					const char *buf, size_t count)
61448639ecebSTejun Heo {
61458639ecebSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
61468639ecebSTejun Heo 	struct workqueue_attrs *attrs;
61478639ecebSTejun Heo 	int v, ret = -ENOMEM;
61488639ecebSTejun Heo 
61498639ecebSTejun Heo 	if (sscanf(buf, "%d", &v) != 1)
61508639ecebSTejun Heo 		return -EINVAL;
61518639ecebSTejun Heo 
61528639ecebSTejun Heo 	apply_wqattrs_lock();
61538639ecebSTejun Heo 	attrs = wq_sysfs_prep_attrs(wq);
61548639ecebSTejun Heo 	if (attrs) {
61558639ecebSTejun Heo 		attrs->affn_strict = (bool)v;
61568639ecebSTejun Heo 		ret = apply_workqueue_attrs_locked(wq, attrs);
61578639ecebSTejun Heo 	}
61588639ecebSTejun Heo 	apply_wqattrs_unlock();
61598639ecebSTejun Heo 	free_workqueue_attrs(attrs);
61608639ecebSTejun Heo 	return ret ?: count;
61618639ecebSTejun Heo }
61628639ecebSTejun Heo 
61636ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
61646ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
61656ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
616663c5484eSTejun Heo 	__ATTR(affinity_scope, 0644, wq_affn_scope_show, wq_affn_scope_store),
61678639ecebSTejun Heo 	__ATTR(affinity_strict, 0644, wq_affinity_strict_show, wq_affinity_strict_store),
61686ba94429SFrederic Weisbecker 	__ATTR_NULL,
61696ba94429SFrederic Weisbecker };
61706ba94429SFrederic Weisbecker 
61716ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
61726ba94429SFrederic Weisbecker 	.name				= "workqueue",
61736ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
61746ba94429SFrederic Weisbecker };
61756ba94429SFrederic Weisbecker 
617649277a5bSWaiman Long /**
617749277a5bSWaiman Long  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
617849277a5bSWaiman Long  *  @cpumask: the cpumask to set
617949277a5bSWaiman Long  *
618049277a5bSWaiman Long  *  The low-level workqueues cpumask is a global cpumask that limits
618149277a5bSWaiman Long  *  the affinity of all unbound workqueues.  This function check the @cpumask
618249277a5bSWaiman Long  *  and apply it to all unbound workqueues and updates all pwqs of them.
618349277a5bSWaiman Long  *
618449277a5bSWaiman Long  *  Return:	0	- Success
618549277a5bSWaiman Long  *		-EINVAL	- Invalid @cpumask
618649277a5bSWaiman Long  *		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
618749277a5bSWaiman Long  */
618849277a5bSWaiman Long static int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
618949277a5bSWaiman Long {
619049277a5bSWaiman Long 	int ret = -EINVAL;
619149277a5bSWaiman Long 
619249277a5bSWaiman Long 	/*
619349277a5bSWaiman Long 	 * Not excluding isolated cpus on purpose.
619449277a5bSWaiman Long 	 * If the user wishes to include them, we allow that.
619549277a5bSWaiman Long 	 */
619649277a5bSWaiman Long 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
619749277a5bSWaiman Long 	if (!cpumask_empty(cpumask)) {
619849277a5bSWaiman Long 		apply_wqattrs_lock();
619949277a5bSWaiman Long 		cpumask_copy(wq_requested_unbound_cpumask, cpumask);
620049277a5bSWaiman Long 		if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
620149277a5bSWaiman Long 			ret = 0;
620249277a5bSWaiman Long 			goto out_unlock;
620349277a5bSWaiman Long 		}
620449277a5bSWaiman Long 
620549277a5bSWaiman Long 		ret = workqueue_apply_unbound_cpumask(cpumask);
620649277a5bSWaiman Long 
620749277a5bSWaiman Long out_unlock:
620849277a5bSWaiman Long 		apply_wqattrs_unlock();
620949277a5bSWaiman Long 	}
621049277a5bSWaiman Long 
621149277a5bSWaiman Long 	return ret;
621249277a5bSWaiman Long }
621349277a5bSWaiman Long 
6214fe28f631SWaiman Long static ssize_t __wq_cpumask_show(struct device *dev,
6215fe28f631SWaiman Long 		struct device_attribute *attr, char *buf, cpumask_var_t mask)
6216b05a7928SFrederic Weisbecker {
6217b05a7928SFrederic Weisbecker 	int written;
6218b05a7928SFrederic Weisbecker 
6219042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
6220fe28f631SWaiman Long 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n", cpumask_pr_args(mask));
6221042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
6222b05a7928SFrederic Weisbecker 
6223b05a7928SFrederic Weisbecker 	return written;
6224b05a7928SFrederic Weisbecker }
6225b05a7928SFrederic Weisbecker 
6226fe28f631SWaiman Long static ssize_t wq_unbound_cpumask_show(struct device *dev,
6227fe28f631SWaiman Long 		struct device_attribute *attr, char *buf)
6228fe28f631SWaiman Long {
6229fe28f631SWaiman Long 	return __wq_cpumask_show(dev, attr, buf, wq_unbound_cpumask);
6230fe28f631SWaiman Long }
6231fe28f631SWaiman Long 
6232fe28f631SWaiman Long static ssize_t wq_requested_cpumask_show(struct device *dev,
6233fe28f631SWaiman Long 		struct device_attribute *attr, char *buf)
6234fe28f631SWaiman Long {
6235fe28f631SWaiman Long 	return __wq_cpumask_show(dev, attr, buf, wq_requested_unbound_cpumask);
6236fe28f631SWaiman Long }
6237fe28f631SWaiman Long 
6238fe28f631SWaiman Long static ssize_t wq_isolated_cpumask_show(struct device *dev,
6239fe28f631SWaiman Long 		struct device_attribute *attr, char *buf)
6240fe28f631SWaiman Long {
6241fe28f631SWaiman Long 	return __wq_cpumask_show(dev, attr, buf, wq_isolated_cpumask);
6242fe28f631SWaiman Long }
6243fe28f631SWaiman Long 
6244042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
6245042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
6246042f7df1SLai Jiangshan {
6247042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
6248042f7df1SLai Jiangshan 	int ret;
6249042f7df1SLai Jiangshan 
6250042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
6251042f7df1SLai Jiangshan 		return -ENOMEM;
6252042f7df1SLai Jiangshan 
6253042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
6254042f7df1SLai Jiangshan 	if (!ret)
6255042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
6256042f7df1SLai Jiangshan 
6257042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
6258042f7df1SLai Jiangshan 	return ret ? ret : count;
6259042f7df1SLai Jiangshan }
6260042f7df1SLai Jiangshan 
6261fe28f631SWaiman Long static struct device_attribute wq_sysfs_cpumask_attrs[] = {
6262042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
6263fe28f631SWaiman Long 	       wq_unbound_cpumask_store),
6264fe28f631SWaiman Long 	__ATTR(cpumask_requested, 0444, wq_requested_cpumask_show, NULL),
6265fe28f631SWaiman Long 	__ATTR(cpumask_isolated, 0444, wq_isolated_cpumask_show, NULL),
6266fe28f631SWaiman Long 	__ATTR_NULL,
6267fe28f631SWaiman Long };
6268b05a7928SFrederic Weisbecker 
62696ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
62706ba94429SFrederic Weisbecker {
6271686f6697SGreg Kroah-Hartman 	struct device *dev_root;
6272b05a7928SFrederic Weisbecker 	int err;
6273b05a7928SFrederic Weisbecker 
6274b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
6275b05a7928SFrederic Weisbecker 	if (err)
6276b05a7928SFrederic Weisbecker 		return err;
6277b05a7928SFrederic Weisbecker 
6278686f6697SGreg Kroah-Hartman 	dev_root = bus_get_dev_root(&wq_subsys);
6279686f6697SGreg Kroah-Hartman 	if (dev_root) {
6280fe28f631SWaiman Long 		struct device_attribute *attr;
6281fe28f631SWaiman Long 
6282fe28f631SWaiman Long 		for (attr = wq_sysfs_cpumask_attrs; attr->attr.name; attr++) {
6283fe28f631SWaiman Long 			err = device_create_file(dev_root, attr);
6284fe28f631SWaiman Long 			if (err)
6285fe28f631SWaiman Long 				break;
6286fe28f631SWaiman Long 		}
6287686f6697SGreg Kroah-Hartman 		put_device(dev_root);
6288686f6697SGreg Kroah-Hartman 	}
6289686f6697SGreg Kroah-Hartman 	return err;
62906ba94429SFrederic Weisbecker }
62916ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
62926ba94429SFrederic Weisbecker 
62936ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
62946ba94429SFrederic Weisbecker {
62956ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
62966ba94429SFrederic Weisbecker 
62976ba94429SFrederic Weisbecker 	kfree(wq_dev);
62986ba94429SFrederic Weisbecker }
62996ba94429SFrederic Weisbecker 
63006ba94429SFrederic Weisbecker /**
63016ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
63026ba94429SFrederic Weisbecker  * @wq: the workqueue to register
63036ba94429SFrederic Weisbecker  *
63046ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
63056ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
63066ba94429SFrederic Weisbecker  * which is the preferred method.
63076ba94429SFrederic Weisbecker  *
63086ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
63096ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
63106ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
63116ba94429SFrederic Weisbecker  * attributes.
63126ba94429SFrederic Weisbecker  *
63136ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
63146ba94429SFrederic Weisbecker  */
63156ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
63166ba94429SFrederic Weisbecker {
63176ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
63186ba94429SFrederic Weisbecker 	int ret;
63196ba94429SFrederic Weisbecker 
63206ba94429SFrederic Weisbecker 	/*
6321402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
63226ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
63236ba94429SFrederic Weisbecker 	 * workqueues.
63246ba94429SFrederic Weisbecker 	 */
63250a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
63266ba94429SFrederic Weisbecker 		return -EINVAL;
63276ba94429SFrederic Weisbecker 
63286ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
63296ba94429SFrederic Weisbecker 	if (!wq_dev)
63306ba94429SFrederic Weisbecker 		return -ENOMEM;
63316ba94429SFrederic Weisbecker 
63326ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
63336ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
63346ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
633523217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
63366ba94429SFrederic Weisbecker 
63376ba94429SFrederic Weisbecker 	/*
63386ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
63396ba94429SFrederic Weisbecker 	 * everything is ready.
63406ba94429SFrederic Weisbecker 	 */
63416ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
63426ba94429SFrederic Weisbecker 
63436ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
63446ba94429SFrederic Weisbecker 	if (ret) {
6345537f4146SArvind Yadav 		put_device(&wq_dev->dev);
63466ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
63476ba94429SFrederic Weisbecker 		return ret;
63486ba94429SFrederic Weisbecker 	}
63496ba94429SFrederic Weisbecker 
63506ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
63516ba94429SFrederic Weisbecker 		struct device_attribute *attr;
63526ba94429SFrederic Weisbecker 
63536ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
63546ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
63556ba94429SFrederic Weisbecker 			if (ret) {
63566ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
63576ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
63586ba94429SFrederic Weisbecker 				return ret;
63596ba94429SFrederic Weisbecker 			}
63606ba94429SFrederic Weisbecker 		}
63616ba94429SFrederic Weisbecker 	}
63626ba94429SFrederic Weisbecker 
63636ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
63646ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
63656ba94429SFrederic Weisbecker 	return 0;
63666ba94429SFrederic Weisbecker }
63676ba94429SFrederic Weisbecker 
63686ba94429SFrederic Weisbecker /**
63696ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
63706ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
63716ba94429SFrederic Weisbecker  *
63726ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
63736ba94429SFrederic Weisbecker  */
63746ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
63756ba94429SFrederic Weisbecker {
63766ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
63776ba94429SFrederic Weisbecker 
63786ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
63796ba94429SFrederic Weisbecker 		return;
63806ba94429SFrederic Weisbecker 
63816ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
63826ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
63836ba94429SFrederic Weisbecker }
63846ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
63856ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
63866ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
63876ba94429SFrederic Weisbecker 
638882607adcSTejun Heo /*
638982607adcSTejun Heo  * Workqueue watchdog.
639082607adcSTejun Heo  *
639182607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
639282607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
639382607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
639482607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
639582607adcSTejun Heo  * largely opaque.
639682607adcSTejun Heo  *
639782607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
639882607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
639982607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
640082607adcSTejun Heo  *
640182607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
640282607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
640382607adcSTejun Heo  * corresponding sysfs parameter file.
640482607adcSTejun Heo  */
640582607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
640682607adcSTejun Heo 
640782607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
64085cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
640982607adcSTejun Heo 
641082607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
641182607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
641282607adcSTejun Heo 
6413cd2440d6SPetr Mladek /*
6414cd2440d6SPetr Mladek  * Show workers that might prevent the processing of pending work items.
6415cd2440d6SPetr Mladek  * The only candidates are CPU-bound workers in the running state.
6416cd2440d6SPetr Mladek  * Pending work items should be handled by another idle worker
6417cd2440d6SPetr Mladek  * in all other situations.
6418cd2440d6SPetr Mladek  */
6419cd2440d6SPetr Mladek static void show_cpu_pool_hog(struct worker_pool *pool)
6420cd2440d6SPetr Mladek {
6421cd2440d6SPetr Mladek 	struct worker *worker;
6422cd2440d6SPetr Mladek 	unsigned long flags;
6423cd2440d6SPetr Mladek 	int bkt;
6424cd2440d6SPetr Mladek 
6425cd2440d6SPetr Mladek 	raw_spin_lock_irqsave(&pool->lock, flags);
6426cd2440d6SPetr Mladek 
6427cd2440d6SPetr Mladek 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
6428cd2440d6SPetr Mladek 		if (task_is_running(worker->task)) {
6429cd2440d6SPetr Mladek 			/*
6430cd2440d6SPetr Mladek 			 * Defer printing to avoid deadlocks in console
6431cd2440d6SPetr Mladek 			 * drivers that queue work while holding locks
6432cd2440d6SPetr Mladek 			 * also taken in their write paths.
6433cd2440d6SPetr Mladek 			 */
6434cd2440d6SPetr Mladek 			printk_deferred_enter();
6435cd2440d6SPetr Mladek 
6436cd2440d6SPetr Mladek 			pr_info("pool %d:\n", pool->id);
6437cd2440d6SPetr Mladek 			sched_show_task(worker->task);
6438cd2440d6SPetr Mladek 
6439cd2440d6SPetr Mladek 			printk_deferred_exit();
6440cd2440d6SPetr Mladek 		}
6441cd2440d6SPetr Mladek 	}
6442cd2440d6SPetr Mladek 
6443cd2440d6SPetr Mladek 	raw_spin_unlock_irqrestore(&pool->lock, flags);
6444cd2440d6SPetr Mladek }
6445cd2440d6SPetr Mladek 
6446cd2440d6SPetr Mladek static void show_cpu_pools_hogs(void)
6447cd2440d6SPetr Mladek {
6448cd2440d6SPetr Mladek 	struct worker_pool *pool;
6449cd2440d6SPetr Mladek 	int pi;
6450cd2440d6SPetr Mladek 
6451cd2440d6SPetr Mladek 	pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
6452cd2440d6SPetr Mladek 
6453cd2440d6SPetr Mladek 	rcu_read_lock();
6454cd2440d6SPetr Mladek 
6455cd2440d6SPetr Mladek 	for_each_pool(pool, pi) {
6456cd2440d6SPetr Mladek 		if (pool->cpu_stall)
6457cd2440d6SPetr Mladek 			show_cpu_pool_hog(pool);
6458cd2440d6SPetr Mladek 
6459cd2440d6SPetr Mladek 	}
6460cd2440d6SPetr Mladek 
6461cd2440d6SPetr Mladek 	rcu_read_unlock();
6462cd2440d6SPetr Mladek }
6463cd2440d6SPetr Mladek 
646482607adcSTejun Heo static void wq_watchdog_reset_touched(void)
646582607adcSTejun Heo {
646682607adcSTejun Heo 	int cpu;
646782607adcSTejun Heo 
646882607adcSTejun Heo 	wq_watchdog_touched = jiffies;
646982607adcSTejun Heo 	for_each_possible_cpu(cpu)
647082607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
647182607adcSTejun Heo }
647282607adcSTejun Heo 
64735cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
647482607adcSTejun Heo {
647582607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
647682607adcSTejun Heo 	bool lockup_detected = false;
6477cd2440d6SPetr Mladek 	bool cpu_pool_stall = false;
6478940d71c6SSergey Senozhatsky 	unsigned long now = jiffies;
647982607adcSTejun Heo 	struct worker_pool *pool;
648082607adcSTejun Heo 	int pi;
648182607adcSTejun Heo 
648282607adcSTejun Heo 	if (!thresh)
648382607adcSTejun Heo 		return;
648482607adcSTejun Heo 
648582607adcSTejun Heo 	rcu_read_lock();
648682607adcSTejun Heo 
648782607adcSTejun Heo 	for_each_pool(pool, pi) {
648882607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
648982607adcSTejun Heo 
6490cd2440d6SPetr Mladek 		pool->cpu_stall = false;
649182607adcSTejun Heo 		if (list_empty(&pool->worklist))
649282607adcSTejun Heo 			continue;
649382607adcSTejun Heo 
6494940d71c6SSergey Senozhatsky 		/*
6495940d71c6SSergey Senozhatsky 		 * If a virtual machine is stopped by the host it can look to
6496940d71c6SSergey Senozhatsky 		 * the watchdog like a stall.
6497940d71c6SSergey Senozhatsky 		 */
6498940d71c6SSergey Senozhatsky 		kvm_check_and_clear_guest_paused();
6499940d71c6SSergey Senozhatsky 
650082607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
650189e28ce6SWang Qing 		if (pool->cpu >= 0)
650289e28ce6SWang Qing 			touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
650389e28ce6SWang Qing 		else
650482607adcSTejun Heo 			touched = READ_ONCE(wq_watchdog_touched);
650589e28ce6SWang Qing 		pool_ts = READ_ONCE(pool->watchdog_ts);
650682607adcSTejun Heo 
650782607adcSTejun Heo 		if (time_after(pool_ts, touched))
650882607adcSTejun Heo 			ts = pool_ts;
650982607adcSTejun Heo 		else
651082607adcSTejun Heo 			ts = touched;
651182607adcSTejun Heo 
651282607adcSTejun Heo 		/* did we stall? */
6513940d71c6SSergey Senozhatsky 		if (time_after(now, ts + thresh)) {
651482607adcSTejun Heo 			lockup_detected = true;
6515cd2440d6SPetr Mladek 			if (pool->cpu >= 0) {
6516cd2440d6SPetr Mladek 				pool->cpu_stall = true;
6517cd2440d6SPetr Mladek 				cpu_pool_stall = true;
6518cd2440d6SPetr Mladek 			}
651982607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
652082607adcSTejun Heo 			pr_cont_pool_info(pool);
652182607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
6522940d71c6SSergey Senozhatsky 				jiffies_to_msecs(now - pool_ts) / 1000);
652382607adcSTejun Heo 		}
6524cd2440d6SPetr Mladek 
6525cd2440d6SPetr Mladek 
652682607adcSTejun Heo 	}
652782607adcSTejun Heo 
652882607adcSTejun Heo 	rcu_read_unlock();
652982607adcSTejun Heo 
653082607adcSTejun Heo 	if (lockup_detected)
653155df0933SImran Khan 		show_all_workqueues();
653282607adcSTejun Heo 
6533cd2440d6SPetr Mladek 	if (cpu_pool_stall)
6534cd2440d6SPetr Mladek 		show_cpu_pools_hogs();
6535cd2440d6SPetr Mladek 
653682607adcSTejun Heo 	wq_watchdog_reset_touched();
653782607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
653882607adcSTejun Heo }
653982607adcSTejun Heo 
6540cb9d7fd5SVincent Whitchurch notrace void wq_watchdog_touch(int cpu)
654182607adcSTejun Heo {
654282607adcSTejun Heo 	if (cpu >= 0)
654382607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
654489e28ce6SWang Qing 
654582607adcSTejun Heo 	wq_watchdog_touched = jiffies;
654682607adcSTejun Heo }
654782607adcSTejun Heo 
654882607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
654982607adcSTejun Heo {
655082607adcSTejun Heo 	wq_watchdog_thresh = 0;
655182607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
655282607adcSTejun Heo 
655382607adcSTejun Heo 	if (thresh) {
655482607adcSTejun Heo 		wq_watchdog_thresh = thresh;
655582607adcSTejun Heo 		wq_watchdog_reset_touched();
655682607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
655782607adcSTejun Heo 	}
655882607adcSTejun Heo }
655982607adcSTejun Heo 
656082607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
656182607adcSTejun Heo 					const struct kernel_param *kp)
656282607adcSTejun Heo {
656382607adcSTejun Heo 	unsigned long thresh;
656482607adcSTejun Heo 	int ret;
656582607adcSTejun Heo 
656682607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
656782607adcSTejun Heo 	if (ret)
656882607adcSTejun Heo 		return ret;
656982607adcSTejun Heo 
657082607adcSTejun Heo 	if (system_wq)
657182607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
657282607adcSTejun Heo 	else
657382607adcSTejun Heo 		wq_watchdog_thresh = thresh;
657482607adcSTejun Heo 
657582607adcSTejun Heo 	return 0;
657682607adcSTejun Heo }
657782607adcSTejun Heo 
657882607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
657982607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
658082607adcSTejun Heo 	.get	= param_get_ulong,
658182607adcSTejun Heo };
658282607adcSTejun Heo 
658382607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
658482607adcSTejun Heo 		0644);
658582607adcSTejun Heo 
658682607adcSTejun Heo static void wq_watchdog_init(void)
658782607adcSTejun Heo {
65885cd79d6aSKees Cook 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
658982607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
659082607adcSTejun Heo }
659182607adcSTejun Heo 
659282607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
659382607adcSTejun Heo 
659482607adcSTejun Heo static inline void wq_watchdog_init(void) { }
659582607adcSTejun Heo 
659682607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
659782607adcSTejun Heo 
65984a6c5607STejun Heo static void __init restrict_unbound_cpumask(const char *name, const struct cpumask *mask)
65994a6c5607STejun Heo {
66004a6c5607STejun Heo 	if (!cpumask_intersects(wq_unbound_cpumask, mask)) {
66014a6c5607STejun Heo 		pr_warn("workqueue: Restricting unbound_cpumask (%*pb) with %s (%*pb) leaves no CPU, ignoring\n",
66024a6c5607STejun Heo 			cpumask_pr_args(wq_unbound_cpumask), name, cpumask_pr_args(mask));
66034a6c5607STejun Heo 		return;
66044a6c5607STejun Heo 	}
66054a6c5607STejun Heo 
66064a6c5607STejun Heo 	cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, mask);
66074a6c5607STejun Heo }
66084a6c5607STejun Heo 
66093347fa09STejun Heo /**
66103347fa09STejun Heo  * workqueue_init_early - early init for workqueue subsystem
66113347fa09STejun Heo  *
66122930155bSTejun Heo  * This is the first step of three-staged workqueue subsystem initialization and
66132930155bSTejun Heo  * invoked as soon as the bare basics - memory allocation, cpumasks and idr are
66142930155bSTejun Heo  * up. It sets up all the data structures and system workqueues and allows early
66152930155bSTejun Heo  * boot code to create workqueues and queue/cancel work items. Actual work item
66162930155bSTejun Heo  * execution starts only after kthreads can be created and scheduled right
66172930155bSTejun Heo  * before early initcalls.
66183347fa09STejun Heo  */
66192333e829SYu Chen void __init workqueue_init_early(void)
66201da177e4SLinus Torvalds {
662184193c07STejun Heo 	struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_SYSTEM];
66227a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
66237a4e344cSTejun Heo 	int i, cpu;
6624c34056a3STejun Heo 
662510cdb157SLai Jiangshan 	BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
6626e904e6c2STejun Heo 
6627b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
6628fe28f631SWaiman Long 	BUG_ON(!alloc_cpumask_var(&wq_requested_unbound_cpumask, GFP_KERNEL));
6629fe28f631SWaiman Long 	BUG_ON(!zalloc_cpumask_var(&wq_isolated_cpumask, GFP_KERNEL));
6630b05a7928SFrederic Weisbecker 
66314a6c5607STejun Heo 	cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
66324a6c5607STejun Heo 	restrict_unbound_cpumask("HK_TYPE_WQ", housekeeping_cpumask(HK_TYPE_WQ));
66334a6c5607STejun Heo 	restrict_unbound_cpumask("HK_TYPE_DOMAIN", housekeeping_cpumask(HK_TYPE_DOMAIN));
6634ace3c549Stiozhang 	if (!cpumask_empty(&wq_cmdline_cpumask))
66354a6c5607STejun Heo 		restrict_unbound_cpumask("workqueue.unbound_cpus", &wq_cmdline_cpumask);
6636ace3c549Stiozhang 
6637fe28f631SWaiman Long 	cpumask_copy(wq_requested_unbound_cpumask, wq_unbound_cpumask);
66388b03ae3cSTejun Heo 
66398b03ae3cSTejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6640e22bee78STejun Heo 
66412930155bSTejun Heo 	wq_update_pod_attrs_buf = alloc_workqueue_attrs();
66422930155bSTejun Heo 	BUG_ON(!wq_update_pod_attrs_buf);
66432930155bSTejun Heo 
66447bd20b6bSMarcelo Tosatti 	/*
66457bd20b6bSMarcelo Tosatti 	 * If nohz_full is enabled, set power efficient workqueue as unbound.
66467bd20b6bSMarcelo Tosatti 	 * This allows workqueue items to be moved to HK CPUs.
66477bd20b6bSMarcelo Tosatti 	 */
66487bd20b6bSMarcelo Tosatti 	if (housekeeping_enabled(HK_TYPE_TICK))
66497bd20b6bSMarcelo Tosatti 		wq_power_efficient = true;
66507bd20b6bSMarcelo Tosatti 
665184193c07STejun Heo 	/* initialize WQ_AFFN_SYSTEM pods */
665284193c07STejun Heo 	pt->pod_cpus = kcalloc(1, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
665384193c07STejun Heo 	pt->pod_node = kcalloc(1, sizeof(pt->pod_node[0]), GFP_KERNEL);
665484193c07STejun Heo 	pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
665584193c07STejun Heo 	BUG_ON(!pt->pod_cpus || !pt->pod_node || !pt->cpu_pod);
665684193c07STejun Heo 
665784193c07STejun Heo 	BUG_ON(!zalloc_cpumask_var_node(&pt->pod_cpus[0], GFP_KERNEL, NUMA_NO_NODE));
665884193c07STejun Heo 
665984193c07STejun Heo 	pt->nr_pods = 1;
666084193c07STejun Heo 	cpumask_copy(pt->pod_cpus[0], cpu_possible_mask);
666184193c07STejun Heo 	pt->pod_node[0] = NUMA_NO_NODE;
666284193c07STejun Heo 	pt->cpu_pod[0] = 0;
666384193c07STejun Heo 
6664f02ae73aSTejun Heo 	/* initialize CPU pools */
666524647570STejun Heo 	for_each_possible_cpu(cpu) {
6666ebf44d16STejun Heo 		struct worker_pool *pool;
6667e22bee78STejun Heo 
66684ce62e9eSTejun Heo 		i = 0;
6669e22bee78STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
667029c91e99STejun Heo 			BUG_ON(init_worker_pool(pool));
667129c91e99STejun Heo 			pool->cpu = cpu;
667229c91e99STejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
66739546b29eSTejun Heo 			cpumask_copy(pool->attrs->__pod_cpumask, cpumask_of(cpu));
66741da177e4SLinus Torvalds 			pool->attrs->nice = std_nice[i++];
66758639ecebSTejun Heo 			pool->attrs->affn_strict = true;
66761da177e4SLinus Torvalds 			pool->node = cpu_to_node(cpu);
66771da177e4SLinus Torvalds 
66781da177e4SLinus Torvalds 			/* alloc pool ID */
66791da177e4SLinus Torvalds 			mutex_lock(&wq_pool_mutex);
66801da177e4SLinus Torvalds 			BUG_ON(worker_pool_assign_id(pool));
66811da177e4SLinus Torvalds 			mutex_unlock(&wq_pool_mutex);
668229c91e99STejun Heo 		}
668329c91e99STejun Heo 	}
668429c91e99STejun Heo 
66858a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
668629c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
668729c91e99STejun Heo 		struct workqueue_attrs *attrs;
668829c91e99STejun Heo 
6689be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
669029c91e99STejun Heo 		attrs->nice = std_nice[i];
669129c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
66928a2b7538STejun Heo 
66938a2b7538STejun Heo 		/*
66948a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
66958a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
66968a2b7538STejun Heo 		 */
6697be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
66988a2b7538STejun Heo 		attrs->nice = std_nice[i];
6699af73f5c9STejun Heo 		attrs->ordered = true;
67008a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
670129c91e99STejun Heo 	}
670229c91e99STejun Heo 
67031da177e4SLinus Torvalds 	system_wq = alloc_workqueue("events", 0, 0);
67041aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
67051da177e4SLinus Torvalds 	system_long_wq = alloc_workqueue("events_long", 0, 0);
67061da177e4SLinus Torvalds 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
6707636b927eSTejun Heo 					    WQ_MAX_ACTIVE);
67081da177e4SLinus Torvalds 	system_freezable_wq = alloc_workqueue("events_freezable",
67091da177e4SLinus Torvalds 					      WQ_FREEZABLE, 0);
67100668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
67110668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
67128318d6a6SAudra Mitchell 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_pwr_efficient",
67130668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
67140668106cSViresh Kumar 					      0);
67151aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
67160668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
67170668106cSViresh Kumar 	       !system_power_efficient_wq ||
67180668106cSViresh Kumar 	       !system_freezable_power_efficient_wq);
67193347fa09STejun Heo }
67203347fa09STejun Heo 
6721aa6fde93STejun Heo static void __init wq_cpu_intensive_thresh_init(void)
6722aa6fde93STejun Heo {
6723aa6fde93STejun Heo 	unsigned long thresh;
6724aa6fde93STejun Heo 	unsigned long bogo;
6725aa6fde93STejun Heo 
6726dd64c873SZqiang 	pwq_release_worker = kthread_create_worker(0, "pool_workqueue_release");
6727dd64c873SZqiang 	BUG_ON(IS_ERR(pwq_release_worker));
6728dd64c873SZqiang 
6729aa6fde93STejun Heo 	/* if the user set it to a specific value, keep it */
6730aa6fde93STejun Heo 	if (wq_cpu_intensive_thresh_us != ULONG_MAX)
6731aa6fde93STejun Heo 		return;
6732aa6fde93STejun Heo 
6733aa6fde93STejun Heo 	/*
6734aa6fde93STejun Heo 	 * The default of 10ms is derived from the fact that most modern (as of
6735aa6fde93STejun Heo 	 * 2023) processors can do a lot in 10ms and that it's just below what
6736aa6fde93STejun Heo 	 * most consider human-perceivable. However, the kernel also runs on a
6737aa6fde93STejun Heo 	 * lot slower CPUs including microcontrollers where the threshold is way
6738aa6fde93STejun Heo 	 * too low.
6739aa6fde93STejun Heo 	 *
6740aa6fde93STejun Heo 	 * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
6741aa6fde93STejun Heo 	 * This is by no means accurate but it doesn't have to be. The mechanism
6742aa6fde93STejun Heo 	 * is still useful even when the threshold is fully scaled up. Also, as
6743aa6fde93STejun Heo 	 * the reports would usually be applicable to everyone, some machines
6744aa6fde93STejun Heo 	 * operating on longer thresholds won't significantly diminish their
6745aa6fde93STejun Heo 	 * usefulness.
6746aa6fde93STejun Heo 	 */
6747aa6fde93STejun Heo 	thresh = 10 * USEC_PER_MSEC;
6748aa6fde93STejun Heo 
6749aa6fde93STejun Heo 	/* see init/calibrate.c for lpj -> BogoMIPS calculation */
6750aa6fde93STejun Heo 	bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
6751aa6fde93STejun Heo 	if (bogo < 4000)
6752aa6fde93STejun Heo 		thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
6753aa6fde93STejun Heo 
6754aa6fde93STejun Heo 	pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
6755aa6fde93STejun Heo 		 loops_per_jiffy, bogo, thresh);
6756aa6fde93STejun Heo 
6757aa6fde93STejun Heo 	wq_cpu_intensive_thresh_us = thresh;
6758aa6fde93STejun Heo }
6759aa6fde93STejun Heo 
67603347fa09STejun Heo /**
67613347fa09STejun Heo  * workqueue_init - bring workqueue subsystem fully online
67623347fa09STejun Heo  *
67632930155bSTejun Heo  * This is the second step of three-staged workqueue subsystem initialization
67642930155bSTejun Heo  * and invoked as soon as kthreads can be created and scheduled. Workqueues have
67652930155bSTejun Heo  * been created and work items queued on them, but there are no kworkers
67662930155bSTejun Heo  * executing the work items yet. Populate the worker pools with the initial
67672930155bSTejun Heo  * workers and enable future kworker creations.
67683347fa09STejun Heo  */
67692333e829SYu Chen void __init workqueue_init(void)
67703347fa09STejun Heo {
67712186d9f9STejun Heo 	struct workqueue_struct *wq;
67723347fa09STejun Heo 	struct worker_pool *pool;
67733347fa09STejun Heo 	int cpu, bkt;
67743347fa09STejun Heo 
6775aa6fde93STejun Heo 	wq_cpu_intensive_thresh_init();
6776aa6fde93STejun Heo 
67772186d9f9STejun Heo 	mutex_lock(&wq_pool_mutex);
67782186d9f9STejun Heo 
67792930155bSTejun Heo 	/*
67802930155bSTejun Heo 	 * Per-cpu pools created earlier could be missing node hint. Fix them
67812930155bSTejun Heo 	 * up. Also, create a rescuer for workqueues that requested it.
67822930155bSTejun Heo 	 */
67832186d9f9STejun Heo 	for_each_possible_cpu(cpu) {
67842186d9f9STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
67852186d9f9STejun Heo 			pool->node = cpu_to_node(cpu);
67862186d9f9STejun Heo 		}
67872186d9f9STejun Heo 	}
67882186d9f9STejun Heo 
678940c17f75STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
679040c17f75STejun Heo 		WARN(init_rescuer(wq),
679140c17f75STejun Heo 		     "workqueue: failed to create early rescuer for %s",
679240c17f75STejun Heo 		     wq->name);
679340c17f75STejun Heo 	}
67942186d9f9STejun Heo 
67952186d9f9STejun Heo 	mutex_unlock(&wq_pool_mutex);
67962186d9f9STejun Heo 
67973347fa09STejun Heo 	/* create the initial workers */
67983347fa09STejun Heo 	for_each_online_cpu(cpu) {
67993347fa09STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
68003347fa09STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
68013347fa09STejun Heo 			BUG_ON(!create_worker(pool));
68023347fa09STejun Heo 		}
68033347fa09STejun Heo 	}
68043347fa09STejun Heo 
68053347fa09STejun Heo 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
68063347fa09STejun Heo 		BUG_ON(!create_worker(pool));
68073347fa09STejun Heo 
68083347fa09STejun Heo 	wq_online = true;
680982607adcSTejun Heo 	wq_watchdog_init();
68101da177e4SLinus Torvalds }
6811c4f135d6STetsuo Handa 
6812025e1684STejun Heo /*
6813025e1684STejun Heo  * Initialize @pt by first initializing @pt->cpu_pod[] with pod IDs according to
6814025e1684STejun Heo  * @cpu_shares_pod(). Each subset of CPUs that share a pod is assigned a unique
6815025e1684STejun Heo  * and consecutive pod ID. The rest of @pt is initialized accordingly.
6816025e1684STejun Heo  */
6817025e1684STejun Heo static void __init init_pod_type(struct wq_pod_type *pt,
6818025e1684STejun Heo 				 bool (*cpus_share_pod)(int, int))
6819025e1684STejun Heo {
6820025e1684STejun Heo 	int cur, pre, cpu, pod;
6821025e1684STejun Heo 
6822025e1684STejun Heo 	pt->nr_pods = 0;
6823025e1684STejun Heo 
6824025e1684STejun Heo 	/* init @pt->cpu_pod[] according to @cpus_share_pod() */
6825025e1684STejun Heo 	pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
6826025e1684STejun Heo 	BUG_ON(!pt->cpu_pod);
6827025e1684STejun Heo 
6828025e1684STejun Heo 	for_each_possible_cpu(cur) {
6829025e1684STejun Heo 		for_each_possible_cpu(pre) {
6830025e1684STejun Heo 			if (pre >= cur) {
6831025e1684STejun Heo 				pt->cpu_pod[cur] = pt->nr_pods++;
6832025e1684STejun Heo 				break;
6833025e1684STejun Heo 			}
6834025e1684STejun Heo 			if (cpus_share_pod(cur, pre)) {
6835025e1684STejun Heo 				pt->cpu_pod[cur] = pt->cpu_pod[pre];
6836025e1684STejun Heo 				break;
6837025e1684STejun Heo 			}
6838025e1684STejun Heo 		}
6839025e1684STejun Heo 	}
6840025e1684STejun Heo 
6841025e1684STejun Heo 	/* init the rest to match @pt->cpu_pod[] */
6842025e1684STejun Heo 	pt->pod_cpus = kcalloc(pt->nr_pods, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
6843025e1684STejun Heo 	pt->pod_node = kcalloc(pt->nr_pods, sizeof(pt->pod_node[0]), GFP_KERNEL);
6844025e1684STejun Heo 	BUG_ON(!pt->pod_cpus || !pt->pod_node);
6845025e1684STejun Heo 
6846025e1684STejun Heo 	for (pod = 0; pod < pt->nr_pods; pod++)
6847025e1684STejun Heo 		BUG_ON(!zalloc_cpumask_var(&pt->pod_cpus[pod], GFP_KERNEL));
6848025e1684STejun Heo 
6849025e1684STejun Heo 	for_each_possible_cpu(cpu) {
6850025e1684STejun Heo 		cpumask_set_cpu(cpu, pt->pod_cpus[pt->cpu_pod[cpu]]);
6851025e1684STejun Heo 		pt->pod_node[pt->cpu_pod[cpu]] = cpu_to_node(cpu);
6852025e1684STejun Heo 	}
6853025e1684STejun Heo }
6854025e1684STejun Heo 
685563c5484eSTejun Heo static bool __init cpus_dont_share(int cpu0, int cpu1)
685663c5484eSTejun Heo {
685763c5484eSTejun Heo 	return false;
685863c5484eSTejun Heo }
685963c5484eSTejun Heo 
686063c5484eSTejun Heo static bool __init cpus_share_smt(int cpu0, int cpu1)
686163c5484eSTejun Heo {
686263c5484eSTejun Heo #ifdef CONFIG_SCHED_SMT
686363c5484eSTejun Heo 	return cpumask_test_cpu(cpu0, cpu_smt_mask(cpu1));
686463c5484eSTejun Heo #else
686563c5484eSTejun Heo 	return false;
686663c5484eSTejun Heo #endif
686763c5484eSTejun Heo }
686863c5484eSTejun Heo 
6869025e1684STejun Heo static bool __init cpus_share_numa(int cpu0, int cpu1)
6870025e1684STejun Heo {
6871025e1684STejun Heo 	return cpu_to_node(cpu0) == cpu_to_node(cpu1);
6872025e1684STejun Heo }
6873025e1684STejun Heo 
68742930155bSTejun Heo /**
68752930155bSTejun Heo  * workqueue_init_topology - initialize CPU pods for unbound workqueues
68762930155bSTejun Heo  *
68772930155bSTejun Heo  * This is the third step of there-staged workqueue subsystem initialization and
68782930155bSTejun Heo  * invoked after SMP and topology information are fully initialized. It
68792930155bSTejun Heo  * initializes the unbound CPU pods accordingly.
68802930155bSTejun Heo  */
68812930155bSTejun Heo void __init workqueue_init_topology(void)
6882a86feae6STejun Heo {
68832930155bSTejun Heo 	struct workqueue_struct *wq;
6884025e1684STejun Heo 	int cpu;
6885a86feae6STejun Heo 
688663c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_CPU], cpus_dont_share);
688763c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_SMT], cpus_share_smt);
688863c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_CACHE], cpus_share_cache);
6889025e1684STejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_NUMA], cpus_share_numa);
6890a86feae6STejun Heo 
68912930155bSTejun Heo 	mutex_lock(&wq_pool_mutex);
6892a86feae6STejun Heo 
6893a86feae6STejun Heo 	/*
68942930155bSTejun Heo 	 * Workqueues allocated earlier would have all CPUs sharing the default
68952930155bSTejun Heo 	 * worker pool. Explicitly call wq_update_pod() on all workqueue and CPU
68962930155bSTejun Heo 	 * combinations to apply per-pod sharing.
68972930155bSTejun Heo 	 */
68982930155bSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
68992930155bSTejun Heo 		for_each_online_cpu(cpu) {
69002930155bSTejun Heo 			wq_update_pod(wq, cpu, cpu, true);
69012930155bSTejun Heo 		}
69022930155bSTejun Heo 	}
69032930155bSTejun Heo 
69042930155bSTejun Heo 	mutex_unlock(&wq_pool_mutex);
6905a86feae6STejun Heo }
6906a86feae6STejun Heo 
690720bdedafSTetsuo Handa void __warn_flushing_systemwide_wq(void)
690820bdedafSTetsuo Handa {
690920bdedafSTetsuo Handa 	pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
691020bdedafSTetsuo Handa 	dump_stack();
691120bdedafSTetsuo Handa }
6912c4f135d6STetsuo Handa EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
6913ace3c549Stiozhang 
6914ace3c549Stiozhang static int __init workqueue_unbound_cpus_setup(char *str)
6915ace3c549Stiozhang {
6916ace3c549Stiozhang 	if (cpulist_parse(str, &wq_cmdline_cpumask) < 0) {
6917ace3c549Stiozhang 		cpumask_clear(&wq_cmdline_cpumask);
6918ace3c549Stiozhang 		pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
6919ace3c549Stiozhang 	}
6920ace3c549Stiozhang 
6921ace3c549Stiozhang 	return 1;
6922ace3c549Stiozhang }
6923ace3c549Stiozhang __setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup);
6924