xref: /linux-6.15/kernel/workqueue.c (revision 20bdedaf)
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>
55e22bee78STejun Heo 
56ea138446STejun Heo #include "workqueue_internal.h"
571da177e4SLinus Torvalds 
58c8e55f36STejun Heo enum {
59bc2ae0f5STejun Heo 	/*
6024647570STejun Heo 	 * worker_pool flags
61bc2ae0f5STejun Heo 	 *
6224647570STejun Heo 	 * A bound pool is either associated or disassociated with its CPU.
63bc2ae0f5STejun Heo 	 * While associated (!DISASSOCIATED), all workers are bound to the
64bc2ae0f5STejun Heo 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
65bc2ae0f5STejun Heo 	 * is in effect.
66bc2ae0f5STejun Heo 	 *
67bc2ae0f5STejun Heo 	 * While DISASSOCIATED, the cpu may be offline and all workers have
68bc2ae0f5STejun Heo 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
6924647570STejun Heo 	 * be executing on any CPU.  The pool behaves as an unbound one.
70bc2ae0f5STejun Heo 	 *
71bc3a1afcSTejun Heo 	 * Note that DISASSOCIATED should be flipped only while holding
721258fae7STejun Heo 	 * wq_pool_attach_mutex to avoid changing binding state while
734736cbf7SLai Jiangshan 	 * worker_attach_to_pool() is in progress.
74bc2ae0f5STejun Heo 	 */
75692b4825STejun Heo 	POOL_MANAGER_ACTIVE	= 1 << 0,	/* being managed */
7624647570STejun Heo 	POOL_DISASSOCIATED	= 1 << 2,	/* cpu can't serve workers */
77db7bccf4STejun Heo 
78c8e55f36STejun Heo 	/* worker flags */
79c8e55f36STejun Heo 	WORKER_DIE		= 1 << 1,	/* die die die */
80c8e55f36STejun Heo 	WORKER_IDLE		= 1 << 2,	/* is idle */
81e22bee78STejun Heo 	WORKER_PREP		= 1 << 3,	/* preparing to run works */
82fb0e7bebSTejun Heo 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
83f3421797STejun Heo 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
84a9ab775bSTejun Heo 	WORKER_REBOUND		= 1 << 8,	/* worker was rebound */
85e22bee78STejun Heo 
86a9ab775bSTejun Heo 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_CPU_INTENSIVE |
87a9ab775bSTejun Heo 				  WORKER_UNBOUND | WORKER_REBOUND,
88db7bccf4STejun Heo 
89e34cdddbSTejun Heo 	NR_STD_WORKER_POOLS	= 2,		/* # standard pools per cpu */
904ce62e9eSTejun Heo 
9129c91e99STejun Heo 	UNBOUND_POOL_HASH_ORDER	= 6,		/* hashed by pool->attrs */
92c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
93db7bccf4STejun Heo 
94e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
95e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
96e22bee78STejun Heo 
973233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
983233cdbdSTejun Heo 						/* call for help after 10ms
993233cdbdSTejun Heo 						   (min two ticks) */
100e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
101e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
1021da177e4SLinus Torvalds 
1031da177e4SLinus Torvalds 	/*
104e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
1058698a745SDongsheng Yang 	 * all cpus.  Give MIN_NICE.
106e22bee78STejun Heo 	 */
1078698a745SDongsheng Yang 	RESCUER_NICE_LEVEL	= MIN_NICE,
1088698a745SDongsheng Yang 	HIGHPRI_NICE_LEVEL	= MIN_NICE,
109ecf6881fSTejun Heo 
110ecf6881fSTejun Heo 	WQ_NAME_LEN		= 24,
111c8e55f36STejun Heo };
112c8e55f36STejun Heo 
1131da177e4SLinus Torvalds /*
1144690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1154690c4abSTejun Heo  *
116e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
117e41e704bSTejun Heo  *    everyone else.
1184690c4abSTejun Heo  *
119e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
120e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
121e22bee78STejun Heo  *
122d565ed63STejun Heo  * L: pool->lock protected.  Access with pool->lock held.
1234690c4abSTejun Heo  *
124d565ed63STejun Heo  * X: During normal operation, modification requires pool->lock and should
125d565ed63STejun Heo  *    be done only from local cpu.  Either disabling preemption on local
126d565ed63STejun Heo  *    cpu or grabbing pool->lock is enough for read access.  If
127d565ed63STejun Heo  *    POOL_DISASSOCIATED is set, it's identical to L.
128e22bee78STejun 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 */
16211ebea50STejun Heo 	unsigned int		flags;		/* X: 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 */
218725e8ec5STejun Heo 	PWQ_STAT_MAYDAY,	/* maydays to rescuer */
219725e8ec5STejun Heo 	PWQ_STAT_RESCUED,	/* linked work items executed by rescuer */
220725e8ec5STejun Heo 
221725e8ec5STejun Heo 	PWQ_NR_STATS,
222725e8ec5STejun Heo };
223725e8ec5STejun Heo 
224725e8ec5STejun Heo /*
225112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
226112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
227112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
228112202d9STejun Heo  * number of flag bits.
2291da177e4SLinus Torvalds  */
230112202d9STejun Heo struct pool_workqueue {
231bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
2324690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
23373f53c4aSTejun Heo 	int			work_color;	/* L: current color */
23473f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
2358864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
23673f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
23773f53c4aSTejun Heo 						/* L: nr of in_flight works */
238018f3a13SLai Jiangshan 
239018f3a13SLai Jiangshan 	/*
240018f3a13SLai Jiangshan 	 * nr_active management and WORK_STRUCT_INACTIVE:
241018f3a13SLai Jiangshan 	 *
242018f3a13SLai Jiangshan 	 * When pwq->nr_active >= max_active, new work item is queued to
243018f3a13SLai Jiangshan 	 * pwq->inactive_works instead of pool->worklist and marked with
244018f3a13SLai Jiangshan 	 * WORK_STRUCT_INACTIVE.
245018f3a13SLai Jiangshan 	 *
246018f3a13SLai Jiangshan 	 * All work items marked with WORK_STRUCT_INACTIVE do not participate
247018f3a13SLai Jiangshan 	 * in pwq->nr_active and all work items in pwq->inactive_works are
248018f3a13SLai Jiangshan 	 * marked with WORK_STRUCT_INACTIVE.  But not all WORK_STRUCT_INACTIVE
249018f3a13SLai Jiangshan 	 * work items are in pwq->inactive_works.  Some of them are ready to
250018f3a13SLai Jiangshan 	 * run in pool->worklist or worker->scheduled.  Those work itmes are
251018f3a13SLai Jiangshan 	 * only struct wq_barrier which is used for flush_work() and should
252018f3a13SLai Jiangshan 	 * not participate in pwq->nr_active.  For non-barrier work item, it
253018f3a13SLai Jiangshan 	 * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
254018f3a13SLai Jiangshan 	 */
2551e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
256a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
257f97a4a1aSLai Jiangshan 	struct list_head	inactive_works;	/* L: inactive works */
2583c25a55dSLai Jiangshan 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
2592e109a28STejun Heo 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
2608864b4e5STejun Heo 
261725e8ec5STejun Heo 	u64			stats[PWQ_NR_STATS];
262725e8ec5STejun Heo 
2638864b4e5STejun Heo 	/*
2648864b4e5STejun Heo 	 * Release of unbound pwq is punted to system_wq.  See put_pwq()
2658864b4e5STejun Heo 	 * and pwq_unbound_release_workfn() for details.  pool_workqueue
26624acfb71SThomas Gleixner 	 * itself is also RCU protected so that the first pwq can be
267b09f4fd3SLai Jiangshan 	 * determined without grabbing wq->mutex.
2688864b4e5STejun Heo 	 */
2698864b4e5STejun Heo 	struct work_struct	unbound_release_work;
2708864b4e5STejun Heo 	struct rcu_head		rcu;
271e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2721da177e4SLinus Torvalds 
2731da177e4SLinus Torvalds /*
27473f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
27573f53c4aSTejun Heo  */
27673f53c4aSTejun Heo struct wq_flusher {
2773c25a55dSLai Jiangshan 	struct list_head	list;		/* WQ: list of flushers */
2783c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: flush color waiting for */
27973f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
28073f53c4aSTejun Heo };
2811da177e4SLinus Torvalds 
282226223abSTejun Heo struct wq_device;
283226223abSTejun Heo 
28473f53c4aSTejun Heo /*
285c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
286c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
2871da177e4SLinus Torvalds  */
2881da177e4SLinus Torvalds struct workqueue_struct {
2893c25a55dSLai Jiangshan 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
290e2dca7adSTejun Heo 	struct list_head	list;		/* PR: list of all workqueues */
29173f53c4aSTejun Heo 
2923c25a55dSLai Jiangshan 	struct mutex		mutex;		/* protects this wq */
2933c25a55dSLai Jiangshan 	int			work_color;	/* WQ: current work color */
2943c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: current flush color */
295112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
2963c25a55dSLai Jiangshan 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
2973c25a55dSLai Jiangshan 	struct list_head	flusher_queue;	/* WQ: flush waiters */
2983c25a55dSLai Jiangshan 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
29973f53c4aSTejun Heo 
3002e109a28STejun Heo 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
30130ae2fc0STejun Heo 	struct worker		*rescuer;	/* MD: rescue worker */
302e22bee78STejun Heo 
30387fc741eSLai Jiangshan 	int			nr_drainers;	/* WQ: drain in progress */
304a357fc03SLai Jiangshan 	int			saved_max_active; /* WQ: saved pwq max_active */
305226223abSTejun Heo 
3065b95e1afSLai Jiangshan 	struct workqueue_attrs	*unbound_attrs;	/* PW: only for unbound wqs */
3075b95e1afSLai Jiangshan 	struct pool_workqueue	*dfl_pwq;	/* PW: only for unbound wqs */
3086029a918STejun Heo 
309226223abSTejun Heo #ifdef CONFIG_SYSFS
310226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
311226223abSTejun Heo #endif
3124e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
313669de8bdSBart Van Assche 	char			*lock_name;
314669de8bdSBart Van Assche 	struct lock_class_key	key;
3154e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
3164e6045f1SJohannes Berg #endif
317ecf6881fSTejun Heo 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
3182728fd2fSTejun Heo 
319e2dca7adSTejun Heo 	/*
32024acfb71SThomas Gleixner 	 * Destruction of workqueue_struct is RCU protected to allow walking
32124acfb71SThomas Gleixner 	 * the workqueues list without grabbing wq_pool_mutex.
322e2dca7adSTejun Heo 	 * This is used to dump all workqueues from sysrq.
323e2dca7adSTejun Heo 	 */
324e2dca7adSTejun Heo 	struct rcu_head		rcu;
325e2dca7adSTejun Heo 
3262728fd2fSTejun Heo 	/* hot fields used during command issue, aligned to cacheline */
3272728fd2fSTejun Heo 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
3282728fd2fSTejun Heo 	struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
3295b95e1afSLai Jiangshan 	struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
3301da177e4SLinus Torvalds };
3311da177e4SLinus Torvalds 
332e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
333e904e6c2STejun Heo 
334bce90380STejun Heo static cpumask_var_t *wq_numa_possible_cpumask;
335bce90380STejun Heo 					/* possible CPUs of each node */
336bce90380STejun Heo 
337616db877STejun Heo /*
338616db877STejun Heo  * Per-cpu work items which run for longer than the following threshold are
339616db877STejun Heo  * automatically considered CPU intensive and excluded from concurrency
340616db877STejun Heo  * management to prevent them from noticeably delaying other per-cpu work items.
341616db877STejun Heo  */
342616db877STejun Heo static unsigned long wq_cpu_intensive_thresh_us = 10000;
343616db877STejun Heo module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
344616db877STejun Heo 
345d55262c4STejun Heo static bool wq_disable_numa;
346d55262c4STejun Heo module_param_named(disable_numa, wq_disable_numa, bool, 0444);
347d55262c4STejun Heo 
348cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
349552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
350cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
351cee22a15SViresh Kumar 
352863b710bSTejun Heo static bool wq_online;			/* can kworkers be created yet? */
3533347fa09STejun Heo 
354bce90380STejun Heo static bool wq_numa_enabled;		/* unbound NUMA affinity enabled */
355bce90380STejun Heo 
3564c16bd32STejun Heo /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
3574c16bd32STejun Heo static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
3584c16bd32STejun Heo 
35968e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
3601258fae7STejun Heo static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
361a9b8a985SSebastian Andrzej Siewior static DEFINE_RAW_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
362d8bb65abSSebastian Andrzej Siewior /* wait for manager to go away */
363d8bb65abSSebastian Andrzej Siewior static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
3645bcab335STejun Heo 
365e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
36668e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
3677d19c5ceSTejun Heo 
36899c621efSLai Jiangshan /* PL&A: allowable cpus for unbound wqs and work items */
369ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
370ef557180SMike Galbraith 
371ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
372ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
373b05a7928SFrederic Weisbecker 
374f303fccbSTejun Heo /*
375f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
376f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
377f303fccbSTejun Heo  * to uncover usages which depend on it.
378f303fccbSTejun Heo  */
379f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
380f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
381f303fccbSTejun Heo #else
382f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
383f303fccbSTejun Heo #endif
384f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
385f303fccbSTejun Heo 
3867d19c5ceSTejun Heo /* the per-cpu worker pools */
38725528213SPeter Zijlstra static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
3887d19c5ceSTejun Heo 
38968e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
3907d19c5ceSTejun Heo 
39168e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
39229c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
39329c91e99STejun Heo 
394c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
39529c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
39629c91e99STejun Heo 
3978a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
3988a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
3998a2b7538STejun Heo 
400d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
401ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
402044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
4031aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
404044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
405d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
406044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
407f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
408044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
40924d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
4100668106cSViresh Kumar struct workqueue_struct *system_power_efficient_wq __read_mostly;
4110668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
4120668106cSViresh Kumar struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
4130668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
414d320c038STejun Heo 
4157d19c5ceSTejun Heo static int worker_thread(void *__worker);
4166ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
417c29eb853STejun Heo static void show_pwq(struct pool_workqueue *pwq);
41855df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool);
4197d19c5ceSTejun Heo 
42097bd2347STejun Heo #define CREATE_TRACE_POINTS
42197bd2347STejun Heo #include <trace/events/workqueue.h>
42297bd2347STejun Heo 
42368e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
42424acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
425f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
42624acfb71SThomas Gleixner 			 "RCU or wq_pool_mutex should be held")
4275bcab335STejun Heo 
4285b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
42924acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
430f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
431f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
43224acfb71SThomas Gleixner 			 "RCU, wq->mutex or wq_pool_mutex should be held")
4335b95e1afSLai Jiangshan 
434f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
435f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
436f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
4377a62c2c8STejun Heo 	     (pool)++)
4384ce62e9eSTejun Heo 
43949e3cf44STejun Heo /**
44017116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
44117116969STejun Heo  * @pool: iteration cursor
442611c92a0STejun Heo  * @pi: integer used for iteration
443fa1b54e6STejun Heo  *
44424acfb71SThomas Gleixner  * This must be called either with wq_pool_mutex held or RCU read
44568e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
44668e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
447fa1b54e6STejun Heo  *
448fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
449fa1b54e6STejun Heo  * ignored.
45017116969STejun Heo  */
451611c92a0STejun Heo #define for_each_pool(pool, pi)						\
452611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
45368e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
454fa1b54e6STejun Heo 		else
45517116969STejun Heo 
45617116969STejun Heo /**
457822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
458822d8405STejun Heo  * @worker: iteration cursor
459822d8405STejun Heo  * @pool: worker_pool to iterate workers of
460822d8405STejun Heo  *
4611258fae7STejun Heo  * This must be called with wq_pool_attach_mutex.
462822d8405STejun Heo  *
463822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
464822d8405STejun Heo  * ignored.
465822d8405STejun Heo  */
466da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
467da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
4681258fae7STejun Heo 		if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
469822d8405STejun Heo 		else
470822d8405STejun Heo 
471822d8405STejun Heo /**
47249e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
47349e3cf44STejun Heo  * @pwq: iteration cursor
47449e3cf44STejun Heo  * @wq: the target workqueue
47576af4d93STejun Heo  *
47624acfb71SThomas Gleixner  * This must be called either with wq->mutex held or RCU read locked.
477794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
478794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
47976af4d93STejun Heo  *
48076af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
48176af4d93STejun Heo  * ignored.
48249e3cf44STejun Heo  */
48349e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
48449e9d1a9SSebastian Andrzej Siewior 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node,		\
4855a644662SJoel Fernandes (Google) 				 lockdep_is_held(&(wq->mutex)))
486f3421797STejun Heo 
487dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
488dc186ad7SThomas Gleixner 
489f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr;
490dc186ad7SThomas Gleixner 
49199777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
49299777288SStanislaw Gruszka {
49399777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
49499777288SStanislaw Gruszka }
49599777288SStanislaw Gruszka 
496b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
497b9fdac7fSDu, Changbin {
498b9fdac7fSDu, Changbin 	struct work_struct *work = addr;
499b9fdac7fSDu, Changbin 
500b9fdac7fSDu, Changbin 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
501b9fdac7fSDu, Changbin }
502b9fdac7fSDu, Changbin 
503dc186ad7SThomas Gleixner /*
504dc186ad7SThomas Gleixner  * fixup_init is called when:
505dc186ad7SThomas Gleixner  * - an active object is initialized
506dc186ad7SThomas Gleixner  */
50702a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
508dc186ad7SThomas Gleixner {
509dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
510dc186ad7SThomas Gleixner 
511dc186ad7SThomas Gleixner 	switch (state) {
512dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
513dc186ad7SThomas Gleixner 		cancel_work_sync(work);
514dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
51502a982a6SDu, Changbin 		return true;
516dc186ad7SThomas Gleixner 	default:
51702a982a6SDu, Changbin 		return false;
518dc186ad7SThomas Gleixner 	}
519dc186ad7SThomas Gleixner }
520dc186ad7SThomas Gleixner 
521dc186ad7SThomas Gleixner /*
522dc186ad7SThomas Gleixner  * fixup_free is called when:
523dc186ad7SThomas Gleixner  * - an active object is freed
524dc186ad7SThomas Gleixner  */
52502a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
526dc186ad7SThomas Gleixner {
527dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
528dc186ad7SThomas Gleixner 
529dc186ad7SThomas Gleixner 	switch (state) {
530dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
531dc186ad7SThomas Gleixner 		cancel_work_sync(work);
532dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
53302a982a6SDu, Changbin 		return true;
534dc186ad7SThomas Gleixner 	default:
53502a982a6SDu, Changbin 		return false;
536dc186ad7SThomas Gleixner 	}
537dc186ad7SThomas Gleixner }
538dc186ad7SThomas Gleixner 
539f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr = {
540dc186ad7SThomas Gleixner 	.name		= "work_struct",
54199777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
542b9fdac7fSDu, Changbin 	.is_static_object = work_is_static_object,
543dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
544dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
545dc186ad7SThomas Gleixner };
546dc186ad7SThomas Gleixner 
547dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
548dc186ad7SThomas Gleixner {
549dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
550dc186ad7SThomas Gleixner }
551dc186ad7SThomas Gleixner 
552dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
553dc186ad7SThomas Gleixner {
554dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
555dc186ad7SThomas Gleixner }
556dc186ad7SThomas Gleixner 
557dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
558dc186ad7SThomas Gleixner {
559dc186ad7SThomas Gleixner 	if (onstack)
560dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
561dc186ad7SThomas Gleixner 	else
562dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
563dc186ad7SThomas Gleixner }
564dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
565dc186ad7SThomas Gleixner 
566dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
567dc186ad7SThomas Gleixner {
568dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
569dc186ad7SThomas Gleixner }
570dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
571dc186ad7SThomas Gleixner 
572ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
573ea2e64f2SThomas Gleixner {
574ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
575ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
576ea2e64f2SThomas Gleixner }
577ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
578ea2e64f2SThomas Gleixner 
579dc186ad7SThomas Gleixner #else
580dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
581dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
582dc186ad7SThomas Gleixner #endif
583dc186ad7SThomas Gleixner 
5844e8b22bdSLi Bin /**
58567dc8325SCai Huoqing  * worker_pool_assign_id - allocate ID and assign it to @pool
5864e8b22bdSLi Bin  * @pool: the pool pointer of interest
5874e8b22bdSLi Bin  *
5884e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
5894e8b22bdSLi Bin  * successfully, -errno on failure.
5904e8b22bdSLi Bin  */
5919daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
5929daf9e67STejun Heo {
5939daf9e67STejun Heo 	int ret;
5949daf9e67STejun Heo 
59568e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5965bcab335STejun Heo 
5974e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
5984e8b22bdSLi Bin 			GFP_KERNEL);
599229641a6STejun Heo 	if (ret >= 0) {
600e68035fbSTejun Heo 		pool->id = ret;
601229641a6STejun Heo 		return 0;
602229641a6STejun Heo 	}
6039daf9e67STejun Heo 	return ret;
6049daf9e67STejun Heo }
6059daf9e67STejun Heo 
60676af4d93STejun Heo /**
607df2d5ae4STejun Heo  * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
608df2d5ae4STejun Heo  * @wq: the target workqueue
609df2d5ae4STejun Heo  * @node: the node ID
610df2d5ae4STejun Heo  *
61124acfb71SThomas Gleixner  * This must be called with any of wq_pool_mutex, wq->mutex or RCU
6125b95e1afSLai Jiangshan  * read locked.
613df2d5ae4STejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
614df2d5ae4STejun Heo  * responsible for guaranteeing that the pwq stays online.
615d185af30SYacine Belkadi  *
616d185af30SYacine Belkadi  * Return: The unbound pool_workqueue for @node.
617df2d5ae4STejun Heo  */
618df2d5ae4STejun Heo static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
619df2d5ae4STejun Heo 						  int node)
620df2d5ae4STejun Heo {
6215b95e1afSLai Jiangshan 	assert_rcu_or_wq_mutex_or_pool_mutex(wq);
622d6e022f1STejun Heo 
623d6e022f1STejun Heo 	/*
624d6e022f1STejun Heo 	 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
625d6e022f1STejun Heo 	 * delayed item is pending.  The plan is to keep CPU -> NODE
626d6e022f1STejun Heo 	 * mapping valid and stable across CPU on/offlines.  Once that
627d6e022f1STejun Heo 	 * happens, this workaround can be removed.
628d6e022f1STejun Heo 	 */
629d6e022f1STejun Heo 	if (unlikely(node == NUMA_NO_NODE))
630d6e022f1STejun Heo 		return wq->dfl_pwq;
631d6e022f1STejun Heo 
632df2d5ae4STejun Heo 	return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
633df2d5ae4STejun Heo }
634df2d5ae4STejun Heo 
63573f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
63673f53c4aSTejun Heo {
63773f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
63873f53c4aSTejun Heo }
63973f53c4aSTejun Heo 
640c4560c2cSLai Jiangshan static int get_work_color(unsigned long work_data)
64173f53c4aSTejun Heo {
642c4560c2cSLai Jiangshan 	return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
64373f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
64473f53c4aSTejun Heo }
64573f53c4aSTejun Heo 
64673f53c4aSTejun Heo static int work_next_color(int color)
64773f53c4aSTejun Heo {
64873f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
649a848e3b6SOleg Nesterov }
650a848e3b6SOleg Nesterov 
6514594bf15SDavid Howells /*
652112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
653112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
6547c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
6557a22ad75STejun Heo  *
656112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
657112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
658bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
659bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
6607a22ad75STejun Heo  *
661112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6627c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
663112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
6647c3eed5cSTejun Heo  * available only while the work item is queued.
665bbb68dfaSTejun Heo  *
666bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
667bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
668bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
669bbb68dfaSTejun Heo  * try to steal the PENDING bit.
6704594bf15SDavid Howells  */
6717a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6727a22ad75STejun Heo 				 unsigned long flags)
6737a22ad75STejun Heo {
6746183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
6757a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
6767a22ad75STejun Heo }
6777a22ad75STejun Heo 
678112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6794690c4abSTejun Heo 			 unsigned long extra_flags)
680365970a1SDavid Howells {
681112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
682112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
683365970a1SDavid Howells }
684365970a1SDavid Howells 
6854468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6864468a00fSLai Jiangshan 					   int pool_id)
6874468a00fSLai Jiangshan {
6884468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6894468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6904468a00fSLai Jiangshan }
6914468a00fSLai Jiangshan 
6927c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6937c3eed5cSTejun Heo 					    int pool_id)
6944d707b9fSOleg Nesterov {
69523657bb1STejun Heo 	/*
69623657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
69723657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
69823657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
69923657bb1STejun Heo 	 * owner.
70023657bb1STejun Heo 	 */
70123657bb1STejun Heo 	smp_wmb();
7027c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
703346c09f8SRoman Pen 	/*
704346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
705346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
706346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
7078bdc6201SLiu Song 	 * reordering can lead to a missed execution on attempt to queue
708346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
709346c09f8SRoman Pen 	 *
710346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
711346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
712346c09f8SRoman Pen 	 *
713346c09f8SRoman Pen 	 * 1  STORE event_indicated
714346c09f8SRoman Pen 	 * 2  queue_work_on() {
715346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
716346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
717346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
718346c09f8SRoman Pen 	 * 6                                 smp_mb()
719346c09f8SRoman Pen 	 * 7                               work->current_func() {
720346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
721346c09f8SRoman Pen 	 *				   }
722346c09f8SRoman Pen 	 *
723346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
724346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
725346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
726346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
727346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
728346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
729346c09f8SRoman Pen 	 * before actual STORE.
730346c09f8SRoman Pen 	 */
731346c09f8SRoman Pen 	smp_mb();
7324d707b9fSOleg Nesterov }
7334d707b9fSOleg Nesterov 
7347a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
735365970a1SDavid Howells {
7367c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
7377c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
7387a22ad75STejun Heo }
7397a22ad75STejun Heo 
740afa4bb77SLinus Torvalds static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
741afa4bb77SLinus Torvalds {
742afa4bb77SLinus Torvalds 	return (struct pool_workqueue *)(data & WORK_STRUCT_WQ_DATA_MASK);
743afa4bb77SLinus Torvalds }
744afa4bb77SLinus Torvalds 
745112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
7467a22ad75STejun Heo {
747e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7487a22ad75STejun Heo 
749112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
750afa4bb77SLinus Torvalds 		return work_struct_pwq(data);
751e120153dSTejun Heo 	else
752e120153dSTejun Heo 		return NULL;
7537a22ad75STejun Heo }
7547a22ad75STejun Heo 
7557c3eed5cSTejun Heo /**
7567c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
7577c3eed5cSTejun Heo  * @work: the work item of interest
7587c3eed5cSTejun Heo  *
75968e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
76024acfb71SThomas Gleixner  * access under RCU read lock.  As such, this function should be
76124acfb71SThomas Gleixner  * called under wq_pool_mutex or inside of a rcu_read_lock() region.
762fa1b54e6STejun Heo  *
763fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
764fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
765fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
766fa1b54e6STejun Heo  * returned pool is and stays online.
767d185af30SYacine Belkadi  *
768d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
7697c3eed5cSTejun Heo  */
7707c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
7717a22ad75STejun Heo {
772e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7737c3eed5cSTejun Heo 	int pool_id;
7747a22ad75STejun Heo 
77568e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
776fa1b54e6STejun Heo 
777112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
778afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool;
7797a22ad75STejun Heo 
7807c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
7817c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
7827a22ad75STejun Heo 		return NULL;
7837a22ad75STejun Heo 
784fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
7857c3eed5cSTejun Heo }
7867c3eed5cSTejun Heo 
7877c3eed5cSTejun Heo /**
7887c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
7897c3eed5cSTejun Heo  * @work: the work item of interest
7907c3eed5cSTejun Heo  *
791d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
7927c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
7937c3eed5cSTejun Heo  */
7947c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
7957c3eed5cSTejun Heo {
79654d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
7977c3eed5cSTejun Heo 
798112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
799afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool->id;
80054d5b7d0SLai Jiangshan 
80154d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
8027c3eed5cSTejun Heo }
8037c3eed5cSTejun Heo 
804bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
805bbb68dfaSTejun Heo {
8067c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
807bbb68dfaSTejun Heo 
8087c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
8097c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
810bbb68dfaSTejun Heo }
811bbb68dfaSTejun Heo 
812bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
813bbb68dfaSTejun Heo {
814bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
815bbb68dfaSTejun Heo 
816112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
817bbb68dfaSTejun Heo }
818bbb68dfaSTejun Heo 
819e22bee78STejun Heo /*
8203270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
8213270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
822d565ed63STejun Heo  * they're being called with pool->lock held.
823e22bee78STejun Heo  */
824e22bee78STejun Heo 
82563d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
826649027d7STejun Heo {
827bc35f7efSLai Jiangshan 	return !pool->nr_running;
828649027d7STejun Heo }
829649027d7STejun Heo 
830e22bee78STejun Heo /*
831e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
832e22bee78STejun Heo  * running workers.
833974271c4STejun Heo  *
834974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
835706026c2STejun Heo  * function will always return %true for unbound pools as long as the
836974271c4STejun Heo  * worklist isn't empty.
837e22bee78STejun Heo  */
83863d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
839e22bee78STejun Heo {
84063d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
841e22bee78STejun Heo }
842e22bee78STejun Heo 
843e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
84463d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
845e22bee78STejun Heo {
84663d95a91STejun Heo 	return pool->nr_idle;
847e22bee78STejun Heo }
848e22bee78STejun Heo 
849e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
85063d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
851e22bee78STejun Heo {
852bc35f7efSLai Jiangshan 	return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
853e22bee78STejun Heo }
854e22bee78STejun Heo 
855e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
85663d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
857e22bee78STejun Heo {
85863d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
859e22bee78STejun Heo }
860e22bee78STejun Heo 
861e22bee78STejun Heo /* Do we have too many workers and should some go away? */
86263d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
863e22bee78STejun Heo {
864692b4825STejun Heo 	bool managing = pool->flags & POOL_MANAGER_ACTIVE;
86563d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
86663d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
867e22bee78STejun Heo 
868e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
869e22bee78STejun Heo }
870e22bee78STejun Heo 
871e22bee78STejun Heo /*
872e22bee78STejun Heo  * Wake up functions.
873e22bee78STejun Heo  */
874e22bee78STejun Heo 
8752c1f1a91SLai Jiangshan /* Return the first idle worker.  Called with pool->lock held. */
8761037de36SLai Jiangshan static struct worker *first_idle_worker(struct worker_pool *pool)
8777e11629dSTejun Heo {
87863d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
8797e11629dSTejun Heo 		return NULL;
8807e11629dSTejun Heo 
88163d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
8827e11629dSTejun Heo }
8837e11629dSTejun Heo 
8847e11629dSTejun Heo /**
8857e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
88663d95a91STejun Heo  * @pool: worker pool to wake worker from
8877e11629dSTejun Heo  *
88863d95a91STejun Heo  * Wake up the first idle worker of @pool.
8897e11629dSTejun Heo  *
8907e11629dSTejun Heo  * CONTEXT:
891a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
8927e11629dSTejun Heo  */
89363d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
8947e11629dSTejun Heo {
8951037de36SLai Jiangshan 	struct worker *worker = first_idle_worker(pool);
8967e11629dSTejun Heo 
8977e11629dSTejun Heo 	if (likely(worker))
8987e11629dSTejun Heo 		wake_up_process(worker->task);
8997e11629dSTejun Heo }
9007e11629dSTejun Heo 
9014690c4abSTejun Heo /**
902e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
903cb444766STejun Heo  * @worker: self
904d302f017STejun Heo  * @flags: flags to set
905d302f017STejun Heo  *
906228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
907d302f017STejun Heo  *
908cb444766STejun Heo  * CONTEXT:
909a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock)
910d302f017STejun Heo  */
911228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
912d302f017STejun Heo {
913bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
914e22bee78STejun Heo 
915cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
916cb444766STejun Heo 
917228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
918e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
919e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
920bc35f7efSLai Jiangshan 		pool->nr_running--;
921e22bee78STejun Heo 	}
922e22bee78STejun Heo 
923d302f017STejun Heo 	worker->flags |= flags;
924d302f017STejun Heo }
925d302f017STejun Heo 
926d302f017STejun Heo /**
927e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
928cb444766STejun Heo  * @worker: self
929d302f017STejun Heo  * @flags: flags to clear
930d302f017STejun Heo  *
931e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
932d302f017STejun Heo  *
933cb444766STejun Heo  * CONTEXT:
934a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock)
935d302f017STejun Heo  */
936d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
937d302f017STejun Heo {
93863d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
939e22bee78STejun Heo 	unsigned int oflags = worker->flags;
940e22bee78STejun Heo 
941cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
942cb444766STejun Heo 
943d302f017STejun Heo 	worker->flags &= ~flags;
944e22bee78STejun Heo 
94542c025f3STejun Heo 	/*
94642c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
94742c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
94842c025f3STejun Heo 	 * of multiple flags, not a single flag.
94942c025f3STejun Heo 	 */
950e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
951e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
952bc35f7efSLai Jiangshan 			pool->nr_running++;
953d302f017STejun Heo }
954d302f017STejun Heo 
95563638450STejun Heo #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
95663638450STejun Heo 
95763638450STejun Heo /*
95863638450STejun Heo  * Concurrency-managed per-cpu work items that hog CPU for longer than
95963638450STejun Heo  * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
96063638450STejun Heo  * which prevents them from stalling other concurrency-managed work items. If a
96163638450STejun Heo  * work function keeps triggering this mechanism, it's likely that the work item
96263638450STejun Heo  * should be using an unbound workqueue instead.
96363638450STejun Heo  *
96463638450STejun Heo  * wq_cpu_intensive_report() tracks work functions which trigger such conditions
96563638450STejun Heo  * and report them so that they can be examined and converted to use unbound
96663638450STejun Heo  * workqueues as appropriate. To avoid flooding the console, each violating work
96763638450STejun Heo  * function is tracked and reported with exponential backoff.
96863638450STejun Heo  */
96963638450STejun Heo #define WCI_MAX_ENTS 128
97063638450STejun Heo 
97163638450STejun Heo struct wci_ent {
97263638450STejun Heo 	work_func_t		func;
97363638450STejun Heo 	atomic64_t		cnt;
97463638450STejun Heo 	struct hlist_node	hash_node;
97563638450STejun Heo };
97663638450STejun Heo 
97763638450STejun Heo static struct wci_ent wci_ents[WCI_MAX_ENTS];
97863638450STejun Heo static int wci_nr_ents;
97963638450STejun Heo static DEFINE_RAW_SPINLOCK(wci_lock);
98063638450STejun Heo static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
98163638450STejun Heo 
98263638450STejun Heo static struct wci_ent *wci_find_ent(work_func_t func)
98363638450STejun Heo {
98463638450STejun Heo 	struct wci_ent *ent;
98563638450STejun Heo 
98663638450STejun Heo 	hash_for_each_possible_rcu(wci_hash, ent, hash_node,
98763638450STejun Heo 				   (unsigned long)func) {
98863638450STejun Heo 		if (ent->func == func)
98963638450STejun Heo 			return ent;
99063638450STejun Heo 	}
99163638450STejun Heo 	return NULL;
99263638450STejun Heo }
99363638450STejun Heo 
99463638450STejun Heo static void wq_cpu_intensive_report(work_func_t func)
99563638450STejun Heo {
99663638450STejun Heo 	struct wci_ent *ent;
99763638450STejun Heo 
99863638450STejun Heo restart:
99963638450STejun Heo 	ent = wci_find_ent(func);
100063638450STejun Heo 	if (ent) {
100163638450STejun Heo 		u64 cnt;
100263638450STejun Heo 
100363638450STejun Heo 		/*
100463638450STejun Heo 		 * Start reporting from the fourth time and back off
100563638450STejun Heo 		 * exponentially.
100663638450STejun Heo 		 */
100763638450STejun Heo 		cnt = atomic64_inc_return_relaxed(&ent->cnt);
100863638450STejun Heo 		if (cnt >= 4 && is_power_of_2(cnt))
100963638450STejun Heo 			printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
101063638450STejun Heo 					ent->func, wq_cpu_intensive_thresh_us,
101163638450STejun Heo 					atomic64_read(&ent->cnt));
101263638450STejun Heo 		return;
101363638450STejun Heo 	}
101463638450STejun Heo 
101563638450STejun Heo 	/*
101663638450STejun Heo 	 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
101763638450STejun Heo 	 * is exhausted, something went really wrong and we probably made enough
101863638450STejun Heo 	 * noise already.
101963638450STejun Heo 	 */
102063638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS)
102163638450STejun Heo 		return;
102263638450STejun Heo 
102363638450STejun Heo 	raw_spin_lock(&wci_lock);
102463638450STejun Heo 
102563638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS) {
102663638450STejun Heo 		raw_spin_unlock(&wci_lock);
102763638450STejun Heo 		return;
102863638450STejun Heo 	}
102963638450STejun Heo 
103063638450STejun Heo 	if (wci_find_ent(func)) {
103163638450STejun Heo 		raw_spin_unlock(&wci_lock);
103263638450STejun Heo 		goto restart;
103363638450STejun Heo 	}
103463638450STejun Heo 
103563638450STejun Heo 	ent = &wci_ents[wci_nr_ents++];
103663638450STejun Heo 	ent->func = func;
103763638450STejun Heo 	atomic64_set(&ent->cnt, 1);
103863638450STejun Heo 	hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
103963638450STejun Heo 
104063638450STejun Heo 	raw_spin_unlock(&wci_lock);
104163638450STejun Heo }
104263638450STejun Heo 
104363638450STejun Heo #else	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
104463638450STejun Heo static void wq_cpu_intensive_report(work_func_t func) {}
104563638450STejun Heo #endif	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
104663638450STejun Heo 
1047c54d5046STejun Heo /**
10481da177e4SLinus Torvalds  * wq_worker_running - a worker is running again
10491da177e4SLinus Torvalds  * @task: task waking up
10501da177e4SLinus Torvalds  *
10511da177e4SLinus Torvalds  * This function is called when a worker returns from schedule()
10521da177e4SLinus Torvalds  */
10531da177e4SLinus Torvalds void wq_worker_running(struct task_struct *task)
10541da177e4SLinus Torvalds {
10551da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
10561da177e4SLinus Torvalds 
1057c8f6219bSZqiang 	if (!READ_ONCE(worker->sleeping))
10581da177e4SLinus Torvalds 		return;
10591da177e4SLinus Torvalds 
10601da177e4SLinus Torvalds 	/*
10611da177e4SLinus Torvalds 	 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
10621da177e4SLinus Torvalds 	 * and the nr_running increment below, we may ruin the nr_running reset
10631da177e4SLinus Torvalds 	 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
10641da177e4SLinus Torvalds 	 * pool. Protect against such race.
10651da177e4SLinus Torvalds 	 */
10661da177e4SLinus Torvalds 	preempt_disable();
10671da177e4SLinus Torvalds 	if (!(worker->flags & WORKER_NOT_RUNNING))
10681da177e4SLinus Torvalds 		worker->pool->nr_running++;
10691da177e4SLinus Torvalds 	preempt_enable();
1070616db877STejun Heo 
1071616db877STejun Heo 	/*
1072616db877STejun Heo 	 * CPU intensive auto-detection cares about how long a work item hogged
1073616db877STejun Heo 	 * CPU without sleeping. Reset the starting timestamp on wakeup.
1074616db877STejun Heo 	 */
1075616db877STejun Heo 	worker->current_at = worker->task->se.sum_exec_runtime;
1076616db877STejun Heo 
1077c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 0);
10781da177e4SLinus Torvalds }
10791da177e4SLinus Torvalds 
10801da177e4SLinus Torvalds /**
10811da177e4SLinus Torvalds  * wq_worker_sleeping - a worker is going to sleep
10821da177e4SLinus Torvalds  * @task: task going to sleep
10831da177e4SLinus Torvalds  *
10841da177e4SLinus Torvalds  * This function is called from schedule() when a busy worker is
10851da177e4SLinus Torvalds  * going to sleep.
10861da177e4SLinus Torvalds  */
10871da177e4SLinus Torvalds void wq_worker_sleeping(struct task_struct *task)
10881da177e4SLinus Torvalds {
10891da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
10901da177e4SLinus Torvalds 	struct worker_pool *pool;
10911da177e4SLinus Torvalds 
10921da177e4SLinus Torvalds 	/*
10931da177e4SLinus Torvalds 	 * Rescuers, which may not have all the fields set up like normal
10941da177e4SLinus Torvalds 	 * workers, also reach here, let's not access anything before
10951da177e4SLinus Torvalds 	 * checking NOT_RUNNING.
10961da177e4SLinus Torvalds 	 */
10971da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING)
10981da177e4SLinus Torvalds 		return;
10991da177e4SLinus Torvalds 
11001da177e4SLinus Torvalds 	pool = worker->pool;
11011da177e4SLinus Torvalds 
11021da177e4SLinus Torvalds 	/* Return if preempted before wq_worker_running() was reached */
1103c8f6219bSZqiang 	if (READ_ONCE(worker->sleeping))
11041da177e4SLinus Torvalds 		return;
11051da177e4SLinus Torvalds 
1106c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 1);
11071da177e4SLinus Torvalds 	raw_spin_lock_irq(&pool->lock);
11081da177e4SLinus Torvalds 
11091da177e4SLinus Torvalds 	/*
11101da177e4SLinus Torvalds 	 * Recheck in case unbind_workers() preempted us. We don't
11111da177e4SLinus Torvalds 	 * want to decrement nr_running after the worker is unbound
11121da177e4SLinus Torvalds 	 * and nr_running has been reset.
11131da177e4SLinus Torvalds 	 */
11141da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING) {
11151da177e4SLinus Torvalds 		raw_spin_unlock_irq(&pool->lock);
11161da177e4SLinus Torvalds 		return;
11171da177e4SLinus Torvalds 	}
11181da177e4SLinus Torvalds 
11191da177e4SLinus Torvalds 	pool->nr_running--;
1120725e8ec5STejun Heo 	if (need_more_worker(pool)) {
1121725e8ec5STejun Heo 		worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
11221da177e4SLinus Torvalds 		wake_up_worker(pool);
1123725e8ec5STejun Heo 	}
11241da177e4SLinus Torvalds 	raw_spin_unlock_irq(&pool->lock);
11251da177e4SLinus Torvalds }
11261da177e4SLinus Torvalds 
11271da177e4SLinus Torvalds /**
1128616db877STejun Heo  * wq_worker_tick - a scheduler tick occurred while a kworker is running
1129616db877STejun Heo  * @task: task currently running
1130616db877STejun Heo  *
1131616db877STejun Heo  * Called from scheduler_tick(). We're in the IRQ context and the current
1132616db877STejun Heo  * worker's fields which follow the 'K' locking rule can be accessed safely.
1133616db877STejun Heo  */
1134616db877STejun Heo void wq_worker_tick(struct task_struct *task)
1135616db877STejun Heo {
1136616db877STejun Heo 	struct worker *worker = kthread_data(task);
1137616db877STejun Heo 	struct pool_workqueue *pwq = worker->current_pwq;
1138616db877STejun Heo 	struct worker_pool *pool = worker->pool;
1139616db877STejun Heo 
1140616db877STejun Heo 	if (!pwq)
1141616db877STejun Heo 		return;
1142616db877STejun Heo 
11438a1dd1e5STejun Heo 	pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
11448a1dd1e5STejun Heo 
114518c8ae81SZqiang 	if (!wq_cpu_intensive_thresh_us)
114618c8ae81SZqiang 		return;
114718c8ae81SZqiang 
1148616db877STejun Heo 	/*
1149616db877STejun Heo 	 * If the current worker is concurrency managed and hogged the CPU for
1150616db877STejun Heo 	 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1151616db877STejun Heo 	 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1152c8f6219bSZqiang 	 *
1153c8f6219bSZqiang 	 * Set @worker->sleeping means that @worker is in the process of
1154c8f6219bSZqiang 	 * switching out voluntarily and won't be contributing to
1155c8f6219bSZqiang 	 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1156c8f6219bSZqiang 	 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1157c8f6219bSZqiang 	 * double decrements. The task is releasing the CPU anyway. Let's skip.
1158c8f6219bSZqiang 	 * We probably want to make this prettier in the future.
1159616db877STejun Heo 	 */
1160c8f6219bSZqiang 	if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1161616db877STejun Heo 	    worker->task->se.sum_exec_runtime - worker->current_at <
1162616db877STejun Heo 	    wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1163616db877STejun Heo 		return;
1164616db877STejun Heo 
1165616db877STejun Heo 	raw_spin_lock(&pool->lock);
1166616db877STejun Heo 
1167616db877STejun Heo 	worker_set_flags(worker, WORKER_CPU_INTENSIVE);
116863638450STejun Heo 	wq_cpu_intensive_report(worker->current_func);
1169616db877STejun Heo 	pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1170616db877STejun Heo 
1171616db877STejun Heo 	if (need_more_worker(pool)) {
1172616db877STejun Heo 		pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1173616db877STejun Heo 		wake_up_worker(pool);
1174616db877STejun Heo 	}
1175616db877STejun Heo 
1176616db877STejun Heo 	raw_spin_unlock(&pool->lock);
1177616db877STejun Heo }
1178616db877STejun Heo 
1179616db877STejun Heo /**
11801da177e4SLinus Torvalds  * wq_worker_last_func - retrieve worker's last work function
11811da177e4SLinus Torvalds  * @task: Task to retrieve last work function of.
11821da177e4SLinus Torvalds  *
11831da177e4SLinus Torvalds  * Determine the last function a worker executed. This is called from
11841da177e4SLinus Torvalds  * the scheduler to get a worker's last known identity.
11851da177e4SLinus Torvalds  *
11861da177e4SLinus Torvalds  * CONTEXT:
11879b41ea72SAndrew Morton  * raw_spin_lock_irq(rq->lock)
11881da177e4SLinus Torvalds  *
11891da177e4SLinus Torvalds  * This function is called during schedule() when a kworker is going
1190f756d5e2SNathan Lynch  * to sleep. It's used by psi to identify aggregation workers during
1191f756d5e2SNathan Lynch  * dequeuing, to allow periodic aggregation to shut-off when that
11921da177e4SLinus Torvalds  * worker is the last task in the system or cgroup to go to sleep.
11931da177e4SLinus Torvalds  *
11941da177e4SLinus Torvalds  * As this function doesn't involve any workqueue-related locking, it
11951da177e4SLinus Torvalds  * only returns stable values when called from inside the scheduler's
11961da177e4SLinus Torvalds  * queuing and dequeuing paths, when @task, which must be a kworker,
11971da177e4SLinus Torvalds  * is guaranteed to not be processing any works.
1198365970a1SDavid Howells  *
1199365970a1SDavid Howells  * Return:
1200365970a1SDavid Howells  * The last work function %current executed as a worker, NULL if it
1201365970a1SDavid Howells  * hasn't executed any work yet.
1202365970a1SDavid Howells  */
1203365970a1SDavid Howells work_func_t wq_worker_last_func(struct task_struct *task)
1204365970a1SDavid Howells {
1205365970a1SDavid Howells 	struct worker *worker = kthread_data(task);
1206365970a1SDavid Howells 
1207365970a1SDavid Howells 	return worker->last_func;
1208365970a1SDavid Howells }
1209365970a1SDavid Howells 
1210d302f017STejun Heo /**
12118cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
1212c9e7cf27STejun Heo  * @pool: pool of interest
12138cca0eeaSTejun Heo  * @work: work to find worker for
12148cca0eeaSTejun Heo  *
1215c9e7cf27STejun Heo  * Find a worker which is executing @work on @pool by searching
1216c9e7cf27STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
1217a2c1c57bSTejun Heo  * to match, its current execution should match the address of @work and
1218a2c1c57bSTejun Heo  * its work function.  This is to avoid unwanted dependency between
1219a2c1c57bSTejun Heo  * unrelated work executions through a work item being recycled while still
1220a2c1c57bSTejun Heo  * being executed.
1221a2c1c57bSTejun Heo  *
1222a2c1c57bSTejun Heo  * This is a bit tricky.  A work item may be freed once its execution
1223a2c1c57bSTejun Heo  * starts and nothing prevents the freed area from being recycled for
1224a2c1c57bSTejun Heo  * another work item.  If the same work item address ends up being reused
1225a2c1c57bSTejun Heo  * before the original execution finishes, workqueue will identify the
1226a2c1c57bSTejun Heo  * recycled work item as currently executing and make it wait until the
1227a2c1c57bSTejun Heo  * current execution finishes, introducing an unwanted dependency.
1228a2c1c57bSTejun Heo  *
1229c5aa87bbSTejun Heo  * This function checks the work item address and work function to avoid
1230c5aa87bbSTejun Heo  * false positives.  Note that this isn't complete as one may construct a
1231c5aa87bbSTejun Heo  * work function which can introduce dependency onto itself through a
1232c5aa87bbSTejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
1233c5aa87bbSTejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
1234c5aa87bbSTejun Heo  * actually occurs, it should be easy to locate the culprit work function.
12358cca0eeaSTejun Heo  *
12368cca0eeaSTejun Heo  * CONTEXT:
1237a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
12388cca0eeaSTejun Heo  *
1239d185af30SYacine Belkadi  * Return:
1240d185af30SYacine Belkadi  * Pointer to worker which is executing @work if found, %NULL
12418cca0eeaSTejun Heo  * otherwise.
12428cca0eeaSTejun Heo  */
1243c9e7cf27STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
12448cca0eeaSTejun Heo 						 struct work_struct *work)
12458cca0eeaSTejun Heo {
124642f8570fSSasha Levin 	struct worker *worker;
124742f8570fSSasha Levin 
1248b67bfe0dSSasha Levin 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1249a2c1c57bSTejun Heo 			       (unsigned long)work)
1250a2c1c57bSTejun Heo 		if (worker->current_work == work &&
1251a2c1c57bSTejun Heo 		    worker->current_func == work->func)
125242f8570fSSasha Levin 			return worker;
125342f8570fSSasha Levin 
125442f8570fSSasha Levin 	return NULL;
12558cca0eeaSTejun Heo }
12568cca0eeaSTejun Heo 
12578cca0eeaSTejun Heo /**
1258bf4ede01STejun Heo  * move_linked_works - move linked works to a list
1259bf4ede01STejun Heo  * @work: start of series of works to be scheduled
1260bf4ede01STejun Heo  * @head: target list to append @work to
1261402dd89dSShailendra Verma  * @nextp: out parameter for nested worklist walking
1262bf4ede01STejun Heo  *
1263bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
1264bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
1265bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
1266bf4ede01STejun Heo  *
1267bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
1268bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
1269bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
1270bf4ede01STejun Heo  *
1271bf4ede01STejun Heo  * CONTEXT:
1272a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1273bf4ede01STejun Heo  */
1274bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1275bf4ede01STejun Heo 			      struct work_struct **nextp)
1276bf4ede01STejun Heo {
1277bf4ede01STejun Heo 	struct work_struct *n;
1278bf4ede01STejun Heo 
1279bf4ede01STejun Heo 	/*
1280bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
1281bf4ede01STejun Heo 	 * use NULL for list head.
1282bf4ede01STejun Heo 	 */
1283bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1284bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
1285bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1286bf4ede01STejun Heo 			break;
1287bf4ede01STejun Heo 	}
1288bf4ede01STejun Heo 
1289bf4ede01STejun Heo 	/*
1290bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
1291bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
1292bf4ede01STejun Heo 	 * needs to be updated.
1293bf4ede01STejun Heo 	 */
1294bf4ede01STejun Heo 	if (nextp)
1295bf4ede01STejun Heo 		*nextp = n;
1296bf4ede01STejun Heo }
1297bf4ede01STejun Heo 
12988864b4e5STejun Heo /**
12998864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
13008864b4e5STejun Heo  * @pwq: pool_workqueue to get
13018864b4e5STejun Heo  *
13028864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
13038864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
13048864b4e5STejun Heo  */
13058864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
13068864b4e5STejun Heo {
13078864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
13088864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
13098864b4e5STejun Heo 	pwq->refcnt++;
13108864b4e5STejun Heo }
13118864b4e5STejun Heo 
13128864b4e5STejun Heo /**
13138864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
13148864b4e5STejun Heo  * @pwq: pool_workqueue to put
13158864b4e5STejun Heo  *
13168864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
13178864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
13188864b4e5STejun Heo  */
13198864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
13208864b4e5STejun Heo {
13218864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
13228864b4e5STejun Heo 	if (likely(--pwq->refcnt))
13238864b4e5STejun Heo 		return;
13248864b4e5STejun Heo 	if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
13258864b4e5STejun Heo 		return;
13268864b4e5STejun Heo 	/*
13278864b4e5STejun Heo 	 * @pwq can't be released under pool->lock, bounce to
13288864b4e5STejun Heo 	 * pwq_unbound_release_workfn().  This never recurses on the same
13298864b4e5STejun Heo 	 * pool->lock as this path is taken only for unbound workqueues and
13308864b4e5STejun Heo 	 * the release work item is scheduled on a per-cpu workqueue.  To
13318864b4e5STejun Heo 	 * avoid lockdep warning, unbound pool->locks are given lockdep
13328864b4e5STejun Heo 	 * subclass of 1 in get_unbound_pool().
13338864b4e5STejun Heo 	 */
13348864b4e5STejun Heo 	schedule_work(&pwq->unbound_release_work);
13358864b4e5STejun Heo }
13368864b4e5STejun Heo 
1337dce90d47STejun Heo /**
1338dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1339dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1340dce90d47STejun Heo  *
1341dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1342dce90d47STejun Heo  */
1343dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1344dce90d47STejun Heo {
1345dce90d47STejun Heo 	if (pwq) {
1346dce90d47STejun Heo 		/*
134724acfb71SThomas Gleixner 		 * As both pwqs and pools are RCU protected, the
1348dce90d47STejun Heo 		 * following lock operations are safe.
1349dce90d47STejun Heo 		 */
1350a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
1351dce90d47STejun Heo 		put_pwq(pwq);
1352a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
1353dce90d47STejun Heo 	}
1354dce90d47STejun Heo }
1355dce90d47STejun Heo 
1356f97a4a1aSLai Jiangshan static void pwq_activate_inactive_work(struct work_struct *work)
1357bf4ede01STejun Heo {
1358112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1359bf4ede01STejun Heo 
1360bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
136182607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
136282607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1363112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
1364f97a4a1aSLai Jiangshan 	__clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work));
1365112202d9STejun Heo 	pwq->nr_active++;
1366bf4ede01STejun Heo }
1367bf4ede01STejun Heo 
1368f97a4a1aSLai Jiangshan static void pwq_activate_first_inactive(struct pool_workqueue *pwq)
13693aa62497SLai Jiangshan {
1370f97a4a1aSLai Jiangshan 	struct work_struct *work = list_first_entry(&pwq->inactive_works,
13713aa62497SLai Jiangshan 						    struct work_struct, entry);
13723aa62497SLai Jiangshan 
1373f97a4a1aSLai Jiangshan 	pwq_activate_inactive_work(work);
13743aa62497SLai Jiangshan }
13753aa62497SLai Jiangshan 
1376bf4ede01STejun Heo /**
1377112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1378112202d9STejun Heo  * @pwq: pwq of interest
1379c4560c2cSLai Jiangshan  * @work_data: work_data of work which left the queue
1380bf4ede01STejun Heo  *
1381bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1382112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1383bf4ede01STejun Heo  *
1384bf4ede01STejun Heo  * CONTEXT:
1385a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1386bf4ede01STejun Heo  */
1387c4560c2cSLai Jiangshan static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1388bf4ede01STejun Heo {
1389c4560c2cSLai Jiangshan 	int color = get_work_color(work_data);
1390c4560c2cSLai Jiangshan 
1391018f3a13SLai Jiangshan 	if (!(work_data & WORK_STRUCT_INACTIVE)) {
1392112202d9STejun Heo 		pwq->nr_active--;
1393f97a4a1aSLai Jiangshan 		if (!list_empty(&pwq->inactive_works)) {
1394f97a4a1aSLai Jiangshan 			/* one down, submit an inactive one */
1395112202d9STejun Heo 			if (pwq->nr_active < pwq->max_active)
1396f97a4a1aSLai Jiangshan 				pwq_activate_first_inactive(pwq);
1397bf4ede01STejun Heo 		}
1398018f3a13SLai Jiangshan 	}
1399018f3a13SLai Jiangshan 
1400018f3a13SLai Jiangshan 	pwq->nr_in_flight[color]--;
1401bf4ede01STejun Heo 
1402bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1403112202d9STejun Heo 	if (likely(pwq->flush_color != color))
14048864b4e5STejun Heo 		goto out_put;
1405bf4ede01STejun Heo 
1406bf4ede01STejun Heo 	/* are there still in-flight works? */
1407112202d9STejun Heo 	if (pwq->nr_in_flight[color])
14088864b4e5STejun Heo 		goto out_put;
1409bf4ede01STejun Heo 
1410112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1411112202d9STejun Heo 	pwq->flush_color = -1;
1412bf4ede01STejun Heo 
1413bf4ede01STejun Heo 	/*
1414112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1415bf4ede01STejun Heo 	 * will handle the rest.
1416bf4ede01STejun Heo 	 */
1417112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1418112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
14198864b4e5STejun Heo out_put:
14208864b4e5STejun Heo 	put_pwq(pwq);
1421bf4ede01STejun Heo }
1422bf4ede01STejun Heo 
142336e227d2STejun Heo /**
1424bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
142536e227d2STejun Heo  * @work: work item to steal
142636e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1427bbb68dfaSTejun Heo  * @flags: place to store irq state
142836e227d2STejun Heo  *
142936e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1430d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
143136e227d2STejun Heo  *
1432d185af30SYacine Belkadi  * Return:
14333eb6b31bSMauro Carvalho Chehab  *
14343eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
143536e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
143636e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
143736e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1438bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1439bbb68dfaSTejun Heo  *		for arbitrarily long
14403eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
144136e227d2STejun Heo  *
1442d185af30SYacine Belkadi  * Note:
1443bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1444e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1445e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1446e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1447bbb68dfaSTejun Heo  *
1448bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1449bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1450bbb68dfaSTejun Heo  *
1451e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1452bf4ede01STejun Heo  */
1453bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1454bbb68dfaSTejun Heo 			       unsigned long *flags)
1455bf4ede01STejun Heo {
1456d565ed63STejun Heo 	struct worker_pool *pool;
1457112202d9STejun Heo 	struct pool_workqueue *pwq;
1458bf4ede01STejun Heo 
1459bbb68dfaSTejun Heo 	local_irq_save(*flags);
1460bbb68dfaSTejun Heo 
146136e227d2STejun Heo 	/* try to steal the timer if it exists */
146236e227d2STejun Heo 	if (is_dwork) {
146336e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
146436e227d2STejun Heo 
1465e0aecdd8STejun Heo 		/*
1466e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1467e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1468e0aecdd8STejun Heo 		 * running on the local CPU.
1469e0aecdd8STejun Heo 		 */
147036e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
147136e227d2STejun Heo 			return 1;
147236e227d2STejun Heo 	}
147336e227d2STejun Heo 
147436e227d2STejun Heo 	/* try to claim PENDING the normal way */
1475bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1476bf4ede01STejun Heo 		return 0;
1477bf4ede01STejun Heo 
147824acfb71SThomas Gleixner 	rcu_read_lock();
1479bf4ede01STejun Heo 	/*
1480bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1481bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1482bf4ede01STejun Heo 	 */
1483d565ed63STejun Heo 	pool = get_work_pool(work);
1484d565ed63STejun Heo 	if (!pool)
1485bbb68dfaSTejun Heo 		goto fail;
1486bf4ede01STejun Heo 
1487a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&pool->lock);
1488bf4ede01STejun Heo 	/*
1489112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1490112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1491112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1492112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1493112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
14940b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1495bf4ede01STejun Heo 	 */
1496112202d9STejun Heo 	pwq = get_work_pwq(work);
1497112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1498bf4ede01STejun Heo 		debug_work_deactivate(work);
14993aa62497SLai Jiangshan 
15003aa62497SLai Jiangshan 		/*
1501018f3a13SLai Jiangshan 		 * A cancelable inactive work item must be in the
1502018f3a13SLai Jiangshan 		 * pwq->inactive_works since a queued barrier can't be
1503018f3a13SLai Jiangshan 		 * canceled (see the comments in insert_wq_barrier()).
1504018f3a13SLai Jiangshan 		 *
1505f97a4a1aSLai Jiangshan 		 * An inactive work item cannot be grabbed directly because
1506d812796eSLai Jiangshan 		 * it might have linked barrier work items which, if left
1507f97a4a1aSLai Jiangshan 		 * on the inactive_works list, will confuse pwq->nr_active
150816062836STejun Heo 		 * management later on and cause stall.  Make sure the work
150916062836STejun Heo 		 * item is activated before grabbing.
15103aa62497SLai Jiangshan 		 */
1511f97a4a1aSLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_INACTIVE)
1512f97a4a1aSLai Jiangshan 			pwq_activate_inactive_work(work);
15133aa62497SLai Jiangshan 
1514bf4ede01STejun Heo 		list_del_init(&work->entry);
1515c4560c2cSLai Jiangshan 		pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
151636e227d2STejun Heo 
1517112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
15184468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
15194468a00fSLai Jiangshan 
1520a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock(&pool->lock);
152124acfb71SThomas Gleixner 		rcu_read_unlock();
152236e227d2STejun Heo 		return 1;
1523bf4ede01STejun Heo 	}
1524a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pool->lock);
1525bbb68dfaSTejun Heo fail:
152624acfb71SThomas Gleixner 	rcu_read_unlock();
1527bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1528bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1529bbb68dfaSTejun Heo 		return -ENOENT;
1530bbb68dfaSTejun Heo 	cpu_relax();
153136e227d2STejun Heo 	return -EAGAIN;
1532bf4ede01STejun Heo }
1533bf4ede01STejun Heo 
1534bf4ede01STejun Heo /**
1535706026c2STejun Heo  * insert_work - insert a work into a pool
1536112202d9STejun Heo  * @pwq: pwq @work belongs to
15374690c4abSTejun Heo  * @work: work to insert
15384690c4abSTejun Heo  * @head: insertion point
15394690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
15404690c4abSTejun Heo  *
1541112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1542706026c2STejun Heo  * work_struct flags.
15434690c4abSTejun Heo  *
15444690c4abSTejun Heo  * CONTEXT:
1545a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1546365970a1SDavid Howells  */
1547112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1548112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1549b89deed3SOleg Nesterov {
1550112202d9STejun Heo 	struct worker_pool *pool = pwq->pool;
1551e1d8aa9fSFrederic Weisbecker 
1552e89a85d6SWalter Wu 	/* record the work call stack in order to print it in KASAN reports */
1553f70da745SMarco Elver 	kasan_record_aux_stack_noalloc(work);
1554e89a85d6SWalter Wu 
15554690c4abSTejun Heo 	/* we own @work, set data and link */
1556112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
15571a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
15588864b4e5STejun Heo 	get_pwq(pwq);
1559e22bee78STejun Heo 
156063d95a91STejun Heo 	if (__need_more_worker(pool))
156163d95a91STejun Heo 		wake_up_worker(pool);
1562b89deed3SOleg Nesterov }
1563b89deed3SOleg Nesterov 
1564c8efcc25STejun Heo /*
1565c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
15668d03ecfeSTejun Heo  * same workqueue.
1567c8efcc25STejun Heo  */
1568c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1569c8efcc25STejun Heo {
1570c8efcc25STejun Heo 	struct worker *worker;
1571c8efcc25STejun Heo 
15728d03ecfeSTejun Heo 	worker = current_wq_worker();
1573c8efcc25STejun Heo 	/*
1574bf393fd4SBart Van Assche 	 * Return %true iff I'm a worker executing a work item on @wq.  If
15758d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1576c8efcc25STejun Heo 	 */
1577112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1578c8efcc25STejun Heo }
1579c8efcc25STejun Heo 
1580ef557180SMike Galbraith /*
1581ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
1582ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
1583ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
1584ef557180SMike Galbraith  */
1585ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1586ef557180SMike Galbraith {
1587ef557180SMike Galbraith 	int new_cpu;
1588ef557180SMike Galbraith 
1589f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
1590ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1591ef557180SMike Galbraith 			return cpu;
1592a8ec5880SAmmar Faizi 	} else {
1593a8ec5880SAmmar Faizi 		pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
1594f303fccbSTejun Heo 	}
1595f303fccbSTejun Heo 
1596ef557180SMike Galbraith 	if (cpumask_empty(wq_unbound_cpumask))
1597ef557180SMike Galbraith 		return cpu;
1598ef557180SMike Galbraith 
1599ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
1600ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1601ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
1602ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1603ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
1604ef557180SMike Galbraith 			return cpu;
1605ef557180SMike Galbraith 	}
1606ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
1607ef557180SMike Galbraith 
1608ef557180SMike Galbraith 	return new_cpu;
1609ef557180SMike Galbraith }
1610ef557180SMike Galbraith 
1611d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
16121da177e4SLinus Torvalds 			 struct work_struct *work)
16131da177e4SLinus Torvalds {
1614112202d9STejun Heo 	struct pool_workqueue *pwq;
1615c9178087STejun Heo 	struct worker_pool *last_pool;
16161e19ffc6STejun Heo 	struct list_head *worklist;
16178a2e8e5dSTejun Heo 	unsigned int work_flags;
1618b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
16198930cabaSTejun Heo 
16208930cabaSTejun Heo 	/*
16218930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
16228930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
16238930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
16248930cabaSTejun Heo 	 * happen with IRQ disabled.
16258930cabaSTejun Heo 	 */
16268e8eb730SFrederic Weisbecker 	lockdep_assert_irqs_disabled();
16271da177e4SLinus Torvalds 
16281e19ffc6STejun Heo 
162933e3f0a3SRichard Clark 	/*
163033e3f0a3SRichard Clark 	 * For a draining wq, only works from the same workqueue are
163133e3f0a3SRichard Clark 	 * allowed. The __WQ_DESTROYING helps to spot the issue that
163233e3f0a3SRichard Clark 	 * queues a new work item to a wq after destroy_workqueue(wq).
163333e3f0a3SRichard Clark 	 */
163433e3f0a3SRichard Clark 	if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
163533e3f0a3SRichard Clark 		     WARN_ON_ONCE(!is_chained_work(wq))))
1636e41e704bSTejun Heo 		return;
163724acfb71SThomas Gleixner 	rcu_read_lock();
16389e8cd2f5STejun Heo retry:
1639aa202f1fSHillf Danton 	/* pwq which will be used unless @work is executing elsewhere */
1640aa202f1fSHillf Danton 	if (wq->flags & WQ_UNBOUND) {
1641df2d5ae4STejun Heo 		if (req_cpu == WORK_CPU_UNBOUND)
1642ef557180SMike Galbraith 			cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1643df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1644aa202f1fSHillf Danton 	} else {
1645aa202f1fSHillf Danton 		if (req_cpu == WORK_CPU_UNBOUND)
1646aa202f1fSHillf Danton 			cpu = raw_smp_processor_id();
1647aa202f1fSHillf Danton 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1648aa202f1fSHillf Danton 	}
1649f3421797STejun Heo 
165018aa9effSTejun Heo 	/*
1651c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1652c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1653c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
165418aa9effSTejun Heo 	 */
1655c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1656112202d9STejun Heo 	if (last_pool && last_pool != pwq->pool) {
165718aa9effSTejun Heo 		struct worker *worker;
165818aa9effSTejun Heo 
1659a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&last_pool->lock);
166018aa9effSTejun Heo 
1661c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
166218aa9effSTejun Heo 
1663112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1664c9178087STejun Heo 			pwq = worker->current_pwq;
16658594fadeSLai Jiangshan 		} else {
166618aa9effSTejun Heo 			/* meh... not running there, queue here */
1667a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&last_pool->lock);
1668a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock(&pwq->pool->lock);
166918aa9effSTejun Heo 		}
16708930cabaSTejun Heo 	} else {
1671a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&pwq->pool->lock);
16728930cabaSTejun Heo 	}
1673502ca9d8STejun Heo 
16749e8cd2f5STejun Heo 	/*
16759e8cd2f5STejun Heo 	 * pwq is determined and locked.  For unbound pools, we could have
16769e8cd2f5STejun Heo 	 * raced with pwq release and it could already be dead.  If its
16779e8cd2f5STejun Heo 	 * refcnt is zero, repeat pwq selection.  Note that pwqs never die
1678df2d5ae4STejun Heo 	 * without another pwq replacing it in the numa_pwq_tbl or while
1679df2d5ae4STejun Heo 	 * work items are executing on it, so the retrying is guaranteed to
16809e8cd2f5STejun Heo 	 * make forward-progress.
16819e8cd2f5STejun Heo 	 */
16829e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
16839e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
1684a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&pwq->pool->lock);
16859e8cd2f5STejun Heo 			cpu_relax();
16869e8cd2f5STejun Heo 			goto retry;
16879e8cd2f5STejun Heo 		}
16889e8cd2f5STejun Heo 		/* oops */
16899e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
16909e8cd2f5STejun Heo 			  wq->name, cpu);
16919e8cd2f5STejun Heo 	}
16929e8cd2f5STejun Heo 
1693112202d9STejun Heo 	/* pwq determined, queue */
1694112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1695502ca9d8STejun Heo 
169624acfb71SThomas Gleixner 	if (WARN_ON(!list_empty(&work->entry)))
169724acfb71SThomas Gleixner 		goto out;
16981e19ffc6STejun Heo 
1699112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1700112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
17011e19ffc6STejun Heo 
1702112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1703cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1704112202d9STejun Heo 		pwq->nr_active++;
1705112202d9STejun Heo 		worklist = &pwq->pool->worklist;
170682607adcSTejun Heo 		if (list_empty(worklist))
170782607adcSTejun Heo 			pwq->pool->watchdog_ts = jiffies;
17088a2e8e5dSTejun Heo 	} else {
1709f97a4a1aSLai Jiangshan 		work_flags |= WORK_STRUCT_INACTIVE;
1710f97a4a1aSLai Jiangshan 		worklist = &pwq->inactive_works;
17118a2e8e5dSTejun Heo 	}
17121e19ffc6STejun Heo 
17130687c66bSZqiang 	debug_work_activate(work);
1714112202d9STejun Heo 	insert_work(pwq, work, worklist, work_flags);
17151e19ffc6STejun Heo 
171624acfb71SThomas Gleixner out:
1717a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pwq->pool->lock);
171824acfb71SThomas Gleixner 	rcu_read_unlock();
17191da177e4SLinus Torvalds }
17201da177e4SLinus Torvalds 
17210fcb78c2SRolf Eike Beer /**
1722c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1723c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1724c1a220e7SZhang Rui  * @wq: workqueue to use
1725c1a220e7SZhang Rui  * @work: work to queue
1726c1a220e7SZhang Rui  *
1727c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1728443378f0SPaul E. McKenney  * can't go away.  Callers that fail to ensure that the specified
1729443378f0SPaul E. McKenney  * CPU cannot go away will execute on a randomly chosen CPU.
1730854f5cc5SPaul E. McKenney  * But note well that callers specifying a CPU that never has been
1731854f5cc5SPaul E. McKenney  * online will get a splat.
1732d185af30SYacine Belkadi  *
1733d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
1734c1a220e7SZhang Rui  */
1735d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1736d4283e93STejun Heo 		   struct work_struct *work)
1737c1a220e7SZhang Rui {
1738d4283e93STejun Heo 	bool ret = false;
17398930cabaSTejun Heo 	unsigned long flags;
17408930cabaSTejun Heo 
17418930cabaSTejun Heo 	local_irq_save(flags);
1742c1a220e7SZhang Rui 
174322df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
17444690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1745d4283e93STejun Heo 		ret = true;
1746c1a220e7SZhang Rui 	}
17478930cabaSTejun Heo 
17488930cabaSTejun Heo 	local_irq_restore(flags);
1749c1a220e7SZhang Rui 	return ret;
1750c1a220e7SZhang Rui }
1751ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1752c1a220e7SZhang Rui 
17538204e0c1SAlexander Duyck /**
17548204e0c1SAlexander Duyck  * workqueue_select_cpu_near - Select a CPU based on NUMA node
17558204e0c1SAlexander Duyck  * @node: NUMA node ID that we want to select a CPU from
17568204e0c1SAlexander Duyck  *
17578204e0c1SAlexander Duyck  * This function will attempt to find a "random" cpu available on a given
17588204e0c1SAlexander Duyck  * node. If there are no CPUs available on the given node it will return
17598204e0c1SAlexander Duyck  * WORK_CPU_UNBOUND indicating that we should just schedule to any
17608204e0c1SAlexander Duyck  * available CPU if we need to schedule this work.
17618204e0c1SAlexander Duyck  */
17628204e0c1SAlexander Duyck static int workqueue_select_cpu_near(int node)
17638204e0c1SAlexander Duyck {
17648204e0c1SAlexander Duyck 	int cpu;
17658204e0c1SAlexander Duyck 
17668204e0c1SAlexander Duyck 	/* No point in doing this if NUMA isn't enabled for workqueues */
17678204e0c1SAlexander Duyck 	if (!wq_numa_enabled)
17688204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
17698204e0c1SAlexander Duyck 
17708204e0c1SAlexander Duyck 	/* Delay binding to CPU if node is not valid or online */
17718204e0c1SAlexander Duyck 	if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
17728204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
17738204e0c1SAlexander Duyck 
17748204e0c1SAlexander Duyck 	/* Use local node/cpu if we are already there */
17758204e0c1SAlexander Duyck 	cpu = raw_smp_processor_id();
17768204e0c1SAlexander Duyck 	if (node == cpu_to_node(cpu))
17778204e0c1SAlexander Duyck 		return cpu;
17788204e0c1SAlexander Duyck 
17798204e0c1SAlexander Duyck 	/* Use "random" otherwise know as "first" online CPU of node */
17808204e0c1SAlexander Duyck 	cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
17818204e0c1SAlexander Duyck 
17828204e0c1SAlexander Duyck 	/* If CPU is valid return that, otherwise just defer */
17838204e0c1SAlexander Duyck 	return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
17848204e0c1SAlexander Duyck }
17858204e0c1SAlexander Duyck 
17868204e0c1SAlexander Duyck /**
17878204e0c1SAlexander Duyck  * queue_work_node - queue work on a "random" cpu for a given NUMA node
17888204e0c1SAlexander Duyck  * @node: NUMA node that we are targeting the work for
17898204e0c1SAlexander Duyck  * @wq: workqueue to use
17908204e0c1SAlexander Duyck  * @work: work to queue
17918204e0c1SAlexander Duyck  *
17928204e0c1SAlexander Duyck  * We queue the work to a "random" CPU within a given NUMA node. The basic
17938204e0c1SAlexander Duyck  * idea here is to provide a way to somehow associate work with a given
17948204e0c1SAlexander Duyck  * NUMA node.
17958204e0c1SAlexander Duyck  *
17968204e0c1SAlexander Duyck  * This function will only make a best effort attempt at getting this onto
17978204e0c1SAlexander Duyck  * the right NUMA node. If no node is requested or the requested node is
17988204e0c1SAlexander Duyck  * offline then we just fall back to standard queue_work behavior.
17998204e0c1SAlexander Duyck  *
18008204e0c1SAlexander Duyck  * Currently the "random" CPU ends up being the first available CPU in the
18018204e0c1SAlexander Duyck  * intersection of cpu_online_mask and the cpumask of the node, unless we
18028204e0c1SAlexander Duyck  * are running on the node. In that case we just use the current CPU.
18038204e0c1SAlexander Duyck  *
18048204e0c1SAlexander Duyck  * Return: %false if @work was already on a queue, %true otherwise.
18058204e0c1SAlexander Duyck  */
18068204e0c1SAlexander Duyck bool queue_work_node(int node, struct workqueue_struct *wq,
18078204e0c1SAlexander Duyck 		     struct work_struct *work)
18088204e0c1SAlexander Duyck {
18098204e0c1SAlexander Duyck 	unsigned long flags;
18108204e0c1SAlexander Duyck 	bool ret = false;
18118204e0c1SAlexander Duyck 
18128204e0c1SAlexander Duyck 	/*
18138204e0c1SAlexander Duyck 	 * This current implementation is specific to unbound workqueues.
18148204e0c1SAlexander Duyck 	 * Specifically we only return the first available CPU for a given
18158204e0c1SAlexander Duyck 	 * node instead of cycling through individual CPUs within the node.
18168204e0c1SAlexander Duyck 	 *
18178204e0c1SAlexander Duyck 	 * If this is used with a per-cpu workqueue then the logic in
18188204e0c1SAlexander Duyck 	 * workqueue_select_cpu_near would need to be updated to allow for
18198204e0c1SAlexander Duyck 	 * some round robin type logic.
18208204e0c1SAlexander Duyck 	 */
18218204e0c1SAlexander Duyck 	WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
18228204e0c1SAlexander Duyck 
18238204e0c1SAlexander Duyck 	local_irq_save(flags);
18248204e0c1SAlexander Duyck 
18258204e0c1SAlexander Duyck 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
18268204e0c1SAlexander Duyck 		int cpu = workqueue_select_cpu_near(node);
18278204e0c1SAlexander Duyck 
18288204e0c1SAlexander Duyck 		__queue_work(cpu, wq, work);
18298204e0c1SAlexander Duyck 		ret = true;
18308204e0c1SAlexander Duyck 	}
18318204e0c1SAlexander Duyck 
18328204e0c1SAlexander Duyck 	local_irq_restore(flags);
18338204e0c1SAlexander Duyck 	return ret;
18348204e0c1SAlexander Duyck }
18358204e0c1SAlexander Duyck EXPORT_SYMBOL_GPL(queue_work_node);
18368204e0c1SAlexander Duyck 
18378c20feb6SKees Cook void delayed_work_timer_fn(struct timer_list *t)
18381da177e4SLinus Torvalds {
18398c20feb6SKees Cook 	struct delayed_work *dwork = from_timer(dwork, t, timer);
18401da177e4SLinus Torvalds 
1841e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
184260c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
18431da177e4SLinus Torvalds }
18441438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
18451da177e4SLinus Torvalds 
18467beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
184752bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
18481da177e4SLinus Torvalds {
18497beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
18507beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
18511da177e4SLinus Torvalds 
1852637fdbaeSTejun Heo 	WARN_ON_ONCE(!wq);
18534b243563SSami Tolvanen 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
1854fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1855fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
18567beb2edfSTejun Heo 
18578852aac2STejun Heo 	/*
18588852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
18598852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
18608852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
18618852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
18628852aac2STejun Heo 	 */
18638852aac2STejun Heo 	if (!delay) {
18648852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
18658852aac2STejun Heo 		return;
18668852aac2STejun Heo 	}
18678852aac2STejun Heo 
186860c057bcSLai Jiangshan 	dwork->wq = wq;
18691265057fSTejun Heo 	dwork->cpu = cpu;
18707beb2edfSTejun Heo 	timer->expires = jiffies + delay;
18717beb2edfSTejun Heo 
1872041bd12eSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
18737beb2edfSTejun Heo 		add_timer_on(timer, cpu);
1874041bd12eSTejun Heo 	else
1875041bd12eSTejun Heo 		add_timer(timer);
18767beb2edfSTejun Heo }
18771da177e4SLinus Torvalds 
18780fcb78c2SRolf Eike Beer /**
18790fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
18800fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
18810fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1882af9997e4SRandy Dunlap  * @dwork: work to queue
18830fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
18840fcb78c2SRolf Eike Beer  *
1885d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
1886715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1887715f1300STejun Heo  * execution.
18880fcb78c2SRolf Eike Beer  */
1889d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
189052bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
18917a6bc1cdSVenkatesh Pallipadi {
189252bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1893d4283e93STejun Heo 	bool ret = false;
18948930cabaSTejun Heo 	unsigned long flags;
18958930cabaSTejun Heo 
18968930cabaSTejun Heo 	/* read the comment in __queue_work() */
18978930cabaSTejun Heo 	local_irq_save(flags);
18987a6bc1cdSVenkatesh Pallipadi 
189922df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
19007beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1901d4283e93STejun Heo 		ret = true;
19027a6bc1cdSVenkatesh Pallipadi 	}
19038930cabaSTejun Heo 
19048930cabaSTejun Heo 	local_irq_restore(flags);
19057a6bc1cdSVenkatesh Pallipadi 	return ret;
19067a6bc1cdSVenkatesh Pallipadi }
1907ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
19081da177e4SLinus Torvalds 
1909c8e55f36STejun Heo /**
19108376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
19118376fe22STejun Heo  * @cpu: CPU number to execute work on
19128376fe22STejun Heo  * @wq: workqueue to use
19138376fe22STejun Heo  * @dwork: work to queue
19148376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
19158376fe22STejun Heo  *
19168376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
19178376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
19188376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
19198376fe22STejun Heo  * current state.
19208376fe22STejun Heo  *
1921d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
19228376fe22STejun Heo  * pending and its timer was modified.
19238376fe22STejun Heo  *
1924e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
19258376fe22STejun Heo  * See try_to_grab_pending() for details.
19268376fe22STejun Heo  */
19278376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
19288376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
19298376fe22STejun Heo {
19308376fe22STejun Heo 	unsigned long flags;
19318376fe22STejun Heo 	int ret;
19328376fe22STejun Heo 
19338376fe22STejun Heo 	do {
19348376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
19358376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
19368376fe22STejun Heo 
19378376fe22STejun Heo 	if (likely(ret >= 0)) {
19388376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
19398376fe22STejun Heo 		local_irq_restore(flags);
19408376fe22STejun Heo 	}
19418376fe22STejun Heo 
19428376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
19438376fe22STejun Heo 	return ret;
19448376fe22STejun Heo }
19458376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
19468376fe22STejun Heo 
194705f0fe6bSTejun Heo static void rcu_work_rcufn(struct rcu_head *rcu)
194805f0fe6bSTejun Heo {
194905f0fe6bSTejun Heo 	struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
195005f0fe6bSTejun Heo 
195105f0fe6bSTejun Heo 	/* read the comment in __queue_work() */
195205f0fe6bSTejun Heo 	local_irq_disable();
195305f0fe6bSTejun Heo 	__queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
195405f0fe6bSTejun Heo 	local_irq_enable();
195505f0fe6bSTejun Heo }
195605f0fe6bSTejun Heo 
195705f0fe6bSTejun Heo /**
195805f0fe6bSTejun Heo  * queue_rcu_work - queue work after a RCU grace period
195905f0fe6bSTejun Heo  * @wq: workqueue to use
196005f0fe6bSTejun Heo  * @rwork: work to queue
196105f0fe6bSTejun Heo  *
196205f0fe6bSTejun Heo  * Return: %false if @rwork was already pending, %true otherwise.  Note
196305f0fe6bSTejun Heo  * that a full RCU grace period is guaranteed only after a %true return.
1964bf393fd4SBart Van Assche  * While @rwork is guaranteed to be executed after a %false return, the
196505f0fe6bSTejun Heo  * execution may happen before a full RCU grace period has passed.
196605f0fe6bSTejun Heo  */
196705f0fe6bSTejun Heo bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
196805f0fe6bSTejun Heo {
196905f0fe6bSTejun Heo 	struct work_struct *work = &rwork->work;
197005f0fe6bSTejun Heo 
197105f0fe6bSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
197205f0fe6bSTejun Heo 		rwork->wq = wq;
1973a7e30c0eSUladzislau Rezki 		call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
197405f0fe6bSTejun Heo 		return true;
197505f0fe6bSTejun Heo 	}
197605f0fe6bSTejun Heo 
197705f0fe6bSTejun Heo 	return false;
197805f0fe6bSTejun Heo }
197905f0fe6bSTejun Heo EXPORT_SYMBOL(queue_rcu_work);
198005f0fe6bSTejun Heo 
19818376fe22STejun Heo /**
1982c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1983c8e55f36STejun Heo  * @worker: worker which is entering idle state
1984c8e55f36STejun Heo  *
1985c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1986c8e55f36STejun Heo  * necessary.
1987c8e55f36STejun Heo  *
1988c8e55f36STejun Heo  * LOCKING:
1989a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1990c8e55f36STejun Heo  */
1991c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
19921da177e4SLinus Torvalds {
1993bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1994c8e55f36STejun Heo 
19956183c009STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
19966183c009STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
19976183c009STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
19986183c009STejun Heo 		return;
1999c8e55f36STejun Heo 
2000051e1850SLai Jiangshan 	/* can't use worker_set_flags(), also called from create_worker() */
2001cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
2002bd7bdd43STejun Heo 	pool->nr_idle++;
2003e22bee78STejun Heo 	worker->last_active = jiffies;
2004c8e55f36STejun Heo 
2005c8e55f36STejun Heo 	/* idle_list is LIFO */
2006bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
2007db7bccf4STejun Heo 
200863d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
2009628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
2010cb444766STejun Heo 
2011989442d7SLai Jiangshan 	/* Sanity check nr_running. */
2012bc35f7efSLai Jiangshan 	WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
2013c8e55f36STejun Heo }
2014c8e55f36STejun Heo 
2015c8e55f36STejun Heo /**
2016c8e55f36STejun Heo  * worker_leave_idle - leave idle state
2017c8e55f36STejun Heo  * @worker: worker which is leaving idle state
2018c8e55f36STejun Heo  *
2019c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
2020c8e55f36STejun Heo  *
2021c8e55f36STejun Heo  * LOCKING:
2022a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
2023c8e55f36STejun Heo  */
2024c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
2025c8e55f36STejun Heo {
2026bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2027c8e55f36STejun Heo 
20286183c009STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
20296183c009STejun Heo 		return;
2030d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
2031bd7bdd43STejun Heo 	pool->nr_idle--;
2032c8e55f36STejun Heo 	list_del_init(&worker->entry);
2033c8e55f36STejun Heo }
2034c8e55f36STejun Heo 
2035f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
2036c34056a3STejun Heo {
2037c34056a3STejun Heo 	struct worker *worker;
2038c34056a3STejun Heo 
2039f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
2040c8e55f36STejun Heo 	if (worker) {
2041c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
2042affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
2043da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
2044e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
2045e22bee78STejun Heo 		worker->flags = WORKER_PREP;
2046c8e55f36STejun Heo 	}
2047c34056a3STejun Heo 	return worker;
2048c34056a3STejun Heo }
2049c34056a3STejun Heo 
2050c34056a3STejun Heo /**
20514736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
20524736cbf7SLai Jiangshan  * @worker: worker to be attached
20534736cbf7SLai Jiangshan  * @pool: the target pool
20544736cbf7SLai Jiangshan  *
20554736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
20564736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
20574736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
20584736cbf7SLai Jiangshan  */
20594736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
20604736cbf7SLai Jiangshan 				   struct worker_pool *pool)
20614736cbf7SLai Jiangshan {
20621258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
20634736cbf7SLai Jiangshan 
20644736cbf7SLai Jiangshan 	/*
20651258fae7STejun Heo 	 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
20661258fae7STejun Heo 	 * stable across this function.  See the comments above the flag
20671258fae7STejun Heo 	 * definition for details.
20684736cbf7SLai Jiangshan 	 */
20694736cbf7SLai Jiangshan 	if (pool->flags & POOL_DISASSOCIATED)
20704736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
20715c25b5ffSPeter Zijlstra 	else
20725c25b5ffSPeter Zijlstra 		kthread_set_per_cpu(worker->task, pool->cpu);
20734736cbf7SLai Jiangshan 
2074640f17c8SPeter Zijlstra 	if (worker->rescue_wq)
2075640f17c8SPeter Zijlstra 		set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
2076640f17c8SPeter Zijlstra 
20774736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
2078a2d812a2STejun Heo 	worker->pool = pool;
20794736cbf7SLai Jiangshan 
20801258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
20814736cbf7SLai Jiangshan }
20824736cbf7SLai Jiangshan 
20834736cbf7SLai Jiangshan /**
208460f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
208560f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
208660f5a4bcSLai Jiangshan  *
20874736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
20884736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
20894736cbf7SLai Jiangshan  * other reference to the pool.
209060f5a4bcSLai Jiangshan  */
2091a2d812a2STejun Heo static void worker_detach_from_pool(struct worker *worker)
209260f5a4bcSLai Jiangshan {
2093a2d812a2STejun Heo 	struct worker_pool *pool = worker->pool;
209460f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
209560f5a4bcSLai Jiangshan 
20961258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2097a2d812a2STejun Heo 
20985c25b5ffSPeter Zijlstra 	kthread_set_per_cpu(worker->task, -1);
2099da028469SLai Jiangshan 	list_del(&worker->node);
2100a2d812a2STejun Heo 	worker->pool = NULL;
2101a2d812a2STejun Heo 
2102e02b9312SValentin Schneider 	if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
210360f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
21041258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
210560f5a4bcSLai Jiangshan 
2106b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
2107b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2108b62c0751SLai Jiangshan 
210960f5a4bcSLai Jiangshan 	if (detach_completion)
211060f5a4bcSLai Jiangshan 		complete(detach_completion);
211160f5a4bcSLai Jiangshan }
211260f5a4bcSLai Jiangshan 
211360f5a4bcSLai Jiangshan /**
2114c34056a3STejun Heo  * create_worker - create a new workqueue worker
211563d95a91STejun Heo  * @pool: pool the new worker will belong to
2116c34056a3STejun Heo  *
2117051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
2118c34056a3STejun Heo  *
2119c34056a3STejun Heo  * CONTEXT:
2120c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
2121c34056a3STejun Heo  *
2122d185af30SYacine Belkadi  * Return:
2123c34056a3STejun Heo  * Pointer to the newly created worker.
2124c34056a3STejun Heo  */
2125bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
2126c34056a3STejun Heo {
2127e441b56fSZhen Lei 	struct worker *worker;
2128e441b56fSZhen Lei 	int id;
2129e3c916a4STejun Heo 	char id_buf[16];
2130c34056a3STejun Heo 
21317cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
2132e441b56fSZhen Lei 	id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
21333f0ea0b8SPetr Mladek 	if (id < 0) {
21343f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
21353f0ea0b8SPetr Mladek 			    ERR_PTR(id));
2136e441b56fSZhen Lei 		return NULL;
21373f0ea0b8SPetr Mladek 	}
2138c34056a3STejun Heo 
2139f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
21403f0ea0b8SPetr Mladek 	if (!worker) {
21413f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker\n");
2142c34056a3STejun Heo 		goto fail;
21433f0ea0b8SPetr Mladek 	}
2144c34056a3STejun Heo 
2145c34056a3STejun Heo 	worker->id = id;
2146c34056a3STejun Heo 
214729c91e99STejun Heo 	if (pool->cpu >= 0)
2148e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
2149e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
2150f3421797STejun Heo 	else
2151e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
2152e3c916a4STejun Heo 
2153f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
2154e3c916a4STejun Heo 					      "kworker/%s", id_buf);
21553f0ea0b8SPetr Mladek 	if (IS_ERR(worker->task)) {
215660f54038SPetr Mladek 		if (PTR_ERR(worker->task) == -EINTR) {
215760f54038SPetr Mladek 			pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n",
215860f54038SPetr Mladek 			       id_buf);
215960f54038SPetr Mladek 		} else {
21603f0ea0b8SPetr Mladek 			pr_err_once("workqueue: Failed to create a worker thread: %pe",
21613f0ea0b8SPetr Mladek 				    worker->task);
216260f54038SPetr Mladek 		}
2163c34056a3STejun Heo 		goto fail;
21643f0ea0b8SPetr Mladek 	}
2165c34056a3STejun Heo 
216691151228SOleg Nesterov 	set_user_nice(worker->task, pool->attrs->nice);
216725834c73SPeter Zijlstra 	kthread_bind_mask(worker->task, pool->attrs->cpumask);
216891151228SOleg Nesterov 
2169da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
21704736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
2171822d8405STejun Heo 
2172051e1850SLai Jiangshan 	/* start the newly created worker */
2173a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2174051e1850SLai Jiangshan 	worker->pool->nr_workers++;
2175051e1850SLai Jiangshan 	worker_enter_idle(worker);
2176051e1850SLai Jiangshan 	wake_up_process(worker->task);
2177a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2178051e1850SLai Jiangshan 
2179c34056a3STejun Heo 	return worker;
2180822d8405STejun Heo 
2181c34056a3STejun Heo fail:
2182e441b56fSZhen Lei 	ida_free(&pool->worker_ida, id);
2183c34056a3STejun Heo 	kfree(worker);
2184c34056a3STejun Heo 	return NULL;
2185c34056a3STejun Heo }
2186c34056a3STejun Heo 
2187793777bcSValentin Schneider static void unbind_worker(struct worker *worker)
2188793777bcSValentin Schneider {
2189793777bcSValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2190793777bcSValentin Schneider 
2191793777bcSValentin Schneider 	kthread_set_per_cpu(worker->task, -1);
2192793777bcSValentin Schneider 	if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2193793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2194793777bcSValentin Schneider 	else
2195793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2196793777bcSValentin Schneider }
2197793777bcSValentin Schneider 
2198e02b9312SValentin Schneider static void wake_dying_workers(struct list_head *cull_list)
2199e02b9312SValentin Schneider {
2200e02b9312SValentin Schneider 	struct worker *worker, *tmp;
2201e02b9312SValentin Schneider 
2202e02b9312SValentin Schneider 	list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2203e02b9312SValentin Schneider 		list_del_init(&worker->entry);
2204e02b9312SValentin Schneider 		unbind_worker(worker);
2205e02b9312SValentin Schneider 		/*
2206e02b9312SValentin Schneider 		 * If the worker was somehow already running, then it had to be
2207e02b9312SValentin Schneider 		 * in pool->idle_list when set_worker_dying() happened or we
2208e02b9312SValentin Schneider 		 * wouldn't have gotten here.
2209c34056a3STejun Heo 		 *
2210e02b9312SValentin Schneider 		 * Thus, the worker must either have observed the WORKER_DIE
2211e02b9312SValentin Schneider 		 * flag, or have set its state to TASK_IDLE. Either way, the
2212e02b9312SValentin Schneider 		 * below will be observed by the worker and is safe to do
2213e02b9312SValentin Schneider 		 * outside of pool->lock.
2214e02b9312SValentin Schneider 		 */
2215e02b9312SValentin Schneider 		wake_up_process(worker->task);
2216e02b9312SValentin Schneider 	}
2217e02b9312SValentin Schneider }
2218e02b9312SValentin Schneider 
2219e02b9312SValentin Schneider /**
2220e02b9312SValentin Schneider  * set_worker_dying - Tag a worker for destruction
2221e02b9312SValentin Schneider  * @worker: worker to be destroyed
2222e02b9312SValentin Schneider  * @list: transfer worker away from its pool->idle_list and into list
2223e02b9312SValentin Schneider  *
2224e02b9312SValentin Schneider  * Tag @worker for destruction and adjust @pool stats accordingly.  The worker
2225e02b9312SValentin Schneider  * should be idle.
2226c8e55f36STejun Heo  *
2227c8e55f36STejun Heo  * CONTEXT:
2228a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
2229c34056a3STejun Heo  */
2230e02b9312SValentin Schneider static void set_worker_dying(struct worker *worker, struct list_head *list)
2231c34056a3STejun Heo {
2232bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2233c34056a3STejun Heo 
2234cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
2235e02b9312SValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2236cd549687STejun Heo 
2237c34056a3STejun Heo 	/* sanity check frenzy */
22386183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
223973eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
224073eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
22416183c009STejun Heo 		return;
2242c34056a3STejun Heo 
2243bd7bdd43STejun Heo 	pool->nr_workers--;
2244bd7bdd43STejun Heo 	pool->nr_idle--;
2245c8e55f36STejun Heo 
2246cb444766STejun Heo 	worker->flags |= WORKER_DIE;
2247e02b9312SValentin Schneider 
2248e02b9312SValentin Schneider 	list_move(&worker->entry, list);
2249e02b9312SValentin Schneider 	list_move(&worker->node, &pool->dying_workers);
2250c34056a3STejun Heo }
2251c34056a3STejun Heo 
22523f959aa3SValentin Schneider /**
22533f959aa3SValentin Schneider  * idle_worker_timeout - check if some idle workers can now be deleted.
22543f959aa3SValentin Schneider  * @t: The pool's idle_timer that just expired
22553f959aa3SValentin Schneider  *
22563f959aa3SValentin Schneider  * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
22573f959aa3SValentin Schneider  * worker_leave_idle(), as a worker flicking between idle and active while its
22583f959aa3SValentin Schneider  * pool is at the too_many_workers() tipping point would cause too much timer
22593f959aa3SValentin Schneider  * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
22603f959aa3SValentin Schneider  * it expire and re-evaluate things from there.
22613f959aa3SValentin Schneider  */
226232a6c723SKees Cook static void idle_worker_timeout(struct timer_list *t)
2263e22bee78STejun Heo {
226432a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, idle_timer);
22653f959aa3SValentin Schneider 	bool do_cull = false;
22663f959aa3SValentin Schneider 
22673f959aa3SValentin Schneider 	if (work_pending(&pool->idle_cull_work))
22683f959aa3SValentin Schneider 		return;
22693f959aa3SValentin Schneider 
22703f959aa3SValentin Schneider 	raw_spin_lock_irq(&pool->lock);
22713f959aa3SValentin Schneider 
22723f959aa3SValentin Schneider 	if (too_many_workers(pool)) {
22733f959aa3SValentin Schneider 		struct worker *worker;
22743f959aa3SValentin Schneider 		unsigned long expires;
22753f959aa3SValentin Schneider 
22763f959aa3SValentin Schneider 		/* idle_list is kept in LIFO order, check the last one */
22773f959aa3SValentin Schneider 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
22783f959aa3SValentin Schneider 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
22793f959aa3SValentin Schneider 		do_cull = !time_before(jiffies, expires);
22803f959aa3SValentin Schneider 
22813f959aa3SValentin Schneider 		if (!do_cull)
22823f959aa3SValentin Schneider 			mod_timer(&pool->idle_timer, expires);
22833f959aa3SValentin Schneider 	}
22843f959aa3SValentin Schneider 	raw_spin_unlock_irq(&pool->lock);
22853f959aa3SValentin Schneider 
22863f959aa3SValentin Schneider 	if (do_cull)
22873f959aa3SValentin Schneider 		queue_work(system_unbound_wq, &pool->idle_cull_work);
22883f959aa3SValentin Schneider }
22893f959aa3SValentin Schneider 
22903f959aa3SValentin Schneider /**
22913f959aa3SValentin Schneider  * idle_cull_fn - cull workers that have been idle for too long.
22923f959aa3SValentin Schneider  * @work: the pool's work for handling these idle workers
22933f959aa3SValentin Schneider  *
22943f959aa3SValentin Schneider  * This goes through a pool's idle workers and gets rid of those that have been
22953f959aa3SValentin Schneider  * idle for at least IDLE_WORKER_TIMEOUT seconds.
2296e02b9312SValentin Schneider  *
2297e02b9312SValentin Schneider  * We don't want to disturb isolated CPUs because of a pcpu kworker being
2298e02b9312SValentin Schneider  * culled, so this also resets worker affinity. This requires a sleepable
2299e02b9312SValentin Schneider  * context, hence the split between timer callback and work item.
23003f959aa3SValentin Schneider  */
23013f959aa3SValentin Schneider static void idle_cull_fn(struct work_struct *work)
23023f959aa3SValentin Schneider {
23033f959aa3SValentin Schneider 	struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
2304e02b9312SValentin Schneider 	struct list_head cull_list;
2305e22bee78STejun Heo 
2306e02b9312SValentin Schneider 	INIT_LIST_HEAD(&cull_list);
2307e02b9312SValentin Schneider 	/*
2308e02b9312SValentin Schneider 	 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2309e02b9312SValentin Schneider 	 * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2310e02b9312SValentin Schneider 	 * path. This is required as a previously-preempted worker could run after
2311e02b9312SValentin Schneider 	 * set_worker_dying() has happened but before wake_dying_workers() did.
2312e02b9312SValentin Schneider 	 */
2313e02b9312SValentin Schneider 	mutex_lock(&wq_pool_attach_mutex);
2314a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2315e22bee78STejun Heo 
23163347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
2317e22bee78STejun Heo 		struct worker *worker;
2318e22bee78STejun Heo 		unsigned long expires;
2319e22bee78STejun Heo 
232063d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
2321e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2322e22bee78STejun Heo 
23233347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
232463d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
23253347fc9fSLai Jiangshan 			break;
2326e22bee78STejun Heo 		}
23273347fc9fSLai Jiangshan 
2328e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
2329e22bee78STejun Heo 	}
2330e22bee78STejun Heo 
2331a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2332e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
2333e02b9312SValentin Schneider 	mutex_unlock(&wq_pool_attach_mutex);
2334e22bee78STejun Heo }
2335e22bee78STejun Heo 
2336493a1724STejun Heo static void send_mayday(struct work_struct *work)
2337e22bee78STejun Heo {
2338112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2339112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
2340493a1724STejun Heo 
23412e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
2342e22bee78STejun Heo 
2343493008a8STejun Heo 	if (!wq->rescuer)
2344493a1724STejun Heo 		return;
2345e22bee78STejun Heo 
2346e22bee78STejun Heo 	/* mayday mayday mayday */
2347493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
234877668c8bSLai Jiangshan 		/*
234977668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
235077668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
235177668c8bSLai Jiangshan 		 * rescuer is done with it.
235277668c8bSLai Jiangshan 		 */
235377668c8bSLai Jiangshan 		get_pwq(pwq);
2354493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
2355e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
2356725e8ec5STejun Heo 		pwq->stats[PWQ_STAT_MAYDAY]++;
2357493a1724STejun Heo 	}
2358e22bee78STejun Heo }
2359e22bee78STejun Heo 
236032a6c723SKees Cook static void pool_mayday_timeout(struct timer_list *t)
2361e22bee78STejun Heo {
236232a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2363e22bee78STejun Heo 	struct work_struct *work;
2364e22bee78STejun Heo 
2365a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2366a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&wq_mayday_lock);		/* for wq->maydays */
2367e22bee78STejun Heo 
236863d95a91STejun Heo 	if (need_to_create_worker(pool)) {
2369e22bee78STejun Heo 		/*
2370e22bee78STejun Heo 		 * We've been trying to create a new worker but
2371e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
2372e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
2373e22bee78STejun Heo 		 * rescuers.
2374e22bee78STejun Heo 		 */
237563d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
2376e22bee78STejun Heo 			send_mayday(work);
2377e22bee78STejun Heo 	}
2378e22bee78STejun Heo 
2379a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&wq_mayday_lock);
2380a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2381e22bee78STejun Heo 
238263d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2383e22bee78STejun Heo }
2384e22bee78STejun Heo 
2385e22bee78STejun Heo /**
2386e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
238763d95a91STejun Heo  * @pool: pool to create a new worker for
2388e22bee78STejun Heo  *
238963d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
2390e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
2391e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
239263d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
2393e22bee78STejun Heo  * possible allocation deadlock.
2394e22bee78STejun Heo  *
2395c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
2396c5aa87bbSTejun Heo  * may_start_working() %true.
2397e22bee78STejun Heo  *
2398e22bee78STejun Heo  * LOCKING:
2399a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2400e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
2401e22bee78STejun Heo  * manager.
2402e22bee78STejun Heo  */
240329187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
2404d565ed63STejun Heo __releases(&pool->lock)
2405d565ed63STejun Heo __acquires(&pool->lock)
2406e22bee78STejun Heo {
2407e22bee78STejun Heo restart:
2408a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
24099f9c2364STejun Heo 
2410e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
241163d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2412e22bee78STejun Heo 
2413e22bee78STejun Heo 	while (true) {
2414051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
2415e22bee78STejun Heo 			break;
2416e22bee78STejun Heo 
2417e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
24189f9c2364STejun Heo 
241963d95a91STejun Heo 		if (!need_to_create_worker(pool))
2420e22bee78STejun Heo 			break;
2421e22bee78STejun Heo 	}
2422e22bee78STejun Heo 
242363d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
2424a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2425051e1850SLai Jiangshan 	/*
2426051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
2427051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
2428051e1850SLai Jiangshan 	 * already become busy.
2429051e1850SLai Jiangshan 	 */
243063d95a91STejun Heo 	if (need_to_create_worker(pool))
2431e22bee78STejun Heo 		goto restart;
2432e22bee78STejun Heo }
2433e22bee78STejun Heo 
2434e22bee78STejun Heo /**
2435e22bee78STejun Heo  * manage_workers - manage worker pool
2436e22bee78STejun Heo  * @worker: self
2437e22bee78STejun Heo  *
2438706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
2439e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2440706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2441e22bee78STejun Heo  *
2442e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2443e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2444e22bee78STejun Heo  * and may_start_working() is true.
2445e22bee78STejun Heo  *
2446e22bee78STejun Heo  * CONTEXT:
2447a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2448e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2449e22bee78STejun Heo  *
2450d185af30SYacine Belkadi  * Return:
245129187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
245229187a9eSTejun Heo  * start processing works, %true if management function was performed and
245329187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
245429187a9eSTejun Heo  * no longer be true.
2455e22bee78STejun Heo  */
2456e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2457e22bee78STejun Heo {
245863d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2459e22bee78STejun Heo 
2460692b4825STejun Heo 	if (pool->flags & POOL_MANAGER_ACTIVE)
246129187a9eSTejun Heo 		return false;
2462692b4825STejun Heo 
2463692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
24642607d7a6STejun Heo 	pool->manager = worker;
2465e22bee78STejun Heo 
246629187a9eSTejun Heo 	maybe_create_worker(pool);
2467e22bee78STejun Heo 
24682607d7a6STejun Heo 	pool->manager = NULL;
2469692b4825STejun Heo 	pool->flags &= ~POOL_MANAGER_ACTIVE;
2470d8bb65abSSebastian Andrzej Siewior 	rcuwait_wake_up(&manager_wait);
247129187a9eSTejun Heo 	return true;
2472e22bee78STejun Heo }
2473e22bee78STejun Heo 
2474a62428c0STejun Heo /**
2475a62428c0STejun Heo  * process_one_work - process single work
2476c34056a3STejun Heo  * @worker: self
2477a62428c0STejun Heo  * @work: work to process
2478a62428c0STejun Heo  *
2479a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2480a62428c0STejun Heo  * process a single work including synchronization against and
2481a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2482a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2483a62428c0STejun Heo  * call this function to process a work.
2484a62428c0STejun Heo  *
2485a62428c0STejun Heo  * CONTEXT:
2486a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
2487a62428c0STejun Heo  */
2488c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2489d565ed63STejun Heo __releases(&pool->lock)
2490d565ed63STejun Heo __acquires(&pool->lock)
24911da177e4SLinus Torvalds {
2492112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2493bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2494c4560c2cSLai Jiangshan 	unsigned long work_data;
24957e11629dSTejun Heo 	struct worker *collision;
24964e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
24974e6045f1SJohannes Berg 	/*
2498a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2499a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2500a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2501a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2502a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
25034e6045f1SJohannes Berg 	 */
25044d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
25054d82a1deSPeter Zijlstra 
25064d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
25074e6045f1SJohannes Berg #endif
2508807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
250985327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2510ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
251125511a47STejun Heo 
25127e11629dSTejun Heo 	/*
25137e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
25147e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
25157e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
25167e11629dSTejun Heo 	 * currently executing one.
25177e11629dSTejun Heo 	 */
2518c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
25197e11629dSTejun Heo 	if (unlikely(collision)) {
25207e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
25217e11629dSTejun Heo 		return;
25227e11629dSTejun Heo 	}
25231da177e4SLinus Torvalds 
25248930cabaSTejun Heo 	/* claim and dequeue */
25251da177e4SLinus Torvalds 	debug_work_deactivate(work);
2526c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2527c34056a3STejun Heo 	worker->current_work = work;
2528a2c1c57bSTejun Heo 	worker->current_func = work->func;
2529112202d9STejun Heo 	worker->current_pwq = pwq;
2530616db877STejun Heo 	worker->current_at = worker->task->se.sum_exec_runtime;
2531c4560c2cSLai Jiangshan 	work_data = *work_data_bits(work);
2532d812796eSLai Jiangshan 	worker->current_color = get_work_color(work_data);
25337a22ad75STejun Heo 
25348bf89593STejun Heo 	/*
25358bf89593STejun Heo 	 * Record wq name for cmdline and debug reporting, may get
25368bf89593STejun Heo 	 * overridden through set_worker_desc().
25378bf89593STejun Heo 	 */
25388bf89593STejun Heo 	strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
25398bf89593STejun Heo 
2540a62428c0STejun Heo 	list_del_init(&work->entry);
2541a62428c0STejun Heo 
2542649027d7STejun Heo 	/*
2543228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
2544228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
2545228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
2546228f1d00SLai Jiangshan 	 * execution of the pending work items.
2547fb0e7bebSTejun Heo 	 */
2548616db877STejun Heo 	if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
2549228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2550fb0e7bebSTejun Heo 
2551974271c4STejun Heo 	/*
2552a489a03eSLai Jiangshan 	 * Wake up another worker if necessary.  The condition is always
2553a489a03eSLai Jiangshan 	 * false for normal per-cpu workers since nr_running would always
2554a489a03eSLai Jiangshan 	 * be >= 1 at this point.  This is used to chain execution of the
2555a489a03eSLai Jiangshan 	 * pending work items for WORKER_NOT_RUNNING workers such as the
2556228f1d00SLai Jiangshan 	 * UNBOUND and CPU_INTENSIVE ones.
2557974271c4STejun Heo 	 */
2558a489a03eSLai Jiangshan 	if (need_more_worker(pool))
255963d95a91STejun Heo 		wake_up_worker(pool);
2560974271c4STejun Heo 
25618930cabaSTejun Heo 	/*
25627c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2563d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
256423657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
256523657bb1STejun Heo 	 * disabled.
25668930cabaSTejun Heo 	 */
25677c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
25681da177e4SLinus Torvalds 
2569a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2570365970a1SDavid Howells 
2571a1d14934SPeter Zijlstra 	lock_map_acquire(&pwq->wq->lockdep_map);
25723295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2573e6f3faa7SPeter Zijlstra 	/*
2574f52be570SPeter Zijlstra 	 * Strictly speaking we should mark the invariant state without holding
2575f52be570SPeter Zijlstra 	 * any locks, that is, before these two lock_map_acquire()'s.
2576e6f3faa7SPeter Zijlstra 	 *
2577e6f3faa7SPeter Zijlstra 	 * However, that would result in:
2578e6f3faa7SPeter Zijlstra 	 *
2579e6f3faa7SPeter Zijlstra 	 *   A(W1)
2580e6f3faa7SPeter Zijlstra 	 *   WFC(C)
2581e6f3faa7SPeter Zijlstra 	 *		A(W1)
2582e6f3faa7SPeter Zijlstra 	 *		C(C)
2583e6f3faa7SPeter Zijlstra 	 *
2584e6f3faa7SPeter Zijlstra 	 * Which would create W1->C->W1 dependencies, even though there is no
2585e6f3faa7SPeter Zijlstra 	 * actual deadlock possible. There are two solutions, using a
2586e6f3faa7SPeter Zijlstra 	 * read-recursive acquire on the work(queue) 'locks', but this will then
2587f52be570SPeter Zijlstra 	 * hit the lockdep limitation on recursive locks, or simply discard
2588e6f3faa7SPeter Zijlstra 	 * these locks.
2589e6f3faa7SPeter Zijlstra 	 *
2590e6f3faa7SPeter Zijlstra 	 * AFAICT there is no possible deadlock scenario between the
2591e6f3faa7SPeter Zijlstra 	 * flush_work() and complete() primitives (except for single-threaded
2592e6f3faa7SPeter Zijlstra 	 * workqueues), so hiding them isn't a problem.
2593e6f3faa7SPeter Zijlstra 	 */
2594f52be570SPeter Zijlstra 	lockdep_invariant_state(true);
2595725e8ec5STejun Heo 	pwq->stats[PWQ_STAT_STARTED]++;
2596e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2597a2c1c57bSTejun Heo 	worker->current_func(work);
2598e36c886aSArjan van de Ven 	/*
2599e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2600e36c886aSArjan van de Ven 	 * point will only record its address.
2601e36c886aSArjan van de Ven 	 */
26021c5da0ecSDaniel Jordan 	trace_workqueue_execute_end(work, worker->current_func);
2603725e8ec5STejun Heo 	pwq->stats[PWQ_STAT_COMPLETED]++;
26043295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2605112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
26061da177e4SLinus Torvalds 
2607d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2608044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2609d75f773cSSakari Ailus 		       "     last function: %ps\n",
2610a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2611a2c1c57bSTejun Heo 		       worker->current_func);
2612d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2613d5abe669SPeter Zijlstra 		dump_stack();
2614d5abe669SPeter Zijlstra 	}
2615d5abe669SPeter Zijlstra 
2616b22ce278STejun Heo 	/*
2617025f50f3SSebastian Andrzej Siewior 	 * The following prevents a kworker from hogging CPU on !PREEMPTION
2618b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
2619b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
2620b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
2621789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
2622789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
2623b22ce278STejun Heo 	 */
2624a7e6425eSPaul E. McKenney 	cond_resched();
2625b22ce278STejun Heo 
2626a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2627a62428c0STejun Heo 
2628616db877STejun Heo 	/*
2629616db877STejun Heo 	 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
2630616db877STejun Heo 	 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
2631616db877STejun Heo 	 * wq_cpu_intensive_thresh_us. Clear it.
2632616db877STejun Heo 	 */
2633fb0e7bebSTejun Heo 	worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2634fb0e7bebSTejun Heo 
26351b69ac6bSJohannes Weiner 	/* tag the worker for identification in schedule() */
26361b69ac6bSJohannes Weiner 	worker->last_func = worker->current_func;
26371b69ac6bSJohannes Weiner 
2638a62428c0STejun Heo 	/* we're done with it, release */
263942f8570fSSasha Levin 	hash_del(&worker->hentry);
2640c34056a3STejun Heo 	worker->current_work = NULL;
2641a2c1c57bSTejun Heo 	worker->current_func = NULL;
2642112202d9STejun Heo 	worker->current_pwq = NULL;
2643d812796eSLai Jiangshan 	worker->current_color = INT_MAX;
2644c4560c2cSLai Jiangshan 	pwq_dec_nr_in_flight(pwq, work_data);
26451da177e4SLinus Torvalds }
26461da177e4SLinus Torvalds 
2647affee4b2STejun Heo /**
2648affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2649affee4b2STejun Heo  * @worker: self
2650affee4b2STejun Heo  *
2651affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2652affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2653affee4b2STejun Heo  * fetches a work from the top and executes it.
2654affee4b2STejun Heo  *
2655affee4b2STejun Heo  * CONTEXT:
2656a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2657affee4b2STejun Heo  * multiple times.
2658affee4b2STejun Heo  */
2659affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
26601da177e4SLinus Torvalds {
2661affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2662affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2663a62428c0STejun Heo 						struct work_struct, entry);
2664c34056a3STejun Heo 		process_one_work(worker, work);
2665a62428c0STejun Heo 	}
26661da177e4SLinus Torvalds }
26671da177e4SLinus Torvalds 
2668197f6accSTejun Heo static void set_pf_worker(bool val)
2669197f6accSTejun Heo {
2670197f6accSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2671197f6accSTejun Heo 	if (val)
2672197f6accSTejun Heo 		current->flags |= PF_WQ_WORKER;
2673197f6accSTejun Heo 	else
2674197f6accSTejun Heo 		current->flags &= ~PF_WQ_WORKER;
2675197f6accSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
2676197f6accSTejun Heo }
2677197f6accSTejun Heo 
26784690c4abSTejun Heo /**
26794690c4abSTejun Heo  * worker_thread - the worker thread function
2680c34056a3STejun Heo  * @__worker: self
26814690c4abSTejun Heo  *
2682c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2683c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2684c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2685c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2686c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
2687d185af30SYacine Belkadi  *
2688d185af30SYacine Belkadi  * Return: 0
26894690c4abSTejun Heo  */
2690c34056a3STejun Heo static int worker_thread(void *__worker)
26911da177e4SLinus Torvalds {
2692c34056a3STejun Heo 	struct worker *worker = __worker;
2693bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
26941da177e4SLinus Torvalds 
2695e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2696197f6accSTejun Heo 	set_pf_worker(true);
2697c8e55f36STejun Heo woke_up:
2698a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2699affee4b2STejun Heo 
2700a9ab775bSTejun Heo 	/* am I supposed to die? */
2701a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2702a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
2703197f6accSTejun Heo 		set_pf_worker(false);
270460f5a4bcSLai Jiangshan 
270560f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
2706e441b56fSZhen Lei 		ida_free(&pool->worker_ida, worker->id);
2707a2d812a2STejun Heo 		worker_detach_from_pool(worker);
2708e02b9312SValentin Schneider 		WARN_ON_ONCE(!list_empty(&worker->entry));
270960f5a4bcSLai Jiangshan 		kfree(worker);
2710c8e55f36STejun Heo 		return 0;
2711c8e55f36STejun Heo 	}
2712c8e55f36STejun Heo 
2713c8e55f36STejun Heo 	worker_leave_idle(worker);
2714db7bccf4STejun Heo recheck:
2715e22bee78STejun Heo 	/* no more worker necessary? */
271663d95a91STejun Heo 	if (!need_more_worker(pool))
2717e22bee78STejun Heo 		goto sleep;
2718e22bee78STejun Heo 
2719e22bee78STejun Heo 	/* do we need to manage? */
272063d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2721e22bee78STejun Heo 		goto recheck;
2722e22bee78STejun Heo 
2723c8e55f36STejun Heo 	/*
2724c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2725c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2726c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2727c8e55f36STejun Heo 	 */
27286183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2729c8e55f36STejun Heo 
2730e22bee78STejun Heo 	/*
2731a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2732a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2733a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2734a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2735a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2736e22bee78STejun Heo 	 */
2737a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2738e22bee78STejun Heo 
2739e22bee78STejun Heo 	do {
2740affee4b2STejun Heo 		struct work_struct *work =
2741bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2742affee4b2STejun Heo 					 struct work_struct, entry);
2743affee4b2STejun Heo 
274482607adcSTejun Heo 		pool->watchdog_ts = jiffies;
274582607adcSTejun Heo 
2746c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2747affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2748affee4b2STejun Heo 			process_one_work(worker, work);
2749affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2750affee4b2STejun Heo 				process_scheduled_works(worker);
2751affee4b2STejun Heo 		} else {
2752c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2753affee4b2STejun Heo 			process_scheduled_works(worker);
2754affee4b2STejun Heo 		}
275563d95a91STejun Heo 	} while (keep_working(pool));
2756affee4b2STejun Heo 
2757228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
2758d313dd85STejun Heo sleep:
2759c8e55f36STejun Heo 	/*
2760d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2761d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2762d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2763d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2764d565ed63STejun Heo 	 * event.
2765c8e55f36STejun Heo 	 */
2766c8e55f36STejun Heo 	worker_enter_idle(worker);
2767c5a94a61SPeter Zijlstra 	__set_current_state(TASK_IDLE);
2768a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
27691da177e4SLinus Torvalds 	schedule();
2770c8e55f36STejun Heo 	goto woke_up;
27711da177e4SLinus Torvalds }
27721da177e4SLinus Torvalds 
2773e22bee78STejun Heo /**
2774e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2775111c225aSTejun Heo  * @__rescuer: self
2776e22bee78STejun Heo  *
2777e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2778493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2779e22bee78STejun Heo  *
2780706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2781e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2782e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2783e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2784e22bee78STejun Heo  * the problem rescuer solves.
2785e22bee78STejun Heo  *
2786706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2787706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2788e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2789e22bee78STejun Heo  *
2790e22bee78STejun Heo  * This should happen rarely.
2791d185af30SYacine Belkadi  *
2792d185af30SYacine Belkadi  * Return: 0
2793e22bee78STejun Heo  */
2794111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2795e22bee78STejun Heo {
2796111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2797111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2798e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
27994d595b86SLai Jiangshan 	bool should_stop;
2800e22bee78STejun Heo 
2801e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2802111c225aSTejun Heo 
2803111c225aSTejun Heo 	/*
2804111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2805111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2806111c225aSTejun Heo 	 */
2807197f6accSTejun Heo 	set_pf_worker(true);
2808e22bee78STejun Heo repeat:
2809c5a94a61SPeter Zijlstra 	set_current_state(TASK_IDLE);
28101da177e4SLinus Torvalds 
28114d595b86SLai Jiangshan 	/*
28124d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
28134d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
28144d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
28154d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
28164d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
28174d595b86SLai Jiangshan 	 * list is always empty on exit.
28184d595b86SLai Jiangshan 	 */
28194d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
28201da177e4SLinus Torvalds 
2821493a1724STejun Heo 	/* see whether any pwq is asking for help */
2822a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq_mayday_lock);
2823493a1724STejun Heo 
2824493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2825493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2826493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2827112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2828e22bee78STejun Heo 		struct work_struct *work, *n;
282982607adcSTejun Heo 		bool first = true;
2830e22bee78STejun Heo 
2831e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2832493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2833493a1724STejun Heo 
2834a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
2835e22bee78STejun Heo 
283651697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
283751697d39SLai Jiangshan 
2838a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
2839e22bee78STejun Heo 
2840e22bee78STejun Heo 		/*
2841e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2842e22bee78STejun Heo 		 * process'em.
2843e22bee78STejun Heo 		 */
28440479c8c5STejun Heo 		WARN_ON_ONCE(!list_empty(scheduled));
284582607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
284682607adcSTejun Heo 			if (get_work_pwq(work) == pwq) {
284782607adcSTejun Heo 				if (first)
284882607adcSTejun Heo 					pool->watchdog_ts = jiffies;
2849e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
2850725e8ec5STejun Heo 				pwq->stats[PWQ_STAT_RESCUED]++;
285182607adcSTejun Heo 			}
285282607adcSTejun Heo 			first = false;
285382607adcSTejun Heo 		}
2854e22bee78STejun Heo 
2855008847f6SNeilBrown 		if (!list_empty(scheduled)) {
2856e22bee78STejun Heo 			process_scheduled_works(rescuer);
28577576958aSTejun Heo 
28587576958aSTejun Heo 			/*
2859008847f6SNeilBrown 			 * The above execution of rescued work items could
2860008847f6SNeilBrown 			 * have created more to rescue through
2861f97a4a1aSLai Jiangshan 			 * pwq_activate_first_inactive() or chained
2862008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
2863008847f6SNeilBrown 			 * that such back-to-back work items, which may be
2864008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
2865008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
2866008847f6SNeilBrown 			 */
28674f3f4cf3SLai Jiangshan 			if (pwq->nr_active && need_to_create_worker(pool)) {
2868a9b8a985SSebastian Andrzej Siewior 				raw_spin_lock(&wq_mayday_lock);
2869e66b39afSTejun Heo 				/*
2870e66b39afSTejun Heo 				 * Queue iff we aren't racing destruction
2871e66b39afSTejun Heo 				 * and somebody else hasn't queued it already.
2872e66b39afSTejun Heo 				 */
2873e66b39afSTejun Heo 				if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2874008847f6SNeilBrown 					get_pwq(pwq);
2875e66b39afSTejun Heo 					list_add_tail(&pwq->mayday_node, &wq->maydays);
2876e66b39afSTejun Heo 				}
2877a9b8a985SSebastian Andrzej Siewior 				raw_spin_unlock(&wq_mayday_lock);
2878008847f6SNeilBrown 			}
2879008847f6SNeilBrown 		}
2880008847f6SNeilBrown 
2881008847f6SNeilBrown 		/*
288277668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
288313b1d625SLai Jiangshan 		 * go away while we're still attached to it.
288477668c8bSLai Jiangshan 		 */
288577668c8bSLai Jiangshan 		put_pwq(pwq);
288677668c8bSLai Jiangshan 
288777668c8bSLai Jiangshan 		/*
2888d8ca83e6SLai Jiangshan 		 * Leave this pool.  If need_more_worker() is %true, notify a
28897576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
28907576958aSTejun Heo 		 * and stalling the execution.
28917576958aSTejun Heo 		 */
2892d8ca83e6SLai Jiangshan 		if (need_more_worker(pool))
289363d95a91STejun Heo 			wake_up_worker(pool);
28947576958aSTejun Heo 
2895a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
289613b1d625SLai Jiangshan 
2897a2d812a2STejun Heo 		worker_detach_from_pool(rescuer);
289813b1d625SLai Jiangshan 
2899a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
29001da177e4SLinus Torvalds 	}
29011da177e4SLinus Torvalds 
2902a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq_mayday_lock);
2903493a1724STejun Heo 
29044d595b86SLai Jiangshan 	if (should_stop) {
29054d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
2906197f6accSTejun Heo 		set_pf_worker(false);
29074d595b86SLai Jiangshan 		return 0;
29084d595b86SLai Jiangshan 	}
29094d595b86SLai Jiangshan 
2910111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2911111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2912e22bee78STejun Heo 	schedule();
2913e22bee78STejun Heo 	goto repeat;
29141da177e4SLinus Torvalds }
29151da177e4SLinus Torvalds 
2916fca839c0STejun Heo /**
2917fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
2918fca839c0STejun Heo  * @target_wq: workqueue being flushed
2919fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
2920fca839c0STejun Heo  *
2921fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
2922fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2923fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
2924fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2925fca839c0STejun Heo  * a deadlock.
2926fca839c0STejun Heo  */
2927fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
2928fca839c0STejun Heo 				   struct work_struct *target_work)
2929fca839c0STejun Heo {
2930fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
2931fca839c0STejun Heo 	struct worker *worker;
2932fca839c0STejun Heo 
2933fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
2934fca839c0STejun Heo 		return;
2935fca839c0STejun Heo 
2936fca839c0STejun Heo 	worker = current_wq_worker();
2937fca839c0STejun Heo 
2938fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
2939d75f773cSSakari Ailus 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
2940fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
294123d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
294223d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2943d75f773cSSakari Ailus 		  "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
2944fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
2945fca839c0STejun Heo 		  target_wq->name, target_func);
2946fca839c0STejun Heo }
2947fca839c0STejun Heo 
2948fc2e4d70SOleg Nesterov struct wq_barrier {
2949fc2e4d70SOleg Nesterov 	struct work_struct	work;
2950fc2e4d70SOleg Nesterov 	struct completion	done;
29512607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
2952fc2e4d70SOleg Nesterov };
2953fc2e4d70SOleg Nesterov 
2954fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2955fc2e4d70SOleg Nesterov {
2956fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2957fc2e4d70SOleg Nesterov 	complete(&barr->done);
2958fc2e4d70SOleg Nesterov }
2959fc2e4d70SOleg Nesterov 
29604690c4abSTejun Heo /**
29614690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2962112202d9STejun Heo  * @pwq: pwq to insert barrier into
29634690c4abSTejun Heo  * @barr: wq_barrier to insert
2964affee4b2STejun Heo  * @target: target work to attach @barr to
2965affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
29664690c4abSTejun Heo  *
2967affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2968affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2969affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2970affee4b2STejun Heo  * cpu.
2971affee4b2STejun Heo  *
2972affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2973affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2974affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2975affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2976affee4b2STejun Heo  * after a work with LINKED flag set.
2977affee4b2STejun Heo  *
2978affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2979112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
29804690c4abSTejun Heo  *
29814690c4abSTejun Heo  * CONTEXT:
2982a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
29834690c4abSTejun Heo  */
2984112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2985affee4b2STejun Heo 			      struct wq_barrier *barr,
2986affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2987fc2e4d70SOleg Nesterov {
2988d812796eSLai Jiangshan 	unsigned int work_flags = 0;
2989d812796eSLai Jiangshan 	unsigned int work_color;
2990affee4b2STejun Heo 	struct list_head *head;
2991affee4b2STejun Heo 
2992dc186ad7SThomas Gleixner 	/*
2993d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2994dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2995dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2996dc186ad7SThomas Gleixner 	 * might deadlock.
2997dc186ad7SThomas Gleixner 	 */
2998ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
299922df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
300052fa5bc5SBoqun Feng 
3001fd1a5b04SByungchul Park 	init_completion_map(&barr->done, &target->lockdep_map);
3002fd1a5b04SByungchul Park 
30032607d7a6STejun Heo 	barr->task = current;
300483c22520SOleg Nesterov 
3005018f3a13SLai Jiangshan 	/* The barrier work item does not participate in pwq->nr_active. */
3006018f3a13SLai Jiangshan 	work_flags |= WORK_STRUCT_INACTIVE;
3007018f3a13SLai Jiangshan 
3008affee4b2STejun Heo 	/*
3009affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
3010affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
3011affee4b2STejun Heo 	 */
3012d812796eSLai Jiangshan 	if (worker) {
3013affee4b2STejun Heo 		head = worker->scheduled.next;
3014d812796eSLai Jiangshan 		work_color = worker->current_color;
3015d812796eSLai Jiangshan 	} else {
3016affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
3017affee4b2STejun Heo 
3018affee4b2STejun Heo 		head = target->entry.next;
3019affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
3020d21cece0SLai Jiangshan 		work_flags |= *bits & WORK_STRUCT_LINKED;
3021d812796eSLai Jiangshan 		work_color = get_work_color(*bits);
3022affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
3023affee4b2STejun Heo 	}
3024affee4b2STejun Heo 
3025d812796eSLai Jiangshan 	pwq->nr_in_flight[work_color]++;
3026d812796eSLai Jiangshan 	work_flags |= work_color_to_flags(work_color);
3027d812796eSLai Jiangshan 
3028dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
3029d21cece0SLai Jiangshan 	insert_work(pwq, &barr->work, head, work_flags);
3030fc2e4d70SOleg Nesterov }
3031fc2e4d70SOleg Nesterov 
303273f53c4aSTejun Heo /**
3033112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
303473f53c4aSTejun Heo  * @wq: workqueue being flushed
303573f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
303673f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
303773f53c4aSTejun Heo  *
3038112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
303973f53c4aSTejun Heo  *
3040112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
3041112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
3042112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
3043112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
3044112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
304573f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
304673f53c4aSTejun Heo  *
304773f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
304873f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
304973f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
305073f53c4aSTejun Heo  * is returned.
305173f53c4aSTejun Heo  *
3052112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
305373f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
305473f53c4aSTejun Heo  * advanced to @work_color.
305573f53c4aSTejun Heo  *
305673f53c4aSTejun Heo  * CONTEXT:
30573c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
305873f53c4aSTejun Heo  *
3059d185af30SYacine Belkadi  * Return:
306073f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
306173f53c4aSTejun Heo  * otherwise.
306273f53c4aSTejun Heo  */
3063112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
306473f53c4aSTejun Heo 				      int flush_color, int work_color)
30651da177e4SLinus Torvalds {
306673f53c4aSTejun Heo 	bool wait = false;
306749e3cf44STejun Heo 	struct pool_workqueue *pwq;
30681da177e4SLinus Torvalds 
306973f53c4aSTejun Heo 	if (flush_color >= 0) {
30706183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
3071112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
3072dc186ad7SThomas Gleixner 	}
307314441960SOleg Nesterov 
307449e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3075112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
30761da177e4SLinus Torvalds 
3077a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
307873f53c4aSTejun Heo 
307973f53c4aSTejun Heo 		if (flush_color >= 0) {
30806183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
308173f53c4aSTejun Heo 
3082112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
3083112202d9STejun Heo 				pwq->flush_color = flush_color;
3084112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
308573f53c4aSTejun Heo 				wait = true;
30861da177e4SLinus Torvalds 			}
308773f53c4aSTejun Heo 		}
308873f53c4aSTejun Heo 
308973f53c4aSTejun Heo 		if (work_color >= 0) {
30906183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
3091112202d9STejun Heo 			pwq->work_color = work_color;
309273f53c4aSTejun Heo 		}
309373f53c4aSTejun Heo 
3094a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
30951da177e4SLinus Torvalds 	}
30961da177e4SLinus Torvalds 
3097112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
309873f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
309973f53c4aSTejun Heo 
310073f53c4aSTejun Heo 	return wait;
310183c22520SOleg Nesterov }
31021da177e4SLinus Torvalds 
31030fcb78c2SRolf Eike Beer /**
3104c4f135d6STetsuo Handa  * __flush_workqueue - ensure that any scheduled work has run to completion.
31050fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
31061da177e4SLinus Torvalds  *
3107c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
3108c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
31091da177e4SLinus Torvalds  */
3110c4f135d6STetsuo Handa void __flush_workqueue(struct workqueue_struct *wq)
31111da177e4SLinus Torvalds {
311273f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
311373f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
311473f53c4aSTejun Heo 		.flush_color = -1,
3115fd1a5b04SByungchul Park 		.done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
311673f53c4aSTejun Heo 	};
311773f53c4aSTejun Heo 	int next_color;
3118b1f4ec17SOleg Nesterov 
31193347fa09STejun Heo 	if (WARN_ON(!wq_online))
31203347fa09STejun Heo 		return;
31213347fa09STejun Heo 
312287915adcSJohannes Berg 	lock_map_acquire(&wq->lockdep_map);
312387915adcSJohannes Berg 	lock_map_release(&wq->lockdep_map);
312487915adcSJohannes Berg 
31253c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
312673f53c4aSTejun Heo 
312773f53c4aSTejun Heo 	/*
312873f53c4aSTejun Heo 	 * Start-to-wait phase
312973f53c4aSTejun Heo 	 */
313073f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
313173f53c4aSTejun Heo 
313273f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
313373f53c4aSTejun Heo 		/*
313473f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
313573f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
313673f53c4aSTejun Heo 		 * by one.
313773f53c4aSTejun Heo 		 */
31386183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
313973f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
314073f53c4aSTejun Heo 		wq->work_color = next_color;
314173f53c4aSTejun Heo 
314273f53c4aSTejun Heo 		if (!wq->first_flusher) {
314373f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
31446183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
314573f53c4aSTejun Heo 
314673f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
314773f53c4aSTejun Heo 
3148112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
314973f53c4aSTejun Heo 						       wq->work_color)) {
315073f53c4aSTejun Heo 				/* nothing to flush, done */
315173f53c4aSTejun Heo 				wq->flush_color = next_color;
315273f53c4aSTejun Heo 				wq->first_flusher = NULL;
315373f53c4aSTejun Heo 				goto out_unlock;
315473f53c4aSTejun Heo 			}
315573f53c4aSTejun Heo 		} else {
315673f53c4aSTejun Heo 			/* wait in queue */
31576183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
315873f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
3159112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
316073f53c4aSTejun Heo 		}
316173f53c4aSTejun Heo 	} else {
316273f53c4aSTejun Heo 		/*
316373f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
316473f53c4aSTejun Heo 		 * The next flush completion will assign us
316573f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
316673f53c4aSTejun Heo 		 */
316773f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
316873f53c4aSTejun Heo 	}
316973f53c4aSTejun Heo 
3170fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
3171fca839c0STejun Heo 
31723c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
317373f53c4aSTejun Heo 
317473f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
317573f53c4aSTejun Heo 
317673f53c4aSTejun Heo 	/*
317773f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
317873f53c4aSTejun Heo 	 *
317973f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
318073f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
318173f53c4aSTejun Heo 	 */
318200d5d15bSChris Wilson 	if (READ_ONCE(wq->first_flusher) != &this_flusher)
318373f53c4aSTejun Heo 		return;
318473f53c4aSTejun Heo 
31853c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
318673f53c4aSTejun Heo 
31874ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
31884ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
31894ce48b37STejun Heo 		goto out_unlock;
31904ce48b37STejun Heo 
319100d5d15bSChris Wilson 	WRITE_ONCE(wq->first_flusher, NULL);
319273f53c4aSTejun Heo 
31936183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
31946183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
319573f53c4aSTejun Heo 
319673f53c4aSTejun Heo 	while (true) {
319773f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
319873f53c4aSTejun Heo 
319973f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
320073f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
320173f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
320273f53c4aSTejun Heo 				break;
320373f53c4aSTejun Heo 			list_del_init(&next->list);
320473f53c4aSTejun Heo 			complete(&next->done);
320573f53c4aSTejun Heo 		}
320673f53c4aSTejun Heo 
32076183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
320873f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
320973f53c4aSTejun Heo 
321073f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
321173f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
321273f53c4aSTejun Heo 
321373f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
321473f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
321573f53c4aSTejun Heo 			/*
321673f53c4aSTejun Heo 			 * Assign the same color to all overflowed
321773f53c4aSTejun Heo 			 * flushers, advance work_color and append to
321873f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
321973f53c4aSTejun Heo 			 * phase for these overflowed flushers.
322073f53c4aSTejun Heo 			 */
322173f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
322273f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
322373f53c4aSTejun Heo 
322473f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
322573f53c4aSTejun Heo 
322673f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
322773f53c4aSTejun Heo 					      &wq->flusher_queue);
3228112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
322973f53c4aSTejun Heo 		}
323073f53c4aSTejun Heo 
323173f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
32326183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
323373f53c4aSTejun Heo 			break;
323473f53c4aSTejun Heo 		}
323573f53c4aSTejun Heo 
323673f53c4aSTejun Heo 		/*
323773f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
3238112202d9STejun Heo 		 * the new first flusher and arm pwqs.
323973f53c4aSTejun Heo 		 */
32406183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
32416183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
324273f53c4aSTejun Heo 
324373f53c4aSTejun Heo 		list_del_init(&next->list);
324473f53c4aSTejun Heo 		wq->first_flusher = next;
324573f53c4aSTejun Heo 
3246112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
324773f53c4aSTejun Heo 			break;
324873f53c4aSTejun Heo 
324973f53c4aSTejun Heo 		/*
325073f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
325173f53c4aSTejun Heo 		 * flusher and repeat cascading.
325273f53c4aSTejun Heo 		 */
325373f53c4aSTejun Heo 		wq->first_flusher = NULL;
325473f53c4aSTejun Heo 	}
325573f53c4aSTejun Heo 
325673f53c4aSTejun Heo out_unlock:
32573c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
32581da177e4SLinus Torvalds }
3259c4f135d6STetsuo Handa EXPORT_SYMBOL(__flush_workqueue);
32601da177e4SLinus Torvalds 
32619c5a2ba7STejun Heo /**
32629c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
32639c5a2ba7STejun Heo  * @wq: workqueue to drain
32649c5a2ba7STejun Heo  *
32659c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
32669c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
32679c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
3268b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
32699c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
32709c5a2ba7STejun Heo  * takes too long.
32719c5a2ba7STejun Heo  */
32729c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
32739c5a2ba7STejun Heo {
32749c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
327549e3cf44STejun Heo 	struct pool_workqueue *pwq;
32769c5a2ba7STejun Heo 
32779c5a2ba7STejun Heo 	/*
32789c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
32799c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
3280618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
32819c5a2ba7STejun Heo 	 */
328287fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
32839c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
3284618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
328587fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
32869c5a2ba7STejun Heo reflush:
3287c4f135d6STetsuo Handa 	__flush_workqueue(wq);
32889c5a2ba7STejun Heo 
3289b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
329076af4d93STejun Heo 
329149e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3292fa2563e4SThomas Tuttle 		bool drained;
32939c5a2ba7STejun Heo 
3294a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
3295f97a4a1aSLai Jiangshan 		drained = !pwq->nr_active && list_empty(&pwq->inactive_works);
3296a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
3297fa2563e4SThomas Tuttle 
3298fa2563e4SThomas Tuttle 		if (drained)
32999c5a2ba7STejun Heo 			continue;
33009c5a2ba7STejun Heo 
33019c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
33029c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
3303e9ad2eb3SStephen Zhang 			pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3304e9ad2eb3SStephen Zhang 				wq->name, __func__, flush_cnt);
330576af4d93STejun Heo 
3306b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
33079c5a2ba7STejun Heo 		goto reflush;
33089c5a2ba7STejun Heo 	}
33099c5a2ba7STejun Heo 
33109c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
3311618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
331287fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
33139c5a2ba7STejun Heo }
33149c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
33159c5a2ba7STejun Heo 
3316d6e89786SJohannes Berg static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3317d6e89786SJohannes Berg 			     bool from_cancel)
3318baf59022STejun Heo {
3319baf59022STejun Heo 	struct worker *worker = NULL;
3320c9e7cf27STejun Heo 	struct worker_pool *pool;
3321112202d9STejun Heo 	struct pool_workqueue *pwq;
3322baf59022STejun Heo 
3323baf59022STejun Heo 	might_sleep();
3324baf59022STejun Heo 
332524acfb71SThomas Gleixner 	rcu_read_lock();
3326fa1b54e6STejun Heo 	pool = get_work_pool(work);
3327fa1b54e6STejun Heo 	if (!pool) {
332824acfb71SThomas Gleixner 		rcu_read_unlock();
3329fa1b54e6STejun Heo 		return false;
3330fa1b54e6STejun Heo 	}
3331fa1b54e6STejun Heo 
3332a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
33330b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
3334112202d9STejun Heo 	pwq = get_work_pwq(work);
3335112202d9STejun Heo 	if (pwq) {
3336112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
3337baf59022STejun Heo 			goto already_gone;
3338606a5020STejun Heo 	} else {
3339c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
3340baf59022STejun Heo 		if (!worker)
3341baf59022STejun Heo 			goto already_gone;
3342112202d9STejun Heo 		pwq = worker->current_pwq;
3343606a5020STejun Heo 	}
3344baf59022STejun Heo 
3345fca839c0STejun Heo 	check_flush_dependency(pwq->wq, work);
3346fca839c0STejun Heo 
3347112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
3348a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
3349baf59022STejun Heo 
3350e159489bSTejun Heo 	/*
3351a1d14934SPeter Zijlstra 	 * Force a lock recursion deadlock when using flush_work() inside a
3352a1d14934SPeter Zijlstra 	 * single-threaded or rescuer equipped workqueue.
3353a1d14934SPeter Zijlstra 	 *
3354a1d14934SPeter Zijlstra 	 * For single threaded workqueues the deadlock happens when the work
3355a1d14934SPeter Zijlstra 	 * is after the work issuing the flush_work(). For rescuer equipped
3356a1d14934SPeter Zijlstra 	 * workqueues the deadlock happens when the rescuer stalls, blocking
3357a1d14934SPeter Zijlstra 	 * forward progress.
3358e159489bSTejun Heo 	 */
3359d6e89786SJohannes Berg 	if (!from_cancel &&
3360d6e89786SJohannes Berg 	    (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
3361112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
3362112202d9STejun Heo 		lock_map_release(&pwq->wq->lockdep_map);
3363a1d14934SPeter Zijlstra 	}
336424acfb71SThomas Gleixner 	rcu_read_unlock();
3365baf59022STejun Heo 	return true;
3366baf59022STejun Heo already_gone:
3367a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
336824acfb71SThomas Gleixner 	rcu_read_unlock();
3369baf59022STejun Heo 	return false;
3370baf59022STejun Heo }
3371baf59022STejun Heo 
3372d6e89786SJohannes Berg static bool __flush_work(struct work_struct *work, bool from_cancel)
3373d6e89786SJohannes Berg {
3374d6e89786SJohannes Berg 	struct wq_barrier barr;
3375d6e89786SJohannes Berg 
3376d6e89786SJohannes Berg 	if (WARN_ON(!wq_online))
3377d6e89786SJohannes Berg 		return false;
3378d6e89786SJohannes Berg 
33794d43d395STetsuo Handa 	if (WARN_ON(!work->func))
33804d43d395STetsuo Handa 		return false;
33814d43d395STetsuo Handa 
338287915adcSJohannes Berg 	lock_map_acquire(&work->lockdep_map);
338387915adcSJohannes Berg 	lock_map_release(&work->lockdep_map);
338487915adcSJohannes Berg 
3385d6e89786SJohannes Berg 	if (start_flush_work(work, &barr, from_cancel)) {
3386d6e89786SJohannes Berg 		wait_for_completion(&barr.done);
3387d6e89786SJohannes Berg 		destroy_work_on_stack(&barr.work);
3388d6e89786SJohannes Berg 		return true;
3389d6e89786SJohannes Berg 	} else {
3390d6e89786SJohannes Berg 		return false;
3391d6e89786SJohannes Berg 	}
3392d6e89786SJohannes Berg }
3393d6e89786SJohannes Berg 
3394db700897SOleg Nesterov /**
3395401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
3396401a8d04STejun Heo  * @work: the work to flush
3397db700897SOleg Nesterov  *
3398606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
3399606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
3400401a8d04STejun Heo  *
3401d185af30SYacine Belkadi  * Return:
3402401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3403401a8d04STejun Heo  * %false if it was already idle.
3404db700897SOleg Nesterov  */
3405401a8d04STejun Heo bool flush_work(struct work_struct *work)
3406db700897SOleg Nesterov {
3407d6e89786SJohannes Berg 	return __flush_work(work, false);
3408606a5020STejun Heo }
3409db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
3410db700897SOleg Nesterov 
34118603e1b3STejun Heo struct cwt_wait {
3412ac6424b9SIngo Molnar 	wait_queue_entry_t		wait;
34138603e1b3STejun Heo 	struct work_struct	*work;
34148603e1b3STejun Heo };
34158603e1b3STejun Heo 
3416ac6424b9SIngo Molnar static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
34178603e1b3STejun Heo {
34188603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
34198603e1b3STejun Heo 
34208603e1b3STejun Heo 	if (cwait->work != key)
34218603e1b3STejun Heo 		return 0;
34228603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
34238603e1b3STejun Heo }
34248603e1b3STejun Heo 
342536e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3426401a8d04STejun Heo {
34278603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3428bbb68dfaSTejun Heo 	unsigned long flags;
34291f1f642eSOleg Nesterov 	int ret;
34301f1f642eSOleg Nesterov 
34311f1f642eSOleg Nesterov 	do {
3432bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
3433bbb68dfaSTejun Heo 		/*
34348603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
34358603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
34368603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
34378603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
34388603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
34398603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
34408603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
34418603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
34428603e1b3STejun Heo 		 * we're hogging the CPU.
34438603e1b3STejun Heo 		 *
34448603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
34458603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
34468603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
34478603e1b3STejun Heo 		 * wait and wakeup.
3448bbb68dfaSTejun Heo 		 */
34498603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
34508603e1b3STejun Heo 			struct cwt_wait cwait;
34518603e1b3STejun Heo 
34528603e1b3STejun Heo 			init_wait(&cwait.wait);
34538603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
34548603e1b3STejun Heo 			cwait.work = work;
34558603e1b3STejun Heo 
34568603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
34578603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
34588603e1b3STejun Heo 			if (work_is_canceling(work))
34598603e1b3STejun Heo 				schedule();
34608603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
34618603e1b3STejun Heo 		}
34621f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
34631f1f642eSOleg Nesterov 
3464bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
3465bbb68dfaSTejun Heo 	mark_work_canceling(work);
3466bbb68dfaSTejun Heo 	local_irq_restore(flags);
3467bbb68dfaSTejun Heo 
34683347fa09STejun Heo 	/*
34693347fa09STejun Heo 	 * This allows canceling during early boot.  We know that @work
34703347fa09STejun Heo 	 * isn't executing.
34713347fa09STejun Heo 	 */
34723347fa09STejun Heo 	if (wq_online)
3473d6e89786SJohannes Berg 		__flush_work(work, true);
34743347fa09STejun Heo 
34757a22ad75STejun Heo 	clear_work_data(work);
34768603e1b3STejun Heo 
34778603e1b3STejun Heo 	/*
34788603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
34798603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
34808603e1b3STejun Heo 	 * visible there.
34818603e1b3STejun Heo 	 */
34828603e1b3STejun Heo 	smp_mb();
34838603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
34848603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
34858603e1b3STejun Heo 
34861f1f642eSOleg Nesterov 	return ret;
34871f1f642eSOleg Nesterov }
34881f1f642eSOleg Nesterov 
34896e84d644SOleg Nesterov /**
3490401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
3491401a8d04STejun Heo  * @work: the work to cancel
34926e84d644SOleg Nesterov  *
3493401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
3494401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
3495401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
3496401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
34971f1f642eSOleg Nesterov  *
3498401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
3499401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
35006e84d644SOleg Nesterov  *
3501401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
35026e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
3503401a8d04STejun Heo  *
3504d185af30SYacine Belkadi  * Return:
3505401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
35066e84d644SOleg Nesterov  */
3507401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
35086e84d644SOleg Nesterov {
350936e227d2STejun Heo 	return __cancel_work_timer(work, false);
3510b89deed3SOleg Nesterov }
351128e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
3512b89deed3SOleg Nesterov 
35136e84d644SOleg Nesterov /**
3514401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
3515401a8d04STejun Heo  * @dwork: the delayed work to flush
35166e84d644SOleg Nesterov  *
3517401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
3518401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
3519401a8d04STejun Heo  * considers the last queueing instance of @dwork.
35201f1f642eSOleg Nesterov  *
3521d185af30SYacine Belkadi  * Return:
3522401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3523401a8d04STejun Heo  * %false if it was already idle.
35246e84d644SOleg Nesterov  */
3525401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
3526401a8d04STejun Heo {
35278930cabaSTejun Heo 	local_irq_disable();
3528401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
352960c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
35308930cabaSTejun Heo 	local_irq_enable();
3531401a8d04STejun Heo 	return flush_work(&dwork->work);
3532401a8d04STejun Heo }
3533401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3534401a8d04STejun Heo 
353505f0fe6bSTejun Heo /**
353605f0fe6bSTejun Heo  * flush_rcu_work - wait for a rwork to finish executing the last queueing
353705f0fe6bSTejun Heo  * @rwork: the rcu work to flush
353805f0fe6bSTejun Heo  *
353905f0fe6bSTejun Heo  * Return:
354005f0fe6bSTejun Heo  * %true if flush_rcu_work() waited for the work to finish execution,
354105f0fe6bSTejun Heo  * %false if it was already idle.
354205f0fe6bSTejun Heo  */
354305f0fe6bSTejun Heo bool flush_rcu_work(struct rcu_work *rwork)
354405f0fe6bSTejun Heo {
354505f0fe6bSTejun Heo 	if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
354605f0fe6bSTejun Heo 		rcu_barrier();
354705f0fe6bSTejun Heo 		flush_work(&rwork->work);
354805f0fe6bSTejun Heo 		return true;
354905f0fe6bSTejun Heo 	} else {
355005f0fe6bSTejun Heo 		return flush_work(&rwork->work);
355105f0fe6bSTejun Heo 	}
355205f0fe6bSTejun Heo }
355305f0fe6bSTejun Heo EXPORT_SYMBOL(flush_rcu_work);
355405f0fe6bSTejun Heo 
3555f72b8792SJens Axboe static bool __cancel_work(struct work_struct *work, bool is_dwork)
3556f72b8792SJens Axboe {
3557f72b8792SJens Axboe 	unsigned long flags;
3558f72b8792SJens Axboe 	int ret;
3559f72b8792SJens Axboe 
3560f72b8792SJens Axboe 	do {
3561f72b8792SJens Axboe 		ret = try_to_grab_pending(work, is_dwork, &flags);
3562f72b8792SJens Axboe 	} while (unlikely(ret == -EAGAIN));
3563f72b8792SJens Axboe 
3564f72b8792SJens Axboe 	if (unlikely(ret < 0))
3565f72b8792SJens Axboe 		return false;
3566f72b8792SJens Axboe 
3567f72b8792SJens Axboe 	set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3568f72b8792SJens Axboe 	local_irq_restore(flags);
3569f72b8792SJens Axboe 	return ret;
3570f72b8792SJens Axboe }
3571f72b8792SJens Axboe 
357273b4b532SAndrey Grodzovsky /*
357373b4b532SAndrey Grodzovsky  * See cancel_delayed_work()
357473b4b532SAndrey Grodzovsky  */
357573b4b532SAndrey Grodzovsky bool cancel_work(struct work_struct *work)
357673b4b532SAndrey Grodzovsky {
357773b4b532SAndrey Grodzovsky 	return __cancel_work(work, false);
357873b4b532SAndrey Grodzovsky }
357973b4b532SAndrey Grodzovsky EXPORT_SYMBOL(cancel_work);
358073b4b532SAndrey Grodzovsky 
3581401a8d04STejun Heo /**
358257b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
358357b30ae7STejun Heo  * @dwork: delayed_work to cancel
358409383498STejun Heo  *
3585d185af30SYacine Belkadi  * Kill off a pending delayed_work.
3586d185af30SYacine Belkadi  *
3587d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
3588d185af30SYacine Belkadi  * pending.
3589d185af30SYacine Belkadi  *
3590d185af30SYacine Belkadi  * Note:
3591d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
3592d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
3593d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
359409383498STejun Heo  *
359557b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
359609383498STejun Heo  */
359757b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
359809383498STejun Heo {
3599f72b8792SJens Axboe 	return __cancel_work(&dwork->work, true);
360009383498STejun Heo }
360157b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
360209383498STejun Heo 
360309383498STejun Heo /**
3604401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3605401a8d04STejun Heo  * @dwork: the delayed work cancel
3606401a8d04STejun Heo  *
3607401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
3608401a8d04STejun Heo  *
3609d185af30SYacine Belkadi  * Return:
3610401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
3611401a8d04STejun Heo  */
3612401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
36136e84d644SOleg Nesterov {
361436e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
36156e84d644SOleg Nesterov }
3616f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
36171da177e4SLinus Torvalds 
36180fcb78c2SRolf Eike Beer /**
361931ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3620b6136773SAndrew Morton  * @func: the function to call
3621b6136773SAndrew Morton  *
362231ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
362331ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3624b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
362531ddd871STejun Heo  *
3626d185af30SYacine Belkadi  * Return:
362731ddd871STejun Heo  * 0 on success, -errno on failure.
3628b6136773SAndrew Morton  */
362965f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
363015316ba8SChristoph Lameter {
363115316ba8SChristoph Lameter 	int cpu;
363238f51568SNamhyung Kim 	struct work_struct __percpu *works;
363315316ba8SChristoph Lameter 
3634b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3635b6136773SAndrew Morton 	if (!works)
363615316ba8SChristoph Lameter 		return -ENOMEM;
3637b6136773SAndrew Morton 
3638ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
363993981800STejun Heo 
364015316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
36419bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
36429bfb1839SIngo Molnar 
36439bfb1839SIngo Molnar 		INIT_WORK(work, func);
36448de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
364515316ba8SChristoph Lameter 	}
364693981800STejun Heo 
364793981800STejun Heo 	for_each_online_cpu(cpu)
36488616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
364993981800STejun Heo 
3650ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
3651b6136773SAndrew Morton 	free_percpu(works);
365215316ba8SChristoph Lameter 	return 0;
365315316ba8SChristoph Lameter }
365415316ba8SChristoph Lameter 
3655eef6a7d5SAlan Stern /**
36561fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
36571fa44ecaSJames Bottomley  * @fn:		the function to execute
36581fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
36591fa44ecaSJames Bottomley  *		be available when the work executes)
36601fa44ecaSJames Bottomley  *
36611fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
36621fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
36631fa44ecaSJames Bottomley  *
3664d185af30SYacine Belkadi  * Return:	0 - function was executed
36651fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
36661fa44ecaSJames Bottomley  */
366765f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
36681fa44ecaSJames Bottomley {
36691fa44ecaSJames Bottomley 	if (!in_interrupt()) {
367065f27f38SDavid Howells 		fn(&ew->work);
36711fa44ecaSJames Bottomley 		return 0;
36721fa44ecaSJames Bottomley 	}
36731fa44ecaSJames Bottomley 
367465f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
36751fa44ecaSJames Bottomley 	schedule_work(&ew->work);
36761fa44ecaSJames Bottomley 
36771fa44ecaSJames Bottomley 	return 1;
36781fa44ecaSJames Bottomley }
36791fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
36801fa44ecaSJames Bottomley 
36817a4e344cSTejun Heo /**
36827a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
36837a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
36847a4e344cSTejun Heo  *
36857a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
36867a4e344cSTejun Heo  */
3687513c98d0SDaniel Jordan void free_workqueue_attrs(struct workqueue_attrs *attrs)
36887a4e344cSTejun Heo {
36897a4e344cSTejun Heo 	if (attrs) {
36907a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
36917a4e344cSTejun Heo 		kfree(attrs);
36927a4e344cSTejun Heo 	}
36937a4e344cSTejun Heo }
36947a4e344cSTejun Heo 
36957a4e344cSTejun Heo /**
36967a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
36977a4e344cSTejun Heo  *
36987a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3699d185af30SYacine Belkadi  * return it.
3700d185af30SYacine Belkadi  *
3701d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
37027a4e344cSTejun Heo  */
3703513c98d0SDaniel Jordan struct workqueue_attrs *alloc_workqueue_attrs(void)
37047a4e344cSTejun Heo {
37057a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
37067a4e344cSTejun Heo 
3707be69d00dSThomas Gleixner 	attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
37087a4e344cSTejun Heo 	if (!attrs)
37097a4e344cSTejun Heo 		goto fail;
3710be69d00dSThomas Gleixner 	if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
37117a4e344cSTejun Heo 		goto fail;
37127a4e344cSTejun Heo 
371313e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
37147a4e344cSTejun Heo 	return attrs;
37157a4e344cSTejun Heo fail:
37167a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
37177a4e344cSTejun Heo 	return NULL;
37187a4e344cSTejun Heo }
37197a4e344cSTejun Heo 
372029c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
372129c91e99STejun Heo 				 const struct workqueue_attrs *from)
372229c91e99STejun Heo {
372329c91e99STejun Heo 	to->nice = from->nice;
372429c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
37252865a8fbSShaohua Li 	/*
37262865a8fbSShaohua Li 	 * Unlike hash and equality test, this function doesn't ignore
37272865a8fbSShaohua Li 	 * ->no_numa as it is used for both pool and wq attrs.  Instead,
37282865a8fbSShaohua Li 	 * get_unbound_pool() explicitly clears ->no_numa after copying.
37292865a8fbSShaohua Li 	 */
37302865a8fbSShaohua Li 	to->no_numa = from->no_numa;
373129c91e99STejun Heo }
373229c91e99STejun Heo 
373329c91e99STejun Heo /* hash value of the content of @attr */
373429c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
373529c91e99STejun Heo {
373629c91e99STejun Heo 	u32 hash = 0;
373729c91e99STejun Heo 
373829c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
373913e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
374013e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
374129c91e99STejun Heo 	return hash;
374229c91e99STejun Heo }
374329c91e99STejun Heo 
374429c91e99STejun Heo /* content equality test */
374529c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
374629c91e99STejun Heo 			  const struct workqueue_attrs *b)
374729c91e99STejun Heo {
374829c91e99STejun Heo 	if (a->nice != b->nice)
374929c91e99STejun Heo 		return false;
375029c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
375129c91e99STejun Heo 		return false;
375229c91e99STejun Heo 	return true;
375329c91e99STejun Heo }
375429c91e99STejun Heo 
37557a4e344cSTejun Heo /**
37567a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
37577a4e344cSTejun Heo  * @pool: worker_pool to initialize
37587a4e344cSTejun Heo  *
3759402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3760d185af30SYacine Belkadi  *
3761d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
376229c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
376329c91e99STejun Heo  * on @pool safely to release it.
37647a4e344cSTejun Heo  */
37657a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
37664e1a1f9aSTejun Heo {
3767a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_init(&pool->lock);
376829c91e99STejun Heo 	pool->id = -1;
376929c91e99STejun Heo 	pool->cpu = -1;
3770f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
37714e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
377282607adcSTejun Heo 	pool->watchdog_ts = jiffies;
37734e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
37744e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
37754e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
37764e1a1f9aSTejun Heo 
377732a6c723SKees Cook 	timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
37783f959aa3SValentin Schneider 	INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
37794e1a1f9aSTejun Heo 
378032a6c723SKees Cook 	timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
37814e1a1f9aSTejun Heo 
3782da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
3783e02b9312SValentin Schneider 	INIT_LIST_HEAD(&pool->dying_workers);
37847a4e344cSTejun Heo 
37857cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
378629c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
378729c91e99STejun Heo 	pool->refcnt = 1;
378829c91e99STejun Heo 
378929c91e99STejun Heo 	/* shouldn't fail above this point */
3790be69d00dSThomas Gleixner 	pool->attrs = alloc_workqueue_attrs();
37917a4e344cSTejun Heo 	if (!pool->attrs)
37927a4e344cSTejun Heo 		return -ENOMEM;
37937a4e344cSTejun Heo 	return 0;
37944e1a1f9aSTejun Heo }
37954e1a1f9aSTejun Heo 
3796669de8bdSBart Van Assche #ifdef CONFIG_LOCKDEP
3797669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3798669de8bdSBart Van Assche {
3799669de8bdSBart Van Assche 	char *lock_name;
3800669de8bdSBart Van Assche 
3801669de8bdSBart Van Assche 	lockdep_register_key(&wq->key);
3802669de8bdSBart Van Assche 	lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3803669de8bdSBart Van Assche 	if (!lock_name)
3804669de8bdSBart Van Assche 		lock_name = wq->name;
380569a106c0SQian Cai 
380669a106c0SQian Cai 	wq->lock_name = lock_name;
3807669de8bdSBart Van Assche 	lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3808669de8bdSBart Van Assche }
3809669de8bdSBart Van Assche 
3810669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3811669de8bdSBart Van Assche {
3812669de8bdSBart Van Assche 	lockdep_unregister_key(&wq->key);
3813669de8bdSBart Van Assche }
3814669de8bdSBart Van Assche 
3815669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3816669de8bdSBart Van Assche {
3817669de8bdSBart Van Assche 	if (wq->lock_name != wq->name)
3818669de8bdSBart Van Assche 		kfree(wq->lock_name);
3819669de8bdSBart Van Assche }
3820669de8bdSBart Van Assche #else
3821669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3822669de8bdSBart Van Assche {
3823669de8bdSBart Van Assche }
3824669de8bdSBart Van Assche 
3825669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3826669de8bdSBart Van Assche {
3827669de8bdSBart Van Assche }
3828669de8bdSBart Van Assche 
3829669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3830669de8bdSBart Van Assche {
3831669de8bdSBart Van Assche }
3832669de8bdSBart Van Assche #endif
3833669de8bdSBart Van Assche 
3834e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
3835e2dca7adSTejun Heo {
3836e2dca7adSTejun Heo 	struct workqueue_struct *wq =
3837e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
3838e2dca7adSTejun Heo 
3839669de8bdSBart Van Assche 	wq_free_lockdep(wq);
3840669de8bdSBart Van Assche 
3841e2dca7adSTejun Heo 	if (!(wq->flags & WQ_UNBOUND))
3842e2dca7adSTejun Heo 		free_percpu(wq->cpu_pwqs);
3843e2dca7adSTejun Heo 	else
3844e2dca7adSTejun Heo 		free_workqueue_attrs(wq->unbound_attrs);
3845e2dca7adSTejun Heo 
3846e2dca7adSTejun Heo 	kfree(wq);
3847e2dca7adSTejun Heo }
3848e2dca7adSTejun Heo 
384929c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
385029c91e99STejun Heo {
385129c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
385229c91e99STejun Heo 
38537cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
385429c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
385529c91e99STejun Heo 	kfree(pool);
385629c91e99STejun Heo }
385729c91e99STejun Heo 
385829c91e99STejun Heo /**
385929c91e99STejun Heo  * put_unbound_pool - put a worker_pool
386029c91e99STejun Heo  * @pool: worker_pool to put
386129c91e99STejun Heo  *
386224acfb71SThomas Gleixner  * Put @pool.  If its refcnt reaches zero, it gets destroyed in RCU
3863c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3864c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3865c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
3866a892caccSTejun Heo  *
3867a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
386829c91e99STejun Heo  */
386929c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
387029c91e99STejun Heo {
387160f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
3872e02b9312SValentin Schneider 	struct list_head cull_list;
387329c91e99STejun Heo 	struct worker *worker;
387429c91e99STejun Heo 
3875e02b9312SValentin Schneider 	INIT_LIST_HEAD(&cull_list);
3876e02b9312SValentin Schneider 
3877a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3878a892caccSTejun Heo 
3879a892caccSTejun Heo 	if (--pool->refcnt)
388029c91e99STejun Heo 		return;
388129c91e99STejun Heo 
388229c91e99STejun Heo 	/* sanity checks */
388361d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
3884a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
388529c91e99STejun Heo 		return;
388629c91e99STejun Heo 
388729c91e99STejun Heo 	/* release id and unhash */
388829c91e99STejun Heo 	if (pool->id >= 0)
388929c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
389029c91e99STejun Heo 	hash_del(&pool->hash_node);
389129c91e99STejun Heo 
3892c5aa87bbSTejun Heo 	/*
3893692b4825STejun Heo 	 * Become the manager and destroy all workers.  This prevents
3894692b4825STejun Heo 	 * @pool's workers from blocking on attach_mutex.  We're the last
3895692b4825STejun Heo 	 * manager and @pool gets freed with the flag set.
38969ab03be4SValentin Schneider 	 *
38979ab03be4SValentin Schneider 	 * Having a concurrent manager is quite unlikely to happen as we can
38989ab03be4SValentin Schneider 	 * only get here with
38999ab03be4SValentin Schneider 	 *   pwq->refcnt == pool->refcnt == 0
39009ab03be4SValentin Schneider 	 * which implies no work queued to the pool, which implies no worker can
39019ab03be4SValentin Schneider 	 * become the manager. However a worker could have taken the role of
39029ab03be4SValentin Schneider 	 * manager before the refcnts dropped to 0, since maybe_create_worker()
39039ab03be4SValentin Schneider 	 * drops pool->lock
3904c5aa87bbSTejun Heo 	 */
39059ab03be4SValentin Schneider 	while (true) {
39069ab03be4SValentin Schneider 		rcuwait_wait_event(&manager_wait,
39079ab03be4SValentin Schneider 				   !(pool->flags & POOL_MANAGER_ACTIVE),
3908d8bb65abSSebastian Andrzej Siewior 				   TASK_UNINTERRUPTIBLE);
3909e02b9312SValentin Schneider 
3910e02b9312SValentin Schneider 		mutex_lock(&wq_pool_attach_mutex);
39119ab03be4SValentin Schneider 		raw_spin_lock_irq(&pool->lock);
39129ab03be4SValentin Schneider 		if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
3913692b4825STejun Heo 			pool->flags |= POOL_MANAGER_ACTIVE;
39149ab03be4SValentin Schneider 			break;
39159ab03be4SValentin Schneider 		}
39169ab03be4SValentin Schneider 		raw_spin_unlock_irq(&pool->lock);
3917e02b9312SValentin Schneider 		mutex_unlock(&wq_pool_attach_mutex);
39189ab03be4SValentin Schneider 	}
3919692b4825STejun Heo 
39201037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
3921e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
392229c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
3923a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
392460f5a4bcSLai Jiangshan 
3925e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
3926e02b9312SValentin Schneider 
3927e02b9312SValentin Schneider 	if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
392860f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
39291258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
393060f5a4bcSLai Jiangshan 
393160f5a4bcSLai Jiangshan 	if (pool->detach_completion)
393260f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
393360f5a4bcSLai Jiangshan 
393429c91e99STejun Heo 	/* shut down the timers */
393529c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
39363f959aa3SValentin Schneider 	cancel_work_sync(&pool->idle_cull_work);
393729c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
393829c91e99STejun Heo 
393924acfb71SThomas Gleixner 	/* RCU protected to allow dereferences from get_work_pool() */
394025b00775SPaul E. McKenney 	call_rcu(&pool->rcu, rcu_free_pool);
394129c91e99STejun Heo }
394229c91e99STejun Heo 
394329c91e99STejun Heo /**
394429c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
394529c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
394629c91e99STejun Heo  *
394729c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
394829c91e99STejun Heo  * reference count and return it.  If there already is a matching
394929c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
3950d185af30SYacine Belkadi  * create a new one.
3951a892caccSTejun Heo  *
3952a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
3953d185af30SYacine Belkadi  *
3954d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
3955d185af30SYacine Belkadi  * On failure, %NULL.
395629c91e99STejun Heo  */
395729c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
395829c91e99STejun Heo {
395929c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
396029c91e99STejun Heo 	struct worker_pool *pool;
3961f3f90ad4STejun Heo 	int node;
3962e2273584SXunlei Pang 	int target_node = NUMA_NO_NODE;
396329c91e99STejun Heo 
3964a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
396529c91e99STejun Heo 
396629c91e99STejun Heo 	/* do we already have a matching pool? */
396729c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
396829c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
396929c91e99STejun Heo 			pool->refcnt++;
39703fb1823cSLai Jiangshan 			return pool;
397129c91e99STejun Heo 		}
397229c91e99STejun Heo 	}
397329c91e99STejun Heo 
3974e2273584SXunlei Pang 	/* if cpumask is contained inside a NUMA node, we belong to that node */
3975e2273584SXunlei Pang 	if (wq_numa_enabled) {
3976e2273584SXunlei Pang 		for_each_node(node) {
3977e2273584SXunlei Pang 			if (cpumask_subset(attrs->cpumask,
3978e2273584SXunlei Pang 					   wq_numa_possible_cpumask[node])) {
3979e2273584SXunlei Pang 				target_node = node;
3980e2273584SXunlei Pang 				break;
3981e2273584SXunlei Pang 			}
3982e2273584SXunlei Pang 		}
3983e2273584SXunlei Pang 	}
3984e2273584SXunlei Pang 
398529c91e99STejun Heo 	/* nope, create a new one */
3986e2273584SXunlei Pang 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
398729c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
398829c91e99STejun Heo 		goto fail;
398929c91e99STejun Heo 
39908864b4e5STejun Heo 	lockdep_set_subclass(&pool->lock, 1);	/* see put_pwq() */
399129c91e99STejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
3992e2273584SXunlei Pang 	pool->node = target_node;
399329c91e99STejun Heo 
39942865a8fbSShaohua Li 	/*
39952865a8fbSShaohua Li 	 * no_numa isn't a worker_pool attribute, always clear it.  See
39962865a8fbSShaohua Li 	 * 'struct workqueue_attrs' comments for detail.
39972865a8fbSShaohua Li 	 */
39982865a8fbSShaohua Li 	pool->attrs->no_numa = false;
39992865a8fbSShaohua Li 
400029c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
400129c91e99STejun Heo 		goto fail;
400229c91e99STejun Heo 
400329c91e99STejun Heo 	/* create and start the initial worker */
40043347fa09STejun Heo 	if (wq_online && !create_worker(pool))
400529c91e99STejun Heo 		goto fail;
400629c91e99STejun Heo 
400729c91e99STejun Heo 	/* install */
400829c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
40093fb1823cSLai Jiangshan 
401029c91e99STejun Heo 	return pool;
401129c91e99STejun Heo fail:
401229c91e99STejun Heo 	if (pool)
401329c91e99STejun Heo 		put_unbound_pool(pool);
401429c91e99STejun Heo 	return NULL;
401529c91e99STejun Heo }
401629c91e99STejun Heo 
40178864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
40188864b4e5STejun Heo {
40198864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
40208864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
40218864b4e5STejun Heo }
40228864b4e5STejun Heo 
40238864b4e5STejun Heo /*
40248864b4e5STejun Heo  * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
40258864b4e5STejun Heo  * and needs to be destroyed.
40268864b4e5STejun Heo  */
40278864b4e5STejun Heo static void pwq_unbound_release_workfn(struct work_struct *work)
40288864b4e5STejun Heo {
40298864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
40308864b4e5STejun Heo 						  unbound_release_work);
40318864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
40328864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
4033b42b0bddSYang Yingliang 	bool is_last = false;
40348864b4e5STejun Heo 
4035b42b0bddSYang Yingliang 	/*
4036b42b0bddSYang Yingliang 	 * when @pwq is not linked, it doesn't hold any reference to the
4037b42b0bddSYang Yingliang 	 * @wq, and @wq is invalid to access.
4038b42b0bddSYang Yingliang 	 */
4039b42b0bddSYang Yingliang 	if (!list_empty(&pwq->pwqs_node)) {
40408864b4e5STejun Heo 		if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
40418864b4e5STejun Heo 			return;
40428864b4e5STejun Heo 
40433c25a55dSLai Jiangshan 		mutex_lock(&wq->mutex);
40448864b4e5STejun Heo 		list_del_rcu(&pwq->pwqs_node);
4045bc0caf09STejun Heo 		is_last = list_empty(&wq->pwqs);
40463c25a55dSLai Jiangshan 		mutex_unlock(&wq->mutex);
4047b42b0bddSYang Yingliang 	}
40488864b4e5STejun Heo 
4049a892caccSTejun Heo 	mutex_lock(&wq_pool_mutex);
40508864b4e5STejun Heo 	put_unbound_pool(pool);
4051a892caccSTejun Heo 	mutex_unlock(&wq_pool_mutex);
4052a892caccSTejun Heo 
405325b00775SPaul E. McKenney 	call_rcu(&pwq->rcu, rcu_free_pwq);
40548864b4e5STejun Heo 
40558864b4e5STejun Heo 	/*
40568864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
4057e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
40588864b4e5STejun Heo 	 */
4059669de8bdSBart Van Assche 	if (is_last) {
4060669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
406125b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
40626029a918STejun Heo 	}
4063669de8bdSBart Van Assche }
40648864b4e5STejun Heo 
40650fbd95aaSTejun Heo /**
4066699ce097STejun Heo  * pwq_adjust_max_active - update a pwq's max_active to the current setting
40670fbd95aaSTejun Heo  * @pwq: target pool_workqueue
40680fbd95aaSTejun Heo  *
4069699ce097STejun Heo  * If @pwq isn't freezing, set @pwq->max_active to the associated
4070f97a4a1aSLai Jiangshan  * workqueue's saved_max_active and activate inactive work items
4071699ce097STejun Heo  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
40720fbd95aaSTejun Heo  */
4073699ce097STejun Heo static void pwq_adjust_max_active(struct pool_workqueue *pwq)
40740fbd95aaSTejun Heo {
4075699ce097STejun Heo 	struct workqueue_struct *wq = pwq->wq;
4076699ce097STejun Heo 	bool freezable = wq->flags & WQ_FREEZABLE;
40773347fa09STejun Heo 	unsigned long flags;
4078699ce097STejun Heo 
4079699ce097STejun Heo 	/* for @wq->saved_max_active */
4080a357fc03SLai Jiangshan 	lockdep_assert_held(&wq->mutex);
4081699ce097STejun Heo 
4082699ce097STejun Heo 	/* fast exit for non-freezable wqs */
4083699ce097STejun Heo 	if (!freezable && pwq->max_active == wq->saved_max_active)
4084699ce097STejun Heo 		return;
4085699ce097STejun Heo 
40863347fa09STejun Heo 	/* this function can be called during early boot w/ irq disabled */
4087a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pwq->pool->lock, flags);
4088699ce097STejun Heo 
408974b414eaSLai Jiangshan 	/*
409074b414eaSLai Jiangshan 	 * During [un]freezing, the caller is responsible for ensuring that
409174b414eaSLai Jiangshan 	 * this function is called at least once after @workqueue_freezing
409274b414eaSLai Jiangshan 	 * is updated and visible.
409374b414eaSLai Jiangshan 	 */
409474b414eaSLai Jiangshan 	if (!freezable || !workqueue_freezing) {
409501341fbdSYunfeng Ye 		bool kick = false;
409601341fbdSYunfeng Ye 
4097699ce097STejun Heo 		pwq->max_active = wq->saved_max_active;
40980fbd95aaSTejun Heo 
4099f97a4a1aSLai Jiangshan 		while (!list_empty(&pwq->inactive_works) &&
410001341fbdSYunfeng Ye 		       pwq->nr_active < pwq->max_active) {
4101f97a4a1aSLai Jiangshan 			pwq_activate_first_inactive(pwq);
410201341fbdSYunfeng Ye 			kick = true;
410301341fbdSYunfeng Ye 		}
4104951a078aSLai Jiangshan 
4105951a078aSLai Jiangshan 		/*
4106951a078aSLai Jiangshan 		 * Need to kick a worker after thawed or an unbound wq's
410701341fbdSYunfeng Ye 		 * max_active is bumped. In realtime scenarios, always kicking a
410801341fbdSYunfeng Ye 		 * worker will cause interference on the isolated cpu cores, so
410901341fbdSYunfeng Ye 		 * let's kick iff work items were activated.
4110951a078aSLai Jiangshan 		 */
411101341fbdSYunfeng Ye 		if (kick)
4112951a078aSLai Jiangshan 			wake_up_worker(pwq->pool);
4113699ce097STejun Heo 	} else {
4114699ce097STejun Heo 		pwq->max_active = 0;
4115699ce097STejun Heo 	}
4116699ce097STejun Heo 
4117a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
41180fbd95aaSTejun Heo }
41190fbd95aaSTejun Heo 
412067dc8325SCai Huoqing /* initialize newly allocated @pwq which is associated with @wq and @pool */
4121f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
4122f147f29eSTejun Heo 		     struct worker_pool *pool)
4123d2c1d404STejun Heo {
4124d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
4125d2c1d404STejun Heo 
4126e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
4127e50aba9aSTejun Heo 
4128d2c1d404STejun Heo 	pwq->pool = pool;
4129d2c1d404STejun Heo 	pwq->wq = wq;
4130d2c1d404STejun Heo 	pwq->flush_color = -1;
41318864b4e5STejun Heo 	pwq->refcnt = 1;
4132f97a4a1aSLai Jiangshan 	INIT_LIST_HEAD(&pwq->inactive_works);
41331befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
4134d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
41358864b4e5STejun Heo 	INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
4136f147f29eSTejun Heo }
4137d2c1d404STejun Heo 
4138f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
41391befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
4140f147f29eSTejun Heo {
4141f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
4142f147f29eSTejun Heo 
4143f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
414475ccf595STejun Heo 
41451befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
41461befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
41471befcf30STejun Heo 		return;
41481befcf30STejun Heo 
414929b1cb41SLai Jiangshan 	/* set the matching work_color */
415075ccf595STejun Heo 	pwq->work_color = wq->work_color;
4151983ca25eSTejun Heo 
4152983ca25eSTejun Heo 	/* sync max_active to the current setting */
4153983ca25eSTejun Heo 	pwq_adjust_max_active(pwq);
4154983ca25eSTejun Heo 
4155983ca25eSTejun Heo 	/* link in @pwq */
41569e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
4157df2d5ae4STejun Heo }
41586029a918STejun Heo 
4159f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
4160f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
4161f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
4162f147f29eSTejun Heo {
4163f147f29eSTejun Heo 	struct worker_pool *pool;
4164f147f29eSTejun Heo 	struct pool_workqueue *pwq;
4165f147f29eSTejun Heo 
4166f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
4167f147f29eSTejun Heo 
4168f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
4169f147f29eSTejun Heo 	if (!pool)
4170f147f29eSTejun Heo 		return NULL;
4171f147f29eSTejun Heo 
4172e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
4173f147f29eSTejun Heo 	if (!pwq) {
4174f147f29eSTejun Heo 		put_unbound_pool(pool);
4175f147f29eSTejun Heo 		return NULL;
4176f147f29eSTejun Heo 	}
4177f147f29eSTejun Heo 
4178f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
4179f147f29eSTejun Heo 	return pwq;
4180d2c1d404STejun Heo }
4181d2c1d404STejun Heo 
41824c16bd32STejun Heo /**
418330186c6fSGong Zhaogang  * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
4184042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
41854c16bd32STejun Heo  * @node: the target NUMA node
41864c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
41874c16bd32STejun Heo  * @cpumask: outarg, the resulting cpumask
41884c16bd32STejun Heo  *
41894c16bd32STejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @node.  If
41904c16bd32STejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during
4191d185af30SYacine Belkadi  * calculation.  The result is stored in @cpumask.
41924c16bd32STejun Heo  *
41934c16bd32STejun Heo  * If NUMA affinity is not enabled, @attrs->cpumask is always used.  If
41944c16bd32STejun Heo  * enabled and @node has online CPUs requested by @attrs, the returned
41954c16bd32STejun Heo  * cpumask is the intersection of the possible CPUs of @node and
41964c16bd32STejun Heo  * @attrs->cpumask.
41974c16bd32STejun Heo  *
41984c16bd32STejun Heo  * The caller is responsible for ensuring that the cpumask of @node stays
41994c16bd32STejun Heo  * stable.
4200d185af30SYacine Belkadi  *
4201d185af30SYacine Belkadi  * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
4202d185af30SYacine Belkadi  * %false if equal.
42034c16bd32STejun Heo  */
42044c16bd32STejun Heo static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
42054c16bd32STejun Heo 				 int cpu_going_down, cpumask_t *cpumask)
42064c16bd32STejun Heo {
4207d55262c4STejun Heo 	if (!wq_numa_enabled || attrs->no_numa)
42084c16bd32STejun Heo 		goto use_dfl;
42094c16bd32STejun Heo 
42104c16bd32STejun Heo 	/* does @node have any online CPUs @attrs wants? */
42114c16bd32STejun Heo 	cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
42124c16bd32STejun Heo 	if (cpu_going_down >= 0)
42134c16bd32STejun Heo 		cpumask_clear_cpu(cpu_going_down, cpumask);
42144c16bd32STejun Heo 
42154c16bd32STejun Heo 	if (cpumask_empty(cpumask))
42164c16bd32STejun Heo 		goto use_dfl;
42174c16bd32STejun Heo 
42184c16bd32STejun Heo 	/* yeap, return possible CPUs in @node that @attrs wants */
42194c16bd32STejun Heo 	cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
42201ad0f0a7SMichael Bringmann 
42211ad0f0a7SMichael Bringmann 	if (cpumask_empty(cpumask)) {
42221ad0f0a7SMichael Bringmann 		pr_warn_once("WARNING: workqueue cpumask: online intersect > "
42231ad0f0a7SMichael Bringmann 				"possible intersect\n");
42241ad0f0a7SMichael Bringmann 		return false;
42251ad0f0a7SMichael Bringmann 	}
42261ad0f0a7SMichael Bringmann 
42274c16bd32STejun Heo 	return !cpumask_equal(cpumask, attrs->cpumask);
42284c16bd32STejun Heo 
42294c16bd32STejun Heo use_dfl:
42304c16bd32STejun Heo 	cpumask_copy(cpumask, attrs->cpumask);
42314c16bd32STejun Heo 	return false;
42324c16bd32STejun Heo }
42334c16bd32STejun Heo 
42341befcf30STejun Heo /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
42351befcf30STejun Heo static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
42361befcf30STejun Heo 						   int node,
42371befcf30STejun Heo 						   struct pool_workqueue *pwq)
42381befcf30STejun Heo {
42391befcf30STejun Heo 	struct pool_workqueue *old_pwq;
42401befcf30STejun Heo 
42415b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
42421befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
42431befcf30STejun Heo 
42441befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
42451befcf30STejun Heo 	link_pwq(pwq);
42461befcf30STejun Heo 
42471befcf30STejun Heo 	old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
42481befcf30STejun Heo 	rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
42491befcf30STejun Heo 	return old_pwq;
42501befcf30STejun Heo }
42511befcf30STejun Heo 
42522d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
42532d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
42542d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
42552d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
4256042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
42572d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
42582d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
42592d5f0764SLai Jiangshan };
42602d5f0764SLai Jiangshan 
42612d5f0764SLai Jiangshan /* free the resources after success or abort */
42622d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
42632d5f0764SLai Jiangshan {
42642d5f0764SLai Jiangshan 	if (ctx) {
42652d5f0764SLai Jiangshan 		int node;
42662d5f0764SLai Jiangshan 
42672d5f0764SLai Jiangshan 		for_each_node(node)
42682d5f0764SLai Jiangshan 			put_pwq_unlocked(ctx->pwq_tbl[node]);
42692d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
42702d5f0764SLai Jiangshan 
42712d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
42722d5f0764SLai Jiangshan 
42732d5f0764SLai Jiangshan 		kfree(ctx);
42742d5f0764SLai Jiangshan 	}
42752d5f0764SLai Jiangshan }
42762d5f0764SLai Jiangshan 
42772d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
42782d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
42792d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
428099c621efSLai Jiangshan 		      const struct workqueue_attrs *attrs,
428199c621efSLai Jiangshan 		      const cpumask_var_t unbound_cpumask)
42822d5f0764SLai Jiangshan {
42832d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
42842d5f0764SLai Jiangshan 	struct workqueue_attrs *new_attrs, *tmp_attrs;
42852d5f0764SLai Jiangshan 	int node;
42862d5f0764SLai Jiangshan 
42872d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
42882d5f0764SLai Jiangshan 
4289acafe7e3SKees Cook 	ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_node_ids), GFP_KERNEL);
42902d5f0764SLai Jiangshan 
4291be69d00dSThomas Gleixner 	new_attrs = alloc_workqueue_attrs();
4292be69d00dSThomas Gleixner 	tmp_attrs = alloc_workqueue_attrs();
42932d5f0764SLai Jiangshan 	if (!ctx || !new_attrs || !tmp_attrs)
42942d5f0764SLai Jiangshan 		goto out_free;
42952d5f0764SLai Jiangshan 
4296042f7df1SLai Jiangshan 	/*
429799c621efSLai Jiangshan 	 * Calculate the attrs of the default pwq with unbound_cpumask
429899c621efSLai Jiangshan 	 * which is wq_unbound_cpumask or to set to wq_unbound_cpumask.
4299042f7df1SLai Jiangshan 	 * If the user configured cpumask doesn't overlap with the
4300042f7df1SLai Jiangshan 	 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
4301042f7df1SLai Jiangshan 	 */
43022d5f0764SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
430399c621efSLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, unbound_cpumask);
4304042f7df1SLai Jiangshan 	if (unlikely(cpumask_empty(new_attrs->cpumask)))
430599c621efSLai Jiangshan 		cpumask_copy(new_attrs->cpumask, unbound_cpumask);
43062d5f0764SLai Jiangshan 
43072d5f0764SLai Jiangshan 	/*
43082d5f0764SLai Jiangshan 	 * We may create multiple pwqs with differing cpumasks.  Make a
43092d5f0764SLai Jiangshan 	 * copy of @new_attrs which will be modified and used to obtain
43102d5f0764SLai Jiangshan 	 * pools.
43112d5f0764SLai Jiangshan 	 */
43122d5f0764SLai Jiangshan 	copy_workqueue_attrs(tmp_attrs, new_attrs);
43132d5f0764SLai Jiangshan 
43142d5f0764SLai Jiangshan 	/*
43152d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
43162d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
43172d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
43182d5f0764SLai Jiangshan 	 */
43192d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
43202d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
43212d5f0764SLai Jiangshan 		goto out_free;
43222d5f0764SLai Jiangshan 
43232d5f0764SLai Jiangshan 	for_each_node(node) {
4324042f7df1SLai Jiangshan 		if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
43252d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
43262d5f0764SLai Jiangshan 			if (!ctx->pwq_tbl[node])
43272d5f0764SLai Jiangshan 				goto out_free;
43282d5f0764SLai Jiangshan 		} else {
43292d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
43302d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = ctx->dfl_pwq;
43312d5f0764SLai Jiangshan 		}
43322d5f0764SLai Jiangshan 	}
43332d5f0764SLai Jiangshan 
4334042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
4335042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
4336042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
43372d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
4338042f7df1SLai Jiangshan 
43392d5f0764SLai Jiangshan 	ctx->wq = wq;
43402d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
43412d5f0764SLai Jiangshan 	return ctx;
43422d5f0764SLai Jiangshan 
43432d5f0764SLai Jiangshan out_free:
43442d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
43452d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
43462d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
43472d5f0764SLai Jiangshan 	return NULL;
43482d5f0764SLai Jiangshan }
43492d5f0764SLai Jiangshan 
43502d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
43512d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
43522d5f0764SLai Jiangshan {
43532d5f0764SLai Jiangshan 	int node;
43542d5f0764SLai Jiangshan 
43552d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
43562d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
43572d5f0764SLai Jiangshan 
43582d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
43592d5f0764SLai Jiangshan 
43602d5f0764SLai Jiangshan 	/* save the previous pwq and install the new one */
43612d5f0764SLai Jiangshan 	for_each_node(node)
43622d5f0764SLai Jiangshan 		ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
43632d5f0764SLai Jiangshan 							  ctx->pwq_tbl[node]);
43642d5f0764SLai Jiangshan 
43652d5f0764SLai Jiangshan 	/* @dfl_pwq might not have been used, ensure it's linked */
43662d5f0764SLai Jiangshan 	link_pwq(ctx->dfl_pwq);
43672d5f0764SLai Jiangshan 	swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
43682d5f0764SLai Jiangshan 
43692d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
43702d5f0764SLai Jiangshan }
43712d5f0764SLai Jiangshan 
4372a0111cf6SLai Jiangshan static void apply_wqattrs_lock(void)
4373a0111cf6SLai Jiangshan {
4374a0111cf6SLai Jiangshan 	/* CPUs should stay stable across pwq creations and installations */
4375ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4376a0111cf6SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4377a0111cf6SLai Jiangshan }
4378a0111cf6SLai Jiangshan 
4379a0111cf6SLai Jiangshan static void apply_wqattrs_unlock(void)
4380a0111cf6SLai Jiangshan {
4381a0111cf6SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4382ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4383a0111cf6SLai Jiangshan }
4384a0111cf6SLai Jiangshan 
4385a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4386a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
4387a0111cf6SLai Jiangshan {
4388a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
4389a0111cf6SLai Jiangshan 
4390a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
4391a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4392a0111cf6SLai Jiangshan 		return -EINVAL;
4393a0111cf6SLai Jiangshan 
4394a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
43950a94efb5STejun Heo 	if (!list_empty(&wq->pwqs)) {
43960a94efb5STejun Heo 		if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4397a0111cf6SLai Jiangshan 			return -EINVAL;
4398a0111cf6SLai Jiangshan 
43990a94efb5STejun Heo 		wq->flags &= ~__WQ_ORDERED;
44000a94efb5STejun Heo 	}
44010a94efb5STejun Heo 
440299c621efSLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
44036201171eSwanghaibin 	if (!ctx)
44046201171eSwanghaibin 		return -ENOMEM;
4405a0111cf6SLai Jiangshan 
4406a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
4407a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
4408a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
4409a0111cf6SLai Jiangshan 
44106201171eSwanghaibin 	return 0;
4411a0111cf6SLai Jiangshan }
4412a0111cf6SLai Jiangshan 
44139e8cd2f5STejun Heo /**
44149e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
44159e8cd2f5STejun Heo  * @wq: the target workqueue
44169e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
44179e8cd2f5STejun Heo  *
44184c16bd32STejun Heo  * Apply @attrs to an unbound workqueue @wq.  Unless disabled, on NUMA
44194c16bd32STejun Heo  * machines, this function maps a separate pwq to each NUMA node with
44204c16bd32STejun Heo  * possibles CPUs in @attrs->cpumask so that work items are affine to the
44214c16bd32STejun Heo  * NUMA node it was issued on.  Older pwqs are released as in-flight work
44224c16bd32STejun Heo  * items finish.  Note that a work item which repeatedly requeues itself
44234c16bd32STejun Heo  * back-to-back will stay on its current pwq.
44249e8cd2f5STejun Heo  *
4425d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
4426d185af30SYacine Belkadi  *
4427ffd8bea8SSebastian Andrzej Siewior  * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
4428509b3204SDaniel Jordan  *
4429d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
44309e8cd2f5STejun Heo  */
4431513c98d0SDaniel Jordan int apply_workqueue_attrs(struct workqueue_struct *wq,
44329e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
44339e8cd2f5STejun Heo {
4434a0111cf6SLai Jiangshan 	int ret;
44359e8cd2f5STejun Heo 
4436509b3204SDaniel Jordan 	lockdep_assert_cpus_held();
4437509b3204SDaniel Jordan 
4438509b3204SDaniel Jordan 	mutex_lock(&wq_pool_mutex);
4439a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
4440509b3204SDaniel Jordan 	mutex_unlock(&wq_pool_mutex);
44412d5f0764SLai Jiangshan 
44422d5f0764SLai Jiangshan 	return ret;
44439e8cd2f5STejun Heo }
44449e8cd2f5STejun Heo 
44454c16bd32STejun Heo /**
44464c16bd32STejun Heo  * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
44474c16bd32STejun Heo  * @wq: the target workqueue
44484c16bd32STejun Heo  * @cpu: the CPU coming up or going down
44494c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
44504c16bd32STejun Heo  *
44514c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
44524c16bd32STejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update NUMA affinity of
44534c16bd32STejun Heo  * @wq accordingly.
44544c16bd32STejun Heo  *
44554c16bd32STejun Heo  * If NUMA affinity can't be adjusted due to memory allocation failure, it
44564c16bd32STejun Heo  * falls back to @wq->dfl_pwq which may not be optimal but is always
44574c16bd32STejun Heo  * correct.
44584c16bd32STejun Heo  *
44594c16bd32STejun Heo  * Note that when the last allowed CPU of a NUMA node goes offline for a
44604c16bd32STejun Heo  * workqueue with a cpumask spanning multiple nodes, the workers which were
44614c16bd32STejun Heo  * already executing the work items for the workqueue will lose their CPU
44624c16bd32STejun Heo  * affinity and may execute on any CPU.  This is similar to how per-cpu
44634c16bd32STejun Heo  * workqueues behave on CPU_DOWN.  If a workqueue user wants strict
44644c16bd32STejun Heo  * affinity, it's the user's responsibility to flush the work item from
44654c16bd32STejun Heo  * CPU_DOWN_PREPARE.
44664c16bd32STejun Heo  */
44674c16bd32STejun Heo static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
44684c16bd32STejun Heo 				   bool online)
44694c16bd32STejun Heo {
44704c16bd32STejun Heo 	int node = cpu_to_node(cpu);
44714c16bd32STejun Heo 	int cpu_off = online ? -1 : cpu;
44724c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
44734c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
44744c16bd32STejun Heo 	cpumask_t *cpumask;
44754c16bd32STejun Heo 
44764c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
44774c16bd32STejun Heo 
4478f7142ed4SLai Jiangshan 	if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
4479f7142ed4SLai Jiangshan 	    wq->unbound_attrs->no_numa)
44804c16bd32STejun Heo 		return;
44814c16bd32STejun Heo 
44824c16bd32STejun Heo 	/*
44834c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
44844c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
44854c16bd32STejun Heo 	 * CPU hotplug exclusion.
44864c16bd32STejun Heo 	 */
44874c16bd32STejun Heo 	target_attrs = wq_update_unbound_numa_attrs_buf;
44884c16bd32STejun Heo 	cpumask = target_attrs->cpumask;
44894c16bd32STejun Heo 
44904c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
44914c16bd32STejun Heo 	pwq = unbound_pwq_by_node(wq, node);
44924c16bd32STejun Heo 
44934c16bd32STejun Heo 	/*
44944c16bd32STejun Heo 	 * Let's determine what needs to be done.  If the target cpumask is
4495042f7df1SLai Jiangshan 	 * different from the default pwq's, we need to compare it to @pwq's
4496042f7df1SLai Jiangshan 	 * and create a new one if they don't match.  If the target cpumask
4497042f7df1SLai Jiangshan 	 * equals the default pwq's, the default pwq should be used.
44984c16bd32STejun Heo 	 */
4499042f7df1SLai Jiangshan 	if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
45004c16bd32STejun Heo 		if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
4501f7142ed4SLai Jiangshan 			return;
45024c16bd32STejun Heo 	} else {
45034c16bd32STejun Heo 		goto use_dfl_pwq;
45044c16bd32STejun Heo 	}
45054c16bd32STejun Heo 
45064c16bd32STejun Heo 	/* create a new pwq */
45074c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
45084c16bd32STejun Heo 	if (!pwq) {
45092d916033SFabian Frederick 		pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
45104c16bd32STejun Heo 			wq->name);
451177f300b1SDaeseok Youn 		goto use_dfl_pwq;
45124c16bd32STejun Heo 	}
45134c16bd32STejun Heo 
4514f7142ed4SLai Jiangshan 	/* Install the new pwq. */
45154c16bd32STejun Heo 	mutex_lock(&wq->mutex);
45164c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, pwq);
45174c16bd32STejun Heo 	goto out_unlock;
45184c16bd32STejun Heo 
45194c16bd32STejun Heo use_dfl_pwq:
4520f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
4521a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
45224c16bd32STejun Heo 	get_pwq(wq->dfl_pwq);
4523a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
45244c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
45254c16bd32STejun Heo out_unlock:
45264c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
45274c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
45284c16bd32STejun Heo }
45294c16bd32STejun Heo 
453030cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
45311da177e4SLinus Torvalds {
453249e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
45338a2b7538STejun Heo 	int cpu, ret;
4534e1d8aa9fSFrederic Weisbecker 
453530cdf249STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
4536420c0ddbSTejun Heo 		wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
4537420c0ddbSTejun Heo 		if (!wq->cpu_pwqs)
453830cdf249STejun Heo 			return -ENOMEM;
453930cdf249STejun Heo 
454030cdf249STejun Heo 		for_each_possible_cpu(cpu) {
45417fb98ea7STejun Heo 			struct pool_workqueue *pwq =
45427fb98ea7STejun Heo 				per_cpu_ptr(wq->cpu_pwqs, cpu);
45437a62c2c8STejun Heo 			struct worker_pool *cpu_pools =
4544f02ae73aSTejun Heo 				per_cpu(cpu_worker_pools, cpu);
454530cdf249STejun Heo 
4546f147f29eSTejun Heo 			init_pwq(pwq, wq, &cpu_pools[highpri]);
4547f147f29eSTejun Heo 
4548f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
45491befcf30STejun Heo 			link_pwq(pwq);
4550f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
455130cdf249STejun Heo 		}
455230cdf249STejun Heo 		return 0;
4553509b3204SDaniel Jordan 	}
4554509b3204SDaniel Jordan 
4555ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4556509b3204SDaniel Jordan 	if (wq->flags & __WQ_ORDERED) {
45578a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
45588a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
45598a2b7538STejun Heo 		WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
45608a2b7538STejun Heo 			      wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
45618a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
45629e8cd2f5STejun Heo 	} else {
4563509b3204SDaniel Jordan 		ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
45649e8cd2f5STejun Heo 	}
4565ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4566509b3204SDaniel Jordan 
4567509b3204SDaniel Jordan 	return ret;
45680f900049STejun Heo }
45690f900049STejun Heo 
4570f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
4571f3421797STejun Heo 			       const char *name)
4572b71ab8c2STejun Heo {
4573f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
4574f3421797STejun Heo 
4575f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
4576044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4577f3421797STejun Heo 			max_active, name, 1, lim);
4578b71ab8c2STejun Heo 
4579f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
4580b71ab8c2STejun Heo }
4581b71ab8c2STejun Heo 
4582983c7515STejun Heo /*
4583983c7515STejun Heo  * Workqueues which may be used during memory reclaim should have a rescuer
4584983c7515STejun Heo  * to guarantee forward progress.
4585983c7515STejun Heo  */
4586983c7515STejun Heo static int init_rescuer(struct workqueue_struct *wq)
4587983c7515STejun Heo {
4588983c7515STejun Heo 	struct worker *rescuer;
4589b92b36eaSDan Carpenter 	int ret;
4590983c7515STejun Heo 
4591983c7515STejun Heo 	if (!(wq->flags & WQ_MEM_RECLAIM))
4592983c7515STejun Heo 		return 0;
4593983c7515STejun Heo 
4594983c7515STejun Heo 	rescuer = alloc_worker(NUMA_NO_NODE);
45954c0736a7SPetr Mladek 	if (!rescuer) {
45964c0736a7SPetr Mladek 		pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
45974c0736a7SPetr Mladek 		       wq->name);
4598983c7515STejun Heo 		return -ENOMEM;
45994c0736a7SPetr Mladek 	}
4600983c7515STejun Heo 
4601983c7515STejun Heo 	rescuer->rescue_wq = wq;
4602983c7515STejun Heo 	rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name);
4603f187b697SSean Fu 	if (IS_ERR(rescuer->task)) {
4604b92b36eaSDan Carpenter 		ret = PTR_ERR(rescuer->task);
46054c0736a7SPetr Mladek 		pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
46064c0736a7SPetr Mladek 		       wq->name, ERR_PTR(ret));
4607983c7515STejun Heo 		kfree(rescuer);
4608b92b36eaSDan Carpenter 		return ret;
4609983c7515STejun Heo 	}
4610983c7515STejun Heo 
4611983c7515STejun Heo 	wq->rescuer = rescuer;
4612983c7515STejun Heo 	kthread_bind_mask(rescuer->task, cpu_possible_mask);
4613983c7515STejun Heo 	wake_up_process(rescuer->task);
4614983c7515STejun Heo 
4615983c7515STejun Heo 	return 0;
4616983c7515STejun Heo }
4617983c7515STejun Heo 
4618a2775bbcSMathieu Malaterre __printf(1, 4)
4619669de8bdSBart Van Assche struct workqueue_struct *alloc_workqueue(const char *fmt,
462097e37d7bSTejun Heo 					 unsigned int flags,
4621669de8bdSBart Van Assche 					 int max_active, ...)
46223af24433SOleg Nesterov {
4623df2d5ae4STejun Heo 	size_t tbl_size = 0;
4624ecf6881fSTejun Heo 	va_list args;
46253af24433SOleg Nesterov 	struct workqueue_struct *wq;
462649e3cf44STejun Heo 	struct pool_workqueue *pwq;
4627b196be89STejun Heo 
46285c0338c6STejun Heo 	/*
46295c0338c6STejun Heo 	 * Unbound && max_active == 1 used to imply ordered, which is no
46305c0338c6STejun Heo 	 * longer the case on NUMA machines due to per-node pools.  While
46315c0338c6STejun Heo 	 * alloc_ordered_workqueue() is the right way to create an ordered
46325c0338c6STejun Heo 	 * workqueue, keep the previous behavior to avoid subtle breakages
46335c0338c6STejun Heo 	 * on NUMA.
46345c0338c6STejun Heo 	 */
46355c0338c6STejun Heo 	if ((flags & WQ_UNBOUND) && max_active == 1)
46365c0338c6STejun Heo 		flags |= __WQ_ORDERED;
46375c0338c6STejun Heo 
4638cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
4639cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4640cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
4641cee22a15SViresh Kumar 
4642ecf6881fSTejun Heo 	/* allocate wq and format name */
4643df2d5ae4STejun Heo 	if (flags & WQ_UNBOUND)
4644ddcb57e2SLai Jiangshan 		tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
4645df2d5ae4STejun Heo 
4646df2d5ae4STejun Heo 	wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
4647b196be89STejun Heo 	if (!wq)
4648d2c1d404STejun Heo 		return NULL;
4649b196be89STejun Heo 
46506029a918STejun Heo 	if (flags & WQ_UNBOUND) {
4651be69d00dSThomas Gleixner 		wq->unbound_attrs = alloc_workqueue_attrs();
46526029a918STejun Heo 		if (!wq->unbound_attrs)
46536029a918STejun Heo 			goto err_free_wq;
46546029a918STejun Heo 	}
46556029a918STejun Heo 
4656669de8bdSBart Van Assche 	va_start(args, max_active);
4657ecf6881fSTejun Heo 	vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4658b196be89STejun Heo 	va_end(args);
46593af24433SOleg Nesterov 
4660d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
4661b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
46623af24433SOleg Nesterov 
4663b196be89STejun Heo 	/* init wq */
466497e37d7bSTejun Heo 	wq->flags = flags;
4665a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
46663c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
4667112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
466830cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
466973f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
467073f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
4671493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
46723af24433SOleg Nesterov 
4673669de8bdSBart Van Assche 	wq_init_lockdep(wq);
4674cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
46753af24433SOleg Nesterov 
467630cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
467782efcab3SBart Van Assche 		goto err_unreg_lockdep;
46781537663fSTejun Heo 
467940c17f75STejun Heo 	if (wq_online && init_rescuer(wq) < 0)
4680d2c1d404STejun Heo 		goto err_destroy;
4681e22bee78STejun Heo 
4682226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4683226223abSTejun Heo 		goto err_destroy;
4684226223abSTejun Heo 
46856af8bf3dSOleg Nesterov 	/*
468668e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
468768e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
468868e13a67SLai Jiangshan 	 * list.
46896af8bf3dSOleg Nesterov 	 */
469068e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4691a0a1a5fdSTejun Heo 
4692a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
469349e3cf44STejun Heo 	for_each_pwq(pwq, wq)
4694699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4695a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4696a0a1a5fdSTejun Heo 
4697e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
4698a0a1a5fdSTejun Heo 
469968e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
47003af24433SOleg Nesterov 
47013af24433SOleg Nesterov 	return wq;
4702d2c1d404STejun Heo 
470382efcab3SBart Van Assche err_unreg_lockdep:
4704009bb421SBart Van Assche 	wq_unregister_lockdep(wq);
4705009bb421SBart Van Assche 	wq_free_lockdep(wq);
470682efcab3SBart Van Assche err_free_wq:
47076029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
47084690c4abSTejun Heo 	kfree(wq);
4709d2c1d404STejun Heo 	return NULL;
4710d2c1d404STejun Heo err_destroy:
4711d2c1d404STejun Heo 	destroy_workqueue(wq);
47124690c4abSTejun Heo 	return NULL;
47131da177e4SLinus Torvalds }
4714669de8bdSBart Van Assche EXPORT_SYMBOL_GPL(alloc_workqueue);
47151da177e4SLinus Torvalds 
4716c29eb853STejun Heo static bool pwq_busy(struct pool_workqueue *pwq)
4717c29eb853STejun Heo {
4718c29eb853STejun Heo 	int i;
4719c29eb853STejun Heo 
4720c29eb853STejun Heo 	for (i = 0; i < WORK_NR_COLORS; i++)
4721c29eb853STejun Heo 		if (pwq->nr_in_flight[i])
4722c29eb853STejun Heo 			return true;
4723c29eb853STejun Heo 
4724c29eb853STejun Heo 	if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4725c29eb853STejun Heo 		return true;
4726f97a4a1aSLai Jiangshan 	if (pwq->nr_active || !list_empty(&pwq->inactive_works))
4727c29eb853STejun Heo 		return true;
4728c29eb853STejun Heo 
4729c29eb853STejun Heo 	return false;
4730c29eb853STejun Heo }
4731c29eb853STejun Heo 
47323af24433SOleg Nesterov /**
47333af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
47343af24433SOleg Nesterov  * @wq: target workqueue
47353af24433SOleg Nesterov  *
47363af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
47373af24433SOleg Nesterov  */
47383af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
47393af24433SOleg Nesterov {
474049e3cf44STejun Heo 	struct pool_workqueue *pwq;
47414c16bd32STejun Heo 	int node;
47423af24433SOleg Nesterov 
4743def98c84STejun Heo 	/*
4744def98c84STejun Heo 	 * Remove it from sysfs first so that sanity check failure doesn't
4745def98c84STejun Heo 	 * lead to sysfs name conflicts.
4746def98c84STejun Heo 	 */
4747def98c84STejun Heo 	workqueue_sysfs_unregister(wq);
4748def98c84STejun Heo 
474933e3f0a3SRichard Clark 	/* mark the workqueue destruction is in progress */
475033e3f0a3SRichard Clark 	mutex_lock(&wq->mutex);
475133e3f0a3SRichard Clark 	wq->flags |= __WQ_DESTROYING;
475233e3f0a3SRichard Clark 	mutex_unlock(&wq->mutex);
475333e3f0a3SRichard Clark 
47549c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
47559c5a2ba7STejun Heo 	drain_workqueue(wq);
4756c8efcc25STejun Heo 
4757def98c84STejun Heo 	/* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4758def98c84STejun Heo 	if (wq->rescuer) {
4759def98c84STejun Heo 		struct worker *rescuer = wq->rescuer;
4760def98c84STejun Heo 
4761def98c84STejun Heo 		/* this prevents new queueing */
4762a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
4763def98c84STejun Heo 		wq->rescuer = NULL;
4764a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
4765def98c84STejun Heo 
4766def98c84STejun Heo 		/* rescuer will empty maydays list before exiting */
4767def98c84STejun Heo 		kthread_stop(rescuer->task);
47688efe1223STejun Heo 		kfree(rescuer);
4769def98c84STejun Heo 	}
4770def98c84STejun Heo 
4771c29eb853STejun Heo 	/*
4772c29eb853STejun Heo 	 * Sanity checks - grab all the locks so that we wait for all
4773c29eb853STejun Heo 	 * in-flight operations which may do put_pwq().
4774c29eb853STejun Heo 	 */
4775c29eb853STejun Heo 	mutex_lock(&wq_pool_mutex);
4776b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
477749e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
4778a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
4779c29eb853STejun Heo 		if (WARN_ON(pwq_busy(pwq))) {
47801d9a6159SKefeng Wang 			pr_warn("%s: %s has the following busy pwq\n",
4781e66b39afSTejun Heo 				__func__, wq->name);
4782c29eb853STejun Heo 			show_pwq(pwq);
4783a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pwq->pool->lock);
4784b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
4785c29eb853STejun Heo 			mutex_unlock(&wq_pool_mutex);
478655df0933SImran Khan 			show_one_workqueue(wq);
47876183c009STejun Heo 			return;
478876af4d93STejun Heo 		}
4789a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
479076af4d93STejun Heo 	}
4791b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
47926183c009STejun Heo 
4793a0a1a5fdSTejun Heo 	/*
4794a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
4795a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
4796a0a1a5fdSTejun Heo 	 */
4797e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
479868e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
47993af24433SOleg Nesterov 
48008864b4e5STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
4801669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
480229c91e99STejun Heo 		/*
48038864b4e5STejun Heo 		 * The base ref is never dropped on per-cpu pwqs.  Directly
4804e2dca7adSTejun Heo 		 * schedule RCU free.
480529c91e99STejun Heo 		 */
480625b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
48078864b4e5STejun Heo 	} else {
48088864b4e5STejun Heo 		/*
48098864b4e5STejun Heo 		 * We're the sole accessor of @wq at this point.  Directly
48104c16bd32STejun Heo 		 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
48114c16bd32STejun Heo 		 * @wq will be freed when the last pwq is released.
48128864b4e5STejun Heo 		 */
48134c16bd32STejun Heo 		for_each_node(node) {
48144c16bd32STejun Heo 			pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
48154c16bd32STejun Heo 			RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
48164c16bd32STejun Heo 			put_pwq_unlocked(pwq);
48174c16bd32STejun Heo 		}
48184c16bd32STejun Heo 
48194c16bd32STejun Heo 		/*
48204c16bd32STejun Heo 		 * Put dfl_pwq.  @wq may be freed any time after dfl_pwq is
48214c16bd32STejun Heo 		 * put.  Don't access it afterwards.
48224c16bd32STejun Heo 		 */
48234c16bd32STejun Heo 		pwq = wq->dfl_pwq;
48244c16bd32STejun Heo 		wq->dfl_pwq = NULL;
4825dce90d47STejun Heo 		put_pwq_unlocked(pwq);
482629c91e99STejun Heo 	}
48273af24433SOleg Nesterov }
48283af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
48293af24433SOleg Nesterov 
4830dcd989cbSTejun Heo /**
4831dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
4832dcd989cbSTejun Heo  * @wq: target workqueue
4833dcd989cbSTejun Heo  * @max_active: new max_active value.
4834dcd989cbSTejun Heo  *
4835dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
4836dcd989cbSTejun Heo  *
4837dcd989cbSTejun Heo  * CONTEXT:
4838dcd989cbSTejun Heo  * Don't call from IRQ context.
4839dcd989cbSTejun Heo  */
4840dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4841dcd989cbSTejun Heo {
484249e3cf44STejun Heo 	struct pool_workqueue *pwq;
4843dcd989cbSTejun Heo 
48448719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
48450a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
48468719dceaSTejun Heo 		return;
48478719dceaSTejun Heo 
4848f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4849dcd989cbSTejun Heo 
4850a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4851dcd989cbSTejun Heo 
48520a94efb5STejun Heo 	wq->flags &= ~__WQ_ORDERED;
4853dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4854dcd989cbSTejun Heo 
4855699ce097STejun Heo 	for_each_pwq(pwq, wq)
4856699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4857dcd989cbSTejun Heo 
4858a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4859dcd989cbSTejun Heo }
4860dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4861dcd989cbSTejun Heo 
4862dcd989cbSTejun Heo /**
486327d4ee03SLukas Wunner  * current_work - retrieve %current task's work struct
486427d4ee03SLukas Wunner  *
486527d4ee03SLukas Wunner  * Determine if %current task is a workqueue worker and what it's working on.
486627d4ee03SLukas Wunner  * Useful to find out the context that the %current task is running in.
486727d4ee03SLukas Wunner  *
486827d4ee03SLukas Wunner  * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
486927d4ee03SLukas Wunner  */
487027d4ee03SLukas Wunner struct work_struct *current_work(void)
487127d4ee03SLukas Wunner {
487227d4ee03SLukas Wunner 	struct worker *worker = current_wq_worker();
487327d4ee03SLukas Wunner 
487427d4ee03SLukas Wunner 	return worker ? worker->current_work : NULL;
487527d4ee03SLukas Wunner }
487627d4ee03SLukas Wunner EXPORT_SYMBOL(current_work);
487727d4ee03SLukas Wunner 
487827d4ee03SLukas Wunner /**
4879e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4880e6267616STejun Heo  *
4881e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4882e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4883d185af30SYacine Belkadi  *
4884d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
4885e6267616STejun Heo  */
4886e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4887e6267616STejun Heo {
4888e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4889e6267616STejun Heo 
48906a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
4891e6267616STejun Heo }
4892e6267616STejun Heo 
4893e6267616STejun Heo /**
4894dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4895dcd989cbSTejun Heo  * @cpu: CPU in question
4896dcd989cbSTejun Heo  * @wq: target workqueue
4897dcd989cbSTejun Heo  *
4898dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4899dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4900dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4901dcd989cbSTejun Heo  *
4902d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4903d3251859STejun Heo  * Note that both per-cpu and unbound workqueues may be associated with
4904d3251859STejun Heo  * multiple pool_workqueues which have separate congested states.  A
4905d3251859STejun Heo  * workqueue being congested on one CPU doesn't mean the workqueue is also
4906d3251859STejun Heo  * contested on other CPUs / NUMA nodes.
4907d3251859STejun Heo  *
4908d185af30SYacine Belkadi  * Return:
4909dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4910dcd989cbSTejun Heo  */
4911d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4912dcd989cbSTejun Heo {
49137fb98ea7STejun Heo 	struct pool_workqueue *pwq;
491476af4d93STejun Heo 	bool ret;
491576af4d93STejun Heo 
491624acfb71SThomas Gleixner 	rcu_read_lock();
491724acfb71SThomas Gleixner 	preempt_disable();
49187fb98ea7STejun Heo 
4919d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
4920d3251859STejun Heo 		cpu = smp_processor_id();
4921d3251859STejun Heo 
49227fb98ea7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
49237fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
49247fb98ea7STejun Heo 	else
4925df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4926dcd989cbSTejun Heo 
4927f97a4a1aSLai Jiangshan 	ret = !list_empty(&pwq->inactive_works);
492824acfb71SThomas Gleixner 	preempt_enable();
492924acfb71SThomas Gleixner 	rcu_read_unlock();
493076af4d93STejun Heo 
493176af4d93STejun Heo 	return ret;
4932dcd989cbSTejun Heo }
4933dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4934dcd989cbSTejun Heo 
4935dcd989cbSTejun Heo /**
4936dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4937dcd989cbSTejun Heo  * @work: the work to be tested
4938dcd989cbSTejun Heo  *
4939dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4940dcd989cbSTejun Heo  * synchronization around this function and the test result is
4941dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4942dcd989cbSTejun Heo  *
4943d185af30SYacine Belkadi  * Return:
4944dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
4945dcd989cbSTejun Heo  */
4946dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4947dcd989cbSTejun Heo {
4948fa1b54e6STejun Heo 	struct worker_pool *pool;
4949dcd989cbSTejun Heo 	unsigned long flags;
4950dcd989cbSTejun Heo 	unsigned int ret = 0;
4951dcd989cbSTejun Heo 
4952dcd989cbSTejun Heo 	if (work_pending(work))
4953dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
4954038366c5SLai Jiangshan 
495524acfb71SThomas Gleixner 	rcu_read_lock();
4956fa1b54e6STejun Heo 	pool = get_work_pool(work);
4957038366c5SLai Jiangshan 	if (pool) {
4958a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pool->lock, flags);
4959c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
4960dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
4961a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pool->lock, flags);
4962038366c5SLai Jiangshan 	}
496324acfb71SThomas Gleixner 	rcu_read_unlock();
4964dcd989cbSTejun Heo 
4965dcd989cbSTejun Heo 	return ret;
4966dcd989cbSTejun Heo }
4967dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
4968dcd989cbSTejun Heo 
49693d1cb205STejun Heo /**
49703d1cb205STejun Heo  * set_worker_desc - set description for the current work item
49713d1cb205STejun Heo  * @fmt: printf-style format string
49723d1cb205STejun Heo  * @...: arguments for the format string
49733d1cb205STejun Heo  *
49743d1cb205STejun Heo  * This function can be called by a running work function to describe what
49753d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
49763d1cb205STejun Heo  * information will be printed out together to help debugging.  The
49773d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
49783d1cb205STejun Heo  */
49793d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
49803d1cb205STejun Heo {
49813d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
49823d1cb205STejun Heo 	va_list args;
49833d1cb205STejun Heo 
49843d1cb205STejun Heo 	if (worker) {
49853d1cb205STejun Heo 		va_start(args, fmt);
49863d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
49873d1cb205STejun Heo 		va_end(args);
49883d1cb205STejun Heo 	}
49893d1cb205STejun Heo }
49905c750d58SSteffen Maier EXPORT_SYMBOL_GPL(set_worker_desc);
49913d1cb205STejun Heo 
49923d1cb205STejun Heo /**
49933d1cb205STejun Heo  * print_worker_info - print out worker information and description
49943d1cb205STejun Heo  * @log_lvl: the log level to use when printing
49953d1cb205STejun Heo  * @task: target task
49963d1cb205STejun Heo  *
49973d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
49983d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
49993d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
50003d1cb205STejun Heo  *
50013d1cb205STejun Heo  * This function can be safely called on any task as long as the
50023d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
50033d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
50043d1cb205STejun Heo  */
50053d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
50063d1cb205STejun Heo {
50073d1cb205STejun Heo 	work_func_t *fn = NULL;
50083d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
50093d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
50103d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
50113d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
50123d1cb205STejun Heo 	struct worker *worker;
50133d1cb205STejun Heo 
50143d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
50153d1cb205STejun Heo 		return;
50163d1cb205STejun Heo 
50173d1cb205STejun Heo 	/*
50183d1cb205STejun Heo 	 * This function is called without any synchronization and @task
50193d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
50203d1cb205STejun Heo 	 */
5021e700591aSPetr Mladek 	worker = kthread_probe_data(task);
50223d1cb205STejun Heo 
50233d1cb205STejun Heo 	/*
50248bf89593STejun Heo 	 * Carefully copy the associated workqueue's workfn, name and desc.
50258bf89593STejun Heo 	 * Keep the original last '\0' in case the original is garbage.
50263d1cb205STejun Heo 	 */
5027fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
5028fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
5029fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
5030fe557319SChristoph Hellwig 	copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
5031fe557319SChristoph Hellwig 	copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
50323d1cb205STejun Heo 
50333d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
5034d75f773cSSakari Ailus 		printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
50358bf89593STejun Heo 		if (strcmp(name, desc))
50363d1cb205STejun Heo 			pr_cont(" (%s)", desc);
50373d1cb205STejun Heo 		pr_cont("\n");
50383d1cb205STejun Heo 	}
50393d1cb205STejun Heo }
50403d1cb205STejun Heo 
50413494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
50423494fc30STejun Heo {
50433494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
50443494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
50453494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
50463494fc30STejun Heo 	pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
50473494fc30STejun Heo }
50483494fc30STejun Heo 
5049c76feb0dSPaul E. McKenney struct pr_cont_work_struct {
5050c76feb0dSPaul E. McKenney 	bool comma;
5051c76feb0dSPaul E. McKenney 	work_func_t func;
5052c76feb0dSPaul E. McKenney 	long ctr;
5053c76feb0dSPaul E. McKenney };
5054c76feb0dSPaul E. McKenney 
5055c76feb0dSPaul E. McKenney static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
5056c76feb0dSPaul E. McKenney {
5057c76feb0dSPaul E. McKenney 	if (!pcwsp->ctr)
5058c76feb0dSPaul E. McKenney 		goto out_record;
5059c76feb0dSPaul E. McKenney 	if (func == pcwsp->func) {
5060c76feb0dSPaul E. McKenney 		pcwsp->ctr++;
5061c76feb0dSPaul E. McKenney 		return;
5062c76feb0dSPaul E. McKenney 	}
5063c76feb0dSPaul E. McKenney 	if (pcwsp->ctr == 1)
5064c76feb0dSPaul E. McKenney 		pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
5065c76feb0dSPaul E. McKenney 	else
5066c76feb0dSPaul E. McKenney 		pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
5067c76feb0dSPaul E. McKenney 	pcwsp->ctr = 0;
5068c76feb0dSPaul E. McKenney out_record:
5069c76feb0dSPaul E. McKenney 	if ((long)func == -1L)
5070c76feb0dSPaul E. McKenney 		return;
5071c76feb0dSPaul E. McKenney 	pcwsp->comma = comma;
5072c76feb0dSPaul E. McKenney 	pcwsp->func = func;
5073c76feb0dSPaul E. McKenney 	pcwsp->ctr = 1;
5074c76feb0dSPaul E. McKenney }
5075c76feb0dSPaul E. McKenney 
5076c76feb0dSPaul E. McKenney static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
50773494fc30STejun Heo {
50783494fc30STejun Heo 	if (work->func == wq_barrier_func) {
50793494fc30STejun Heo 		struct wq_barrier *barr;
50803494fc30STejun Heo 
50813494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
50823494fc30STejun Heo 
5083c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
50843494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
50853494fc30STejun Heo 			task_pid_nr(barr->task));
50863494fc30STejun Heo 	} else {
5087c76feb0dSPaul E. McKenney 		if (!comma)
5088c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5089c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, work->func, pcwsp);
50903494fc30STejun Heo 	}
50913494fc30STejun Heo }
50923494fc30STejun Heo 
50933494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
50943494fc30STejun Heo {
5095c76feb0dSPaul E. McKenney 	struct pr_cont_work_struct pcws = { .ctr = 0, };
50963494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
50973494fc30STejun Heo 	struct work_struct *work;
50983494fc30STejun Heo 	struct worker *worker;
50993494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
51003494fc30STejun Heo 	int bkt;
51013494fc30STejun Heo 
51023494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
51033494fc30STejun Heo 	pr_cont_pool_info(pool);
51043494fc30STejun Heo 
5105e66b39afSTejun Heo 	pr_cont(" active=%d/%d refcnt=%d%s\n",
5106e66b39afSTejun Heo 		pwq->nr_active, pwq->max_active, pwq->refcnt,
51073494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
51083494fc30STejun Heo 
51093494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
51103494fc30STejun Heo 		if (worker->current_pwq == pwq) {
51113494fc30STejun Heo 			has_in_flight = true;
51123494fc30STejun Heo 			break;
51133494fc30STejun Heo 		}
51143494fc30STejun Heo 	}
51153494fc30STejun Heo 	if (has_in_flight) {
51163494fc30STejun Heo 		bool comma = false;
51173494fc30STejun Heo 
51183494fc30STejun Heo 		pr_info("    in-flight:");
51193494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
51203494fc30STejun Heo 			if (worker->current_pwq != pwq)
51213494fc30STejun Heo 				continue;
51223494fc30STejun Heo 
5123d75f773cSSakari Ailus 			pr_cont("%s %d%s:%ps", comma ? "," : "",
51243494fc30STejun Heo 				task_pid_nr(worker->task),
512530ae2fc0STejun Heo 				worker->rescue_wq ? "(RESCUER)" : "",
51263494fc30STejun Heo 				worker->current_func);
51273494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
5128c76feb0dSPaul E. McKenney 				pr_cont_work(false, work, &pcws);
5129c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
51303494fc30STejun Heo 			comma = true;
51313494fc30STejun Heo 		}
51323494fc30STejun Heo 		pr_cont("\n");
51333494fc30STejun Heo 	}
51343494fc30STejun Heo 
51353494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
51363494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
51373494fc30STejun Heo 			has_pending = true;
51383494fc30STejun Heo 			break;
51393494fc30STejun Heo 		}
51403494fc30STejun Heo 	}
51413494fc30STejun Heo 	if (has_pending) {
51423494fc30STejun Heo 		bool comma = false;
51433494fc30STejun Heo 
51443494fc30STejun Heo 		pr_info("    pending:");
51453494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
51463494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
51473494fc30STejun Heo 				continue;
51483494fc30STejun Heo 
5149c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
51503494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
51513494fc30STejun Heo 		}
5152c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
51533494fc30STejun Heo 		pr_cont("\n");
51543494fc30STejun Heo 	}
51553494fc30STejun Heo 
5156f97a4a1aSLai Jiangshan 	if (!list_empty(&pwq->inactive_works)) {
51573494fc30STejun Heo 		bool comma = false;
51583494fc30STejun Heo 
5159f97a4a1aSLai Jiangshan 		pr_info("    inactive:");
5160f97a4a1aSLai Jiangshan 		list_for_each_entry(work, &pwq->inactive_works, entry) {
5161c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
51623494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
51633494fc30STejun Heo 		}
5164c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
51653494fc30STejun Heo 		pr_cont("\n");
51663494fc30STejun Heo 	}
51673494fc30STejun Heo }
51683494fc30STejun Heo 
51693494fc30STejun Heo /**
517055df0933SImran Khan  * show_one_workqueue - dump state of specified workqueue
517155df0933SImran Khan  * @wq: workqueue whose state will be printed
51723494fc30STejun Heo  */
517355df0933SImran Khan void show_one_workqueue(struct workqueue_struct *wq)
51743494fc30STejun Heo {
51753494fc30STejun Heo 	struct pool_workqueue *pwq;
51763494fc30STejun Heo 	bool idle = true;
517755df0933SImran Khan 	unsigned long flags;
51783494fc30STejun Heo 
51793494fc30STejun Heo 	for_each_pwq(pwq, wq) {
5180f97a4a1aSLai Jiangshan 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
51813494fc30STejun Heo 			idle = false;
51823494fc30STejun Heo 			break;
51833494fc30STejun Heo 		}
51843494fc30STejun Heo 	}
518555df0933SImran Khan 	if (idle) /* Nothing to print for idle workqueue */
518655df0933SImran Khan 		return;
51873494fc30STejun Heo 
51883494fc30STejun Heo 	pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
51893494fc30STejun Heo 
51903494fc30STejun Heo 	for_each_pwq(pwq, wq) {
5191a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pwq->pool->lock, flags);
519257116ce1SJohan Hovold 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
519357116ce1SJohan Hovold 			/*
519457116ce1SJohan Hovold 			 * Defer printing to avoid deadlocks in console
519557116ce1SJohan Hovold 			 * drivers that queue work while holding locks
519657116ce1SJohan Hovold 			 * also taken in their write paths.
519757116ce1SJohan Hovold 			 */
519857116ce1SJohan Hovold 			printk_deferred_enter();
51993494fc30STejun Heo 			show_pwq(pwq);
520057116ce1SJohan Hovold 			printk_deferred_exit();
520157116ce1SJohan Hovold 		}
5202a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
520362635ea8SSergey Senozhatsky 		/*
520462635ea8SSergey Senozhatsky 		 * We could be printing a lot from atomic context, e.g.
520555df0933SImran Khan 		 * sysrq-t -> show_all_workqueues(). Avoid triggering
520662635ea8SSergey Senozhatsky 		 * hard lockup.
520762635ea8SSergey Senozhatsky 		 */
520862635ea8SSergey Senozhatsky 		touch_nmi_watchdog();
52093494fc30STejun Heo 	}
521055df0933SImran Khan 
52113494fc30STejun Heo }
52123494fc30STejun Heo 
521355df0933SImran Khan /**
521455df0933SImran Khan  * show_one_worker_pool - dump state of specified worker pool
521555df0933SImran Khan  * @pool: worker pool whose state will be printed
521655df0933SImran Khan  */
521755df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool)
521855df0933SImran Khan {
52193494fc30STejun Heo 	struct worker *worker;
52203494fc30STejun Heo 	bool first = true;
522155df0933SImran Khan 	unsigned long flags;
5222335a42ebSPetr Mladek 	unsigned long hung = 0;
52233494fc30STejun Heo 
5224a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pool->lock, flags);
52253494fc30STejun Heo 	if (pool->nr_workers == pool->nr_idle)
52263494fc30STejun Heo 		goto next_pool;
5227335a42ebSPetr Mladek 
5228335a42ebSPetr Mladek 	/* How long the first pending work is waiting for a worker. */
5229335a42ebSPetr Mladek 	if (!list_empty(&pool->worklist))
5230335a42ebSPetr Mladek 		hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
5231335a42ebSPetr Mladek 
523257116ce1SJohan Hovold 	/*
523357116ce1SJohan Hovold 	 * Defer printing to avoid deadlocks in console drivers that
523457116ce1SJohan Hovold 	 * queue work while holding locks also taken in their write
523557116ce1SJohan Hovold 	 * paths.
523657116ce1SJohan Hovold 	 */
523757116ce1SJohan Hovold 	printk_deferred_enter();
52383494fc30STejun Heo 	pr_info("pool %d:", pool->id);
52393494fc30STejun Heo 	pr_cont_pool_info(pool);
5240335a42ebSPetr Mladek 	pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
52413494fc30STejun Heo 	if (pool->manager)
52423494fc30STejun Heo 		pr_cont(" manager: %d",
52433494fc30STejun Heo 			task_pid_nr(pool->manager->task));
52443494fc30STejun Heo 	list_for_each_entry(worker, &pool->idle_list, entry) {
52453494fc30STejun Heo 		pr_cont(" %s%d", first ? "idle: " : "",
52463494fc30STejun Heo 			task_pid_nr(worker->task));
52473494fc30STejun Heo 		first = false;
52483494fc30STejun Heo 	}
52493494fc30STejun Heo 	pr_cont("\n");
525057116ce1SJohan Hovold 	printk_deferred_exit();
52513494fc30STejun Heo next_pool:
5252a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pool->lock, flags);
525362635ea8SSergey Senozhatsky 	/*
525462635ea8SSergey Senozhatsky 	 * We could be printing a lot from atomic context, e.g.
525555df0933SImran Khan 	 * sysrq-t -> show_all_workqueues(). Avoid triggering
525662635ea8SSergey Senozhatsky 	 * hard lockup.
525762635ea8SSergey Senozhatsky 	 */
525862635ea8SSergey Senozhatsky 	touch_nmi_watchdog();
525955df0933SImran Khan 
52603494fc30STejun Heo }
52613494fc30STejun Heo 
526255df0933SImran Khan /**
526355df0933SImran Khan  * show_all_workqueues - dump workqueue state
526455df0933SImran Khan  *
5265704bc669SJungseung Lee  * Called from a sysrq handler and prints out all busy workqueues and pools.
526655df0933SImran Khan  */
526755df0933SImran Khan void show_all_workqueues(void)
526855df0933SImran Khan {
526955df0933SImran Khan 	struct workqueue_struct *wq;
527055df0933SImran Khan 	struct worker_pool *pool;
527155df0933SImran Khan 	int pi;
527255df0933SImran Khan 
527355df0933SImran Khan 	rcu_read_lock();
527455df0933SImran Khan 
527555df0933SImran Khan 	pr_info("Showing busy workqueues and worker pools:\n");
527655df0933SImran Khan 
527755df0933SImran Khan 	list_for_each_entry_rcu(wq, &workqueues, list)
527855df0933SImran Khan 		show_one_workqueue(wq);
527955df0933SImran Khan 
528055df0933SImran Khan 	for_each_pool(pool, pi)
528155df0933SImran Khan 		show_one_worker_pool(pool);
528255df0933SImran Khan 
528324acfb71SThomas Gleixner 	rcu_read_unlock();
52843494fc30STejun Heo }
52853494fc30STejun Heo 
5286704bc669SJungseung Lee /**
5287704bc669SJungseung Lee  * show_freezable_workqueues - dump freezable workqueue state
5288704bc669SJungseung Lee  *
5289704bc669SJungseung Lee  * Called from try_to_freeze_tasks() and prints out all freezable workqueues
5290704bc669SJungseung Lee  * still busy.
5291704bc669SJungseung Lee  */
5292704bc669SJungseung Lee void show_freezable_workqueues(void)
5293704bc669SJungseung Lee {
5294704bc669SJungseung Lee 	struct workqueue_struct *wq;
5295704bc669SJungseung Lee 
5296704bc669SJungseung Lee 	rcu_read_lock();
5297704bc669SJungseung Lee 
5298704bc669SJungseung Lee 	pr_info("Showing freezable workqueues that are still busy:\n");
5299704bc669SJungseung Lee 
5300704bc669SJungseung Lee 	list_for_each_entry_rcu(wq, &workqueues, list) {
5301704bc669SJungseung Lee 		if (!(wq->flags & WQ_FREEZABLE))
5302704bc669SJungseung Lee 			continue;
5303704bc669SJungseung Lee 		show_one_workqueue(wq);
5304704bc669SJungseung Lee 	}
5305704bc669SJungseung Lee 
5306704bc669SJungseung Lee 	rcu_read_unlock();
5307704bc669SJungseung Lee }
5308704bc669SJungseung Lee 
53096b59808bSTejun Heo /* used to show worker information through /proc/PID/{comm,stat,status} */
53106b59808bSTejun Heo void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
53116b59808bSTejun Heo {
53126b59808bSTejun Heo 	int off;
53136b59808bSTejun Heo 
53146b59808bSTejun Heo 	/* always show the actual comm */
53156b59808bSTejun Heo 	off = strscpy(buf, task->comm, size);
53166b59808bSTejun Heo 	if (off < 0)
53176b59808bSTejun Heo 		return;
53186b59808bSTejun Heo 
5319197f6accSTejun Heo 	/* stabilize PF_WQ_WORKER and worker pool association */
53206b59808bSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
53216b59808bSTejun Heo 
5322197f6accSTejun Heo 	if (task->flags & PF_WQ_WORKER) {
5323197f6accSTejun Heo 		struct worker *worker = kthread_data(task);
5324197f6accSTejun Heo 		struct worker_pool *pool = worker->pool;
53256b59808bSTejun Heo 
53266b59808bSTejun Heo 		if (pool) {
5327a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock_irq(&pool->lock);
53286b59808bSTejun Heo 			/*
5329197f6accSTejun Heo 			 * ->desc tracks information (wq name or
5330197f6accSTejun Heo 			 * set_worker_desc()) for the latest execution.  If
5331197f6accSTejun Heo 			 * current, prepend '+', otherwise '-'.
53326b59808bSTejun Heo 			 */
53336b59808bSTejun Heo 			if (worker->desc[0] != '\0') {
53346b59808bSTejun Heo 				if (worker->current_work)
53356b59808bSTejun Heo 					scnprintf(buf + off, size - off, "+%s",
53366b59808bSTejun Heo 						  worker->desc);
53376b59808bSTejun Heo 				else
53386b59808bSTejun Heo 					scnprintf(buf + off, size - off, "-%s",
53396b59808bSTejun Heo 						  worker->desc);
53406b59808bSTejun Heo 			}
5341a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pool->lock);
53426b59808bSTejun Heo 		}
5343197f6accSTejun Heo 	}
53446b59808bSTejun Heo 
53456b59808bSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
53466b59808bSTejun Heo }
53476b59808bSTejun Heo 
534866448bc2SMathieu Malaterre #ifdef CONFIG_SMP
534966448bc2SMathieu Malaterre 
5350db7bccf4STejun Heo /*
5351db7bccf4STejun Heo  * CPU hotplug.
5352db7bccf4STejun Heo  *
5353e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
5354112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
5355706026c2STejun Heo  * pool which make migrating pending and scheduled works very
5356e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
535794cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
5358e22bee78STejun Heo  * blocked draining impractical.
5359e22bee78STejun Heo  *
536024647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
5361628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
5362628c78e7STejun Heo  * cpu comes back online.
5363db7bccf4STejun Heo  */
5364db7bccf4STejun Heo 
5365e8b3f8dbSLai Jiangshan static void unbind_workers(int cpu)
5366db7bccf4STejun Heo {
53674ce62e9eSTejun Heo 	struct worker_pool *pool;
5368db7bccf4STejun Heo 	struct worker *worker;
5369db7bccf4STejun Heo 
5370f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
53711258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
5372a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
5373e22bee78STejun Heo 
5374f2d5a0eeSTejun Heo 		/*
537592f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
537694cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
537711b45b0bSLai Jiangshan 		 * must be on the cpu.  After this, they may become diasporas.
5378b4ac9384SLai Jiangshan 		 * And the preemption disabled section in their sched callbacks
5379b4ac9384SLai Jiangshan 		 * are guaranteed to see WORKER_UNBOUND since the code here
5380b4ac9384SLai Jiangshan 		 * is on the same cpu.
5381f2d5a0eeSTejun Heo 		 */
5382da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
5383403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
5384db7bccf4STejun Heo 
538524647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
5386f2d5a0eeSTejun Heo 
5387e22bee78STejun Heo 		/*
5388989442d7SLai Jiangshan 		 * The handling of nr_running in sched callbacks are disabled
5389989442d7SLai Jiangshan 		 * now.  Zap nr_running.  After this, nr_running stays zero and
5390989442d7SLai Jiangshan 		 * need_more_worker() and keep_working() are always true as
5391989442d7SLai Jiangshan 		 * long as the worklist is not empty.  This pool now behaves as
5392989442d7SLai Jiangshan 		 * an unbound (in terms of concurrency management) pool which
5393eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
5394e22bee78STejun Heo 		 */
5395bc35f7efSLai Jiangshan 		pool->nr_running = 0;
5396eb283428SLai Jiangshan 
5397eb283428SLai Jiangshan 		/*
5398eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
5399eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
5400eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
5401eb283428SLai Jiangshan 		 */
5402eb283428SLai Jiangshan 		wake_up_worker(pool);
5403989442d7SLai Jiangshan 
5404a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
5405989442d7SLai Jiangshan 
5406793777bcSValentin Schneider 		for_each_pool_worker(worker, pool)
5407793777bcSValentin Schneider 			unbind_worker(worker);
5408989442d7SLai Jiangshan 
5409989442d7SLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
5410eb283428SLai Jiangshan 	}
5411db7bccf4STejun Heo }
5412db7bccf4STejun Heo 
5413bd7c089eSTejun Heo /**
5414bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
5415bd7c089eSTejun Heo  * @pool: pool of interest
5416bd7c089eSTejun Heo  *
5417a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
5418bd7c089eSTejun Heo  */
5419bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
5420bd7c089eSTejun Heo {
5421a9ab775bSTejun Heo 	struct worker *worker;
5422bd7c089eSTejun Heo 
54231258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
5424bd7c089eSTejun Heo 
5425bd7c089eSTejun Heo 	/*
5426a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
5427a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
5428402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
5429a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
5430a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
5431bd7c089eSTejun Heo 	 */
5432c63a2e52SValentin Schneider 	for_each_pool_worker(worker, pool) {
5433c63a2e52SValentin Schneider 		kthread_set_per_cpu(worker->task, pool->cpu);
5434c63a2e52SValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
5435c63a2e52SValentin Schneider 						  pool->attrs->cpumask) < 0);
5436c63a2e52SValentin Schneider 	}
5437a9ab775bSTejun Heo 
5438a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
5439f7c17d26SWanpeng Li 
54403de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
5441a9ab775bSTejun Heo 
5442da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
5443a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
5444a9ab775bSTejun Heo 
5445a9ab775bSTejun Heo 		/*
5446a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
5447a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
5448a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5449a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
5450a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
5451a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
5452a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
5453a9ab775bSTejun Heo 		 *
5454c95491edSMark Rutland 		 * WRITE_ONCE() is necessary because @worker->flags may be
5455a9ab775bSTejun Heo 		 * tested without holding any lock in
54566d25be57SThomas Gleixner 		 * wq_worker_running().  Without it, NOT_RUNNING test may
5457a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
5458a9ab775bSTejun Heo 		 * management operations.
5459bd7c089eSTejun Heo 		 */
5460a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5461a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
5462a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
5463c95491edSMark Rutland 		WRITE_ONCE(worker->flags, worker_flags);
5464bd7c089eSTejun Heo 	}
5465a9ab775bSTejun Heo 
5466a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
5467bd7c089eSTejun Heo }
5468bd7c089eSTejun Heo 
54697dbc725eSTejun Heo /**
54707dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
54717dbc725eSTejun Heo  * @pool: unbound pool of interest
54727dbc725eSTejun Heo  * @cpu: the CPU which is coming up
54737dbc725eSTejun Heo  *
54747dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
54757dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
54767dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
54777dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
54787dbc725eSTejun Heo  */
54797dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
54807dbc725eSTejun Heo {
54817dbc725eSTejun Heo 	static cpumask_t cpumask;
54827dbc725eSTejun Heo 	struct worker *worker;
54837dbc725eSTejun Heo 
54841258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
54857dbc725eSTejun Heo 
54867dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
54877dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
54887dbc725eSTejun Heo 		return;
54897dbc725eSTejun Heo 
54907dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
54917dbc725eSTejun Heo 
54927dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
5493da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
5494d945b5e9SPeter Zijlstra 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
54957dbc725eSTejun Heo }
54967dbc725eSTejun Heo 
54977ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
54981da177e4SLinus Torvalds {
54994ce62e9eSTejun Heo 	struct worker_pool *pool;
55001da177e4SLinus Torvalds 
5501f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
55023ce63377STejun Heo 		if (pool->nr_workers)
55033ce63377STejun Heo 			continue;
5504051e1850SLai Jiangshan 		if (!create_worker(pool))
55057ee681b2SThomas Gleixner 			return -ENOMEM;
55063af24433SOleg Nesterov 	}
55077ee681b2SThomas Gleixner 	return 0;
55087ee681b2SThomas Gleixner }
55091da177e4SLinus Torvalds 
55107ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
55117ee681b2SThomas Gleixner {
55127ee681b2SThomas Gleixner 	struct worker_pool *pool;
55137ee681b2SThomas Gleixner 	struct workqueue_struct *wq;
55147ee681b2SThomas Gleixner 	int pi;
55157ee681b2SThomas Gleixner 
551668e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
55177dbc725eSTejun Heo 
55187dbc725eSTejun Heo 	for_each_pool(pool, pi) {
55191258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
552094cf58bbSTejun Heo 
5521f05b558dSLai Jiangshan 		if (pool->cpu == cpu)
552294cf58bbSTejun Heo 			rebind_workers(pool);
5523f05b558dSLai Jiangshan 		else if (pool->cpu < 0)
55247dbc725eSTejun Heo 			restore_unbound_workers_cpumask(pool, cpu);
552594cf58bbSTejun Heo 
55261258fae7STejun Heo 		mutex_unlock(&wq_pool_attach_mutex);
552794cf58bbSTejun Heo 	}
55287dbc725eSTejun Heo 
55294c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
55304c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
55314c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, true);
55324c16bd32STejun Heo 
553368e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
55347ee681b2SThomas Gleixner 	return 0;
553565758202STejun Heo }
553665758202STejun Heo 
55377ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
553865758202STejun Heo {
55394c16bd32STejun Heo 	struct workqueue_struct *wq;
55408db25e78STejun Heo 
55414c16bd32STejun Heo 	/* unbinding per-cpu workers should happen on the local CPU */
5542e8b3f8dbSLai Jiangshan 	if (WARN_ON(cpu != smp_processor_id()))
5543e8b3f8dbSLai Jiangshan 		return -1;
5544e8b3f8dbSLai Jiangshan 
5545e8b3f8dbSLai Jiangshan 	unbind_workers(cpu);
55464c16bd32STejun Heo 
55474c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
55484c16bd32STejun Heo 	mutex_lock(&wq_pool_mutex);
55494c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
55504c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, false);
55514c16bd32STejun Heo 	mutex_unlock(&wq_pool_mutex);
55524c16bd32STejun Heo 
55537ee681b2SThomas Gleixner 	return 0;
555465758202STejun Heo }
555565758202STejun Heo 
55562d3854a3SRusty Russell struct work_for_cpu {
5557ed48ece2STejun Heo 	struct work_struct work;
55582d3854a3SRusty Russell 	long (*fn)(void *);
55592d3854a3SRusty Russell 	void *arg;
55602d3854a3SRusty Russell 	long ret;
55612d3854a3SRusty Russell };
55622d3854a3SRusty Russell 
5563ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
55642d3854a3SRusty Russell {
5565ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5566ed48ece2STejun Heo 
55672d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
55682d3854a3SRusty Russell }
55692d3854a3SRusty Russell 
55702d3854a3SRusty Russell /**
557122aceb31SAnna-Maria Gleixner  * work_on_cpu - run a function in thread context on a particular cpu
55722d3854a3SRusty Russell  * @cpu: the cpu to run on
55732d3854a3SRusty Russell  * @fn: the function to run
55742d3854a3SRusty Russell  * @arg: the function arg
55752d3854a3SRusty Russell  *
557631ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
55776b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
5578d185af30SYacine Belkadi  *
5579d185af30SYacine Belkadi  * Return: The value @fn returns.
55802d3854a3SRusty Russell  */
5581d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
55822d3854a3SRusty Russell {
5583ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
55842d3854a3SRusty Russell 
5585ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
5586ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
558712997d1aSBjorn Helgaas 	flush_work(&wfc.work);
5588440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
55892d3854a3SRusty Russell 	return wfc.ret;
55902d3854a3SRusty Russell }
55912d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
55920e8d6a93SThomas Gleixner 
55930e8d6a93SThomas Gleixner /**
55940e8d6a93SThomas Gleixner  * work_on_cpu_safe - run a function in thread context on a particular cpu
55950e8d6a93SThomas Gleixner  * @cpu: the cpu to run on
55960e8d6a93SThomas Gleixner  * @fn:  the function to run
55970e8d6a93SThomas Gleixner  * @arg: the function argument
55980e8d6a93SThomas Gleixner  *
55990e8d6a93SThomas Gleixner  * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
56000e8d6a93SThomas Gleixner  * any locks which would prevent @fn from completing.
56010e8d6a93SThomas Gleixner  *
56020e8d6a93SThomas Gleixner  * Return: The value @fn returns.
56030e8d6a93SThomas Gleixner  */
56040e8d6a93SThomas Gleixner long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
56050e8d6a93SThomas Gleixner {
56060e8d6a93SThomas Gleixner 	long ret = -ENODEV;
56070e8d6a93SThomas Gleixner 
5608ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
56090e8d6a93SThomas Gleixner 	if (cpu_online(cpu))
56100e8d6a93SThomas Gleixner 		ret = work_on_cpu(cpu, fn, arg);
5611ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
56120e8d6a93SThomas Gleixner 	return ret;
56130e8d6a93SThomas Gleixner }
56140e8d6a93SThomas Gleixner EXPORT_SYMBOL_GPL(work_on_cpu_safe);
56152d3854a3SRusty Russell #endif /* CONFIG_SMP */
56162d3854a3SRusty Russell 
5617a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
5618e7577c50SRusty Russell 
5619a0a1a5fdSTejun Heo /**
5620a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
5621a0a1a5fdSTejun Heo  *
562258a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
5623f97a4a1aSLai Jiangshan  * workqueues will queue new works to their inactive_works list instead of
5624706026c2STejun Heo  * pool->worklist.
5625a0a1a5fdSTejun Heo  *
5626a0a1a5fdSTejun Heo  * CONTEXT:
5627a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5628a0a1a5fdSTejun Heo  */
5629a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
5630a0a1a5fdSTejun Heo {
563124b8a847STejun Heo 	struct workqueue_struct *wq;
563224b8a847STejun Heo 	struct pool_workqueue *pwq;
5633a0a1a5fdSTejun Heo 
563468e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5635a0a1a5fdSTejun Heo 
56366183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
5637a0a1a5fdSTejun Heo 	workqueue_freezing = true;
5638a0a1a5fdSTejun Heo 
563924b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5640a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5641699ce097STejun Heo 		for_each_pwq(pwq, wq)
5642699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5643a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
5644a1056305STejun Heo 	}
56455bcab335STejun Heo 
564668e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5647a0a1a5fdSTejun Heo }
5648a0a1a5fdSTejun Heo 
5649a0a1a5fdSTejun Heo /**
565058a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
5651a0a1a5fdSTejun Heo  *
5652a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
5653a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
5654a0a1a5fdSTejun Heo  *
5655a0a1a5fdSTejun Heo  * CONTEXT:
565668e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
5657a0a1a5fdSTejun Heo  *
5658d185af30SYacine Belkadi  * Return:
565958a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
566058a69cb4STejun Heo  * is complete.
5661a0a1a5fdSTejun Heo  */
5662a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
5663a0a1a5fdSTejun Heo {
5664a0a1a5fdSTejun Heo 	bool busy = false;
566524b8a847STejun Heo 	struct workqueue_struct *wq;
566624b8a847STejun Heo 	struct pool_workqueue *pwq;
5667a0a1a5fdSTejun Heo 
566868e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5669a0a1a5fdSTejun Heo 
56706183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
5671a0a1a5fdSTejun Heo 
567224b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
567324b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
567424b8a847STejun Heo 			continue;
5675a0a1a5fdSTejun Heo 		/*
5676a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
5677a0a1a5fdSTejun Heo 		 * to peek without lock.
5678a0a1a5fdSTejun Heo 		 */
567924acfb71SThomas Gleixner 		rcu_read_lock();
568024b8a847STejun Heo 		for_each_pwq(pwq, wq) {
56816183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
5682112202d9STejun Heo 			if (pwq->nr_active) {
5683a0a1a5fdSTejun Heo 				busy = true;
568424acfb71SThomas Gleixner 				rcu_read_unlock();
5685a0a1a5fdSTejun Heo 				goto out_unlock;
5686a0a1a5fdSTejun Heo 			}
5687a0a1a5fdSTejun Heo 		}
568824acfb71SThomas Gleixner 		rcu_read_unlock();
5689a0a1a5fdSTejun Heo 	}
5690a0a1a5fdSTejun Heo out_unlock:
569168e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5692a0a1a5fdSTejun Heo 	return busy;
5693a0a1a5fdSTejun Heo }
5694a0a1a5fdSTejun Heo 
5695a0a1a5fdSTejun Heo /**
5696a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
5697a0a1a5fdSTejun Heo  *
5698a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
5699706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
5700a0a1a5fdSTejun Heo  *
5701a0a1a5fdSTejun Heo  * CONTEXT:
5702a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5703a0a1a5fdSTejun Heo  */
5704a0a1a5fdSTejun Heo void thaw_workqueues(void)
5705a0a1a5fdSTejun Heo {
570624b8a847STejun Heo 	struct workqueue_struct *wq;
570724b8a847STejun Heo 	struct pool_workqueue *pwq;
5708a0a1a5fdSTejun Heo 
570968e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5710a0a1a5fdSTejun Heo 
5711a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
5712a0a1a5fdSTejun Heo 		goto out_unlock;
5713a0a1a5fdSTejun Heo 
571474b414eaSLai Jiangshan 	workqueue_freezing = false;
571524b8a847STejun Heo 
571624b8a847STejun Heo 	/* restore max_active and repopulate worklist */
571724b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5718a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5719699ce097STejun Heo 		for_each_pwq(pwq, wq)
5720699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5721a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
572224b8a847STejun Heo 	}
572324b8a847STejun Heo 
5724a0a1a5fdSTejun Heo out_unlock:
572568e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5726a0a1a5fdSTejun Heo }
5727a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
5728a0a1a5fdSTejun Heo 
572999c621efSLai Jiangshan static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
5730042f7df1SLai Jiangshan {
5731042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
5732042f7df1SLai Jiangshan 	int ret = 0;
5733042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
5734042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
5735042f7df1SLai Jiangshan 
5736042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5737042f7df1SLai Jiangshan 
5738042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
5739042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
5740042f7df1SLai Jiangshan 			continue;
5741042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
5742042f7df1SLai Jiangshan 		if (wq->flags & __WQ_ORDERED)
5743042f7df1SLai Jiangshan 			continue;
5744042f7df1SLai Jiangshan 
574599c621efSLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
5746042f7df1SLai Jiangshan 		if (!ctx) {
5747042f7df1SLai Jiangshan 			ret = -ENOMEM;
5748042f7df1SLai Jiangshan 			break;
5749042f7df1SLai Jiangshan 		}
5750042f7df1SLai Jiangshan 
5751042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
5752042f7df1SLai Jiangshan 	}
5753042f7df1SLai Jiangshan 
5754042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
5755042f7df1SLai Jiangshan 		if (!ret)
5756042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
5757042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
5758042f7df1SLai Jiangshan 	}
5759042f7df1SLai Jiangshan 
576099c621efSLai Jiangshan 	if (!ret) {
576199c621efSLai Jiangshan 		mutex_lock(&wq_pool_attach_mutex);
576299c621efSLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
576399c621efSLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
576499c621efSLai Jiangshan 	}
5765042f7df1SLai Jiangshan 	return ret;
5766042f7df1SLai Jiangshan }
5767042f7df1SLai Jiangshan 
5768042f7df1SLai Jiangshan /**
5769042f7df1SLai Jiangshan  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5770042f7df1SLai Jiangshan  *  @cpumask: the cpumask to set
5771042f7df1SLai Jiangshan  *
5772042f7df1SLai Jiangshan  *  The low-level workqueues cpumask is a global cpumask that limits
5773042f7df1SLai Jiangshan  *  the affinity of all unbound workqueues.  This function check the @cpumask
5774042f7df1SLai Jiangshan  *  and apply it to all unbound workqueues and updates all pwqs of them.
5775042f7df1SLai Jiangshan  *
577667dc8325SCai Huoqing  *  Return:	0	- Success
5777042f7df1SLai Jiangshan  *  		-EINVAL	- Invalid @cpumask
5778042f7df1SLai Jiangshan  *  		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
5779042f7df1SLai Jiangshan  */
5780042f7df1SLai Jiangshan int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5781042f7df1SLai Jiangshan {
5782042f7df1SLai Jiangshan 	int ret = -EINVAL;
5783042f7df1SLai Jiangshan 
5784c98a9805STal Shorer 	/*
5785c98a9805STal Shorer 	 * Not excluding isolated cpus on purpose.
5786c98a9805STal Shorer 	 * If the user wishes to include them, we allow that.
5787c98a9805STal Shorer 	 */
5788042f7df1SLai Jiangshan 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
5789042f7df1SLai Jiangshan 	if (!cpumask_empty(cpumask)) {
5790a0111cf6SLai Jiangshan 		apply_wqattrs_lock();
5791d25302e4SMenglong Dong 		if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
5792d25302e4SMenglong Dong 			ret = 0;
5793d25302e4SMenglong Dong 			goto out_unlock;
5794d25302e4SMenglong Dong 		}
5795d25302e4SMenglong Dong 
579699c621efSLai Jiangshan 		ret = workqueue_apply_unbound_cpumask(cpumask);
5797042f7df1SLai Jiangshan 
5798d25302e4SMenglong Dong out_unlock:
5799a0111cf6SLai Jiangshan 		apply_wqattrs_unlock();
5800042f7df1SLai Jiangshan 	}
5801042f7df1SLai Jiangshan 
5802042f7df1SLai Jiangshan 	return ret;
5803042f7df1SLai Jiangshan }
5804042f7df1SLai Jiangshan 
58056ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
58066ba94429SFrederic Weisbecker /*
58076ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
58086ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
58096ba94429SFrederic Weisbecker  * following attributes.
58106ba94429SFrederic Weisbecker  *
58116ba94429SFrederic Weisbecker  *  per_cpu	RO bool	: whether the workqueue is per-cpu or unbound
58126ba94429SFrederic Weisbecker  *  max_active	RW int	: maximum number of in-flight work items
58136ba94429SFrederic Weisbecker  *
58146ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
58156ba94429SFrederic Weisbecker  *
58169a19b463SWang Long  *  pool_ids	RO int	: the associated pool IDs for each node
58176ba94429SFrederic Weisbecker  *  nice	RW int	: nice value of the workers
58186ba94429SFrederic Weisbecker  *  cpumask	RW mask	: bitmask of allowed CPUs for the workers
58199a19b463SWang Long  *  numa	RW bool	: whether enable NUMA affinity
58206ba94429SFrederic Weisbecker  */
58216ba94429SFrederic Weisbecker struct wq_device {
58226ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
58236ba94429SFrederic Weisbecker 	struct device			dev;
58246ba94429SFrederic Weisbecker };
58256ba94429SFrederic Weisbecker 
58266ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
58276ba94429SFrederic Weisbecker {
58286ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
58296ba94429SFrederic Weisbecker 
58306ba94429SFrederic Weisbecker 	return wq_dev->wq;
58316ba94429SFrederic Weisbecker }
58326ba94429SFrederic Weisbecker 
58336ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
58346ba94429SFrederic Weisbecker 			    char *buf)
58356ba94429SFrederic Weisbecker {
58366ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
58376ba94429SFrederic Weisbecker 
58386ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
58396ba94429SFrederic Weisbecker }
58406ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
58416ba94429SFrederic Weisbecker 
58426ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
58436ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
58446ba94429SFrederic Weisbecker {
58456ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
58466ba94429SFrederic Weisbecker 
58476ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
58486ba94429SFrederic Weisbecker }
58496ba94429SFrederic Weisbecker 
58506ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
58516ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
58526ba94429SFrederic Weisbecker 				size_t count)
58536ba94429SFrederic Weisbecker {
58546ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
58556ba94429SFrederic Weisbecker 	int val;
58566ba94429SFrederic Weisbecker 
58576ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
58586ba94429SFrederic Weisbecker 		return -EINVAL;
58596ba94429SFrederic Weisbecker 
58606ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
58616ba94429SFrederic Weisbecker 	return count;
58626ba94429SFrederic Weisbecker }
58636ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
58646ba94429SFrederic Weisbecker 
58656ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
58666ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
58676ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
58686ba94429SFrederic Weisbecker 	NULL,
58696ba94429SFrederic Weisbecker };
58706ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
58716ba94429SFrederic Weisbecker 
58726ba94429SFrederic Weisbecker static ssize_t wq_pool_ids_show(struct device *dev,
58736ba94429SFrederic Weisbecker 				struct device_attribute *attr, char *buf)
58746ba94429SFrederic Weisbecker {
58756ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
58766ba94429SFrederic Weisbecker 	const char *delim = "";
58776ba94429SFrederic Weisbecker 	int node, written = 0;
58786ba94429SFrederic Weisbecker 
5879ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
588024acfb71SThomas Gleixner 	rcu_read_lock();
58816ba94429SFrederic Weisbecker 	for_each_node(node) {
58826ba94429SFrederic Weisbecker 		written += scnprintf(buf + written, PAGE_SIZE - written,
58836ba94429SFrederic Weisbecker 				     "%s%d:%d", delim, node,
58846ba94429SFrederic Weisbecker 				     unbound_pwq_by_node(wq, node)->pool->id);
58856ba94429SFrederic Weisbecker 		delim = " ";
58866ba94429SFrederic Weisbecker 	}
58876ba94429SFrederic Weisbecker 	written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
588824acfb71SThomas Gleixner 	rcu_read_unlock();
5889ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
58906ba94429SFrederic Weisbecker 
58916ba94429SFrederic Weisbecker 	return written;
58926ba94429SFrederic Weisbecker }
58936ba94429SFrederic Weisbecker 
58946ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
58956ba94429SFrederic Weisbecker 			    char *buf)
58966ba94429SFrederic Weisbecker {
58976ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
58986ba94429SFrederic Weisbecker 	int written;
58996ba94429SFrederic Weisbecker 
59006ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
59016ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
59026ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
59036ba94429SFrederic Weisbecker 
59046ba94429SFrederic Weisbecker 	return written;
59056ba94429SFrederic Weisbecker }
59066ba94429SFrederic Weisbecker 
59076ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
59086ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
59096ba94429SFrederic Weisbecker {
59106ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
59116ba94429SFrederic Weisbecker 
5912899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5913899a94feSLai Jiangshan 
5914be69d00dSThomas Gleixner 	attrs = alloc_workqueue_attrs();
59156ba94429SFrederic Weisbecker 	if (!attrs)
59166ba94429SFrederic Weisbecker 		return NULL;
59176ba94429SFrederic Weisbecker 
59186ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
59196ba94429SFrederic Weisbecker 	return attrs;
59206ba94429SFrederic Weisbecker }
59216ba94429SFrederic Weisbecker 
59226ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
59236ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
59246ba94429SFrederic Weisbecker {
59256ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
59266ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5927d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5928d4d3e257SLai Jiangshan 
5929d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
59306ba94429SFrederic Weisbecker 
59316ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
59326ba94429SFrederic Weisbecker 	if (!attrs)
5933d4d3e257SLai Jiangshan 		goto out_unlock;
59346ba94429SFrederic Weisbecker 
59356ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
59366ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5937d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
59386ba94429SFrederic Weisbecker 	else
59396ba94429SFrederic Weisbecker 		ret = -EINVAL;
59406ba94429SFrederic Weisbecker 
5941d4d3e257SLai Jiangshan out_unlock:
5942d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
59436ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
59446ba94429SFrederic Weisbecker 	return ret ?: count;
59456ba94429SFrederic Weisbecker }
59466ba94429SFrederic Weisbecker 
59476ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
59486ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
59496ba94429SFrederic Weisbecker {
59506ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
59516ba94429SFrederic Weisbecker 	int written;
59526ba94429SFrederic Weisbecker 
59536ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
59546ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
59556ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
59566ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
59576ba94429SFrederic Weisbecker 	return written;
59586ba94429SFrederic Weisbecker }
59596ba94429SFrederic Weisbecker 
59606ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
59616ba94429SFrederic Weisbecker 				struct device_attribute *attr,
59626ba94429SFrederic Weisbecker 				const char *buf, size_t count)
59636ba94429SFrederic Weisbecker {
59646ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
59656ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5966d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5967d4d3e257SLai Jiangshan 
5968d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
59696ba94429SFrederic Weisbecker 
59706ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
59716ba94429SFrederic Weisbecker 	if (!attrs)
5972d4d3e257SLai Jiangshan 		goto out_unlock;
59736ba94429SFrederic Weisbecker 
59746ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
59756ba94429SFrederic Weisbecker 	if (!ret)
5976d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
59776ba94429SFrederic Weisbecker 
5978d4d3e257SLai Jiangshan out_unlock:
5979d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
59806ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
59816ba94429SFrederic Weisbecker 	return ret ?: count;
59826ba94429SFrederic Weisbecker }
59836ba94429SFrederic Weisbecker 
59846ba94429SFrederic Weisbecker static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
59856ba94429SFrederic Weisbecker 			    char *buf)
59866ba94429SFrederic Weisbecker {
59876ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
59886ba94429SFrederic Weisbecker 	int written;
59896ba94429SFrederic Weisbecker 
59906ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
59916ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n",
59926ba94429SFrederic Weisbecker 			    !wq->unbound_attrs->no_numa);
59936ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
59946ba94429SFrederic Weisbecker 
59956ba94429SFrederic Weisbecker 	return written;
59966ba94429SFrederic Weisbecker }
59976ba94429SFrederic Weisbecker 
59986ba94429SFrederic Weisbecker static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
59996ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
60006ba94429SFrederic Weisbecker {
60016ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
60026ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
6003d4d3e257SLai Jiangshan 	int v, ret = -ENOMEM;
6004d4d3e257SLai Jiangshan 
6005d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
60066ba94429SFrederic Weisbecker 
60076ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
60086ba94429SFrederic Weisbecker 	if (!attrs)
6009d4d3e257SLai Jiangshan 		goto out_unlock;
60106ba94429SFrederic Weisbecker 
60116ba94429SFrederic Weisbecker 	ret = -EINVAL;
60126ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &v) == 1) {
60136ba94429SFrederic Weisbecker 		attrs->no_numa = !v;
6014d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
60156ba94429SFrederic Weisbecker 	}
60166ba94429SFrederic Weisbecker 
6017d4d3e257SLai Jiangshan out_unlock:
6018d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
60196ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
60206ba94429SFrederic Weisbecker 	return ret ?: count;
60216ba94429SFrederic Weisbecker }
60226ba94429SFrederic Weisbecker 
60236ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
60246ba94429SFrederic Weisbecker 	__ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
60256ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
60266ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
60276ba94429SFrederic Weisbecker 	__ATTR(numa, 0644, wq_numa_show, wq_numa_store),
60286ba94429SFrederic Weisbecker 	__ATTR_NULL,
60296ba94429SFrederic Weisbecker };
60306ba94429SFrederic Weisbecker 
60316ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
60326ba94429SFrederic Weisbecker 	.name				= "workqueue",
60336ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
60346ba94429SFrederic Weisbecker };
60356ba94429SFrederic Weisbecker 
6036b05a7928SFrederic Weisbecker static ssize_t wq_unbound_cpumask_show(struct device *dev,
6037b05a7928SFrederic Weisbecker 		struct device_attribute *attr, char *buf)
6038b05a7928SFrederic Weisbecker {
6039b05a7928SFrederic Weisbecker 	int written;
6040b05a7928SFrederic Weisbecker 
6041042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
6042b05a7928SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
6043b05a7928SFrederic Weisbecker 			    cpumask_pr_args(wq_unbound_cpumask));
6044042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
6045b05a7928SFrederic Weisbecker 
6046b05a7928SFrederic Weisbecker 	return written;
6047b05a7928SFrederic Weisbecker }
6048b05a7928SFrederic Weisbecker 
6049042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
6050042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
6051042f7df1SLai Jiangshan {
6052042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
6053042f7df1SLai Jiangshan 	int ret;
6054042f7df1SLai Jiangshan 
6055042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
6056042f7df1SLai Jiangshan 		return -ENOMEM;
6057042f7df1SLai Jiangshan 
6058042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
6059042f7df1SLai Jiangshan 	if (!ret)
6060042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
6061042f7df1SLai Jiangshan 
6062042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
6063042f7df1SLai Jiangshan 	return ret ? ret : count;
6064042f7df1SLai Jiangshan }
6065042f7df1SLai Jiangshan 
6066b05a7928SFrederic Weisbecker static struct device_attribute wq_sysfs_cpumask_attr =
6067042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
6068042f7df1SLai Jiangshan 	       wq_unbound_cpumask_store);
6069b05a7928SFrederic Weisbecker 
60706ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
60716ba94429SFrederic Weisbecker {
6072686f6697SGreg Kroah-Hartman 	struct device *dev_root;
6073b05a7928SFrederic Weisbecker 	int err;
6074b05a7928SFrederic Weisbecker 
6075b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
6076b05a7928SFrederic Weisbecker 	if (err)
6077b05a7928SFrederic Weisbecker 		return err;
6078b05a7928SFrederic Weisbecker 
6079686f6697SGreg Kroah-Hartman 	dev_root = bus_get_dev_root(&wq_subsys);
6080686f6697SGreg Kroah-Hartman 	if (dev_root) {
6081686f6697SGreg Kroah-Hartman 		err = device_create_file(dev_root, &wq_sysfs_cpumask_attr);
6082686f6697SGreg Kroah-Hartman 		put_device(dev_root);
6083686f6697SGreg Kroah-Hartman 	}
6084686f6697SGreg Kroah-Hartman 	return err;
60856ba94429SFrederic Weisbecker }
60866ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
60876ba94429SFrederic Weisbecker 
60886ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
60896ba94429SFrederic Weisbecker {
60906ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
60916ba94429SFrederic Weisbecker 
60926ba94429SFrederic Weisbecker 	kfree(wq_dev);
60936ba94429SFrederic Weisbecker }
60946ba94429SFrederic Weisbecker 
60956ba94429SFrederic Weisbecker /**
60966ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
60976ba94429SFrederic Weisbecker  * @wq: the workqueue to register
60986ba94429SFrederic Weisbecker  *
60996ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
61006ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
61016ba94429SFrederic Weisbecker  * which is the preferred method.
61026ba94429SFrederic Weisbecker  *
61036ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
61046ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
61056ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
61066ba94429SFrederic Weisbecker  * attributes.
61076ba94429SFrederic Weisbecker  *
61086ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
61096ba94429SFrederic Weisbecker  */
61106ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
61116ba94429SFrederic Weisbecker {
61126ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
61136ba94429SFrederic Weisbecker 	int ret;
61146ba94429SFrederic Weisbecker 
61156ba94429SFrederic Weisbecker 	/*
6116402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
61176ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
61186ba94429SFrederic Weisbecker 	 * workqueues.
61196ba94429SFrederic Weisbecker 	 */
61200a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
61216ba94429SFrederic Weisbecker 		return -EINVAL;
61226ba94429SFrederic Weisbecker 
61236ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
61246ba94429SFrederic Weisbecker 	if (!wq_dev)
61256ba94429SFrederic Weisbecker 		return -ENOMEM;
61266ba94429SFrederic Weisbecker 
61276ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
61286ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
61296ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
613023217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
61316ba94429SFrederic Weisbecker 
61326ba94429SFrederic Weisbecker 	/*
61336ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
61346ba94429SFrederic Weisbecker 	 * everything is ready.
61356ba94429SFrederic Weisbecker 	 */
61366ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
61376ba94429SFrederic Weisbecker 
61386ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
61396ba94429SFrederic Weisbecker 	if (ret) {
6140537f4146SArvind Yadav 		put_device(&wq_dev->dev);
61416ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
61426ba94429SFrederic Weisbecker 		return ret;
61436ba94429SFrederic Weisbecker 	}
61446ba94429SFrederic Weisbecker 
61456ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
61466ba94429SFrederic Weisbecker 		struct device_attribute *attr;
61476ba94429SFrederic Weisbecker 
61486ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
61496ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
61506ba94429SFrederic Weisbecker 			if (ret) {
61516ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
61526ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
61536ba94429SFrederic Weisbecker 				return ret;
61546ba94429SFrederic Weisbecker 			}
61556ba94429SFrederic Weisbecker 		}
61566ba94429SFrederic Weisbecker 	}
61576ba94429SFrederic Weisbecker 
61586ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
61596ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
61606ba94429SFrederic Weisbecker 	return 0;
61616ba94429SFrederic Weisbecker }
61626ba94429SFrederic Weisbecker 
61636ba94429SFrederic Weisbecker /**
61646ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
61656ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
61666ba94429SFrederic Weisbecker  *
61676ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
61686ba94429SFrederic Weisbecker  */
61696ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
61706ba94429SFrederic Weisbecker {
61716ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
61726ba94429SFrederic Weisbecker 
61736ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
61746ba94429SFrederic Weisbecker 		return;
61756ba94429SFrederic Weisbecker 
61766ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
61776ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
61786ba94429SFrederic Weisbecker }
61796ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
61806ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
61816ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
61826ba94429SFrederic Weisbecker 
618382607adcSTejun Heo /*
618482607adcSTejun Heo  * Workqueue watchdog.
618582607adcSTejun Heo  *
618682607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
618782607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
618882607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
618982607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
619082607adcSTejun Heo  * largely opaque.
619182607adcSTejun Heo  *
619282607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
619382607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
619482607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
619582607adcSTejun Heo  *
619682607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
619782607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
619882607adcSTejun Heo  * corresponding sysfs parameter file.
619982607adcSTejun Heo  */
620082607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
620182607adcSTejun Heo 
620282607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
62035cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
620482607adcSTejun Heo 
620582607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
620682607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
620782607adcSTejun Heo 
6208cd2440d6SPetr Mladek /*
6209cd2440d6SPetr Mladek  * Show workers that might prevent the processing of pending work items.
6210cd2440d6SPetr Mladek  * The only candidates are CPU-bound workers in the running state.
6211cd2440d6SPetr Mladek  * Pending work items should be handled by another idle worker
6212cd2440d6SPetr Mladek  * in all other situations.
6213cd2440d6SPetr Mladek  */
6214cd2440d6SPetr Mladek static void show_cpu_pool_hog(struct worker_pool *pool)
6215cd2440d6SPetr Mladek {
6216cd2440d6SPetr Mladek 	struct worker *worker;
6217cd2440d6SPetr Mladek 	unsigned long flags;
6218cd2440d6SPetr Mladek 	int bkt;
6219cd2440d6SPetr Mladek 
6220cd2440d6SPetr Mladek 	raw_spin_lock_irqsave(&pool->lock, flags);
6221cd2440d6SPetr Mladek 
6222cd2440d6SPetr Mladek 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
6223cd2440d6SPetr Mladek 		if (task_is_running(worker->task)) {
6224cd2440d6SPetr Mladek 			/*
6225cd2440d6SPetr Mladek 			 * Defer printing to avoid deadlocks in console
6226cd2440d6SPetr Mladek 			 * drivers that queue work while holding locks
6227cd2440d6SPetr Mladek 			 * also taken in their write paths.
6228cd2440d6SPetr Mladek 			 */
6229cd2440d6SPetr Mladek 			printk_deferred_enter();
6230cd2440d6SPetr Mladek 
6231cd2440d6SPetr Mladek 			pr_info("pool %d:\n", pool->id);
6232cd2440d6SPetr Mladek 			sched_show_task(worker->task);
6233cd2440d6SPetr Mladek 
6234cd2440d6SPetr Mladek 			printk_deferred_exit();
6235cd2440d6SPetr Mladek 		}
6236cd2440d6SPetr Mladek 	}
6237cd2440d6SPetr Mladek 
6238cd2440d6SPetr Mladek 	raw_spin_unlock_irqrestore(&pool->lock, flags);
6239cd2440d6SPetr Mladek }
6240cd2440d6SPetr Mladek 
6241cd2440d6SPetr Mladek static void show_cpu_pools_hogs(void)
6242cd2440d6SPetr Mladek {
6243cd2440d6SPetr Mladek 	struct worker_pool *pool;
6244cd2440d6SPetr Mladek 	int pi;
6245cd2440d6SPetr Mladek 
6246cd2440d6SPetr Mladek 	pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
6247cd2440d6SPetr Mladek 
6248cd2440d6SPetr Mladek 	rcu_read_lock();
6249cd2440d6SPetr Mladek 
6250cd2440d6SPetr Mladek 	for_each_pool(pool, pi) {
6251cd2440d6SPetr Mladek 		if (pool->cpu_stall)
6252cd2440d6SPetr Mladek 			show_cpu_pool_hog(pool);
6253cd2440d6SPetr Mladek 
6254cd2440d6SPetr Mladek 	}
6255cd2440d6SPetr Mladek 
6256cd2440d6SPetr Mladek 	rcu_read_unlock();
6257cd2440d6SPetr Mladek }
6258cd2440d6SPetr Mladek 
625982607adcSTejun Heo static void wq_watchdog_reset_touched(void)
626082607adcSTejun Heo {
626182607adcSTejun Heo 	int cpu;
626282607adcSTejun Heo 
626382607adcSTejun Heo 	wq_watchdog_touched = jiffies;
626482607adcSTejun Heo 	for_each_possible_cpu(cpu)
626582607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
626682607adcSTejun Heo }
626782607adcSTejun Heo 
62685cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
626982607adcSTejun Heo {
627082607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
627182607adcSTejun Heo 	bool lockup_detected = false;
6272cd2440d6SPetr Mladek 	bool cpu_pool_stall = false;
6273940d71c6SSergey Senozhatsky 	unsigned long now = jiffies;
627482607adcSTejun Heo 	struct worker_pool *pool;
627582607adcSTejun Heo 	int pi;
627682607adcSTejun Heo 
627782607adcSTejun Heo 	if (!thresh)
627882607adcSTejun Heo 		return;
627982607adcSTejun Heo 
628082607adcSTejun Heo 	rcu_read_lock();
628182607adcSTejun Heo 
628282607adcSTejun Heo 	for_each_pool(pool, pi) {
628382607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
628482607adcSTejun Heo 
6285cd2440d6SPetr Mladek 		pool->cpu_stall = false;
628682607adcSTejun Heo 		if (list_empty(&pool->worklist))
628782607adcSTejun Heo 			continue;
628882607adcSTejun Heo 
6289940d71c6SSergey Senozhatsky 		/*
6290940d71c6SSergey Senozhatsky 		 * If a virtual machine is stopped by the host it can look to
6291940d71c6SSergey Senozhatsky 		 * the watchdog like a stall.
6292940d71c6SSergey Senozhatsky 		 */
6293940d71c6SSergey Senozhatsky 		kvm_check_and_clear_guest_paused();
6294940d71c6SSergey Senozhatsky 
629582607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
629689e28ce6SWang Qing 		if (pool->cpu >= 0)
629789e28ce6SWang Qing 			touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
629889e28ce6SWang Qing 		else
629982607adcSTejun Heo 			touched = READ_ONCE(wq_watchdog_touched);
630089e28ce6SWang Qing 		pool_ts = READ_ONCE(pool->watchdog_ts);
630182607adcSTejun Heo 
630282607adcSTejun Heo 		if (time_after(pool_ts, touched))
630382607adcSTejun Heo 			ts = pool_ts;
630482607adcSTejun Heo 		else
630582607adcSTejun Heo 			ts = touched;
630682607adcSTejun Heo 
630782607adcSTejun Heo 		/* did we stall? */
6308940d71c6SSergey Senozhatsky 		if (time_after(now, ts + thresh)) {
630982607adcSTejun Heo 			lockup_detected = true;
6310cd2440d6SPetr Mladek 			if (pool->cpu >= 0) {
6311cd2440d6SPetr Mladek 				pool->cpu_stall = true;
6312cd2440d6SPetr Mladek 				cpu_pool_stall = true;
6313cd2440d6SPetr Mladek 			}
631482607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
631582607adcSTejun Heo 			pr_cont_pool_info(pool);
631682607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
6317940d71c6SSergey Senozhatsky 				jiffies_to_msecs(now - pool_ts) / 1000);
631882607adcSTejun Heo 		}
6319cd2440d6SPetr Mladek 
6320cd2440d6SPetr Mladek 
632182607adcSTejun Heo 	}
632282607adcSTejun Heo 
632382607adcSTejun Heo 	rcu_read_unlock();
632482607adcSTejun Heo 
632582607adcSTejun Heo 	if (lockup_detected)
632655df0933SImran Khan 		show_all_workqueues();
632782607adcSTejun Heo 
6328cd2440d6SPetr Mladek 	if (cpu_pool_stall)
6329cd2440d6SPetr Mladek 		show_cpu_pools_hogs();
6330cd2440d6SPetr Mladek 
633182607adcSTejun Heo 	wq_watchdog_reset_touched();
633282607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
633382607adcSTejun Heo }
633482607adcSTejun Heo 
6335cb9d7fd5SVincent Whitchurch notrace void wq_watchdog_touch(int cpu)
633682607adcSTejun Heo {
633782607adcSTejun Heo 	if (cpu >= 0)
633882607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
633989e28ce6SWang Qing 
634082607adcSTejun Heo 	wq_watchdog_touched = jiffies;
634182607adcSTejun Heo }
634282607adcSTejun Heo 
634382607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
634482607adcSTejun Heo {
634582607adcSTejun Heo 	wq_watchdog_thresh = 0;
634682607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
634782607adcSTejun Heo 
634882607adcSTejun Heo 	if (thresh) {
634982607adcSTejun Heo 		wq_watchdog_thresh = thresh;
635082607adcSTejun Heo 		wq_watchdog_reset_touched();
635182607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
635282607adcSTejun Heo 	}
635382607adcSTejun Heo }
635482607adcSTejun Heo 
635582607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
635682607adcSTejun Heo 					const struct kernel_param *kp)
635782607adcSTejun Heo {
635882607adcSTejun Heo 	unsigned long thresh;
635982607adcSTejun Heo 	int ret;
636082607adcSTejun Heo 
636182607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
636282607adcSTejun Heo 	if (ret)
636382607adcSTejun Heo 		return ret;
636482607adcSTejun Heo 
636582607adcSTejun Heo 	if (system_wq)
636682607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
636782607adcSTejun Heo 	else
636882607adcSTejun Heo 		wq_watchdog_thresh = thresh;
636982607adcSTejun Heo 
637082607adcSTejun Heo 	return 0;
637182607adcSTejun Heo }
637282607adcSTejun Heo 
637382607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
637482607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
637582607adcSTejun Heo 	.get	= param_get_ulong,
637682607adcSTejun Heo };
637782607adcSTejun Heo 
637882607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
637982607adcSTejun Heo 		0644);
638082607adcSTejun Heo 
638182607adcSTejun Heo static void wq_watchdog_init(void)
638282607adcSTejun Heo {
63835cd79d6aSKees Cook 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
638482607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
638582607adcSTejun Heo }
638682607adcSTejun Heo 
638782607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
638882607adcSTejun Heo 
638982607adcSTejun Heo static inline void wq_watchdog_init(void) { }
639082607adcSTejun Heo 
639182607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
639282607adcSTejun Heo 
6393bce90380STejun Heo static void __init wq_numa_init(void)
6394bce90380STejun Heo {
6395bce90380STejun Heo 	cpumask_var_t *tbl;
6396bce90380STejun Heo 	int node, cpu;
6397bce90380STejun Heo 
6398bce90380STejun Heo 	if (num_possible_nodes() <= 1)
6399bce90380STejun Heo 		return;
6400bce90380STejun Heo 
6401d55262c4STejun Heo 	if (wq_disable_numa) {
6402d55262c4STejun Heo 		pr_info("workqueue: NUMA affinity support disabled\n");
6403d55262c4STejun Heo 		return;
6404d55262c4STejun Heo 	}
6405d55262c4STejun Heo 
6406f728c4a9SZhen Lei 	for_each_possible_cpu(cpu) {
6407f728c4a9SZhen Lei 		if (WARN_ON(cpu_to_node(cpu) == NUMA_NO_NODE)) {
6408f728c4a9SZhen Lei 			pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
6409f728c4a9SZhen Lei 			return;
6410f728c4a9SZhen Lei 		}
6411f728c4a9SZhen Lei 	}
6412f728c4a9SZhen Lei 
6413be69d00dSThomas Gleixner 	wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs();
64144c16bd32STejun Heo 	BUG_ON(!wq_update_unbound_numa_attrs_buf);
64154c16bd32STejun Heo 
6416bce90380STejun Heo 	/*
6417bce90380STejun Heo 	 * We want masks of possible CPUs of each node which isn't readily
6418bce90380STejun Heo 	 * available.  Build one from cpu_to_node() which should have been
6419bce90380STejun Heo 	 * fully initialized by now.
6420bce90380STejun Heo 	 */
64216396bb22SKees Cook 	tbl = kcalloc(nr_node_ids, sizeof(tbl[0]), GFP_KERNEL);
6422bce90380STejun Heo 	BUG_ON(!tbl);
6423bce90380STejun Heo 
6424bce90380STejun Heo 	for_each_node(node)
64255a6024f1SYasuaki Ishimatsu 		BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
64261be0c25dSTejun Heo 				node_online(node) ? node : NUMA_NO_NODE));
6427bce90380STejun Heo 
6428bce90380STejun Heo 	for_each_possible_cpu(cpu) {
6429bce90380STejun Heo 		node = cpu_to_node(cpu);
6430bce90380STejun Heo 		cpumask_set_cpu(cpu, tbl[node]);
6431bce90380STejun Heo 	}
6432bce90380STejun Heo 
6433bce90380STejun Heo 	wq_numa_possible_cpumask = tbl;
6434bce90380STejun Heo 	wq_numa_enabled = true;
6435bce90380STejun Heo }
6436bce90380STejun Heo 
64373347fa09STejun Heo /**
64383347fa09STejun Heo  * workqueue_init_early - early init for workqueue subsystem
64393347fa09STejun Heo  *
64403347fa09STejun Heo  * This is the first half of two-staged workqueue subsystem initialization
64413347fa09STejun Heo  * and invoked as soon as the bare basics - memory allocation, cpumasks and
64423347fa09STejun Heo  * idr are up.  It sets up all the data structures and system workqueues
64433347fa09STejun Heo  * and allows early boot code to create workqueues and queue/cancel work
64443347fa09STejun Heo  * items.  Actual work item execution starts only after kthreads can be
64453347fa09STejun Heo  * created and scheduled right before early initcalls.
64463347fa09STejun Heo  */
64472333e829SYu Chen void __init workqueue_init_early(void)
64481da177e4SLinus Torvalds {
64497a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
64507a4e344cSTejun Heo 	int i, cpu;
6451c34056a3STejun Heo 
645210cdb157SLai Jiangshan 	BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
6453e904e6c2STejun Heo 
6454b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
645504d4e665SFrederic Weisbecker 	cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_WQ));
645604d4e665SFrederic Weisbecker 	cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_DOMAIN));
6457b05a7928SFrederic Weisbecker 
6458e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6459e904e6c2STejun Heo 
6460706026c2STejun Heo 	/* initialize CPU pools */
646129c91e99STejun Heo 	for_each_possible_cpu(cpu) {
64624ce62e9eSTejun Heo 		struct worker_pool *pool;
64638b03ae3cSTejun Heo 
64647a4e344cSTejun Heo 		i = 0;
6465f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
64667a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
6467ec22ca5eSTejun Heo 			pool->cpu = cpu;
64687a4e344cSTejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
64697a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
6470f3f90ad4STejun Heo 			pool->node = cpu_to_node(cpu);
64717a4e344cSTejun Heo 
64729daf9e67STejun Heo 			/* alloc pool ID */
647368e13a67SLai Jiangshan 			mutex_lock(&wq_pool_mutex);
64749daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
647568e13a67SLai Jiangshan 			mutex_unlock(&wq_pool_mutex);
64764ce62e9eSTejun Heo 		}
64778b03ae3cSTejun Heo 	}
64788b03ae3cSTejun Heo 
64798a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
648029c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
648129c91e99STejun Heo 		struct workqueue_attrs *attrs;
648229c91e99STejun Heo 
6483be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
648429c91e99STejun Heo 		attrs->nice = std_nice[i];
648529c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
64868a2b7538STejun Heo 
64878a2b7538STejun Heo 		/*
64888a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
64898a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
64908a2b7538STejun Heo 		 * Turn off NUMA so that dfl_pwq is used for all nodes.
64918a2b7538STejun Heo 		 */
6492be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
64938a2b7538STejun Heo 		attrs->nice = std_nice[i];
64948a2b7538STejun Heo 		attrs->no_numa = true;
64958a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
649629c91e99STejun Heo 	}
649729c91e99STejun Heo 
6498d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
64991aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
6500d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
6501f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
6502f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
650324d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
650424d51addSTejun Heo 					      WQ_FREEZABLE, 0);
65050668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
65060668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
65070668106cSViresh Kumar 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
65080668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
65090668106cSViresh Kumar 					      0);
65101aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
65110668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
65120668106cSViresh Kumar 	       !system_power_efficient_wq ||
65130668106cSViresh Kumar 	       !system_freezable_power_efficient_wq);
65143347fa09STejun Heo }
65153347fa09STejun Heo 
65163347fa09STejun Heo /**
65173347fa09STejun Heo  * workqueue_init - bring workqueue subsystem fully online
65183347fa09STejun Heo  *
65193347fa09STejun Heo  * This is the latter half of two-staged workqueue subsystem initialization
65203347fa09STejun Heo  * and invoked as soon as kthreads can be created and scheduled.
65213347fa09STejun Heo  * Workqueues have been created and work items queued on them, but there
65223347fa09STejun Heo  * are no kworkers executing the work items yet.  Populate the worker pools
65233347fa09STejun Heo  * with the initial workers and enable future kworker creations.
65243347fa09STejun Heo  */
65252333e829SYu Chen void __init workqueue_init(void)
65263347fa09STejun Heo {
65272186d9f9STejun Heo 	struct workqueue_struct *wq;
65283347fa09STejun Heo 	struct worker_pool *pool;
65293347fa09STejun Heo 	int cpu, bkt;
65303347fa09STejun Heo 
65312186d9f9STejun Heo 	/*
65322186d9f9STejun Heo 	 * It'd be simpler to initialize NUMA in workqueue_init_early() but
65332186d9f9STejun Heo 	 * CPU to node mapping may not be available that early on some
65342186d9f9STejun Heo 	 * archs such as power and arm64.  As per-cpu pools created
65352186d9f9STejun Heo 	 * previously could be missing node hint and unbound pools NUMA
65362186d9f9STejun Heo 	 * affinity, fix them up.
653740c17f75STejun Heo 	 *
653840c17f75STejun Heo 	 * Also, while iterating workqueues, create rescuers if requested.
65392186d9f9STejun Heo 	 */
65402186d9f9STejun Heo 	wq_numa_init();
65412186d9f9STejun Heo 
65422186d9f9STejun Heo 	mutex_lock(&wq_pool_mutex);
65432186d9f9STejun Heo 
65442186d9f9STejun Heo 	for_each_possible_cpu(cpu) {
65452186d9f9STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
65462186d9f9STejun Heo 			pool->node = cpu_to_node(cpu);
65472186d9f9STejun Heo 		}
65482186d9f9STejun Heo 	}
65492186d9f9STejun Heo 
655040c17f75STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
65512186d9f9STejun Heo 		wq_update_unbound_numa(wq, smp_processor_id(), true);
655240c17f75STejun Heo 		WARN(init_rescuer(wq),
655340c17f75STejun Heo 		     "workqueue: failed to create early rescuer for %s",
655440c17f75STejun Heo 		     wq->name);
655540c17f75STejun Heo 	}
65562186d9f9STejun Heo 
65572186d9f9STejun Heo 	mutex_unlock(&wq_pool_mutex);
65582186d9f9STejun Heo 
65593347fa09STejun Heo 	/* create the initial workers */
65603347fa09STejun Heo 	for_each_online_cpu(cpu) {
65613347fa09STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
65623347fa09STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
65633347fa09STejun Heo 			BUG_ON(!create_worker(pool));
65643347fa09STejun Heo 		}
65653347fa09STejun Heo 	}
65663347fa09STejun Heo 
65673347fa09STejun Heo 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
65683347fa09STejun Heo 		BUG_ON(!create_worker(pool));
65693347fa09STejun Heo 
65703347fa09STejun Heo 	wq_online = true;
657182607adcSTejun Heo 	wq_watchdog_init();
65721da177e4SLinus Torvalds }
6573c4f135d6STetsuo Handa 
6574*20bdedafSTetsuo Handa void __warn_flushing_systemwide_wq(void)
6575*20bdedafSTetsuo Handa {
6576*20bdedafSTetsuo Handa 	pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
6577*20bdedafSTetsuo Handa 	dump_stack();
6578*20bdedafSTetsuo Handa }
6579c4f135d6STetsuo Handa EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
6580