xref: /linux-6.15/kernel/workqueue.c (revision 0f36ee24)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
3c54fce6eSTejun Heo  * kernel/workqueue.c - generic async execution with shared worker pool
41da177e4SLinus Torvalds  *
5c54fce6eSTejun Heo  * Copyright (C) 2002		Ingo Molnar
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  *   Derived from the taskqueue/keventd code by:
81da177e4SLinus Torvalds  *     David Woodhouse <[email protected]>
9e1f8e874SFrancois Cami  *     Andrew Morton
101da177e4SLinus Torvalds  *     Kai Petzke <[email protected]>
111da177e4SLinus Torvalds  *     Theodore Ts'o <[email protected]>
1289ada679SChristoph Lameter  *
13cde53535SChristoph Lameter  * Made to use alloc_percpu by Christoph Lameter.
14c54fce6eSTejun Heo  *
15c54fce6eSTejun Heo  * Copyright (C) 2010		SUSE Linux Products GmbH
16c54fce6eSTejun Heo  * Copyright (C) 2010		Tejun Heo <[email protected]>
17c54fce6eSTejun Heo  *
18c54fce6eSTejun Heo  * This is the generic async execution mechanism.  Work items as are
19c54fce6eSTejun Heo  * executed in process context.  The worker pool is shared and
20b11895c4SLibin  * automatically managed.  There are two worker pools for each CPU (one for
21b11895c4SLibin  * normal work items and the other for high priority ones) and some extra
22b11895c4SLibin  * pools for workqueues which are not bound to any specific CPU - the
23b11895c4SLibin  * number of these backing pools is dynamic.
24c54fce6eSTejun Heo  *
259a261491SBenjamin Peterson  * Please read Documentation/core-api/workqueue.rst for details.
261da177e4SLinus Torvalds  */
271da177e4SLinus Torvalds 
289984de1aSPaul Gortmaker #include <linux/export.h>
291da177e4SLinus Torvalds #include <linux/kernel.h>
301da177e4SLinus Torvalds #include <linux/sched.h>
311da177e4SLinus Torvalds #include <linux/init.h>
321da177e4SLinus Torvalds #include <linux/signal.h>
331da177e4SLinus Torvalds #include <linux/completion.h>
341da177e4SLinus Torvalds #include <linux/workqueue.h>
351da177e4SLinus Torvalds #include <linux/slab.h>
361da177e4SLinus Torvalds #include <linux/cpu.h>
371da177e4SLinus Torvalds #include <linux/notifier.h>
381da177e4SLinus Torvalds #include <linux/kthread.h>
391fa44ecaSJames Bottomley #include <linux/hardirq.h>
4046934023SChristoph Lameter #include <linux/mempolicy.h>
41341a5958SRafael J. Wysocki #include <linux/freezer.h>
42d5abe669SPeter Zijlstra #include <linux/debug_locks.h>
434e6045f1SJohannes Berg #include <linux/lockdep.h>
44c34056a3STejun Heo #include <linux/idr.h>
4529c91e99STejun Heo #include <linux/jhash.h>
4642f8570fSSasha Levin #include <linux/hashtable.h>
4776af4d93STejun Heo #include <linux/rculist.h>
48bce90380STejun Heo #include <linux/nodemask.h>
494c16bd32STejun Heo #include <linux/moduleparam.h>
503d1cb205STejun Heo #include <linux/uaccess.h>
51c98a9805STal Shorer #include <linux/sched/isolation.h>
52cd2440d6SPetr Mladek #include <linux/sched/debug.h>
5362635ea8SSergey Senozhatsky #include <linux/nmi.h>
54940d71c6SSergey Senozhatsky #include <linux/kvm_para.h>
55aa6fde93STejun Heo #include <linux/delay.h>
56e22bee78STejun Heo 
57ea138446STejun Heo #include "workqueue_internal.h"
581da177e4SLinus Torvalds 
59c8e55f36STejun Heo enum {
60bc2ae0f5STejun Heo 	/*
6124647570STejun Heo 	 * worker_pool flags
62bc2ae0f5STejun Heo 	 *
6324647570STejun Heo 	 * A bound pool is either associated or disassociated with its CPU.
64bc2ae0f5STejun Heo 	 * While associated (!DISASSOCIATED), all workers are bound to the
65bc2ae0f5STejun Heo 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
66bc2ae0f5STejun Heo 	 * is in effect.
67bc2ae0f5STejun Heo 	 *
68bc2ae0f5STejun Heo 	 * While DISASSOCIATED, the cpu may be offline and all workers have
69bc2ae0f5STejun Heo 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
7024647570STejun Heo 	 * be executing on any CPU.  The pool behaves as an unbound one.
71bc2ae0f5STejun Heo 	 *
72bc3a1afcSTejun Heo 	 * Note that DISASSOCIATED should be flipped only while holding
731258fae7STejun Heo 	 * wq_pool_attach_mutex to avoid changing binding state while
744736cbf7SLai Jiangshan 	 * worker_attach_to_pool() is in progress.
75bc2ae0f5STejun Heo 	 */
76692b4825STejun Heo 	POOL_MANAGER_ACTIVE	= 1 << 0,	/* being managed */
7724647570STejun Heo 	POOL_DISASSOCIATED	= 1 << 2,	/* cpu can't serve workers */
78db7bccf4STejun Heo 
79c8e55f36STejun Heo 	/* worker flags */
80c8e55f36STejun Heo 	WORKER_DIE		= 1 << 1,	/* die die die */
81c8e55f36STejun Heo 	WORKER_IDLE		= 1 << 2,	/* is idle */
82e22bee78STejun Heo 	WORKER_PREP		= 1 << 3,	/* preparing to run works */
83fb0e7bebSTejun Heo 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
84f3421797STejun Heo 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
85a9ab775bSTejun Heo 	WORKER_REBOUND		= 1 << 8,	/* worker was rebound */
86e22bee78STejun Heo 
87a9ab775bSTejun Heo 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_CPU_INTENSIVE |
88a9ab775bSTejun Heo 				  WORKER_UNBOUND | WORKER_REBOUND,
89db7bccf4STejun Heo 
90e34cdddbSTejun Heo 	NR_STD_WORKER_POOLS	= 2,		/* # standard pools per cpu */
914ce62e9eSTejun Heo 
9229c91e99STejun Heo 	UNBOUND_POOL_HASH_ORDER	= 6,		/* hashed by pool->attrs */
93c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
94db7bccf4STejun Heo 
95e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
96e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
97e22bee78STejun Heo 
983233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
993233cdbdSTejun Heo 						/* call for help after 10ms
1003233cdbdSTejun Heo 						   (min two ticks) */
101e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
102e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
1031da177e4SLinus Torvalds 
1041da177e4SLinus Torvalds 	/*
105e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
1068698a745SDongsheng Yang 	 * all cpus.  Give MIN_NICE.
107e22bee78STejun Heo 	 */
1088698a745SDongsheng Yang 	RESCUER_NICE_LEVEL	= MIN_NICE,
1098698a745SDongsheng Yang 	HIGHPRI_NICE_LEVEL	= MIN_NICE,
110ecf6881fSTejun Heo 
111ecf6881fSTejun Heo 	WQ_NAME_LEN		= 24,
112c8e55f36STejun Heo };
113c8e55f36STejun Heo 
1141da177e4SLinus Torvalds /*
1154690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1164690c4abSTejun Heo  *
117e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
118e41e704bSTejun Heo  *    everyone else.
1194690c4abSTejun Heo  *
120e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
121e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
122e22bee78STejun Heo  *
123d565ed63STejun Heo  * L: pool->lock protected.  Access with pool->lock held.
1244690c4abSTejun Heo  *
125bdf8b9bfSTejun Heo  * K: Only modified by worker while holding pool->lock. Can be safely read by
126bdf8b9bfSTejun Heo  *    self, while holding pool->lock or from IRQ context if %current is the
127bdf8b9bfSTejun Heo  *    kworker.
128bdf8b9bfSTejun Heo  *
129bdf8b9bfSTejun Heo  * S: Only modified by worker self.
130bdf8b9bfSTejun Heo  *
1311258fae7STejun Heo  * A: wq_pool_attach_mutex protected.
132822d8405STejun Heo  *
13368e13a67SLai Jiangshan  * PL: wq_pool_mutex protected.
13476af4d93STejun Heo  *
13524acfb71SThomas Gleixner  * PR: wq_pool_mutex protected for writes.  RCU protected for reads.
1365bcab335STejun Heo  *
1375b95e1afSLai Jiangshan  * PW: wq_pool_mutex and wq->mutex protected for writes.  Either for reads.
1385b95e1afSLai Jiangshan  *
1395b95e1afSLai Jiangshan  * PWR: wq_pool_mutex and wq->mutex protected for writes.  Either or
14024acfb71SThomas Gleixner  *      RCU for reads.
1415b95e1afSLai Jiangshan  *
1423c25a55dSLai Jiangshan  * WQ: wq->mutex protected.
1433c25a55dSLai Jiangshan  *
14424acfb71SThomas Gleixner  * WR: wq->mutex protected for writes.  RCU protected for reads.
1452e109a28STejun Heo  *
1462e109a28STejun Heo  * MD: wq_mayday_lock protected.
147cd2440d6SPetr Mladek  *
148cd2440d6SPetr Mladek  * WD: Used internally by the watchdog.
1494690c4abSTejun Heo  */
1504690c4abSTejun Heo 
1512eaebdb3STejun Heo /* struct worker is defined in workqueue_internal.h */
152c34056a3STejun Heo 
153bd7bdd43STejun Heo struct worker_pool {
154a9b8a985SSebastian Andrzej Siewior 	raw_spinlock_t		lock;		/* the pool lock */
155d84ff051STejun Heo 	int			cpu;		/* I: the associated cpu */
156f3f90ad4STejun Heo 	int			node;		/* I: the associated node ID */
1579daf9e67STejun Heo 	int			id;		/* I: pool ID */
158bc8b50c2STejun Heo 	unsigned int		flags;		/* L: flags */
159bd7bdd43STejun Heo 
16082607adcSTejun Heo 	unsigned long		watchdog_ts;	/* L: watchdog timestamp */
161cd2440d6SPetr Mladek 	bool			cpu_stall;	/* WD: stalled cpu bound pool */
16282607adcSTejun Heo 
163bc35f7efSLai Jiangshan 	/*
164bc35f7efSLai Jiangshan 	 * The counter is incremented in a process context on the associated CPU
165bc35f7efSLai Jiangshan 	 * w/ preemption disabled, and decremented or reset in the same context
166bc35f7efSLai Jiangshan 	 * but w/ pool->lock held. The readers grab pool->lock and are
167bc35f7efSLai Jiangshan 	 * guaranteed to see if the counter reached zero.
168bc35f7efSLai Jiangshan 	 */
169bc35f7efSLai Jiangshan 	int			nr_running;
17084f91c62SLai Jiangshan 
171bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
172ea1abd61SLai Jiangshan 
1735826cc8fSLai Jiangshan 	int			nr_workers;	/* L: total number of workers */
1745826cc8fSLai Jiangshan 	int			nr_idle;	/* L: currently idle workers */
175bd7bdd43STejun Heo 
1762c1f1a91SLai Jiangshan 	struct list_head	idle_list;	/* L: list of idle workers */
177bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
1783f959aa3SValentin Schneider 	struct work_struct      idle_cull_work; /* L: worker idle cleanup */
1793f959aa3SValentin Schneider 
180bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	  /* L: SOS timer for workers */
181bd7bdd43STejun Heo 
182c5aa87bbSTejun Heo 	/* a workers is either on busy_hash or idle_list, or the manager */
183c9e7cf27STejun Heo 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
184c9e7cf27STejun Heo 						/* L: hash of busy workers */
185c9e7cf27STejun Heo 
1862607d7a6STejun Heo 	struct worker		*manager;	/* L: purely informational */
18792f9c5c4SLai Jiangshan 	struct list_head	workers;	/* A: attached workers */
188e02b9312SValentin Schneider 	struct list_head        dying_workers;  /* A: workers about to die */
18960f5a4bcSLai Jiangshan 	struct completion	*detach_completion; /* all workers detached */
190e19e397aSTejun Heo 
1917cda9aaeSLai Jiangshan 	struct ida		worker_ida;	/* worker IDs for task name */
192e19e397aSTejun Heo 
1937a4e344cSTejun Heo 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
19468e13a67SLai Jiangshan 	struct hlist_node	hash_node;	/* PL: unbound_pool_hash node */
19568e13a67SLai Jiangshan 	int			refcnt;		/* PL: refcnt for unbound pools */
1967a4e344cSTejun Heo 
197e19e397aSTejun Heo 	/*
19824acfb71SThomas Gleixner 	 * Destruction of pool is RCU protected to allow dereferences
19929c91e99STejun Heo 	 * from get_work_pool().
20029c91e99STejun Heo 	 */
20129c91e99STejun Heo 	struct rcu_head		rcu;
20284f91c62SLai Jiangshan };
2038b03ae3cSTejun Heo 
2048b03ae3cSTejun Heo /*
205725e8ec5STejun Heo  * Per-pool_workqueue statistics. These can be monitored using
206725e8ec5STejun Heo  * tools/workqueue/wq_monitor.py.
207725e8ec5STejun Heo  */
208725e8ec5STejun Heo enum pool_workqueue_stats {
209725e8ec5STejun Heo 	PWQ_STAT_STARTED,	/* work items started execution */
210725e8ec5STejun Heo 	PWQ_STAT_COMPLETED,	/* work items completed execution */
2118a1dd1e5STejun Heo 	PWQ_STAT_CPU_TIME,	/* total CPU time consumed */
212616db877STejun Heo 	PWQ_STAT_CPU_INTENSIVE,	/* wq_cpu_intensive_thresh_us violations */
213725e8ec5STejun Heo 	PWQ_STAT_CM_WAKEUP,	/* concurrency-management worker wakeups */
214725e8ec5STejun Heo 	PWQ_STAT_MAYDAY,	/* maydays to rescuer */
215725e8ec5STejun Heo 	PWQ_STAT_RESCUED,	/* linked work items executed by rescuer */
216725e8ec5STejun Heo 
217725e8ec5STejun Heo 	PWQ_NR_STATS,
218725e8ec5STejun Heo };
219725e8ec5STejun Heo 
220725e8ec5STejun Heo /*
221112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
222112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
223112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
224112202d9STejun Heo  * number of flag bits.
2251da177e4SLinus Torvalds  */
226112202d9STejun Heo struct pool_workqueue {
227bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
2284690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
22973f53c4aSTejun Heo 	int			work_color;	/* L: current color */
23073f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
2318864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
23273f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
23373f53c4aSTejun Heo 						/* L: nr of in_flight works */
234018f3a13SLai Jiangshan 
235018f3a13SLai Jiangshan 	/*
236018f3a13SLai Jiangshan 	 * nr_active management and WORK_STRUCT_INACTIVE:
237018f3a13SLai Jiangshan 	 *
238018f3a13SLai Jiangshan 	 * When pwq->nr_active >= max_active, new work item is queued to
239018f3a13SLai Jiangshan 	 * pwq->inactive_works instead of pool->worklist and marked with
240018f3a13SLai Jiangshan 	 * WORK_STRUCT_INACTIVE.
241018f3a13SLai Jiangshan 	 *
242018f3a13SLai Jiangshan 	 * All work items marked with WORK_STRUCT_INACTIVE do not participate
243018f3a13SLai Jiangshan 	 * in pwq->nr_active and all work items in pwq->inactive_works are
244018f3a13SLai Jiangshan 	 * marked with WORK_STRUCT_INACTIVE.  But not all WORK_STRUCT_INACTIVE
245018f3a13SLai Jiangshan 	 * work items are in pwq->inactive_works.  Some of them are ready to
246018f3a13SLai Jiangshan 	 * run in pool->worklist or worker->scheduled.  Those work itmes are
247018f3a13SLai Jiangshan 	 * only struct wq_barrier which is used for flush_work() and should
248018f3a13SLai Jiangshan 	 * not participate in pwq->nr_active.  For non-barrier work item, it
249018f3a13SLai Jiangshan 	 * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
250018f3a13SLai Jiangshan 	 */
2511e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
252a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
253f97a4a1aSLai Jiangshan 	struct list_head	inactive_works;	/* L: inactive works */
2543c25a55dSLai Jiangshan 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
2552e109a28STejun Heo 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
2568864b4e5STejun Heo 
257725e8ec5STejun Heo 	u64			stats[PWQ_NR_STATS];
258725e8ec5STejun Heo 
2598864b4e5STejun Heo 	/*
260967b494eSTejun Heo 	 * Release of unbound pwq is punted to a kthread_worker. See put_pwq()
261687a9aa5STejun Heo 	 * and pwq_release_workfn() for details. pool_workqueue itself is also
262687a9aa5STejun Heo 	 * RCU protected so that the first pwq can be determined without
263967b494eSTejun Heo 	 * grabbing wq->mutex.
2648864b4e5STejun Heo 	 */
265687a9aa5STejun Heo 	struct kthread_work	release_work;
2668864b4e5STejun Heo 	struct rcu_head		rcu;
267e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2681da177e4SLinus Torvalds 
2691da177e4SLinus Torvalds /*
27073f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
27173f53c4aSTejun Heo  */
27273f53c4aSTejun Heo struct wq_flusher {
2733c25a55dSLai Jiangshan 	struct list_head	list;		/* WQ: list of flushers */
2743c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: flush color waiting for */
27573f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
27673f53c4aSTejun Heo };
2771da177e4SLinus Torvalds 
278226223abSTejun Heo struct wq_device;
279226223abSTejun Heo 
28073f53c4aSTejun Heo /*
281c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
282c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
2831da177e4SLinus Torvalds  */
2841da177e4SLinus Torvalds struct workqueue_struct {
2853c25a55dSLai Jiangshan 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
286e2dca7adSTejun Heo 	struct list_head	list;		/* PR: list of all workqueues */
28773f53c4aSTejun Heo 
2883c25a55dSLai Jiangshan 	struct mutex		mutex;		/* protects this wq */
2893c25a55dSLai Jiangshan 	int			work_color;	/* WQ: current work color */
2903c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: current flush color */
291112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
2923c25a55dSLai Jiangshan 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
2933c25a55dSLai Jiangshan 	struct list_head	flusher_queue;	/* WQ: flush waiters */
2943c25a55dSLai Jiangshan 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
29573f53c4aSTejun Heo 
2962e109a28STejun Heo 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
29730ae2fc0STejun Heo 	struct worker		*rescuer;	/* MD: rescue worker */
298e22bee78STejun Heo 
29987fc741eSLai Jiangshan 	int			nr_drainers;	/* WQ: drain in progress */
300a357fc03SLai Jiangshan 	int			saved_max_active; /* WQ: saved pwq max_active */
301226223abSTejun Heo 
3025b95e1afSLai Jiangshan 	struct workqueue_attrs	*unbound_attrs;	/* PW: only for unbound wqs */
3035b95e1afSLai Jiangshan 	struct pool_workqueue	*dfl_pwq;	/* PW: only for unbound wqs */
3046029a918STejun Heo 
305226223abSTejun Heo #ifdef CONFIG_SYSFS
306226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
307226223abSTejun Heo #endif
3084e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
309669de8bdSBart Van Assche 	char			*lock_name;
310669de8bdSBart Van Assche 	struct lock_class_key	key;
3114e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
3124e6045f1SJohannes Berg #endif
313ecf6881fSTejun Heo 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
3142728fd2fSTejun Heo 
315e2dca7adSTejun Heo 	/*
31624acfb71SThomas Gleixner 	 * Destruction of workqueue_struct is RCU protected to allow walking
31724acfb71SThomas Gleixner 	 * the workqueues list without grabbing wq_pool_mutex.
318e2dca7adSTejun Heo 	 * This is used to dump all workqueues from sysrq.
319e2dca7adSTejun Heo 	 */
320e2dca7adSTejun Heo 	struct rcu_head		rcu;
321e2dca7adSTejun Heo 
3222728fd2fSTejun Heo 	/* hot fields used during command issue, aligned to cacheline */
3232728fd2fSTejun Heo 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
324636b927eSTejun Heo 	struct pool_workqueue __percpu __rcu **cpu_pwq; /* I: per-cpu pwqs */
3251da177e4SLinus Torvalds };
3261da177e4SLinus Torvalds 
327e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
328e904e6c2STejun Heo 
329fef59c9cSTejun Heo static cpumask_var_t *wq_pod_cpus;	/* possible CPUs of each node */
330bce90380STejun Heo 
331616db877STejun Heo /*
332616db877STejun Heo  * Per-cpu work items which run for longer than the following threshold are
333616db877STejun Heo  * automatically considered CPU intensive and excluded from concurrency
334616db877STejun Heo  * management to prevent them from noticeably delaying other per-cpu work items.
335aa6fde93STejun Heo  * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
336aa6fde93STejun Heo  * The actual value is initialized in wq_cpu_intensive_thresh_init().
337616db877STejun Heo  */
338aa6fde93STejun Heo static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
339616db877STejun Heo module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
340616db877STejun Heo 
341cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
342552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
343cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
344cee22a15SViresh Kumar 
345863b710bSTejun Heo static bool wq_online;			/* can kworkers be created yet? */
3463347fa09STejun Heo 
347fef59c9cSTejun Heo static bool wq_pod_enabled;		/* unbound CPU pod affinity enabled */
348bce90380STejun Heo 
349fef59c9cSTejun Heo /* buf for wq_update_unbound_pod_attrs(), protected by CPU hotplug exclusion */
350fef59c9cSTejun Heo static struct workqueue_attrs *wq_update_pod_attrs_buf;
351*0f36ee24STejun Heo static cpumask_var_t wq_update_pod_cpumask_buf;
3524c16bd32STejun Heo 
35368e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
3541258fae7STejun Heo static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
355a9b8a985SSebastian Andrzej Siewior static DEFINE_RAW_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
356d8bb65abSSebastian Andrzej Siewior /* wait for manager to go away */
357d8bb65abSSebastian Andrzej Siewior static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
3585bcab335STejun Heo 
359e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
36068e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
3617d19c5ceSTejun Heo 
36299c621efSLai Jiangshan /* PL&A: allowable cpus for unbound wqs and work items */
363ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
364ef557180SMike Galbraith 
365ace3c549Stiozhang /* for further constrain wq_unbound_cpumask by cmdline parameter*/
366ace3c549Stiozhang static struct cpumask wq_cmdline_cpumask __initdata;
367ace3c549Stiozhang 
368ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
369ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
370b05a7928SFrederic Weisbecker 
371f303fccbSTejun Heo /*
372f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
373f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
374f303fccbSTejun Heo  * to uncover usages which depend on it.
375f303fccbSTejun Heo  */
376f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
377f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
378f303fccbSTejun Heo #else
379f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
380f303fccbSTejun Heo #endif
381f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
382f303fccbSTejun Heo 
3837d19c5ceSTejun Heo /* the per-cpu worker pools */
38425528213SPeter Zijlstra static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
3857d19c5ceSTejun Heo 
38668e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
3877d19c5ceSTejun Heo 
38868e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
38929c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
39029c91e99STejun Heo 
391c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
39229c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
39329c91e99STejun Heo 
3948a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
3958a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
3968a2b7538STejun Heo 
397967b494eSTejun Heo /*
398967b494eSTejun Heo  * I: kthread_worker to release pwq's. pwq release needs to be bounced to a
399967b494eSTejun Heo  * process context while holding a pool lock. Bounce to a dedicated kthread
400967b494eSTejun Heo  * worker to avoid A-A deadlocks.
401967b494eSTejun Heo  */
402967b494eSTejun Heo static struct kthread_worker *pwq_release_worker;
403967b494eSTejun Heo 
404d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
405ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
406044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
4071aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
408044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
409d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
410044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
411f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
412044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
41324d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
4140668106cSViresh Kumar struct workqueue_struct *system_power_efficient_wq __read_mostly;
4150668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
4160668106cSViresh Kumar struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
4170668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
418d320c038STejun Heo 
4197d19c5ceSTejun Heo static int worker_thread(void *__worker);
4206ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
421c29eb853STejun Heo static void show_pwq(struct pool_workqueue *pwq);
42255df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool);
4237d19c5ceSTejun Heo 
42497bd2347STejun Heo #define CREATE_TRACE_POINTS
42597bd2347STejun Heo #include <trace/events/workqueue.h>
42697bd2347STejun Heo 
42768e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
42824acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
429f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
43024acfb71SThomas Gleixner 			 "RCU or wq_pool_mutex should be held")
4315bcab335STejun Heo 
4325b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
43324acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
434f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
435f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
43624acfb71SThomas Gleixner 			 "RCU, wq->mutex or wq_pool_mutex should be held")
4375b95e1afSLai Jiangshan 
438f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
439f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
440f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
4417a62c2c8STejun Heo 	     (pool)++)
4424ce62e9eSTejun Heo 
44349e3cf44STejun Heo /**
44417116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
44517116969STejun Heo  * @pool: iteration cursor
446611c92a0STejun Heo  * @pi: integer used for iteration
447fa1b54e6STejun Heo  *
44824acfb71SThomas Gleixner  * This must be called either with wq_pool_mutex held or RCU read
44968e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
45068e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
451fa1b54e6STejun Heo  *
452fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
453fa1b54e6STejun Heo  * ignored.
45417116969STejun Heo  */
455611c92a0STejun Heo #define for_each_pool(pool, pi)						\
456611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
45768e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
458fa1b54e6STejun Heo 		else
45917116969STejun Heo 
46017116969STejun Heo /**
461822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
462822d8405STejun Heo  * @worker: iteration cursor
463822d8405STejun Heo  * @pool: worker_pool to iterate workers of
464822d8405STejun Heo  *
4651258fae7STejun Heo  * This must be called with wq_pool_attach_mutex.
466822d8405STejun Heo  *
467822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
468822d8405STejun Heo  * ignored.
469822d8405STejun Heo  */
470da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
471da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
4721258fae7STejun Heo 		if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
473822d8405STejun Heo 		else
474822d8405STejun Heo 
475822d8405STejun Heo /**
47649e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
47749e3cf44STejun Heo  * @pwq: iteration cursor
47849e3cf44STejun Heo  * @wq: the target workqueue
47976af4d93STejun Heo  *
48024acfb71SThomas Gleixner  * This must be called either with wq->mutex held or RCU read locked.
481794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
482794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
48376af4d93STejun Heo  *
48476af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
48576af4d93STejun Heo  * ignored.
48649e3cf44STejun Heo  */
48749e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
48849e9d1a9SSebastian Andrzej Siewior 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node,		\
4895a644662SJoel Fernandes (Google) 				 lockdep_is_held(&(wq->mutex)))
490f3421797STejun Heo 
491dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
492dc186ad7SThomas Gleixner 
493f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr;
494dc186ad7SThomas Gleixner 
49599777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
49699777288SStanislaw Gruszka {
49799777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
49899777288SStanislaw Gruszka }
49999777288SStanislaw Gruszka 
500b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
501b9fdac7fSDu, Changbin {
502b9fdac7fSDu, Changbin 	struct work_struct *work = addr;
503b9fdac7fSDu, Changbin 
504b9fdac7fSDu, Changbin 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
505b9fdac7fSDu, Changbin }
506b9fdac7fSDu, Changbin 
507dc186ad7SThomas Gleixner /*
508dc186ad7SThomas Gleixner  * fixup_init is called when:
509dc186ad7SThomas Gleixner  * - an active object is initialized
510dc186ad7SThomas Gleixner  */
51102a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
512dc186ad7SThomas Gleixner {
513dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
514dc186ad7SThomas Gleixner 
515dc186ad7SThomas Gleixner 	switch (state) {
516dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
517dc186ad7SThomas Gleixner 		cancel_work_sync(work);
518dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
51902a982a6SDu, Changbin 		return true;
520dc186ad7SThomas Gleixner 	default:
52102a982a6SDu, Changbin 		return false;
522dc186ad7SThomas Gleixner 	}
523dc186ad7SThomas Gleixner }
524dc186ad7SThomas Gleixner 
525dc186ad7SThomas Gleixner /*
526dc186ad7SThomas Gleixner  * fixup_free is called when:
527dc186ad7SThomas Gleixner  * - an active object is freed
528dc186ad7SThomas Gleixner  */
52902a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
530dc186ad7SThomas Gleixner {
531dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
532dc186ad7SThomas Gleixner 
533dc186ad7SThomas Gleixner 	switch (state) {
534dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
535dc186ad7SThomas Gleixner 		cancel_work_sync(work);
536dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
53702a982a6SDu, Changbin 		return true;
538dc186ad7SThomas Gleixner 	default:
53902a982a6SDu, Changbin 		return false;
540dc186ad7SThomas Gleixner 	}
541dc186ad7SThomas Gleixner }
542dc186ad7SThomas Gleixner 
543f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr = {
544dc186ad7SThomas Gleixner 	.name		= "work_struct",
54599777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
546b9fdac7fSDu, Changbin 	.is_static_object = work_is_static_object,
547dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
548dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
549dc186ad7SThomas Gleixner };
550dc186ad7SThomas Gleixner 
551dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
552dc186ad7SThomas Gleixner {
553dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
554dc186ad7SThomas Gleixner }
555dc186ad7SThomas Gleixner 
556dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
557dc186ad7SThomas Gleixner {
558dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
559dc186ad7SThomas Gleixner }
560dc186ad7SThomas Gleixner 
561dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
562dc186ad7SThomas Gleixner {
563dc186ad7SThomas Gleixner 	if (onstack)
564dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
565dc186ad7SThomas Gleixner 	else
566dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
567dc186ad7SThomas Gleixner }
568dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
569dc186ad7SThomas Gleixner 
570dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
571dc186ad7SThomas Gleixner {
572dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
573dc186ad7SThomas Gleixner }
574dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
575dc186ad7SThomas Gleixner 
576ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
577ea2e64f2SThomas Gleixner {
578ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
579ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
580ea2e64f2SThomas Gleixner }
581ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
582ea2e64f2SThomas Gleixner 
583dc186ad7SThomas Gleixner #else
584dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
585dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
586dc186ad7SThomas Gleixner #endif
587dc186ad7SThomas Gleixner 
5884e8b22bdSLi Bin /**
58967dc8325SCai Huoqing  * worker_pool_assign_id - allocate ID and assign it to @pool
5904e8b22bdSLi Bin  * @pool: the pool pointer of interest
5914e8b22bdSLi Bin  *
5924e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
5934e8b22bdSLi Bin  * successfully, -errno on failure.
5944e8b22bdSLi Bin  */
5959daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
5969daf9e67STejun Heo {
5979daf9e67STejun Heo 	int ret;
5989daf9e67STejun Heo 
59968e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
6005bcab335STejun Heo 
6014e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
6024e8b22bdSLi Bin 			GFP_KERNEL);
603229641a6STejun Heo 	if (ret >= 0) {
604e68035fbSTejun Heo 		pool->id = ret;
605229641a6STejun Heo 		return 0;
606229641a6STejun Heo 	}
6079daf9e67STejun Heo 	return ret;
6089daf9e67STejun Heo }
6099daf9e67STejun Heo 
61073f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
61173f53c4aSTejun Heo {
61273f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
61373f53c4aSTejun Heo }
61473f53c4aSTejun Heo 
615c4560c2cSLai Jiangshan static int get_work_color(unsigned long work_data)
61673f53c4aSTejun Heo {
617c4560c2cSLai Jiangshan 	return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
61873f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
61973f53c4aSTejun Heo }
62073f53c4aSTejun Heo 
62173f53c4aSTejun Heo static int work_next_color(int color)
62273f53c4aSTejun Heo {
62373f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
624a848e3b6SOleg Nesterov }
625a848e3b6SOleg Nesterov 
6264594bf15SDavid Howells /*
627112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
628112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
6297c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
6307a22ad75STejun Heo  *
631112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
632112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
633bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
634bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
6357a22ad75STejun Heo  *
636112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6377c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
638112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
6397c3eed5cSTejun Heo  * available only while the work item is queued.
640bbb68dfaSTejun Heo  *
641bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
642bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
643bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
644bbb68dfaSTejun Heo  * try to steal the PENDING bit.
6454594bf15SDavid Howells  */
6467a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6477a22ad75STejun Heo 				 unsigned long flags)
6487a22ad75STejun Heo {
6496183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
6507a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
6517a22ad75STejun Heo }
6527a22ad75STejun Heo 
653112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6544690c4abSTejun Heo 			 unsigned long extra_flags)
655365970a1SDavid Howells {
656112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
657112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
658365970a1SDavid Howells }
659365970a1SDavid Howells 
6604468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6614468a00fSLai Jiangshan 					   int pool_id)
6624468a00fSLai Jiangshan {
6634468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6644468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6654468a00fSLai Jiangshan }
6664468a00fSLai Jiangshan 
6677c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6687c3eed5cSTejun Heo 					    int pool_id)
6694d707b9fSOleg Nesterov {
67023657bb1STejun Heo 	/*
67123657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
67223657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
67323657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
67423657bb1STejun Heo 	 * owner.
67523657bb1STejun Heo 	 */
67623657bb1STejun Heo 	smp_wmb();
6777c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
678346c09f8SRoman Pen 	/*
679346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
680346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
681346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
6828bdc6201SLiu Song 	 * reordering can lead to a missed execution on attempt to queue
683346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
684346c09f8SRoman Pen 	 *
685346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
686346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
687346c09f8SRoman Pen 	 *
688346c09f8SRoman Pen 	 * 1  STORE event_indicated
689346c09f8SRoman Pen 	 * 2  queue_work_on() {
690346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
691346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
692346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
693346c09f8SRoman Pen 	 * 6                                 smp_mb()
694346c09f8SRoman Pen 	 * 7                               work->current_func() {
695346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
696346c09f8SRoman Pen 	 *				   }
697346c09f8SRoman Pen 	 *
698346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
699346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
700346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
701346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
702346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
703346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
704346c09f8SRoman Pen 	 * before actual STORE.
705346c09f8SRoman Pen 	 */
706346c09f8SRoman Pen 	smp_mb();
7074d707b9fSOleg Nesterov }
7084d707b9fSOleg Nesterov 
7097a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
710365970a1SDavid Howells {
7117c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
7127c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
7137a22ad75STejun Heo }
7147a22ad75STejun Heo 
715afa4bb77SLinus Torvalds static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
716afa4bb77SLinus Torvalds {
717afa4bb77SLinus Torvalds 	return (struct pool_workqueue *)(data & WORK_STRUCT_WQ_DATA_MASK);
718afa4bb77SLinus Torvalds }
719afa4bb77SLinus Torvalds 
720112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
7217a22ad75STejun Heo {
722e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7237a22ad75STejun Heo 
724112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
725afa4bb77SLinus Torvalds 		return work_struct_pwq(data);
726e120153dSTejun Heo 	else
727e120153dSTejun Heo 		return NULL;
7287a22ad75STejun Heo }
7297a22ad75STejun Heo 
7307c3eed5cSTejun Heo /**
7317c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
7327c3eed5cSTejun Heo  * @work: the work item of interest
7337c3eed5cSTejun Heo  *
73468e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
73524acfb71SThomas Gleixner  * access under RCU read lock.  As such, this function should be
73624acfb71SThomas Gleixner  * called under wq_pool_mutex or inside of a rcu_read_lock() region.
737fa1b54e6STejun Heo  *
738fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
739fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
740fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
741fa1b54e6STejun Heo  * returned pool is and stays online.
742d185af30SYacine Belkadi  *
743d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
7447c3eed5cSTejun Heo  */
7457c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
7467a22ad75STejun Heo {
747e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7487c3eed5cSTejun Heo 	int pool_id;
7497a22ad75STejun Heo 
75068e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
751fa1b54e6STejun Heo 
752112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
753afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool;
7547a22ad75STejun Heo 
7557c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
7567c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
7577a22ad75STejun Heo 		return NULL;
7587a22ad75STejun Heo 
759fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
7607c3eed5cSTejun Heo }
7617c3eed5cSTejun Heo 
7627c3eed5cSTejun Heo /**
7637c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
7647c3eed5cSTejun Heo  * @work: the work item of interest
7657c3eed5cSTejun Heo  *
766d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
7677c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
7687c3eed5cSTejun Heo  */
7697c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
7707c3eed5cSTejun Heo {
77154d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
7727c3eed5cSTejun Heo 
773112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
774afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool->id;
77554d5b7d0SLai Jiangshan 
77654d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
7777c3eed5cSTejun Heo }
7787c3eed5cSTejun Heo 
779bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
780bbb68dfaSTejun Heo {
7817c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
782bbb68dfaSTejun Heo 
7837c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
7847c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
785bbb68dfaSTejun Heo }
786bbb68dfaSTejun Heo 
787bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
788bbb68dfaSTejun Heo {
789bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
790bbb68dfaSTejun Heo 
791112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
792bbb68dfaSTejun Heo }
793bbb68dfaSTejun Heo 
794e22bee78STejun Heo /*
7953270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
7963270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
797d565ed63STejun Heo  * they're being called with pool->lock held.
798e22bee78STejun Heo  */
799e22bee78STejun Heo 
80063d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
801649027d7STejun Heo {
802bc35f7efSLai Jiangshan 	return !pool->nr_running;
803649027d7STejun Heo }
804649027d7STejun Heo 
805e22bee78STejun Heo /*
806e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
807e22bee78STejun Heo  * running workers.
808974271c4STejun Heo  *
809974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
810706026c2STejun Heo  * function will always return %true for unbound pools as long as the
811974271c4STejun Heo  * worklist isn't empty.
812e22bee78STejun Heo  */
81363d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
814e22bee78STejun Heo {
81563d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
816e22bee78STejun Heo }
817e22bee78STejun Heo 
818e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
81963d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
820e22bee78STejun Heo {
82163d95a91STejun Heo 	return pool->nr_idle;
822e22bee78STejun Heo }
823e22bee78STejun Heo 
824e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
82563d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
826e22bee78STejun Heo {
827bc35f7efSLai Jiangshan 	return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
828e22bee78STejun Heo }
829e22bee78STejun Heo 
830e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
83163d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
832e22bee78STejun Heo {
83363d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
834e22bee78STejun Heo }
835e22bee78STejun Heo 
836e22bee78STejun Heo /* Do we have too many workers and should some go away? */
83763d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
838e22bee78STejun Heo {
839692b4825STejun Heo 	bool managing = pool->flags & POOL_MANAGER_ACTIVE;
84063d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
84163d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
842e22bee78STejun Heo 
843e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
844e22bee78STejun Heo }
845e22bee78STejun Heo 
8464690c4abSTejun Heo /**
847e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
848cb444766STejun Heo  * @worker: self
849d302f017STejun Heo  * @flags: flags to set
850d302f017STejun Heo  *
851228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
852d302f017STejun Heo  */
853228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
854d302f017STejun Heo {
855bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
856e22bee78STejun Heo 
857bc8b50c2STejun Heo 	lockdep_assert_held(&pool->lock);
858cb444766STejun Heo 
859228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
860e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
861e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
862bc35f7efSLai Jiangshan 		pool->nr_running--;
863e22bee78STejun Heo 	}
864e22bee78STejun Heo 
865d302f017STejun Heo 	worker->flags |= flags;
866d302f017STejun Heo }
867d302f017STejun Heo 
868d302f017STejun Heo /**
869e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
870cb444766STejun Heo  * @worker: self
871d302f017STejun Heo  * @flags: flags to clear
872d302f017STejun Heo  *
873e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
874d302f017STejun Heo  */
875d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
876d302f017STejun Heo {
87763d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
878e22bee78STejun Heo 	unsigned int oflags = worker->flags;
879e22bee78STejun Heo 
880bc8b50c2STejun Heo 	lockdep_assert_held(&pool->lock);
881cb444766STejun Heo 
882d302f017STejun Heo 	worker->flags &= ~flags;
883e22bee78STejun Heo 
88442c025f3STejun Heo 	/*
88542c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
88642c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
88742c025f3STejun Heo 	 * of multiple flags, not a single flag.
88842c025f3STejun Heo 	 */
889e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
890e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
891bc35f7efSLai Jiangshan 			pool->nr_running++;
892d302f017STejun Heo }
893d302f017STejun Heo 
894797e8345STejun Heo /* Return the first idle worker.  Called with pool->lock held. */
895797e8345STejun Heo static struct worker *first_idle_worker(struct worker_pool *pool)
896797e8345STejun Heo {
897797e8345STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
898797e8345STejun Heo 		return NULL;
899797e8345STejun Heo 
900797e8345STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
901797e8345STejun Heo }
902797e8345STejun Heo 
903797e8345STejun Heo /**
904797e8345STejun Heo  * worker_enter_idle - enter idle state
905797e8345STejun Heo  * @worker: worker which is entering idle state
906797e8345STejun Heo  *
907797e8345STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
908797e8345STejun Heo  * necessary.
909797e8345STejun Heo  *
910797e8345STejun Heo  * LOCKING:
911797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
912797e8345STejun Heo  */
913797e8345STejun Heo static void worker_enter_idle(struct worker *worker)
914797e8345STejun Heo {
915797e8345STejun Heo 	struct worker_pool *pool = worker->pool;
916797e8345STejun Heo 
917797e8345STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
918797e8345STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
919797e8345STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
920797e8345STejun Heo 		return;
921797e8345STejun Heo 
922797e8345STejun Heo 	/* can't use worker_set_flags(), also called from create_worker() */
923797e8345STejun Heo 	worker->flags |= WORKER_IDLE;
924797e8345STejun Heo 	pool->nr_idle++;
925797e8345STejun Heo 	worker->last_active = jiffies;
926797e8345STejun Heo 
927797e8345STejun Heo 	/* idle_list is LIFO */
928797e8345STejun Heo 	list_add(&worker->entry, &pool->idle_list);
929797e8345STejun Heo 
930797e8345STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
931797e8345STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
932797e8345STejun Heo 
933797e8345STejun Heo 	/* Sanity check nr_running. */
934797e8345STejun Heo 	WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
935797e8345STejun Heo }
936797e8345STejun Heo 
937797e8345STejun Heo /**
938797e8345STejun Heo  * worker_leave_idle - leave idle state
939797e8345STejun Heo  * @worker: worker which is leaving idle state
940797e8345STejun Heo  *
941797e8345STejun Heo  * @worker is leaving idle state.  Update stats.
942797e8345STejun Heo  *
943797e8345STejun Heo  * LOCKING:
944797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
945797e8345STejun Heo  */
946797e8345STejun Heo static void worker_leave_idle(struct worker *worker)
947797e8345STejun Heo {
948797e8345STejun Heo 	struct worker_pool *pool = worker->pool;
949797e8345STejun Heo 
950797e8345STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
951797e8345STejun Heo 		return;
952797e8345STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
953797e8345STejun Heo 	pool->nr_idle--;
954797e8345STejun Heo 	list_del_init(&worker->entry);
955797e8345STejun Heo }
956797e8345STejun Heo 
957797e8345STejun Heo /**
958797e8345STejun Heo  * find_worker_executing_work - find worker which is executing a work
959797e8345STejun Heo  * @pool: pool of interest
960797e8345STejun Heo  * @work: work to find worker for
961797e8345STejun Heo  *
962797e8345STejun Heo  * Find a worker which is executing @work on @pool by searching
963797e8345STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
964797e8345STejun Heo  * to match, its current execution should match the address of @work and
965797e8345STejun Heo  * its work function.  This is to avoid unwanted dependency between
966797e8345STejun Heo  * unrelated work executions through a work item being recycled while still
967797e8345STejun Heo  * being executed.
968797e8345STejun Heo  *
969797e8345STejun Heo  * This is a bit tricky.  A work item may be freed once its execution
970797e8345STejun Heo  * starts and nothing prevents the freed area from being recycled for
971797e8345STejun Heo  * another work item.  If the same work item address ends up being reused
972797e8345STejun Heo  * before the original execution finishes, workqueue will identify the
973797e8345STejun Heo  * recycled work item as currently executing and make it wait until the
974797e8345STejun Heo  * current execution finishes, introducing an unwanted dependency.
975797e8345STejun Heo  *
976797e8345STejun Heo  * This function checks the work item address and work function to avoid
977797e8345STejun Heo  * false positives.  Note that this isn't complete as one may construct a
978797e8345STejun Heo  * work function which can introduce dependency onto itself through a
979797e8345STejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
980797e8345STejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
981797e8345STejun Heo  * actually occurs, it should be easy to locate the culprit work function.
982797e8345STejun Heo  *
983797e8345STejun Heo  * CONTEXT:
984797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
985797e8345STejun Heo  *
986797e8345STejun Heo  * Return:
987797e8345STejun Heo  * Pointer to worker which is executing @work if found, %NULL
988797e8345STejun Heo  * otherwise.
989797e8345STejun Heo  */
990797e8345STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
991797e8345STejun Heo 						 struct work_struct *work)
992797e8345STejun Heo {
993797e8345STejun Heo 	struct worker *worker;
994797e8345STejun Heo 
995797e8345STejun Heo 	hash_for_each_possible(pool->busy_hash, worker, hentry,
996797e8345STejun Heo 			       (unsigned long)work)
997797e8345STejun Heo 		if (worker->current_work == work &&
998797e8345STejun Heo 		    worker->current_func == work->func)
999797e8345STejun Heo 			return worker;
1000797e8345STejun Heo 
1001797e8345STejun Heo 	return NULL;
1002797e8345STejun Heo }
1003797e8345STejun Heo 
1004797e8345STejun Heo /**
1005797e8345STejun Heo  * move_linked_works - move linked works to a list
1006797e8345STejun Heo  * @work: start of series of works to be scheduled
1007797e8345STejun Heo  * @head: target list to append @work to
1008797e8345STejun Heo  * @nextp: out parameter for nested worklist walking
1009797e8345STejun Heo  *
1010797e8345STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
1011797e8345STejun Heo  * be scheduled starts at @work and includes any consecutive work with
1012797e8345STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
1013797e8345STejun Heo  *
1014797e8345STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
1015797e8345STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
1016797e8345STejun Heo  * nested inside outer list_for_each_entry_safe().
1017797e8345STejun Heo  *
1018797e8345STejun Heo  * CONTEXT:
1019797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1020797e8345STejun Heo  */
1021797e8345STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1022797e8345STejun Heo 			      struct work_struct **nextp)
1023797e8345STejun Heo {
1024797e8345STejun Heo 	struct work_struct *n;
1025797e8345STejun Heo 
1026797e8345STejun Heo 	/*
1027797e8345STejun Heo 	 * Linked worklist will always end before the end of the list,
1028797e8345STejun Heo 	 * use NULL for list head.
1029797e8345STejun Heo 	 */
1030797e8345STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1031797e8345STejun Heo 		list_move_tail(&work->entry, head);
1032797e8345STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1033797e8345STejun Heo 			break;
1034797e8345STejun Heo 	}
1035797e8345STejun Heo 
1036797e8345STejun Heo 	/*
1037797e8345STejun Heo 	 * If we're already inside safe list traversal and have moved
1038797e8345STejun Heo 	 * multiple works to the scheduled queue, the next position
1039797e8345STejun Heo 	 * needs to be updated.
1040797e8345STejun Heo 	 */
1041797e8345STejun Heo 	if (nextp)
1042797e8345STejun Heo 		*nextp = n;
1043797e8345STejun Heo }
1044797e8345STejun Heo 
1045797e8345STejun Heo /**
1046797e8345STejun Heo  * wake_up_worker - wake up an idle worker
1047797e8345STejun Heo  * @pool: worker pool to wake worker from
1048797e8345STejun Heo  *
1049797e8345STejun Heo  * Wake up the first idle worker of @pool.
1050797e8345STejun Heo  *
1051797e8345STejun Heo  * CONTEXT:
1052797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1053797e8345STejun Heo  */
1054797e8345STejun Heo static void wake_up_worker(struct worker_pool *pool)
1055797e8345STejun Heo {
1056797e8345STejun Heo 	struct worker *worker = first_idle_worker(pool);
1057797e8345STejun Heo 
1058797e8345STejun Heo 	if (likely(worker))
1059797e8345STejun Heo 		wake_up_process(worker->task);
1060797e8345STejun Heo }
1061797e8345STejun Heo 
106263638450STejun Heo #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
106363638450STejun Heo 
106463638450STejun Heo /*
106563638450STejun Heo  * Concurrency-managed per-cpu work items that hog CPU for longer than
106663638450STejun Heo  * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
106763638450STejun Heo  * which prevents them from stalling other concurrency-managed work items. If a
106863638450STejun Heo  * work function keeps triggering this mechanism, it's likely that the work item
106963638450STejun Heo  * should be using an unbound workqueue instead.
107063638450STejun Heo  *
107163638450STejun Heo  * wq_cpu_intensive_report() tracks work functions which trigger such conditions
107263638450STejun Heo  * and report them so that they can be examined and converted to use unbound
107363638450STejun Heo  * workqueues as appropriate. To avoid flooding the console, each violating work
107463638450STejun Heo  * function is tracked and reported with exponential backoff.
107563638450STejun Heo  */
107663638450STejun Heo #define WCI_MAX_ENTS 128
107763638450STejun Heo 
107863638450STejun Heo struct wci_ent {
107963638450STejun Heo 	work_func_t		func;
108063638450STejun Heo 	atomic64_t		cnt;
108163638450STejun Heo 	struct hlist_node	hash_node;
108263638450STejun Heo };
108363638450STejun Heo 
108463638450STejun Heo static struct wci_ent wci_ents[WCI_MAX_ENTS];
108563638450STejun Heo static int wci_nr_ents;
108663638450STejun Heo static DEFINE_RAW_SPINLOCK(wci_lock);
108763638450STejun Heo static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
108863638450STejun Heo 
108963638450STejun Heo static struct wci_ent *wci_find_ent(work_func_t func)
109063638450STejun Heo {
109163638450STejun Heo 	struct wci_ent *ent;
109263638450STejun Heo 
109363638450STejun Heo 	hash_for_each_possible_rcu(wci_hash, ent, hash_node,
109463638450STejun Heo 				   (unsigned long)func) {
109563638450STejun Heo 		if (ent->func == func)
109663638450STejun Heo 			return ent;
109763638450STejun Heo 	}
109863638450STejun Heo 	return NULL;
109963638450STejun Heo }
110063638450STejun Heo 
110163638450STejun Heo static void wq_cpu_intensive_report(work_func_t func)
110263638450STejun Heo {
110363638450STejun Heo 	struct wci_ent *ent;
110463638450STejun Heo 
110563638450STejun Heo restart:
110663638450STejun Heo 	ent = wci_find_ent(func);
110763638450STejun Heo 	if (ent) {
110863638450STejun Heo 		u64 cnt;
110963638450STejun Heo 
111063638450STejun Heo 		/*
111163638450STejun Heo 		 * Start reporting from the fourth time and back off
111263638450STejun Heo 		 * exponentially.
111363638450STejun Heo 		 */
111463638450STejun Heo 		cnt = atomic64_inc_return_relaxed(&ent->cnt);
111563638450STejun Heo 		if (cnt >= 4 && is_power_of_2(cnt))
111663638450STejun Heo 			printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
111763638450STejun Heo 					ent->func, wq_cpu_intensive_thresh_us,
111863638450STejun Heo 					atomic64_read(&ent->cnt));
111963638450STejun Heo 		return;
112063638450STejun Heo 	}
112163638450STejun Heo 
112263638450STejun Heo 	/*
112363638450STejun Heo 	 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
112463638450STejun Heo 	 * is exhausted, something went really wrong and we probably made enough
112563638450STejun Heo 	 * noise already.
112663638450STejun Heo 	 */
112763638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS)
112863638450STejun Heo 		return;
112963638450STejun Heo 
113063638450STejun Heo 	raw_spin_lock(&wci_lock);
113163638450STejun Heo 
113263638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS) {
113363638450STejun Heo 		raw_spin_unlock(&wci_lock);
113463638450STejun Heo 		return;
113563638450STejun Heo 	}
113663638450STejun Heo 
113763638450STejun Heo 	if (wci_find_ent(func)) {
113863638450STejun Heo 		raw_spin_unlock(&wci_lock);
113963638450STejun Heo 		goto restart;
114063638450STejun Heo 	}
114163638450STejun Heo 
114263638450STejun Heo 	ent = &wci_ents[wci_nr_ents++];
114363638450STejun Heo 	ent->func = func;
114463638450STejun Heo 	atomic64_set(&ent->cnt, 1);
114563638450STejun Heo 	hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
114663638450STejun Heo 
114763638450STejun Heo 	raw_spin_unlock(&wci_lock);
114863638450STejun Heo }
114963638450STejun Heo 
115063638450STejun Heo #else	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
115163638450STejun Heo static void wq_cpu_intensive_report(work_func_t func) {}
115263638450STejun Heo #endif	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
115363638450STejun Heo 
1154c54d5046STejun Heo /**
11551da177e4SLinus Torvalds  * wq_worker_running - a worker is running again
11561da177e4SLinus Torvalds  * @task: task waking up
11571da177e4SLinus Torvalds  *
11581da177e4SLinus Torvalds  * This function is called when a worker returns from schedule()
11591da177e4SLinus Torvalds  */
11601da177e4SLinus Torvalds void wq_worker_running(struct task_struct *task)
11611da177e4SLinus Torvalds {
11621da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
11631da177e4SLinus Torvalds 
1164c8f6219bSZqiang 	if (!READ_ONCE(worker->sleeping))
11651da177e4SLinus Torvalds 		return;
11661da177e4SLinus Torvalds 
11671da177e4SLinus Torvalds 	/*
11681da177e4SLinus Torvalds 	 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
11691da177e4SLinus Torvalds 	 * and the nr_running increment below, we may ruin the nr_running reset
11701da177e4SLinus Torvalds 	 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
11711da177e4SLinus Torvalds 	 * pool. Protect against such race.
11721da177e4SLinus Torvalds 	 */
11731da177e4SLinus Torvalds 	preempt_disable();
11741da177e4SLinus Torvalds 	if (!(worker->flags & WORKER_NOT_RUNNING))
11751da177e4SLinus Torvalds 		worker->pool->nr_running++;
11761da177e4SLinus Torvalds 	preempt_enable();
1177616db877STejun Heo 
1178616db877STejun Heo 	/*
1179616db877STejun Heo 	 * CPU intensive auto-detection cares about how long a work item hogged
1180616db877STejun Heo 	 * CPU without sleeping. Reset the starting timestamp on wakeup.
1181616db877STejun Heo 	 */
1182616db877STejun Heo 	worker->current_at = worker->task->se.sum_exec_runtime;
1183616db877STejun Heo 
1184c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 0);
11851da177e4SLinus Torvalds }
11861da177e4SLinus Torvalds 
11871da177e4SLinus Torvalds /**
11881da177e4SLinus Torvalds  * wq_worker_sleeping - a worker is going to sleep
11891da177e4SLinus Torvalds  * @task: task going to sleep
11901da177e4SLinus Torvalds  *
11911da177e4SLinus Torvalds  * This function is called from schedule() when a busy worker is
11921da177e4SLinus Torvalds  * going to sleep.
11931da177e4SLinus Torvalds  */
11941da177e4SLinus Torvalds void wq_worker_sleeping(struct task_struct *task)
11951da177e4SLinus Torvalds {
11961da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
11971da177e4SLinus Torvalds 	struct worker_pool *pool;
11981da177e4SLinus Torvalds 
11991da177e4SLinus Torvalds 	/*
12001da177e4SLinus Torvalds 	 * Rescuers, which may not have all the fields set up like normal
12011da177e4SLinus Torvalds 	 * workers, also reach here, let's not access anything before
12021da177e4SLinus Torvalds 	 * checking NOT_RUNNING.
12031da177e4SLinus Torvalds 	 */
12041da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING)
12051da177e4SLinus Torvalds 		return;
12061da177e4SLinus Torvalds 
12071da177e4SLinus Torvalds 	pool = worker->pool;
12081da177e4SLinus Torvalds 
12091da177e4SLinus Torvalds 	/* Return if preempted before wq_worker_running() was reached */
1210c8f6219bSZqiang 	if (READ_ONCE(worker->sleeping))
12111da177e4SLinus Torvalds 		return;
12121da177e4SLinus Torvalds 
1213c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 1);
12141da177e4SLinus Torvalds 	raw_spin_lock_irq(&pool->lock);
12151da177e4SLinus Torvalds 
12161da177e4SLinus Torvalds 	/*
12171da177e4SLinus Torvalds 	 * Recheck in case unbind_workers() preempted us. We don't
12181da177e4SLinus Torvalds 	 * want to decrement nr_running after the worker is unbound
12191da177e4SLinus Torvalds 	 * and nr_running has been reset.
12201da177e4SLinus Torvalds 	 */
12211da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING) {
12221da177e4SLinus Torvalds 		raw_spin_unlock_irq(&pool->lock);
12231da177e4SLinus Torvalds 		return;
12241da177e4SLinus Torvalds 	}
12251da177e4SLinus Torvalds 
12261da177e4SLinus Torvalds 	pool->nr_running--;
1227725e8ec5STejun Heo 	if (need_more_worker(pool)) {
1228725e8ec5STejun Heo 		worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
12291da177e4SLinus Torvalds 		wake_up_worker(pool);
1230725e8ec5STejun Heo 	}
12311da177e4SLinus Torvalds 	raw_spin_unlock_irq(&pool->lock);
12321da177e4SLinus Torvalds }
12331da177e4SLinus Torvalds 
12341da177e4SLinus Torvalds /**
1235616db877STejun Heo  * wq_worker_tick - a scheduler tick occurred while a kworker is running
1236616db877STejun Heo  * @task: task currently running
1237616db877STejun Heo  *
1238616db877STejun Heo  * Called from scheduler_tick(). We're in the IRQ context and the current
1239616db877STejun Heo  * worker's fields which follow the 'K' locking rule can be accessed safely.
1240616db877STejun Heo  */
1241616db877STejun Heo void wq_worker_tick(struct task_struct *task)
1242616db877STejun Heo {
1243616db877STejun Heo 	struct worker *worker = kthread_data(task);
1244616db877STejun Heo 	struct pool_workqueue *pwq = worker->current_pwq;
1245616db877STejun Heo 	struct worker_pool *pool = worker->pool;
1246616db877STejun Heo 
1247616db877STejun Heo 	if (!pwq)
1248616db877STejun Heo 		return;
1249616db877STejun Heo 
12508a1dd1e5STejun Heo 	pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
12518a1dd1e5STejun Heo 
125218c8ae81SZqiang 	if (!wq_cpu_intensive_thresh_us)
125318c8ae81SZqiang 		return;
125418c8ae81SZqiang 
1255616db877STejun Heo 	/*
1256616db877STejun Heo 	 * If the current worker is concurrency managed and hogged the CPU for
1257616db877STejun Heo 	 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1258616db877STejun Heo 	 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1259c8f6219bSZqiang 	 *
1260c8f6219bSZqiang 	 * Set @worker->sleeping means that @worker is in the process of
1261c8f6219bSZqiang 	 * switching out voluntarily and won't be contributing to
1262c8f6219bSZqiang 	 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1263c8f6219bSZqiang 	 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1264c8f6219bSZqiang 	 * double decrements. The task is releasing the CPU anyway. Let's skip.
1265c8f6219bSZqiang 	 * We probably want to make this prettier in the future.
1266616db877STejun Heo 	 */
1267c8f6219bSZqiang 	if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1268616db877STejun Heo 	    worker->task->se.sum_exec_runtime - worker->current_at <
1269616db877STejun Heo 	    wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1270616db877STejun Heo 		return;
1271616db877STejun Heo 
1272616db877STejun Heo 	raw_spin_lock(&pool->lock);
1273616db877STejun Heo 
1274616db877STejun Heo 	worker_set_flags(worker, WORKER_CPU_INTENSIVE);
127563638450STejun Heo 	wq_cpu_intensive_report(worker->current_func);
1276616db877STejun Heo 	pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1277616db877STejun Heo 
1278616db877STejun Heo 	if (need_more_worker(pool)) {
1279616db877STejun Heo 		pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1280616db877STejun Heo 		wake_up_worker(pool);
1281616db877STejun Heo 	}
1282616db877STejun Heo 
1283616db877STejun Heo 	raw_spin_unlock(&pool->lock);
1284616db877STejun Heo }
1285616db877STejun Heo 
1286616db877STejun Heo /**
12871da177e4SLinus Torvalds  * wq_worker_last_func - retrieve worker's last work function
12881da177e4SLinus Torvalds  * @task: Task to retrieve last work function of.
12891da177e4SLinus Torvalds  *
12901da177e4SLinus Torvalds  * Determine the last function a worker executed. This is called from
12911da177e4SLinus Torvalds  * the scheduler to get a worker's last known identity.
12921da177e4SLinus Torvalds  *
12931da177e4SLinus Torvalds  * CONTEXT:
12949b41ea72SAndrew Morton  * raw_spin_lock_irq(rq->lock)
12951da177e4SLinus Torvalds  *
12961da177e4SLinus Torvalds  * This function is called during schedule() when a kworker is going
1297f756d5e2SNathan Lynch  * to sleep. It's used by psi to identify aggregation workers during
1298f756d5e2SNathan Lynch  * dequeuing, to allow periodic aggregation to shut-off when that
12991da177e4SLinus Torvalds  * worker is the last task in the system or cgroup to go to sleep.
13001da177e4SLinus Torvalds  *
13011da177e4SLinus Torvalds  * As this function doesn't involve any workqueue-related locking, it
13021da177e4SLinus Torvalds  * only returns stable values when called from inside the scheduler's
13031da177e4SLinus Torvalds  * queuing and dequeuing paths, when @task, which must be a kworker,
13041da177e4SLinus Torvalds  * is guaranteed to not be processing any works.
1305365970a1SDavid Howells  *
1306365970a1SDavid Howells  * Return:
1307365970a1SDavid Howells  * The last work function %current executed as a worker, NULL if it
1308365970a1SDavid Howells  * hasn't executed any work yet.
1309365970a1SDavid Howells  */
1310365970a1SDavid Howells work_func_t wq_worker_last_func(struct task_struct *task)
1311365970a1SDavid Howells {
1312365970a1SDavid Howells 	struct worker *worker = kthread_data(task);
1313365970a1SDavid Howells 
1314365970a1SDavid Howells 	return worker->last_func;
1315365970a1SDavid Howells }
1316365970a1SDavid Howells 
1317d302f017STejun Heo /**
13188864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
13198864b4e5STejun Heo  * @pwq: pool_workqueue to get
13208864b4e5STejun Heo  *
13218864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
13228864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
13238864b4e5STejun Heo  */
13248864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
13258864b4e5STejun Heo {
13268864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
13278864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
13288864b4e5STejun Heo 	pwq->refcnt++;
13298864b4e5STejun Heo }
13308864b4e5STejun Heo 
13318864b4e5STejun Heo /**
13328864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
13338864b4e5STejun Heo  * @pwq: pool_workqueue to put
13348864b4e5STejun Heo  *
13358864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
13368864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
13378864b4e5STejun Heo  */
13388864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
13398864b4e5STejun Heo {
13408864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
13418864b4e5STejun Heo 	if (likely(--pwq->refcnt))
13428864b4e5STejun Heo 		return;
13438864b4e5STejun Heo 	/*
1344967b494eSTejun Heo 	 * @pwq can't be released under pool->lock, bounce to a dedicated
1345967b494eSTejun Heo 	 * kthread_worker to avoid A-A deadlocks.
13468864b4e5STejun Heo 	 */
1347687a9aa5STejun Heo 	kthread_queue_work(pwq_release_worker, &pwq->release_work);
13488864b4e5STejun Heo }
13498864b4e5STejun Heo 
1350dce90d47STejun Heo /**
1351dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1352dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1353dce90d47STejun Heo  *
1354dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1355dce90d47STejun Heo  */
1356dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1357dce90d47STejun Heo {
1358dce90d47STejun Heo 	if (pwq) {
1359dce90d47STejun Heo 		/*
136024acfb71SThomas Gleixner 		 * As both pwqs and pools are RCU protected, the
1361dce90d47STejun Heo 		 * following lock operations are safe.
1362dce90d47STejun Heo 		 */
1363a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
1364dce90d47STejun Heo 		put_pwq(pwq);
1365a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
1366dce90d47STejun Heo 	}
1367dce90d47STejun Heo }
1368dce90d47STejun Heo 
1369f97a4a1aSLai Jiangshan static void pwq_activate_inactive_work(struct work_struct *work)
1370bf4ede01STejun Heo {
1371112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1372bf4ede01STejun Heo 
1373bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
137482607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
137582607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1376112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
1377f97a4a1aSLai Jiangshan 	__clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work));
1378112202d9STejun Heo 	pwq->nr_active++;
1379bf4ede01STejun Heo }
1380bf4ede01STejun Heo 
1381f97a4a1aSLai Jiangshan static void pwq_activate_first_inactive(struct pool_workqueue *pwq)
13823aa62497SLai Jiangshan {
1383f97a4a1aSLai Jiangshan 	struct work_struct *work = list_first_entry(&pwq->inactive_works,
13843aa62497SLai Jiangshan 						    struct work_struct, entry);
13853aa62497SLai Jiangshan 
1386f97a4a1aSLai Jiangshan 	pwq_activate_inactive_work(work);
13873aa62497SLai Jiangshan }
13883aa62497SLai Jiangshan 
1389bf4ede01STejun Heo /**
1390112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1391112202d9STejun Heo  * @pwq: pwq of interest
1392c4560c2cSLai Jiangshan  * @work_data: work_data of work which left the queue
1393bf4ede01STejun Heo  *
1394bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1395112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1396bf4ede01STejun Heo  *
1397bf4ede01STejun Heo  * CONTEXT:
1398a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1399bf4ede01STejun Heo  */
1400c4560c2cSLai Jiangshan static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1401bf4ede01STejun Heo {
1402c4560c2cSLai Jiangshan 	int color = get_work_color(work_data);
1403c4560c2cSLai Jiangshan 
1404018f3a13SLai Jiangshan 	if (!(work_data & WORK_STRUCT_INACTIVE)) {
1405112202d9STejun Heo 		pwq->nr_active--;
1406f97a4a1aSLai Jiangshan 		if (!list_empty(&pwq->inactive_works)) {
1407f97a4a1aSLai Jiangshan 			/* one down, submit an inactive one */
1408112202d9STejun Heo 			if (pwq->nr_active < pwq->max_active)
1409f97a4a1aSLai Jiangshan 				pwq_activate_first_inactive(pwq);
1410bf4ede01STejun Heo 		}
1411018f3a13SLai Jiangshan 	}
1412018f3a13SLai Jiangshan 
1413018f3a13SLai Jiangshan 	pwq->nr_in_flight[color]--;
1414bf4ede01STejun Heo 
1415bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1416112202d9STejun Heo 	if (likely(pwq->flush_color != color))
14178864b4e5STejun Heo 		goto out_put;
1418bf4ede01STejun Heo 
1419bf4ede01STejun Heo 	/* are there still in-flight works? */
1420112202d9STejun Heo 	if (pwq->nr_in_flight[color])
14218864b4e5STejun Heo 		goto out_put;
1422bf4ede01STejun Heo 
1423112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1424112202d9STejun Heo 	pwq->flush_color = -1;
1425bf4ede01STejun Heo 
1426bf4ede01STejun Heo 	/*
1427112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1428bf4ede01STejun Heo 	 * will handle the rest.
1429bf4ede01STejun Heo 	 */
1430112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1431112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
14328864b4e5STejun Heo out_put:
14338864b4e5STejun Heo 	put_pwq(pwq);
1434bf4ede01STejun Heo }
1435bf4ede01STejun Heo 
143636e227d2STejun Heo /**
1437bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
143836e227d2STejun Heo  * @work: work item to steal
143936e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1440bbb68dfaSTejun Heo  * @flags: place to store irq state
144136e227d2STejun Heo  *
144236e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1443d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
144436e227d2STejun Heo  *
1445d185af30SYacine Belkadi  * Return:
14463eb6b31bSMauro Carvalho Chehab  *
14473eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
144836e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
144936e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
145036e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1451bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1452bbb68dfaSTejun Heo  *		for arbitrarily long
14533eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
145436e227d2STejun Heo  *
1455d185af30SYacine Belkadi  * Note:
1456bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1457e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1458e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1459e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1460bbb68dfaSTejun Heo  *
1461bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1462bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1463bbb68dfaSTejun Heo  *
1464e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1465bf4ede01STejun Heo  */
1466bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1467bbb68dfaSTejun Heo 			       unsigned long *flags)
1468bf4ede01STejun Heo {
1469d565ed63STejun Heo 	struct worker_pool *pool;
1470112202d9STejun Heo 	struct pool_workqueue *pwq;
1471bf4ede01STejun Heo 
1472bbb68dfaSTejun Heo 	local_irq_save(*flags);
1473bbb68dfaSTejun Heo 
147436e227d2STejun Heo 	/* try to steal the timer if it exists */
147536e227d2STejun Heo 	if (is_dwork) {
147636e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
147736e227d2STejun Heo 
1478e0aecdd8STejun Heo 		/*
1479e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1480e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1481e0aecdd8STejun Heo 		 * running on the local CPU.
1482e0aecdd8STejun Heo 		 */
148336e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
148436e227d2STejun Heo 			return 1;
148536e227d2STejun Heo 	}
148636e227d2STejun Heo 
148736e227d2STejun Heo 	/* try to claim PENDING the normal way */
1488bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1489bf4ede01STejun Heo 		return 0;
1490bf4ede01STejun Heo 
149124acfb71SThomas Gleixner 	rcu_read_lock();
1492bf4ede01STejun Heo 	/*
1493bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1494bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1495bf4ede01STejun Heo 	 */
1496d565ed63STejun Heo 	pool = get_work_pool(work);
1497d565ed63STejun Heo 	if (!pool)
1498bbb68dfaSTejun Heo 		goto fail;
1499bf4ede01STejun Heo 
1500a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&pool->lock);
1501bf4ede01STejun Heo 	/*
1502112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1503112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1504112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1505112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1506112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
15070b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1508bf4ede01STejun Heo 	 */
1509112202d9STejun Heo 	pwq = get_work_pwq(work);
1510112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1511bf4ede01STejun Heo 		debug_work_deactivate(work);
15123aa62497SLai Jiangshan 
15133aa62497SLai Jiangshan 		/*
1514018f3a13SLai Jiangshan 		 * A cancelable inactive work item must be in the
1515018f3a13SLai Jiangshan 		 * pwq->inactive_works since a queued barrier can't be
1516018f3a13SLai Jiangshan 		 * canceled (see the comments in insert_wq_barrier()).
1517018f3a13SLai Jiangshan 		 *
1518f97a4a1aSLai Jiangshan 		 * An inactive work item cannot be grabbed directly because
1519d812796eSLai Jiangshan 		 * it might have linked barrier work items which, if left
1520f97a4a1aSLai Jiangshan 		 * on the inactive_works list, will confuse pwq->nr_active
152116062836STejun Heo 		 * management later on and cause stall.  Make sure the work
152216062836STejun Heo 		 * item is activated before grabbing.
15233aa62497SLai Jiangshan 		 */
1524f97a4a1aSLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_INACTIVE)
1525f97a4a1aSLai Jiangshan 			pwq_activate_inactive_work(work);
15263aa62497SLai Jiangshan 
1527bf4ede01STejun Heo 		list_del_init(&work->entry);
1528c4560c2cSLai Jiangshan 		pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
152936e227d2STejun Heo 
1530112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
15314468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
15324468a00fSLai Jiangshan 
1533a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock(&pool->lock);
153424acfb71SThomas Gleixner 		rcu_read_unlock();
153536e227d2STejun Heo 		return 1;
1536bf4ede01STejun Heo 	}
1537a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pool->lock);
1538bbb68dfaSTejun Heo fail:
153924acfb71SThomas Gleixner 	rcu_read_unlock();
1540bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1541bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1542bbb68dfaSTejun Heo 		return -ENOENT;
1543bbb68dfaSTejun Heo 	cpu_relax();
154436e227d2STejun Heo 	return -EAGAIN;
1545bf4ede01STejun Heo }
1546bf4ede01STejun Heo 
1547bf4ede01STejun Heo /**
1548706026c2STejun Heo  * insert_work - insert a work into a pool
1549112202d9STejun Heo  * @pwq: pwq @work belongs to
15504690c4abSTejun Heo  * @work: work to insert
15514690c4abSTejun Heo  * @head: insertion point
15524690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
15534690c4abSTejun Heo  *
1554112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1555706026c2STejun Heo  * work_struct flags.
15564690c4abSTejun Heo  *
15574690c4abSTejun Heo  * CONTEXT:
1558a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1559365970a1SDavid Howells  */
1560112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1561112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1562b89deed3SOleg Nesterov {
1563fe089f87STejun Heo 	debug_work_activate(work);
1564e1d8aa9fSFrederic Weisbecker 
1565e89a85d6SWalter Wu 	/* record the work call stack in order to print it in KASAN reports */
1566f70da745SMarco Elver 	kasan_record_aux_stack_noalloc(work);
1567e89a85d6SWalter Wu 
15684690c4abSTejun Heo 	/* we own @work, set data and link */
1569112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
15701a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
15718864b4e5STejun Heo 	get_pwq(pwq);
1572b89deed3SOleg Nesterov }
1573b89deed3SOleg Nesterov 
1574c8efcc25STejun Heo /*
1575c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
15768d03ecfeSTejun Heo  * same workqueue.
1577c8efcc25STejun Heo  */
1578c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1579c8efcc25STejun Heo {
1580c8efcc25STejun Heo 	struct worker *worker;
1581c8efcc25STejun Heo 
15828d03ecfeSTejun Heo 	worker = current_wq_worker();
1583c8efcc25STejun Heo 	/*
1584bf393fd4SBart Van Assche 	 * Return %true iff I'm a worker executing a work item on @wq.  If
15858d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1586c8efcc25STejun Heo 	 */
1587112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1588c8efcc25STejun Heo }
1589c8efcc25STejun Heo 
1590ef557180SMike Galbraith /*
1591ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
1592ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
1593ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
1594ef557180SMike Galbraith  */
1595ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1596ef557180SMike Galbraith {
1597ef557180SMike Galbraith 	int new_cpu;
1598ef557180SMike Galbraith 
1599f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
1600ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1601ef557180SMike Galbraith 			return cpu;
1602a8ec5880SAmmar Faizi 	} else {
1603a8ec5880SAmmar Faizi 		pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
1604f303fccbSTejun Heo 	}
1605f303fccbSTejun Heo 
1606ef557180SMike Galbraith 	if (cpumask_empty(wq_unbound_cpumask))
1607ef557180SMike Galbraith 		return cpu;
1608ef557180SMike Galbraith 
1609ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
1610ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1611ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
1612ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1613ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
1614ef557180SMike Galbraith 			return cpu;
1615ef557180SMike Galbraith 	}
1616ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
1617ef557180SMike Galbraith 
1618ef557180SMike Galbraith 	return new_cpu;
1619ef557180SMike Galbraith }
1620ef557180SMike Galbraith 
1621d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
16221da177e4SLinus Torvalds 			 struct work_struct *work)
16231da177e4SLinus Torvalds {
1624112202d9STejun Heo 	struct pool_workqueue *pwq;
1625fe089f87STejun Heo 	struct worker_pool *last_pool, *pool;
16268a2e8e5dSTejun Heo 	unsigned int work_flags;
1627b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
16288930cabaSTejun Heo 
16298930cabaSTejun Heo 	/*
16308930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
16318930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
16328930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
16338930cabaSTejun Heo 	 * happen with IRQ disabled.
16348930cabaSTejun Heo 	 */
16358e8eb730SFrederic Weisbecker 	lockdep_assert_irqs_disabled();
16361da177e4SLinus Torvalds 
16371e19ffc6STejun Heo 
163833e3f0a3SRichard Clark 	/*
163933e3f0a3SRichard Clark 	 * For a draining wq, only works from the same workqueue are
164033e3f0a3SRichard Clark 	 * allowed. The __WQ_DESTROYING helps to spot the issue that
164133e3f0a3SRichard Clark 	 * queues a new work item to a wq after destroy_workqueue(wq).
164233e3f0a3SRichard Clark 	 */
164333e3f0a3SRichard Clark 	if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
164433e3f0a3SRichard Clark 		     WARN_ON_ONCE(!is_chained_work(wq))))
1645e41e704bSTejun Heo 		return;
164624acfb71SThomas Gleixner 	rcu_read_lock();
16479e8cd2f5STejun Heo retry:
1648aa202f1fSHillf Danton 	/* pwq which will be used unless @work is executing elsewhere */
1649636b927eSTejun Heo 	if (req_cpu == WORK_CPU_UNBOUND) {
1650636b927eSTejun Heo 		if (wq->flags & WQ_UNBOUND)
1651ef557180SMike Galbraith 			cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1652636b927eSTejun Heo 		else
1653aa202f1fSHillf Danton 			cpu = raw_smp_processor_id();
1654aa202f1fSHillf Danton 	}
1655f3421797STejun Heo 
1656636b927eSTejun Heo 	pwq = rcu_dereference(*per_cpu_ptr(wq->cpu_pwq, cpu));
1657fe089f87STejun Heo 	pool = pwq->pool;
1658fe089f87STejun Heo 
165918aa9effSTejun Heo 	/*
1660c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1661c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1662c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
166318aa9effSTejun Heo 	 */
1664c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1665fe089f87STejun Heo 	if (last_pool && last_pool != pool) {
166618aa9effSTejun Heo 		struct worker *worker;
166718aa9effSTejun Heo 
1668a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&last_pool->lock);
166918aa9effSTejun Heo 
1670c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
167118aa9effSTejun Heo 
1672112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1673c9178087STejun Heo 			pwq = worker->current_pwq;
1674fe089f87STejun Heo 			pool = pwq->pool;
1675fe089f87STejun Heo 			WARN_ON_ONCE(pool != last_pool);
16768594fadeSLai Jiangshan 		} else {
167718aa9effSTejun Heo 			/* meh... not running there, queue here */
1678a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&last_pool->lock);
1679fe089f87STejun Heo 			raw_spin_lock(&pool->lock);
168018aa9effSTejun Heo 		}
16818930cabaSTejun Heo 	} else {
1682fe089f87STejun Heo 		raw_spin_lock(&pool->lock);
16838930cabaSTejun Heo 	}
1684502ca9d8STejun Heo 
16859e8cd2f5STejun Heo 	/*
1686636b927eSTejun Heo 	 * pwq is determined and locked. For unbound pools, we could have raced
1687636b927eSTejun Heo 	 * with pwq release and it could already be dead. If its refcnt is zero,
1688636b927eSTejun Heo 	 * repeat pwq selection. Note that unbound pwqs never die without
1689636b927eSTejun Heo 	 * another pwq replacing it in cpu_pwq or while work items are executing
1690636b927eSTejun Heo 	 * on it, so the retrying is guaranteed to make forward-progress.
16919e8cd2f5STejun Heo 	 */
16929e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
16939e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
1694fe089f87STejun Heo 			raw_spin_unlock(&pool->lock);
16959e8cd2f5STejun Heo 			cpu_relax();
16969e8cd2f5STejun Heo 			goto retry;
16979e8cd2f5STejun Heo 		}
16989e8cd2f5STejun Heo 		/* oops */
16999e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
17009e8cd2f5STejun Heo 			  wq->name, cpu);
17019e8cd2f5STejun Heo 	}
17029e8cd2f5STejun Heo 
1703112202d9STejun Heo 	/* pwq determined, queue */
1704112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1705502ca9d8STejun Heo 
170624acfb71SThomas Gleixner 	if (WARN_ON(!list_empty(&work->entry)))
170724acfb71SThomas Gleixner 		goto out;
17081e19ffc6STejun Heo 
1709112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1710112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
17111e19ffc6STejun Heo 
1712112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1713fe089f87STejun Heo 		if (list_empty(&pool->worklist))
1714fe089f87STejun Heo 			pool->watchdog_ts = jiffies;
1715fe089f87STejun Heo 
1716cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1717112202d9STejun Heo 		pwq->nr_active++;
1718fe089f87STejun Heo 		insert_work(pwq, work, &pool->worklist, work_flags);
1719fe089f87STejun Heo 
1720fe089f87STejun Heo 		if (__need_more_worker(pool))
1721fe089f87STejun Heo 			wake_up_worker(pool);
17228a2e8e5dSTejun Heo 	} else {
1723f97a4a1aSLai Jiangshan 		work_flags |= WORK_STRUCT_INACTIVE;
1724fe089f87STejun Heo 		insert_work(pwq, work, &pwq->inactive_works, work_flags);
17258a2e8e5dSTejun Heo 	}
17261e19ffc6STejun Heo 
172724acfb71SThomas Gleixner out:
1728fe089f87STejun Heo 	raw_spin_unlock(&pool->lock);
172924acfb71SThomas Gleixner 	rcu_read_unlock();
17301da177e4SLinus Torvalds }
17311da177e4SLinus Torvalds 
17320fcb78c2SRolf Eike Beer /**
1733c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1734c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1735c1a220e7SZhang Rui  * @wq: workqueue to use
1736c1a220e7SZhang Rui  * @work: work to queue
1737c1a220e7SZhang Rui  *
1738c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1739443378f0SPaul E. McKenney  * can't go away.  Callers that fail to ensure that the specified
1740443378f0SPaul E. McKenney  * CPU cannot go away will execute on a randomly chosen CPU.
1741854f5cc5SPaul E. McKenney  * But note well that callers specifying a CPU that never has been
1742854f5cc5SPaul E. McKenney  * online will get a splat.
1743d185af30SYacine Belkadi  *
1744d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
1745c1a220e7SZhang Rui  */
1746d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1747d4283e93STejun Heo 		   struct work_struct *work)
1748c1a220e7SZhang Rui {
1749d4283e93STejun Heo 	bool ret = false;
17508930cabaSTejun Heo 	unsigned long flags;
17518930cabaSTejun Heo 
17528930cabaSTejun Heo 	local_irq_save(flags);
1753c1a220e7SZhang Rui 
175422df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
17554690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1756d4283e93STejun Heo 		ret = true;
1757c1a220e7SZhang Rui 	}
17588930cabaSTejun Heo 
17598930cabaSTejun Heo 	local_irq_restore(flags);
1760c1a220e7SZhang Rui 	return ret;
1761c1a220e7SZhang Rui }
1762ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1763c1a220e7SZhang Rui 
17648204e0c1SAlexander Duyck /**
1765fef59c9cSTejun Heo  * select_numa_node_cpu - Select a CPU based on NUMA node
17668204e0c1SAlexander Duyck  * @node: NUMA node ID that we want to select a CPU from
17678204e0c1SAlexander Duyck  *
17688204e0c1SAlexander Duyck  * This function will attempt to find a "random" cpu available on a given
17698204e0c1SAlexander Duyck  * node. If there are no CPUs available on the given node it will return
17708204e0c1SAlexander Duyck  * WORK_CPU_UNBOUND indicating that we should just schedule to any
17718204e0c1SAlexander Duyck  * available CPU if we need to schedule this work.
17728204e0c1SAlexander Duyck  */
1773fef59c9cSTejun Heo static int select_numa_node_cpu(int node)
17748204e0c1SAlexander Duyck {
17758204e0c1SAlexander Duyck 	int cpu;
17768204e0c1SAlexander Duyck 
17778204e0c1SAlexander Duyck 	/* No point in doing this if NUMA isn't enabled for workqueues */
1778fef59c9cSTejun Heo 	if (!wq_pod_enabled)
17798204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
17808204e0c1SAlexander Duyck 
17818204e0c1SAlexander Duyck 	/* Delay binding to CPU if node is not valid or online */
17828204e0c1SAlexander Duyck 	if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
17838204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
17848204e0c1SAlexander Duyck 
17858204e0c1SAlexander Duyck 	/* Use local node/cpu if we are already there */
17868204e0c1SAlexander Duyck 	cpu = raw_smp_processor_id();
17878204e0c1SAlexander Duyck 	if (node == cpu_to_node(cpu))
17888204e0c1SAlexander Duyck 		return cpu;
17898204e0c1SAlexander Duyck 
17908204e0c1SAlexander Duyck 	/* Use "random" otherwise know as "first" online CPU of node */
17918204e0c1SAlexander Duyck 	cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
17928204e0c1SAlexander Duyck 
17938204e0c1SAlexander Duyck 	/* If CPU is valid return that, otherwise just defer */
17948204e0c1SAlexander Duyck 	return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
17958204e0c1SAlexander Duyck }
17968204e0c1SAlexander Duyck 
17978204e0c1SAlexander Duyck /**
17988204e0c1SAlexander Duyck  * queue_work_node - queue work on a "random" cpu for a given NUMA node
17998204e0c1SAlexander Duyck  * @node: NUMA node that we are targeting the work for
18008204e0c1SAlexander Duyck  * @wq: workqueue to use
18018204e0c1SAlexander Duyck  * @work: work to queue
18028204e0c1SAlexander Duyck  *
18038204e0c1SAlexander Duyck  * We queue the work to a "random" CPU within a given NUMA node. The basic
18048204e0c1SAlexander Duyck  * idea here is to provide a way to somehow associate work with a given
18058204e0c1SAlexander Duyck  * NUMA node.
18068204e0c1SAlexander Duyck  *
18078204e0c1SAlexander Duyck  * This function will only make a best effort attempt at getting this onto
18088204e0c1SAlexander Duyck  * the right NUMA node. If no node is requested or the requested node is
18098204e0c1SAlexander Duyck  * offline then we just fall back to standard queue_work behavior.
18108204e0c1SAlexander Duyck  *
18118204e0c1SAlexander Duyck  * Currently the "random" CPU ends up being the first available CPU in the
18128204e0c1SAlexander Duyck  * intersection of cpu_online_mask and the cpumask of the node, unless we
18138204e0c1SAlexander Duyck  * are running on the node. In that case we just use the current CPU.
18148204e0c1SAlexander Duyck  *
18158204e0c1SAlexander Duyck  * Return: %false if @work was already on a queue, %true otherwise.
18168204e0c1SAlexander Duyck  */
18178204e0c1SAlexander Duyck bool queue_work_node(int node, struct workqueue_struct *wq,
18188204e0c1SAlexander Duyck 		     struct work_struct *work)
18198204e0c1SAlexander Duyck {
18208204e0c1SAlexander Duyck 	unsigned long flags;
18218204e0c1SAlexander Duyck 	bool ret = false;
18228204e0c1SAlexander Duyck 
18238204e0c1SAlexander Duyck 	/*
18248204e0c1SAlexander Duyck 	 * This current implementation is specific to unbound workqueues.
18258204e0c1SAlexander Duyck 	 * Specifically we only return the first available CPU for a given
18268204e0c1SAlexander Duyck 	 * node instead of cycling through individual CPUs within the node.
18278204e0c1SAlexander Duyck 	 *
18288204e0c1SAlexander Duyck 	 * If this is used with a per-cpu workqueue then the logic in
18298204e0c1SAlexander Duyck 	 * workqueue_select_cpu_near would need to be updated to allow for
18308204e0c1SAlexander Duyck 	 * some round robin type logic.
18318204e0c1SAlexander Duyck 	 */
18328204e0c1SAlexander Duyck 	WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
18338204e0c1SAlexander Duyck 
18348204e0c1SAlexander Duyck 	local_irq_save(flags);
18358204e0c1SAlexander Duyck 
18368204e0c1SAlexander Duyck 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1837fef59c9cSTejun Heo 		int cpu = select_numa_node_cpu(node);
18388204e0c1SAlexander Duyck 
18398204e0c1SAlexander Duyck 		__queue_work(cpu, wq, work);
18408204e0c1SAlexander Duyck 		ret = true;
18418204e0c1SAlexander Duyck 	}
18428204e0c1SAlexander Duyck 
18438204e0c1SAlexander Duyck 	local_irq_restore(flags);
18448204e0c1SAlexander Duyck 	return ret;
18458204e0c1SAlexander Duyck }
18468204e0c1SAlexander Duyck EXPORT_SYMBOL_GPL(queue_work_node);
18478204e0c1SAlexander Duyck 
18488c20feb6SKees Cook void delayed_work_timer_fn(struct timer_list *t)
18491da177e4SLinus Torvalds {
18508c20feb6SKees Cook 	struct delayed_work *dwork = from_timer(dwork, t, timer);
18511da177e4SLinus Torvalds 
1852e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
185360c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
18541da177e4SLinus Torvalds }
18551438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
18561da177e4SLinus Torvalds 
18577beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
185852bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
18591da177e4SLinus Torvalds {
18607beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
18617beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
18621da177e4SLinus Torvalds 
1863637fdbaeSTejun Heo 	WARN_ON_ONCE(!wq);
18644b243563SSami Tolvanen 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
1865fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1866fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
18677beb2edfSTejun Heo 
18688852aac2STejun Heo 	/*
18698852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
18708852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
18718852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
18728852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
18738852aac2STejun Heo 	 */
18748852aac2STejun Heo 	if (!delay) {
18758852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
18768852aac2STejun Heo 		return;
18778852aac2STejun Heo 	}
18788852aac2STejun Heo 
187960c057bcSLai Jiangshan 	dwork->wq = wq;
18801265057fSTejun Heo 	dwork->cpu = cpu;
18817beb2edfSTejun Heo 	timer->expires = jiffies + delay;
18827beb2edfSTejun Heo 
1883041bd12eSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
18847beb2edfSTejun Heo 		add_timer_on(timer, cpu);
1885041bd12eSTejun Heo 	else
1886041bd12eSTejun Heo 		add_timer(timer);
18877beb2edfSTejun Heo }
18881da177e4SLinus Torvalds 
18890fcb78c2SRolf Eike Beer /**
18900fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
18910fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
18920fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1893af9997e4SRandy Dunlap  * @dwork: work to queue
18940fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
18950fcb78c2SRolf Eike Beer  *
1896d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
1897715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1898715f1300STejun Heo  * execution.
18990fcb78c2SRolf Eike Beer  */
1900d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
190152bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
19027a6bc1cdSVenkatesh Pallipadi {
190352bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1904d4283e93STejun Heo 	bool ret = false;
19058930cabaSTejun Heo 	unsigned long flags;
19068930cabaSTejun Heo 
19078930cabaSTejun Heo 	/* read the comment in __queue_work() */
19088930cabaSTejun Heo 	local_irq_save(flags);
19097a6bc1cdSVenkatesh Pallipadi 
191022df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
19117beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1912d4283e93STejun Heo 		ret = true;
19137a6bc1cdSVenkatesh Pallipadi 	}
19148930cabaSTejun Heo 
19158930cabaSTejun Heo 	local_irq_restore(flags);
19167a6bc1cdSVenkatesh Pallipadi 	return ret;
19177a6bc1cdSVenkatesh Pallipadi }
1918ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
19191da177e4SLinus Torvalds 
1920c8e55f36STejun Heo /**
19218376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
19228376fe22STejun Heo  * @cpu: CPU number to execute work on
19238376fe22STejun Heo  * @wq: workqueue to use
19248376fe22STejun Heo  * @dwork: work to queue
19258376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
19268376fe22STejun Heo  *
19278376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
19288376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
19298376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
19308376fe22STejun Heo  * current state.
19318376fe22STejun Heo  *
1932d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
19338376fe22STejun Heo  * pending and its timer was modified.
19348376fe22STejun Heo  *
1935e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
19368376fe22STejun Heo  * See try_to_grab_pending() for details.
19378376fe22STejun Heo  */
19388376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
19398376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
19408376fe22STejun Heo {
19418376fe22STejun Heo 	unsigned long flags;
19428376fe22STejun Heo 	int ret;
19438376fe22STejun Heo 
19448376fe22STejun Heo 	do {
19458376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
19468376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
19478376fe22STejun Heo 
19488376fe22STejun Heo 	if (likely(ret >= 0)) {
19498376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
19508376fe22STejun Heo 		local_irq_restore(flags);
19518376fe22STejun Heo 	}
19528376fe22STejun Heo 
19538376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
19548376fe22STejun Heo 	return ret;
19558376fe22STejun Heo }
19568376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
19578376fe22STejun Heo 
195805f0fe6bSTejun Heo static void rcu_work_rcufn(struct rcu_head *rcu)
195905f0fe6bSTejun Heo {
196005f0fe6bSTejun Heo 	struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
196105f0fe6bSTejun Heo 
196205f0fe6bSTejun Heo 	/* read the comment in __queue_work() */
196305f0fe6bSTejun Heo 	local_irq_disable();
196405f0fe6bSTejun Heo 	__queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
196505f0fe6bSTejun Heo 	local_irq_enable();
196605f0fe6bSTejun Heo }
196705f0fe6bSTejun Heo 
196805f0fe6bSTejun Heo /**
196905f0fe6bSTejun Heo  * queue_rcu_work - queue work after a RCU grace period
197005f0fe6bSTejun Heo  * @wq: workqueue to use
197105f0fe6bSTejun Heo  * @rwork: work to queue
197205f0fe6bSTejun Heo  *
197305f0fe6bSTejun Heo  * Return: %false if @rwork was already pending, %true otherwise.  Note
197405f0fe6bSTejun Heo  * that a full RCU grace period is guaranteed only after a %true return.
1975bf393fd4SBart Van Assche  * While @rwork is guaranteed to be executed after a %false return, the
197605f0fe6bSTejun Heo  * execution may happen before a full RCU grace period has passed.
197705f0fe6bSTejun Heo  */
197805f0fe6bSTejun Heo bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
197905f0fe6bSTejun Heo {
198005f0fe6bSTejun Heo 	struct work_struct *work = &rwork->work;
198105f0fe6bSTejun Heo 
198205f0fe6bSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
198305f0fe6bSTejun Heo 		rwork->wq = wq;
1984a7e30c0eSUladzislau Rezki 		call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
198505f0fe6bSTejun Heo 		return true;
198605f0fe6bSTejun Heo 	}
198705f0fe6bSTejun Heo 
198805f0fe6bSTejun Heo 	return false;
198905f0fe6bSTejun Heo }
199005f0fe6bSTejun Heo EXPORT_SYMBOL(queue_rcu_work);
199105f0fe6bSTejun Heo 
1992f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
1993c34056a3STejun Heo {
1994c34056a3STejun Heo 	struct worker *worker;
1995c34056a3STejun Heo 
1996f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1997c8e55f36STejun Heo 	if (worker) {
1998c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1999affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
2000da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
2001e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
2002e22bee78STejun Heo 		worker->flags = WORKER_PREP;
2003c8e55f36STejun Heo 	}
2004c34056a3STejun Heo 	return worker;
2005c34056a3STejun Heo }
2006c34056a3STejun Heo 
2007c34056a3STejun Heo /**
20084736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
20094736cbf7SLai Jiangshan  * @worker: worker to be attached
20104736cbf7SLai Jiangshan  * @pool: the target pool
20114736cbf7SLai Jiangshan  *
20124736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
20134736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
20144736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
20154736cbf7SLai Jiangshan  */
20164736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
20174736cbf7SLai Jiangshan 				   struct worker_pool *pool)
20184736cbf7SLai Jiangshan {
20191258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
20204736cbf7SLai Jiangshan 
20214736cbf7SLai Jiangshan 	/*
20221258fae7STejun Heo 	 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
20231258fae7STejun Heo 	 * stable across this function.  See the comments above the flag
20241258fae7STejun Heo 	 * definition for details.
20254736cbf7SLai Jiangshan 	 */
20264736cbf7SLai Jiangshan 	if (pool->flags & POOL_DISASSOCIATED)
20274736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
20285c25b5ffSPeter Zijlstra 	else
20295c25b5ffSPeter Zijlstra 		kthread_set_per_cpu(worker->task, pool->cpu);
20304736cbf7SLai Jiangshan 
2031640f17c8SPeter Zijlstra 	if (worker->rescue_wq)
2032640f17c8SPeter Zijlstra 		set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
2033640f17c8SPeter Zijlstra 
20344736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
2035a2d812a2STejun Heo 	worker->pool = pool;
20364736cbf7SLai Jiangshan 
20371258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
20384736cbf7SLai Jiangshan }
20394736cbf7SLai Jiangshan 
20404736cbf7SLai Jiangshan /**
204160f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
204260f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
204360f5a4bcSLai Jiangshan  *
20444736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
20454736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
20464736cbf7SLai Jiangshan  * other reference to the pool.
204760f5a4bcSLai Jiangshan  */
2048a2d812a2STejun Heo static void worker_detach_from_pool(struct worker *worker)
204960f5a4bcSLai Jiangshan {
2050a2d812a2STejun Heo 	struct worker_pool *pool = worker->pool;
205160f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
205260f5a4bcSLai Jiangshan 
20531258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2054a2d812a2STejun Heo 
20555c25b5ffSPeter Zijlstra 	kthread_set_per_cpu(worker->task, -1);
2056da028469SLai Jiangshan 	list_del(&worker->node);
2057a2d812a2STejun Heo 	worker->pool = NULL;
2058a2d812a2STejun Heo 
2059e02b9312SValentin Schneider 	if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
206060f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
20611258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
206260f5a4bcSLai Jiangshan 
2063b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
2064b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2065b62c0751SLai Jiangshan 
206660f5a4bcSLai Jiangshan 	if (detach_completion)
206760f5a4bcSLai Jiangshan 		complete(detach_completion);
206860f5a4bcSLai Jiangshan }
206960f5a4bcSLai Jiangshan 
207060f5a4bcSLai Jiangshan /**
2071c34056a3STejun Heo  * create_worker - create a new workqueue worker
207263d95a91STejun Heo  * @pool: pool the new worker will belong to
2073c34056a3STejun Heo  *
2074051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
2075c34056a3STejun Heo  *
2076c34056a3STejun Heo  * CONTEXT:
2077c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
2078c34056a3STejun Heo  *
2079d185af30SYacine Belkadi  * Return:
2080c34056a3STejun Heo  * Pointer to the newly created worker.
2081c34056a3STejun Heo  */
2082bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
2083c34056a3STejun Heo {
2084e441b56fSZhen Lei 	struct worker *worker;
2085e441b56fSZhen Lei 	int id;
2086e3c916a4STejun Heo 	char id_buf[16];
2087c34056a3STejun Heo 
20887cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
2089e441b56fSZhen Lei 	id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
20903f0ea0b8SPetr Mladek 	if (id < 0) {
20913f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
20923f0ea0b8SPetr Mladek 			    ERR_PTR(id));
2093e441b56fSZhen Lei 		return NULL;
20943f0ea0b8SPetr Mladek 	}
2095c34056a3STejun Heo 
2096f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
20973f0ea0b8SPetr Mladek 	if (!worker) {
20983f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker\n");
2099c34056a3STejun Heo 		goto fail;
21003f0ea0b8SPetr Mladek 	}
2101c34056a3STejun Heo 
2102c34056a3STejun Heo 	worker->id = id;
2103c34056a3STejun Heo 
210429c91e99STejun Heo 	if (pool->cpu >= 0)
2105e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
2106e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
2107f3421797STejun Heo 	else
2108e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
2109e3c916a4STejun Heo 
2110f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
2111e3c916a4STejun Heo 					      "kworker/%s", id_buf);
21123f0ea0b8SPetr Mladek 	if (IS_ERR(worker->task)) {
211360f54038SPetr Mladek 		if (PTR_ERR(worker->task) == -EINTR) {
211460f54038SPetr Mladek 			pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n",
211560f54038SPetr Mladek 			       id_buf);
211660f54038SPetr Mladek 		} else {
21173f0ea0b8SPetr Mladek 			pr_err_once("workqueue: Failed to create a worker thread: %pe",
21183f0ea0b8SPetr Mladek 				    worker->task);
211960f54038SPetr Mladek 		}
2120c34056a3STejun Heo 		goto fail;
21213f0ea0b8SPetr Mladek 	}
2122c34056a3STejun Heo 
212391151228SOleg Nesterov 	set_user_nice(worker->task, pool->attrs->nice);
212425834c73SPeter Zijlstra 	kthread_bind_mask(worker->task, pool->attrs->cpumask);
212591151228SOleg Nesterov 
2126da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
21274736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
2128822d8405STejun Heo 
2129051e1850SLai Jiangshan 	/* start the newly created worker */
2130a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2131051e1850SLai Jiangshan 	worker->pool->nr_workers++;
2132051e1850SLai Jiangshan 	worker_enter_idle(worker);
2133051e1850SLai Jiangshan 	wake_up_process(worker->task);
2134a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2135051e1850SLai Jiangshan 
2136c34056a3STejun Heo 	return worker;
2137822d8405STejun Heo 
2138c34056a3STejun Heo fail:
2139e441b56fSZhen Lei 	ida_free(&pool->worker_ida, id);
2140c34056a3STejun Heo 	kfree(worker);
2141c34056a3STejun Heo 	return NULL;
2142c34056a3STejun Heo }
2143c34056a3STejun Heo 
2144793777bcSValentin Schneider static void unbind_worker(struct worker *worker)
2145793777bcSValentin Schneider {
2146793777bcSValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2147793777bcSValentin Schneider 
2148793777bcSValentin Schneider 	kthread_set_per_cpu(worker->task, -1);
2149793777bcSValentin Schneider 	if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2150793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2151793777bcSValentin Schneider 	else
2152793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2153793777bcSValentin Schneider }
2154793777bcSValentin Schneider 
2155e02b9312SValentin Schneider static void wake_dying_workers(struct list_head *cull_list)
2156e02b9312SValentin Schneider {
2157e02b9312SValentin Schneider 	struct worker *worker, *tmp;
2158e02b9312SValentin Schneider 
2159e02b9312SValentin Schneider 	list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2160e02b9312SValentin Schneider 		list_del_init(&worker->entry);
2161e02b9312SValentin Schneider 		unbind_worker(worker);
2162e02b9312SValentin Schneider 		/*
2163e02b9312SValentin Schneider 		 * If the worker was somehow already running, then it had to be
2164e02b9312SValentin Schneider 		 * in pool->idle_list when set_worker_dying() happened or we
2165e02b9312SValentin Schneider 		 * wouldn't have gotten here.
2166c34056a3STejun Heo 		 *
2167e02b9312SValentin Schneider 		 * Thus, the worker must either have observed the WORKER_DIE
2168e02b9312SValentin Schneider 		 * flag, or have set its state to TASK_IDLE. Either way, the
2169e02b9312SValentin Schneider 		 * below will be observed by the worker and is safe to do
2170e02b9312SValentin Schneider 		 * outside of pool->lock.
2171e02b9312SValentin Schneider 		 */
2172e02b9312SValentin Schneider 		wake_up_process(worker->task);
2173e02b9312SValentin Schneider 	}
2174e02b9312SValentin Schneider }
2175e02b9312SValentin Schneider 
2176e02b9312SValentin Schneider /**
2177e02b9312SValentin Schneider  * set_worker_dying - Tag a worker for destruction
2178e02b9312SValentin Schneider  * @worker: worker to be destroyed
2179e02b9312SValentin Schneider  * @list: transfer worker away from its pool->idle_list and into list
2180e02b9312SValentin Schneider  *
2181e02b9312SValentin Schneider  * Tag @worker for destruction and adjust @pool stats accordingly.  The worker
2182e02b9312SValentin Schneider  * should be idle.
2183c8e55f36STejun Heo  *
2184c8e55f36STejun Heo  * CONTEXT:
2185a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
2186c34056a3STejun Heo  */
2187e02b9312SValentin Schneider static void set_worker_dying(struct worker *worker, struct list_head *list)
2188c34056a3STejun Heo {
2189bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2190c34056a3STejun Heo 
2191cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
2192e02b9312SValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2193cd549687STejun Heo 
2194c34056a3STejun Heo 	/* sanity check frenzy */
21956183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
219673eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
219773eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
21986183c009STejun Heo 		return;
2199c34056a3STejun Heo 
2200bd7bdd43STejun Heo 	pool->nr_workers--;
2201bd7bdd43STejun Heo 	pool->nr_idle--;
2202c8e55f36STejun Heo 
2203cb444766STejun Heo 	worker->flags |= WORKER_DIE;
2204e02b9312SValentin Schneider 
2205e02b9312SValentin Schneider 	list_move(&worker->entry, list);
2206e02b9312SValentin Schneider 	list_move(&worker->node, &pool->dying_workers);
2207c34056a3STejun Heo }
2208c34056a3STejun Heo 
22093f959aa3SValentin Schneider /**
22103f959aa3SValentin Schneider  * idle_worker_timeout - check if some idle workers can now be deleted.
22113f959aa3SValentin Schneider  * @t: The pool's idle_timer that just expired
22123f959aa3SValentin Schneider  *
22133f959aa3SValentin Schneider  * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
22143f959aa3SValentin Schneider  * worker_leave_idle(), as a worker flicking between idle and active while its
22153f959aa3SValentin Schneider  * pool is at the too_many_workers() tipping point would cause too much timer
22163f959aa3SValentin Schneider  * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
22173f959aa3SValentin Schneider  * it expire and re-evaluate things from there.
22183f959aa3SValentin Schneider  */
221932a6c723SKees Cook static void idle_worker_timeout(struct timer_list *t)
2220e22bee78STejun Heo {
222132a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, idle_timer);
22223f959aa3SValentin Schneider 	bool do_cull = false;
22233f959aa3SValentin Schneider 
22243f959aa3SValentin Schneider 	if (work_pending(&pool->idle_cull_work))
22253f959aa3SValentin Schneider 		return;
22263f959aa3SValentin Schneider 
22273f959aa3SValentin Schneider 	raw_spin_lock_irq(&pool->lock);
22283f959aa3SValentin Schneider 
22293f959aa3SValentin Schneider 	if (too_many_workers(pool)) {
22303f959aa3SValentin Schneider 		struct worker *worker;
22313f959aa3SValentin Schneider 		unsigned long expires;
22323f959aa3SValentin Schneider 
22333f959aa3SValentin Schneider 		/* idle_list is kept in LIFO order, check the last one */
22343f959aa3SValentin Schneider 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
22353f959aa3SValentin Schneider 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
22363f959aa3SValentin Schneider 		do_cull = !time_before(jiffies, expires);
22373f959aa3SValentin Schneider 
22383f959aa3SValentin Schneider 		if (!do_cull)
22393f959aa3SValentin Schneider 			mod_timer(&pool->idle_timer, expires);
22403f959aa3SValentin Schneider 	}
22413f959aa3SValentin Schneider 	raw_spin_unlock_irq(&pool->lock);
22423f959aa3SValentin Schneider 
22433f959aa3SValentin Schneider 	if (do_cull)
22443f959aa3SValentin Schneider 		queue_work(system_unbound_wq, &pool->idle_cull_work);
22453f959aa3SValentin Schneider }
22463f959aa3SValentin Schneider 
22473f959aa3SValentin Schneider /**
22483f959aa3SValentin Schneider  * idle_cull_fn - cull workers that have been idle for too long.
22493f959aa3SValentin Schneider  * @work: the pool's work for handling these idle workers
22503f959aa3SValentin Schneider  *
22513f959aa3SValentin Schneider  * This goes through a pool's idle workers and gets rid of those that have been
22523f959aa3SValentin Schneider  * idle for at least IDLE_WORKER_TIMEOUT seconds.
2253e02b9312SValentin Schneider  *
2254e02b9312SValentin Schneider  * We don't want to disturb isolated CPUs because of a pcpu kworker being
2255e02b9312SValentin Schneider  * culled, so this also resets worker affinity. This requires a sleepable
2256e02b9312SValentin Schneider  * context, hence the split between timer callback and work item.
22573f959aa3SValentin Schneider  */
22583f959aa3SValentin Schneider static void idle_cull_fn(struct work_struct *work)
22593f959aa3SValentin Schneider {
22603f959aa3SValentin Schneider 	struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
22619680540cSYang Yingliang 	LIST_HEAD(cull_list);
2262e22bee78STejun Heo 
2263e02b9312SValentin Schneider 	/*
2264e02b9312SValentin Schneider 	 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2265e02b9312SValentin Schneider 	 * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2266e02b9312SValentin Schneider 	 * path. This is required as a previously-preempted worker could run after
2267e02b9312SValentin Schneider 	 * set_worker_dying() has happened but before wake_dying_workers() did.
2268e02b9312SValentin Schneider 	 */
2269e02b9312SValentin Schneider 	mutex_lock(&wq_pool_attach_mutex);
2270a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2271e22bee78STejun Heo 
22723347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
2273e22bee78STejun Heo 		struct worker *worker;
2274e22bee78STejun Heo 		unsigned long expires;
2275e22bee78STejun Heo 
227663d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
2277e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2278e22bee78STejun Heo 
22793347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
228063d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
22813347fc9fSLai Jiangshan 			break;
2282e22bee78STejun Heo 		}
22833347fc9fSLai Jiangshan 
2284e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
2285e22bee78STejun Heo 	}
2286e22bee78STejun Heo 
2287a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2288e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
2289e02b9312SValentin Schneider 	mutex_unlock(&wq_pool_attach_mutex);
2290e22bee78STejun Heo }
2291e22bee78STejun Heo 
2292493a1724STejun Heo static void send_mayday(struct work_struct *work)
2293e22bee78STejun Heo {
2294112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2295112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
2296493a1724STejun Heo 
22972e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
2298e22bee78STejun Heo 
2299493008a8STejun Heo 	if (!wq->rescuer)
2300493a1724STejun Heo 		return;
2301e22bee78STejun Heo 
2302e22bee78STejun Heo 	/* mayday mayday mayday */
2303493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
230477668c8bSLai Jiangshan 		/*
230577668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
230677668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
230777668c8bSLai Jiangshan 		 * rescuer is done with it.
230877668c8bSLai Jiangshan 		 */
230977668c8bSLai Jiangshan 		get_pwq(pwq);
2310493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
2311e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
2312725e8ec5STejun Heo 		pwq->stats[PWQ_STAT_MAYDAY]++;
2313493a1724STejun Heo 	}
2314e22bee78STejun Heo }
2315e22bee78STejun Heo 
231632a6c723SKees Cook static void pool_mayday_timeout(struct timer_list *t)
2317e22bee78STejun Heo {
231832a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2319e22bee78STejun Heo 	struct work_struct *work;
2320e22bee78STejun Heo 
2321a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2322a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&wq_mayday_lock);		/* for wq->maydays */
2323e22bee78STejun Heo 
232463d95a91STejun Heo 	if (need_to_create_worker(pool)) {
2325e22bee78STejun Heo 		/*
2326e22bee78STejun Heo 		 * We've been trying to create a new worker but
2327e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
2328e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
2329e22bee78STejun Heo 		 * rescuers.
2330e22bee78STejun Heo 		 */
233163d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
2332e22bee78STejun Heo 			send_mayday(work);
2333e22bee78STejun Heo 	}
2334e22bee78STejun Heo 
2335a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&wq_mayday_lock);
2336a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2337e22bee78STejun Heo 
233863d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2339e22bee78STejun Heo }
2340e22bee78STejun Heo 
2341e22bee78STejun Heo /**
2342e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
234363d95a91STejun Heo  * @pool: pool to create a new worker for
2344e22bee78STejun Heo  *
234563d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
2346e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
2347e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
234863d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
2349e22bee78STejun Heo  * possible allocation deadlock.
2350e22bee78STejun Heo  *
2351c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
2352c5aa87bbSTejun Heo  * may_start_working() %true.
2353e22bee78STejun Heo  *
2354e22bee78STejun Heo  * LOCKING:
2355a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2356e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
2357e22bee78STejun Heo  * manager.
2358e22bee78STejun Heo  */
235929187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
2360d565ed63STejun Heo __releases(&pool->lock)
2361d565ed63STejun Heo __acquires(&pool->lock)
2362e22bee78STejun Heo {
2363e22bee78STejun Heo restart:
2364a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
23659f9c2364STejun Heo 
2366e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
236763d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2368e22bee78STejun Heo 
2369e22bee78STejun Heo 	while (true) {
2370051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
2371e22bee78STejun Heo 			break;
2372e22bee78STejun Heo 
2373e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
23749f9c2364STejun Heo 
237563d95a91STejun Heo 		if (!need_to_create_worker(pool))
2376e22bee78STejun Heo 			break;
2377e22bee78STejun Heo 	}
2378e22bee78STejun Heo 
237963d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
2380a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2381051e1850SLai Jiangshan 	/*
2382051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
2383051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
2384051e1850SLai Jiangshan 	 * already become busy.
2385051e1850SLai Jiangshan 	 */
238663d95a91STejun Heo 	if (need_to_create_worker(pool))
2387e22bee78STejun Heo 		goto restart;
2388e22bee78STejun Heo }
2389e22bee78STejun Heo 
2390e22bee78STejun Heo /**
2391e22bee78STejun Heo  * manage_workers - manage worker pool
2392e22bee78STejun Heo  * @worker: self
2393e22bee78STejun Heo  *
2394706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
2395e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2396706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2397e22bee78STejun Heo  *
2398e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2399e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2400e22bee78STejun Heo  * and may_start_working() is true.
2401e22bee78STejun Heo  *
2402e22bee78STejun Heo  * CONTEXT:
2403a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2404e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2405e22bee78STejun Heo  *
2406d185af30SYacine Belkadi  * Return:
240729187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
240829187a9eSTejun Heo  * start processing works, %true if management function was performed and
240929187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
241029187a9eSTejun Heo  * no longer be true.
2411e22bee78STejun Heo  */
2412e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2413e22bee78STejun Heo {
241463d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2415e22bee78STejun Heo 
2416692b4825STejun Heo 	if (pool->flags & POOL_MANAGER_ACTIVE)
241729187a9eSTejun Heo 		return false;
2418692b4825STejun Heo 
2419692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
24202607d7a6STejun Heo 	pool->manager = worker;
2421e22bee78STejun Heo 
242229187a9eSTejun Heo 	maybe_create_worker(pool);
2423e22bee78STejun Heo 
24242607d7a6STejun Heo 	pool->manager = NULL;
2425692b4825STejun Heo 	pool->flags &= ~POOL_MANAGER_ACTIVE;
2426d8bb65abSSebastian Andrzej Siewior 	rcuwait_wake_up(&manager_wait);
242729187a9eSTejun Heo 	return true;
2428e22bee78STejun Heo }
2429e22bee78STejun Heo 
2430a62428c0STejun Heo /**
2431a62428c0STejun Heo  * process_one_work - process single work
2432c34056a3STejun Heo  * @worker: self
2433a62428c0STejun Heo  * @work: work to process
2434a62428c0STejun Heo  *
2435a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2436a62428c0STejun Heo  * process a single work including synchronization against and
2437a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2438a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2439a62428c0STejun Heo  * call this function to process a work.
2440a62428c0STejun Heo  *
2441a62428c0STejun Heo  * CONTEXT:
2442a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
2443a62428c0STejun Heo  */
2444c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2445d565ed63STejun Heo __releases(&pool->lock)
2446d565ed63STejun Heo __acquires(&pool->lock)
24471da177e4SLinus Torvalds {
2448112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2449bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2450c4560c2cSLai Jiangshan 	unsigned long work_data;
24517e11629dSTejun Heo 	struct worker *collision;
24524e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
24534e6045f1SJohannes Berg 	/*
2454a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2455a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2456a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2457a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2458a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
24594e6045f1SJohannes Berg 	 */
24604d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
24614d82a1deSPeter Zijlstra 
24624d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
24634e6045f1SJohannes Berg #endif
2464807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
246585327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2466ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
246725511a47STejun Heo 
24687e11629dSTejun Heo 	/*
24697e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
24707e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
24717e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
24727e11629dSTejun Heo 	 * currently executing one.
24737e11629dSTejun Heo 	 */
2474c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
24757e11629dSTejun Heo 	if (unlikely(collision)) {
24767e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
24777e11629dSTejun Heo 		return;
24787e11629dSTejun Heo 	}
24791da177e4SLinus Torvalds 
24808930cabaSTejun Heo 	/* claim and dequeue */
24811da177e4SLinus Torvalds 	debug_work_deactivate(work);
2482c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2483c34056a3STejun Heo 	worker->current_work = work;
2484a2c1c57bSTejun Heo 	worker->current_func = work->func;
2485112202d9STejun Heo 	worker->current_pwq = pwq;
2486616db877STejun Heo 	worker->current_at = worker->task->se.sum_exec_runtime;
2487c4560c2cSLai Jiangshan 	work_data = *work_data_bits(work);
2488d812796eSLai Jiangshan 	worker->current_color = get_work_color(work_data);
24897a22ad75STejun Heo 
24908bf89593STejun Heo 	/*
24918bf89593STejun Heo 	 * Record wq name for cmdline and debug reporting, may get
24928bf89593STejun Heo 	 * overridden through set_worker_desc().
24938bf89593STejun Heo 	 */
24948bf89593STejun Heo 	strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
24958bf89593STejun Heo 
2496a62428c0STejun Heo 	list_del_init(&work->entry);
2497a62428c0STejun Heo 
2498649027d7STejun Heo 	/*
2499228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
2500228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
2501228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
2502228f1d00SLai Jiangshan 	 * execution of the pending work items.
2503fb0e7bebSTejun Heo 	 */
2504616db877STejun Heo 	if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
2505228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2506fb0e7bebSTejun Heo 
2507974271c4STejun Heo 	/*
2508a489a03eSLai Jiangshan 	 * Wake up another worker if necessary.  The condition is always
2509a489a03eSLai Jiangshan 	 * false for normal per-cpu workers since nr_running would always
2510a489a03eSLai Jiangshan 	 * be >= 1 at this point.  This is used to chain execution of the
2511a489a03eSLai Jiangshan 	 * pending work items for WORKER_NOT_RUNNING workers such as the
2512228f1d00SLai Jiangshan 	 * UNBOUND and CPU_INTENSIVE ones.
2513974271c4STejun Heo 	 */
2514a489a03eSLai Jiangshan 	if (need_more_worker(pool))
251563d95a91STejun Heo 		wake_up_worker(pool);
2516974271c4STejun Heo 
25178930cabaSTejun Heo 	/*
25187c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2519d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
252023657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
252123657bb1STejun Heo 	 * disabled.
25228930cabaSTejun Heo 	 */
25237c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
25241da177e4SLinus Torvalds 
2525a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2526365970a1SDavid Howells 
2527a1d14934SPeter Zijlstra 	lock_map_acquire(&pwq->wq->lockdep_map);
25283295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2529e6f3faa7SPeter Zijlstra 	/*
2530f52be570SPeter Zijlstra 	 * Strictly speaking we should mark the invariant state without holding
2531f52be570SPeter Zijlstra 	 * any locks, that is, before these two lock_map_acquire()'s.
2532e6f3faa7SPeter Zijlstra 	 *
2533e6f3faa7SPeter Zijlstra 	 * However, that would result in:
2534e6f3faa7SPeter Zijlstra 	 *
2535e6f3faa7SPeter Zijlstra 	 *   A(W1)
2536e6f3faa7SPeter Zijlstra 	 *   WFC(C)
2537e6f3faa7SPeter Zijlstra 	 *		A(W1)
2538e6f3faa7SPeter Zijlstra 	 *		C(C)
2539e6f3faa7SPeter Zijlstra 	 *
2540e6f3faa7SPeter Zijlstra 	 * Which would create W1->C->W1 dependencies, even though there is no
2541e6f3faa7SPeter Zijlstra 	 * actual deadlock possible. There are two solutions, using a
2542e6f3faa7SPeter Zijlstra 	 * read-recursive acquire on the work(queue) 'locks', but this will then
2543f52be570SPeter Zijlstra 	 * hit the lockdep limitation on recursive locks, or simply discard
2544e6f3faa7SPeter Zijlstra 	 * these locks.
2545e6f3faa7SPeter Zijlstra 	 *
2546e6f3faa7SPeter Zijlstra 	 * AFAICT there is no possible deadlock scenario between the
2547e6f3faa7SPeter Zijlstra 	 * flush_work() and complete() primitives (except for single-threaded
2548e6f3faa7SPeter Zijlstra 	 * workqueues), so hiding them isn't a problem.
2549e6f3faa7SPeter Zijlstra 	 */
2550f52be570SPeter Zijlstra 	lockdep_invariant_state(true);
2551725e8ec5STejun Heo 	pwq->stats[PWQ_STAT_STARTED]++;
2552e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2553a2c1c57bSTejun Heo 	worker->current_func(work);
2554e36c886aSArjan van de Ven 	/*
2555e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2556e36c886aSArjan van de Ven 	 * point will only record its address.
2557e36c886aSArjan van de Ven 	 */
25581c5da0ecSDaniel Jordan 	trace_workqueue_execute_end(work, worker->current_func);
2559725e8ec5STejun Heo 	pwq->stats[PWQ_STAT_COMPLETED]++;
25603295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2561112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
25621da177e4SLinus Torvalds 
2563d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2564044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2565d75f773cSSakari Ailus 		       "     last function: %ps\n",
2566a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2567a2c1c57bSTejun Heo 		       worker->current_func);
2568d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2569d5abe669SPeter Zijlstra 		dump_stack();
2570d5abe669SPeter Zijlstra 	}
2571d5abe669SPeter Zijlstra 
2572b22ce278STejun Heo 	/*
2573025f50f3SSebastian Andrzej Siewior 	 * The following prevents a kworker from hogging CPU on !PREEMPTION
2574b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
2575b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
2576b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
2577789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
2578789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
2579b22ce278STejun Heo 	 */
2580a7e6425eSPaul E. McKenney 	cond_resched();
2581b22ce278STejun Heo 
2582a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2583a62428c0STejun Heo 
2584616db877STejun Heo 	/*
2585616db877STejun Heo 	 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
2586616db877STejun Heo 	 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
2587616db877STejun Heo 	 * wq_cpu_intensive_thresh_us. Clear it.
2588616db877STejun Heo 	 */
2589fb0e7bebSTejun Heo 	worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2590fb0e7bebSTejun Heo 
25911b69ac6bSJohannes Weiner 	/* tag the worker for identification in schedule() */
25921b69ac6bSJohannes Weiner 	worker->last_func = worker->current_func;
25931b69ac6bSJohannes Weiner 
2594a62428c0STejun Heo 	/* we're done with it, release */
259542f8570fSSasha Levin 	hash_del(&worker->hentry);
2596c34056a3STejun Heo 	worker->current_work = NULL;
2597a2c1c57bSTejun Heo 	worker->current_func = NULL;
2598112202d9STejun Heo 	worker->current_pwq = NULL;
2599d812796eSLai Jiangshan 	worker->current_color = INT_MAX;
2600c4560c2cSLai Jiangshan 	pwq_dec_nr_in_flight(pwq, work_data);
26011da177e4SLinus Torvalds }
26021da177e4SLinus Torvalds 
2603affee4b2STejun Heo /**
2604affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2605affee4b2STejun Heo  * @worker: self
2606affee4b2STejun Heo  *
2607affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2608affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2609affee4b2STejun Heo  * fetches a work from the top and executes it.
2610affee4b2STejun Heo  *
2611affee4b2STejun Heo  * CONTEXT:
2612a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2613affee4b2STejun Heo  * multiple times.
2614affee4b2STejun Heo  */
2615affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
26161da177e4SLinus Torvalds {
2617c0ab017dSTejun Heo 	struct work_struct *work;
2618c0ab017dSTejun Heo 	bool first = true;
2619c0ab017dSTejun Heo 
2620c0ab017dSTejun Heo 	while ((work = list_first_entry_or_null(&worker->scheduled,
2621c0ab017dSTejun Heo 						struct work_struct, entry))) {
2622c0ab017dSTejun Heo 		if (first) {
2623c0ab017dSTejun Heo 			worker->pool->watchdog_ts = jiffies;
2624c0ab017dSTejun Heo 			first = false;
2625c0ab017dSTejun Heo 		}
2626c34056a3STejun Heo 		process_one_work(worker, work);
2627a62428c0STejun Heo 	}
26281da177e4SLinus Torvalds }
26291da177e4SLinus Torvalds 
2630197f6accSTejun Heo static void set_pf_worker(bool val)
2631197f6accSTejun Heo {
2632197f6accSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2633197f6accSTejun Heo 	if (val)
2634197f6accSTejun Heo 		current->flags |= PF_WQ_WORKER;
2635197f6accSTejun Heo 	else
2636197f6accSTejun Heo 		current->flags &= ~PF_WQ_WORKER;
2637197f6accSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
2638197f6accSTejun Heo }
2639197f6accSTejun Heo 
26404690c4abSTejun Heo /**
26414690c4abSTejun Heo  * worker_thread - the worker thread function
2642c34056a3STejun Heo  * @__worker: self
26434690c4abSTejun Heo  *
2644c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2645c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2646c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2647c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2648c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
2649d185af30SYacine Belkadi  *
2650d185af30SYacine Belkadi  * Return: 0
26514690c4abSTejun Heo  */
2652c34056a3STejun Heo static int worker_thread(void *__worker)
26531da177e4SLinus Torvalds {
2654c34056a3STejun Heo 	struct worker *worker = __worker;
2655bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
26561da177e4SLinus Torvalds 
2657e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2658197f6accSTejun Heo 	set_pf_worker(true);
2659c8e55f36STejun Heo woke_up:
2660a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2661affee4b2STejun Heo 
2662a9ab775bSTejun Heo 	/* am I supposed to die? */
2663a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2664a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
2665197f6accSTejun Heo 		set_pf_worker(false);
266660f5a4bcSLai Jiangshan 
266760f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
2668e441b56fSZhen Lei 		ida_free(&pool->worker_ida, worker->id);
2669a2d812a2STejun Heo 		worker_detach_from_pool(worker);
2670e02b9312SValentin Schneider 		WARN_ON_ONCE(!list_empty(&worker->entry));
267160f5a4bcSLai Jiangshan 		kfree(worker);
2672c8e55f36STejun Heo 		return 0;
2673c8e55f36STejun Heo 	}
2674c8e55f36STejun Heo 
2675c8e55f36STejun Heo 	worker_leave_idle(worker);
2676db7bccf4STejun Heo recheck:
2677e22bee78STejun Heo 	/* no more worker necessary? */
267863d95a91STejun Heo 	if (!need_more_worker(pool))
2679e22bee78STejun Heo 		goto sleep;
2680e22bee78STejun Heo 
2681e22bee78STejun Heo 	/* do we need to manage? */
268263d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2683e22bee78STejun Heo 		goto recheck;
2684e22bee78STejun Heo 
2685c8e55f36STejun Heo 	/*
2686c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2687c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2688c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2689c8e55f36STejun Heo 	 */
26906183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2691c8e55f36STejun Heo 
2692e22bee78STejun Heo 	/*
2693a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2694a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2695a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2696a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2697a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2698e22bee78STejun Heo 	 */
2699a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2700e22bee78STejun Heo 
2701e22bee78STejun Heo 	do {
2702affee4b2STejun Heo 		struct work_struct *work =
2703bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2704affee4b2STejun Heo 					 struct work_struct, entry);
2705affee4b2STejun Heo 
2706c8e55f36STejun Heo 		move_linked_works(work, &worker->scheduled, NULL);
2707affee4b2STejun Heo 		process_scheduled_works(worker);
270863d95a91STejun Heo 	} while (keep_working(pool));
2709affee4b2STejun Heo 
2710228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
2711d313dd85STejun Heo sleep:
2712c8e55f36STejun Heo 	/*
2713d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2714d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2715d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2716d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2717d565ed63STejun Heo 	 * event.
2718c8e55f36STejun Heo 	 */
2719c8e55f36STejun Heo 	worker_enter_idle(worker);
2720c5a94a61SPeter Zijlstra 	__set_current_state(TASK_IDLE);
2721a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
27221da177e4SLinus Torvalds 	schedule();
2723c8e55f36STejun Heo 	goto woke_up;
27241da177e4SLinus Torvalds }
27251da177e4SLinus Torvalds 
2726e22bee78STejun Heo /**
2727e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2728111c225aSTejun Heo  * @__rescuer: self
2729e22bee78STejun Heo  *
2730e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2731493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2732e22bee78STejun Heo  *
2733706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2734e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2735e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2736e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2737e22bee78STejun Heo  * the problem rescuer solves.
2738e22bee78STejun Heo  *
2739706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2740706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2741e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2742e22bee78STejun Heo  *
2743e22bee78STejun Heo  * This should happen rarely.
2744d185af30SYacine Belkadi  *
2745d185af30SYacine Belkadi  * Return: 0
2746e22bee78STejun Heo  */
2747111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2748e22bee78STejun Heo {
2749111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2750111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2751e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
27524d595b86SLai Jiangshan 	bool should_stop;
2753e22bee78STejun Heo 
2754e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2755111c225aSTejun Heo 
2756111c225aSTejun Heo 	/*
2757111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2758111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2759111c225aSTejun Heo 	 */
2760197f6accSTejun Heo 	set_pf_worker(true);
2761e22bee78STejun Heo repeat:
2762c5a94a61SPeter Zijlstra 	set_current_state(TASK_IDLE);
27631da177e4SLinus Torvalds 
27644d595b86SLai Jiangshan 	/*
27654d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
27664d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
27674d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
27684d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
27694d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
27704d595b86SLai Jiangshan 	 * list is always empty on exit.
27714d595b86SLai Jiangshan 	 */
27724d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
27731da177e4SLinus Torvalds 
2774493a1724STejun Heo 	/* see whether any pwq is asking for help */
2775a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq_mayday_lock);
2776493a1724STejun Heo 
2777493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2778493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2779493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2780112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2781e22bee78STejun Heo 		struct work_struct *work, *n;
2782e22bee78STejun Heo 
2783e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2784493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2785493a1724STejun Heo 
2786a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
2787e22bee78STejun Heo 
278851697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
278951697d39SLai Jiangshan 
2790a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
2791e22bee78STejun Heo 
2792e22bee78STejun Heo 		/*
2793e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2794e22bee78STejun Heo 		 * process'em.
2795e22bee78STejun Heo 		 */
27960479c8c5STejun Heo 		WARN_ON_ONCE(!list_empty(scheduled));
279782607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
279882607adcSTejun Heo 			if (get_work_pwq(work) == pwq) {
2799e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
2800725e8ec5STejun Heo 				pwq->stats[PWQ_STAT_RESCUED]++;
280182607adcSTejun Heo 			}
280282607adcSTejun Heo 		}
2803e22bee78STejun Heo 
2804008847f6SNeilBrown 		if (!list_empty(scheduled)) {
2805e22bee78STejun Heo 			process_scheduled_works(rescuer);
28067576958aSTejun Heo 
28077576958aSTejun Heo 			/*
2808008847f6SNeilBrown 			 * The above execution of rescued work items could
2809008847f6SNeilBrown 			 * have created more to rescue through
2810f97a4a1aSLai Jiangshan 			 * pwq_activate_first_inactive() or chained
2811008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
2812008847f6SNeilBrown 			 * that such back-to-back work items, which may be
2813008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
2814008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
2815008847f6SNeilBrown 			 */
28164f3f4cf3SLai Jiangshan 			if (pwq->nr_active && need_to_create_worker(pool)) {
2817a9b8a985SSebastian Andrzej Siewior 				raw_spin_lock(&wq_mayday_lock);
2818e66b39afSTejun Heo 				/*
2819e66b39afSTejun Heo 				 * Queue iff we aren't racing destruction
2820e66b39afSTejun Heo 				 * and somebody else hasn't queued it already.
2821e66b39afSTejun Heo 				 */
2822e66b39afSTejun Heo 				if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2823008847f6SNeilBrown 					get_pwq(pwq);
2824e66b39afSTejun Heo 					list_add_tail(&pwq->mayday_node, &wq->maydays);
2825e66b39afSTejun Heo 				}
2826a9b8a985SSebastian Andrzej Siewior 				raw_spin_unlock(&wq_mayday_lock);
2827008847f6SNeilBrown 			}
2828008847f6SNeilBrown 		}
2829008847f6SNeilBrown 
2830008847f6SNeilBrown 		/*
283177668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
283213b1d625SLai Jiangshan 		 * go away while we're still attached to it.
283377668c8bSLai Jiangshan 		 */
283477668c8bSLai Jiangshan 		put_pwq(pwq);
283577668c8bSLai Jiangshan 
283677668c8bSLai Jiangshan 		/*
2837d8ca83e6SLai Jiangshan 		 * Leave this pool.  If need_more_worker() is %true, notify a
28387576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
28397576958aSTejun Heo 		 * and stalling the execution.
28407576958aSTejun Heo 		 */
2841d8ca83e6SLai Jiangshan 		if (need_more_worker(pool))
284263d95a91STejun Heo 			wake_up_worker(pool);
28437576958aSTejun Heo 
2844a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
284513b1d625SLai Jiangshan 
2846a2d812a2STejun Heo 		worker_detach_from_pool(rescuer);
284713b1d625SLai Jiangshan 
2848a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
28491da177e4SLinus Torvalds 	}
28501da177e4SLinus Torvalds 
2851a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq_mayday_lock);
2852493a1724STejun Heo 
28534d595b86SLai Jiangshan 	if (should_stop) {
28544d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
2855197f6accSTejun Heo 		set_pf_worker(false);
28564d595b86SLai Jiangshan 		return 0;
28574d595b86SLai Jiangshan 	}
28584d595b86SLai Jiangshan 
2859111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2860111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2861e22bee78STejun Heo 	schedule();
2862e22bee78STejun Heo 	goto repeat;
28631da177e4SLinus Torvalds }
28641da177e4SLinus Torvalds 
2865fca839c0STejun Heo /**
2866fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
2867fca839c0STejun Heo  * @target_wq: workqueue being flushed
2868fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
2869fca839c0STejun Heo  *
2870fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
2871fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2872fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
2873fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2874fca839c0STejun Heo  * a deadlock.
2875fca839c0STejun Heo  */
2876fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
2877fca839c0STejun Heo 				   struct work_struct *target_work)
2878fca839c0STejun Heo {
2879fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
2880fca839c0STejun Heo 	struct worker *worker;
2881fca839c0STejun Heo 
2882fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
2883fca839c0STejun Heo 		return;
2884fca839c0STejun Heo 
2885fca839c0STejun Heo 	worker = current_wq_worker();
2886fca839c0STejun Heo 
2887fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
2888d75f773cSSakari Ailus 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
2889fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
289023d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
289123d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2892d75f773cSSakari Ailus 		  "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
2893fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
2894fca839c0STejun Heo 		  target_wq->name, target_func);
2895fca839c0STejun Heo }
2896fca839c0STejun Heo 
2897fc2e4d70SOleg Nesterov struct wq_barrier {
2898fc2e4d70SOleg Nesterov 	struct work_struct	work;
2899fc2e4d70SOleg Nesterov 	struct completion	done;
29002607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
2901fc2e4d70SOleg Nesterov };
2902fc2e4d70SOleg Nesterov 
2903fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2904fc2e4d70SOleg Nesterov {
2905fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2906fc2e4d70SOleg Nesterov 	complete(&barr->done);
2907fc2e4d70SOleg Nesterov }
2908fc2e4d70SOleg Nesterov 
29094690c4abSTejun Heo /**
29104690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2911112202d9STejun Heo  * @pwq: pwq to insert barrier into
29124690c4abSTejun Heo  * @barr: wq_barrier to insert
2913affee4b2STejun Heo  * @target: target work to attach @barr to
2914affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
29154690c4abSTejun Heo  *
2916affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2917affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2918affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2919affee4b2STejun Heo  * cpu.
2920affee4b2STejun Heo  *
2921affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2922affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2923affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2924affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2925affee4b2STejun Heo  * after a work with LINKED flag set.
2926affee4b2STejun Heo  *
2927affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2928112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
29294690c4abSTejun Heo  *
29304690c4abSTejun Heo  * CONTEXT:
2931a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
29324690c4abSTejun Heo  */
2933112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2934affee4b2STejun Heo 			      struct wq_barrier *barr,
2935affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2936fc2e4d70SOleg Nesterov {
2937d812796eSLai Jiangshan 	unsigned int work_flags = 0;
2938d812796eSLai Jiangshan 	unsigned int work_color;
2939affee4b2STejun Heo 	struct list_head *head;
2940affee4b2STejun Heo 
2941dc186ad7SThomas Gleixner 	/*
2942d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2943dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2944dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2945dc186ad7SThomas Gleixner 	 * might deadlock.
2946dc186ad7SThomas Gleixner 	 */
2947ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
294822df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
294952fa5bc5SBoqun Feng 
2950fd1a5b04SByungchul Park 	init_completion_map(&barr->done, &target->lockdep_map);
2951fd1a5b04SByungchul Park 
29522607d7a6STejun Heo 	barr->task = current;
295383c22520SOleg Nesterov 
2954018f3a13SLai Jiangshan 	/* The barrier work item does not participate in pwq->nr_active. */
2955018f3a13SLai Jiangshan 	work_flags |= WORK_STRUCT_INACTIVE;
2956018f3a13SLai Jiangshan 
2957affee4b2STejun Heo 	/*
2958affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2959affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2960affee4b2STejun Heo 	 */
2961d812796eSLai Jiangshan 	if (worker) {
2962affee4b2STejun Heo 		head = worker->scheduled.next;
2963d812796eSLai Jiangshan 		work_color = worker->current_color;
2964d812796eSLai Jiangshan 	} else {
2965affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2966affee4b2STejun Heo 
2967affee4b2STejun Heo 		head = target->entry.next;
2968affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2969d21cece0SLai Jiangshan 		work_flags |= *bits & WORK_STRUCT_LINKED;
2970d812796eSLai Jiangshan 		work_color = get_work_color(*bits);
2971affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2972affee4b2STejun Heo 	}
2973affee4b2STejun Heo 
2974d812796eSLai Jiangshan 	pwq->nr_in_flight[work_color]++;
2975d812796eSLai Jiangshan 	work_flags |= work_color_to_flags(work_color);
2976d812796eSLai Jiangshan 
2977d21cece0SLai Jiangshan 	insert_work(pwq, &barr->work, head, work_flags);
2978fc2e4d70SOleg Nesterov }
2979fc2e4d70SOleg Nesterov 
298073f53c4aSTejun Heo /**
2981112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
298273f53c4aSTejun Heo  * @wq: workqueue being flushed
298373f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
298473f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
298573f53c4aSTejun Heo  *
2986112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
298773f53c4aSTejun Heo  *
2988112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
2989112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
2990112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
2991112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
2992112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
299373f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
299473f53c4aSTejun Heo  *
299573f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
299673f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
299773f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
299873f53c4aSTejun Heo  * is returned.
299973f53c4aSTejun Heo  *
3000112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
300173f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
300273f53c4aSTejun Heo  * advanced to @work_color.
300373f53c4aSTejun Heo  *
300473f53c4aSTejun Heo  * CONTEXT:
30053c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
300673f53c4aSTejun Heo  *
3007d185af30SYacine Belkadi  * Return:
300873f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
300973f53c4aSTejun Heo  * otherwise.
301073f53c4aSTejun Heo  */
3011112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
301273f53c4aSTejun Heo 				      int flush_color, int work_color)
30131da177e4SLinus Torvalds {
301473f53c4aSTejun Heo 	bool wait = false;
301549e3cf44STejun Heo 	struct pool_workqueue *pwq;
30161da177e4SLinus Torvalds 
301773f53c4aSTejun Heo 	if (flush_color >= 0) {
30186183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
3019112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
3020dc186ad7SThomas Gleixner 	}
302114441960SOleg Nesterov 
302249e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3023112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
30241da177e4SLinus Torvalds 
3025a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
302673f53c4aSTejun Heo 
302773f53c4aSTejun Heo 		if (flush_color >= 0) {
30286183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
302973f53c4aSTejun Heo 
3030112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
3031112202d9STejun Heo 				pwq->flush_color = flush_color;
3032112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
303373f53c4aSTejun Heo 				wait = true;
30341da177e4SLinus Torvalds 			}
303573f53c4aSTejun Heo 		}
303673f53c4aSTejun Heo 
303773f53c4aSTejun Heo 		if (work_color >= 0) {
30386183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
3039112202d9STejun Heo 			pwq->work_color = work_color;
304073f53c4aSTejun Heo 		}
304173f53c4aSTejun Heo 
3042a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
30431da177e4SLinus Torvalds 	}
30441da177e4SLinus Torvalds 
3045112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
304673f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
304773f53c4aSTejun Heo 
304873f53c4aSTejun Heo 	return wait;
304983c22520SOleg Nesterov }
30501da177e4SLinus Torvalds 
30510fcb78c2SRolf Eike Beer /**
3052c4f135d6STetsuo Handa  * __flush_workqueue - ensure that any scheduled work has run to completion.
30530fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
30541da177e4SLinus Torvalds  *
3055c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
3056c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
30571da177e4SLinus Torvalds  */
3058c4f135d6STetsuo Handa void __flush_workqueue(struct workqueue_struct *wq)
30591da177e4SLinus Torvalds {
306073f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
306173f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
306273f53c4aSTejun Heo 		.flush_color = -1,
3063fd1a5b04SByungchul Park 		.done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
306473f53c4aSTejun Heo 	};
306573f53c4aSTejun Heo 	int next_color;
3066b1f4ec17SOleg Nesterov 
30673347fa09STejun Heo 	if (WARN_ON(!wq_online))
30683347fa09STejun Heo 		return;
30693347fa09STejun Heo 
307087915adcSJohannes Berg 	lock_map_acquire(&wq->lockdep_map);
307187915adcSJohannes Berg 	lock_map_release(&wq->lockdep_map);
307287915adcSJohannes Berg 
30733c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
307473f53c4aSTejun Heo 
307573f53c4aSTejun Heo 	/*
307673f53c4aSTejun Heo 	 * Start-to-wait phase
307773f53c4aSTejun Heo 	 */
307873f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
307973f53c4aSTejun Heo 
308073f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
308173f53c4aSTejun Heo 		/*
308273f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
308373f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
308473f53c4aSTejun Heo 		 * by one.
308573f53c4aSTejun Heo 		 */
30866183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
308773f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
308873f53c4aSTejun Heo 		wq->work_color = next_color;
308973f53c4aSTejun Heo 
309073f53c4aSTejun Heo 		if (!wq->first_flusher) {
309173f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
30926183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
309373f53c4aSTejun Heo 
309473f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
309573f53c4aSTejun Heo 
3096112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
309773f53c4aSTejun Heo 						       wq->work_color)) {
309873f53c4aSTejun Heo 				/* nothing to flush, done */
309973f53c4aSTejun Heo 				wq->flush_color = next_color;
310073f53c4aSTejun Heo 				wq->first_flusher = NULL;
310173f53c4aSTejun Heo 				goto out_unlock;
310273f53c4aSTejun Heo 			}
310373f53c4aSTejun Heo 		} else {
310473f53c4aSTejun Heo 			/* wait in queue */
31056183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
310673f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
3107112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
310873f53c4aSTejun Heo 		}
310973f53c4aSTejun Heo 	} else {
311073f53c4aSTejun Heo 		/*
311173f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
311273f53c4aSTejun Heo 		 * The next flush completion will assign us
311373f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
311473f53c4aSTejun Heo 		 */
311573f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
311673f53c4aSTejun Heo 	}
311773f53c4aSTejun Heo 
3118fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
3119fca839c0STejun Heo 
31203c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
312173f53c4aSTejun Heo 
312273f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
312373f53c4aSTejun Heo 
312473f53c4aSTejun Heo 	/*
312573f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
312673f53c4aSTejun Heo 	 *
312773f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
312873f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
312973f53c4aSTejun Heo 	 */
313000d5d15bSChris Wilson 	if (READ_ONCE(wq->first_flusher) != &this_flusher)
313173f53c4aSTejun Heo 		return;
313273f53c4aSTejun Heo 
31333c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
313473f53c4aSTejun Heo 
31354ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
31364ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
31374ce48b37STejun Heo 		goto out_unlock;
31384ce48b37STejun Heo 
313900d5d15bSChris Wilson 	WRITE_ONCE(wq->first_flusher, NULL);
314073f53c4aSTejun Heo 
31416183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
31426183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
314373f53c4aSTejun Heo 
314473f53c4aSTejun Heo 	while (true) {
314573f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
314673f53c4aSTejun Heo 
314773f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
314873f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
314973f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
315073f53c4aSTejun Heo 				break;
315173f53c4aSTejun Heo 			list_del_init(&next->list);
315273f53c4aSTejun Heo 			complete(&next->done);
315373f53c4aSTejun Heo 		}
315473f53c4aSTejun Heo 
31556183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
315673f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
315773f53c4aSTejun Heo 
315873f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
315973f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
316073f53c4aSTejun Heo 
316173f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
316273f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
316373f53c4aSTejun Heo 			/*
316473f53c4aSTejun Heo 			 * Assign the same color to all overflowed
316573f53c4aSTejun Heo 			 * flushers, advance work_color and append to
316673f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
316773f53c4aSTejun Heo 			 * phase for these overflowed flushers.
316873f53c4aSTejun Heo 			 */
316973f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
317073f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
317173f53c4aSTejun Heo 
317273f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
317373f53c4aSTejun Heo 
317473f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
317573f53c4aSTejun Heo 					      &wq->flusher_queue);
3176112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
317773f53c4aSTejun Heo 		}
317873f53c4aSTejun Heo 
317973f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
31806183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
318173f53c4aSTejun Heo 			break;
318273f53c4aSTejun Heo 		}
318373f53c4aSTejun Heo 
318473f53c4aSTejun Heo 		/*
318573f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
3186112202d9STejun Heo 		 * the new first flusher and arm pwqs.
318773f53c4aSTejun Heo 		 */
31886183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
31896183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
319073f53c4aSTejun Heo 
319173f53c4aSTejun Heo 		list_del_init(&next->list);
319273f53c4aSTejun Heo 		wq->first_flusher = next;
319373f53c4aSTejun Heo 
3194112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
319573f53c4aSTejun Heo 			break;
319673f53c4aSTejun Heo 
319773f53c4aSTejun Heo 		/*
319873f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
319973f53c4aSTejun Heo 		 * flusher and repeat cascading.
320073f53c4aSTejun Heo 		 */
320173f53c4aSTejun Heo 		wq->first_flusher = NULL;
320273f53c4aSTejun Heo 	}
320373f53c4aSTejun Heo 
320473f53c4aSTejun Heo out_unlock:
32053c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
32061da177e4SLinus Torvalds }
3207c4f135d6STetsuo Handa EXPORT_SYMBOL(__flush_workqueue);
32081da177e4SLinus Torvalds 
32099c5a2ba7STejun Heo /**
32109c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
32119c5a2ba7STejun Heo  * @wq: workqueue to drain
32129c5a2ba7STejun Heo  *
32139c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
32149c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
32159c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
3216b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
32179c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
32189c5a2ba7STejun Heo  * takes too long.
32199c5a2ba7STejun Heo  */
32209c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
32219c5a2ba7STejun Heo {
32229c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
322349e3cf44STejun Heo 	struct pool_workqueue *pwq;
32249c5a2ba7STejun Heo 
32259c5a2ba7STejun Heo 	/*
32269c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
32279c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
3228618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
32299c5a2ba7STejun Heo 	 */
323087fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
32319c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
3232618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
323387fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
32349c5a2ba7STejun Heo reflush:
3235c4f135d6STetsuo Handa 	__flush_workqueue(wq);
32369c5a2ba7STejun Heo 
3237b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
323876af4d93STejun Heo 
323949e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3240fa2563e4SThomas Tuttle 		bool drained;
32419c5a2ba7STejun Heo 
3242a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
3243f97a4a1aSLai Jiangshan 		drained = !pwq->nr_active && list_empty(&pwq->inactive_works);
3244a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
3245fa2563e4SThomas Tuttle 
3246fa2563e4SThomas Tuttle 		if (drained)
32479c5a2ba7STejun Heo 			continue;
32489c5a2ba7STejun Heo 
32499c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
32509c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
3251e9ad2eb3SStephen Zhang 			pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3252e9ad2eb3SStephen Zhang 				wq->name, __func__, flush_cnt);
325376af4d93STejun Heo 
3254b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
32559c5a2ba7STejun Heo 		goto reflush;
32569c5a2ba7STejun Heo 	}
32579c5a2ba7STejun Heo 
32589c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
3259618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
326087fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
32619c5a2ba7STejun Heo }
32629c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
32639c5a2ba7STejun Heo 
3264d6e89786SJohannes Berg static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3265d6e89786SJohannes Berg 			     bool from_cancel)
3266baf59022STejun Heo {
3267baf59022STejun Heo 	struct worker *worker = NULL;
3268c9e7cf27STejun Heo 	struct worker_pool *pool;
3269112202d9STejun Heo 	struct pool_workqueue *pwq;
3270baf59022STejun Heo 
3271baf59022STejun Heo 	might_sleep();
3272baf59022STejun Heo 
327324acfb71SThomas Gleixner 	rcu_read_lock();
3274fa1b54e6STejun Heo 	pool = get_work_pool(work);
3275fa1b54e6STejun Heo 	if (!pool) {
327624acfb71SThomas Gleixner 		rcu_read_unlock();
3277fa1b54e6STejun Heo 		return false;
3278fa1b54e6STejun Heo 	}
3279fa1b54e6STejun Heo 
3280a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
32810b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
3282112202d9STejun Heo 	pwq = get_work_pwq(work);
3283112202d9STejun Heo 	if (pwq) {
3284112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
3285baf59022STejun Heo 			goto already_gone;
3286606a5020STejun Heo 	} else {
3287c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
3288baf59022STejun Heo 		if (!worker)
3289baf59022STejun Heo 			goto already_gone;
3290112202d9STejun Heo 		pwq = worker->current_pwq;
3291606a5020STejun Heo 	}
3292baf59022STejun Heo 
3293fca839c0STejun Heo 	check_flush_dependency(pwq->wq, work);
3294fca839c0STejun Heo 
3295112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
3296a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
3297baf59022STejun Heo 
3298e159489bSTejun Heo 	/*
3299a1d14934SPeter Zijlstra 	 * Force a lock recursion deadlock when using flush_work() inside a
3300a1d14934SPeter Zijlstra 	 * single-threaded or rescuer equipped workqueue.
3301a1d14934SPeter Zijlstra 	 *
3302a1d14934SPeter Zijlstra 	 * For single threaded workqueues the deadlock happens when the work
3303a1d14934SPeter Zijlstra 	 * is after the work issuing the flush_work(). For rescuer equipped
3304a1d14934SPeter Zijlstra 	 * workqueues the deadlock happens when the rescuer stalls, blocking
3305a1d14934SPeter Zijlstra 	 * forward progress.
3306e159489bSTejun Heo 	 */
3307d6e89786SJohannes Berg 	if (!from_cancel &&
3308d6e89786SJohannes Berg 	    (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
3309112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
3310112202d9STejun Heo 		lock_map_release(&pwq->wq->lockdep_map);
3311a1d14934SPeter Zijlstra 	}
331224acfb71SThomas Gleixner 	rcu_read_unlock();
3313baf59022STejun Heo 	return true;
3314baf59022STejun Heo already_gone:
3315a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
331624acfb71SThomas Gleixner 	rcu_read_unlock();
3317baf59022STejun Heo 	return false;
3318baf59022STejun Heo }
3319baf59022STejun Heo 
3320d6e89786SJohannes Berg static bool __flush_work(struct work_struct *work, bool from_cancel)
3321d6e89786SJohannes Berg {
3322d6e89786SJohannes Berg 	struct wq_barrier barr;
3323d6e89786SJohannes Berg 
3324d6e89786SJohannes Berg 	if (WARN_ON(!wq_online))
3325d6e89786SJohannes Berg 		return false;
3326d6e89786SJohannes Berg 
33274d43d395STetsuo Handa 	if (WARN_ON(!work->func))
33284d43d395STetsuo Handa 		return false;
33294d43d395STetsuo Handa 
333087915adcSJohannes Berg 	lock_map_acquire(&work->lockdep_map);
333187915adcSJohannes Berg 	lock_map_release(&work->lockdep_map);
333287915adcSJohannes Berg 
3333d6e89786SJohannes Berg 	if (start_flush_work(work, &barr, from_cancel)) {
3334d6e89786SJohannes Berg 		wait_for_completion(&barr.done);
3335d6e89786SJohannes Berg 		destroy_work_on_stack(&barr.work);
3336d6e89786SJohannes Berg 		return true;
3337d6e89786SJohannes Berg 	} else {
3338d6e89786SJohannes Berg 		return false;
3339d6e89786SJohannes Berg 	}
3340d6e89786SJohannes Berg }
3341d6e89786SJohannes Berg 
3342db700897SOleg Nesterov /**
3343401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
3344401a8d04STejun Heo  * @work: the work to flush
3345db700897SOleg Nesterov  *
3346606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
3347606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
3348401a8d04STejun Heo  *
3349d185af30SYacine Belkadi  * Return:
3350401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3351401a8d04STejun Heo  * %false if it was already idle.
3352db700897SOleg Nesterov  */
3353401a8d04STejun Heo bool flush_work(struct work_struct *work)
3354db700897SOleg Nesterov {
3355d6e89786SJohannes Berg 	return __flush_work(work, false);
3356606a5020STejun Heo }
3357db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
3358db700897SOleg Nesterov 
33598603e1b3STejun Heo struct cwt_wait {
3360ac6424b9SIngo Molnar 	wait_queue_entry_t		wait;
33618603e1b3STejun Heo 	struct work_struct	*work;
33628603e1b3STejun Heo };
33638603e1b3STejun Heo 
3364ac6424b9SIngo Molnar static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
33658603e1b3STejun Heo {
33668603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
33678603e1b3STejun Heo 
33688603e1b3STejun Heo 	if (cwait->work != key)
33698603e1b3STejun Heo 		return 0;
33708603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
33718603e1b3STejun Heo }
33728603e1b3STejun Heo 
337336e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3374401a8d04STejun Heo {
33758603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3376bbb68dfaSTejun Heo 	unsigned long flags;
33771f1f642eSOleg Nesterov 	int ret;
33781f1f642eSOleg Nesterov 
33791f1f642eSOleg Nesterov 	do {
3380bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
3381bbb68dfaSTejun Heo 		/*
33828603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
33838603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
33848603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
33858603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
33868603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
33878603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
33888603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
33898603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
33908603e1b3STejun Heo 		 * we're hogging the CPU.
33918603e1b3STejun Heo 		 *
33928603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
33938603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
33948603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
33958603e1b3STejun Heo 		 * wait and wakeup.
3396bbb68dfaSTejun Heo 		 */
33978603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
33988603e1b3STejun Heo 			struct cwt_wait cwait;
33998603e1b3STejun Heo 
34008603e1b3STejun Heo 			init_wait(&cwait.wait);
34018603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
34028603e1b3STejun Heo 			cwait.work = work;
34038603e1b3STejun Heo 
34048603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
34058603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
34068603e1b3STejun Heo 			if (work_is_canceling(work))
34078603e1b3STejun Heo 				schedule();
34088603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
34098603e1b3STejun Heo 		}
34101f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
34111f1f642eSOleg Nesterov 
3412bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
3413bbb68dfaSTejun Heo 	mark_work_canceling(work);
3414bbb68dfaSTejun Heo 	local_irq_restore(flags);
3415bbb68dfaSTejun Heo 
34163347fa09STejun Heo 	/*
34173347fa09STejun Heo 	 * This allows canceling during early boot.  We know that @work
34183347fa09STejun Heo 	 * isn't executing.
34193347fa09STejun Heo 	 */
34203347fa09STejun Heo 	if (wq_online)
3421d6e89786SJohannes Berg 		__flush_work(work, true);
34223347fa09STejun Heo 
34237a22ad75STejun Heo 	clear_work_data(work);
34248603e1b3STejun Heo 
34258603e1b3STejun Heo 	/*
34268603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
34278603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
34288603e1b3STejun Heo 	 * visible there.
34298603e1b3STejun Heo 	 */
34308603e1b3STejun Heo 	smp_mb();
34318603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
34328603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
34338603e1b3STejun Heo 
34341f1f642eSOleg Nesterov 	return ret;
34351f1f642eSOleg Nesterov }
34361f1f642eSOleg Nesterov 
34376e84d644SOleg Nesterov /**
3438401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
3439401a8d04STejun Heo  * @work: the work to cancel
34406e84d644SOleg Nesterov  *
3441401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
3442401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
3443401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
3444401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
34451f1f642eSOleg Nesterov  *
3446401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
3447401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
34486e84d644SOleg Nesterov  *
3449401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
34506e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
3451401a8d04STejun Heo  *
3452d185af30SYacine Belkadi  * Return:
3453401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
34546e84d644SOleg Nesterov  */
3455401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
34566e84d644SOleg Nesterov {
345736e227d2STejun Heo 	return __cancel_work_timer(work, false);
3458b89deed3SOleg Nesterov }
345928e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
3460b89deed3SOleg Nesterov 
34616e84d644SOleg Nesterov /**
3462401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
3463401a8d04STejun Heo  * @dwork: the delayed work to flush
34646e84d644SOleg Nesterov  *
3465401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
3466401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
3467401a8d04STejun Heo  * considers the last queueing instance of @dwork.
34681f1f642eSOleg Nesterov  *
3469d185af30SYacine Belkadi  * Return:
3470401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3471401a8d04STejun Heo  * %false if it was already idle.
34726e84d644SOleg Nesterov  */
3473401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
3474401a8d04STejun Heo {
34758930cabaSTejun Heo 	local_irq_disable();
3476401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
347760c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
34788930cabaSTejun Heo 	local_irq_enable();
3479401a8d04STejun Heo 	return flush_work(&dwork->work);
3480401a8d04STejun Heo }
3481401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3482401a8d04STejun Heo 
348305f0fe6bSTejun Heo /**
348405f0fe6bSTejun Heo  * flush_rcu_work - wait for a rwork to finish executing the last queueing
348505f0fe6bSTejun Heo  * @rwork: the rcu work to flush
348605f0fe6bSTejun Heo  *
348705f0fe6bSTejun Heo  * Return:
348805f0fe6bSTejun Heo  * %true if flush_rcu_work() waited for the work to finish execution,
348905f0fe6bSTejun Heo  * %false if it was already idle.
349005f0fe6bSTejun Heo  */
349105f0fe6bSTejun Heo bool flush_rcu_work(struct rcu_work *rwork)
349205f0fe6bSTejun Heo {
349305f0fe6bSTejun Heo 	if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
349405f0fe6bSTejun Heo 		rcu_barrier();
349505f0fe6bSTejun Heo 		flush_work(&rwork->work);
349605f0fe6bSTejun Heo 		return true;
349705f0fe6bSTejun Heo 	} else {
349805f0fe6bSTejun Heo 		return flush_work(&rwork->work);
349905f0fe6bSTejun Heo 	}
350005f0fe6bSTejun Heo }
350105f0fe6bSTejun Heo EXPORT_SYMBOL(flush_rcu_work);
350205f0fe6bSTejun Heo 
3503f72b8792SJens Axboe static bool __cancel_work(struct work_struct *work, bool is_dwork)
3504f72b8792SJens Axboe {
3505f72b8792SJens Axboe 	unsigned long flags;
3506f72b8792SJens Axboe 	int ret;
3507f72b8792SJens Axboe 
3508f72b8792SJens Axboe 	do {
3509f72b8792SJens Axboe 		ret = try_to_grab_pending(work, is_dwork, &flags);
3510f72b8792SJens Axboe 	} while (unlikely(ret == -EAGAIN));
3511f72b8792SJens Axboe 
3512f72b8792SJens Axboe 	if (unlikely(ret < 0))
3513f72b8792SJens Axboe 		return false;
3514f72b8792SJens Axboe 
3515f72b8792SJens Axboe 	set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3516f72b8792SJens Axboe 	local_irq_restore(flags);
3517f72b8792SJens Axboe 	return ret;
3518f72b8792SJens Axboe }
3519f72b8792SJens Axboe 
352073b4b532SAndrey Grodzovsky /*
352173b4b532SAndrey Grodzovsky  * See cancel_delayed_work()
352273b4b532SAndrey Grodzovsky  */
352373b4b532SAndrey Grodzovsky bool cancel_work(struct work_struct *work)
352473b4b532SAndrey Grodzovsky {
352573b4b532SAndrey Grodzovsky 	return __cancel_work(work, false);
352673b4b532SAndrey Grodzovsky }
352773b4b532SAndrey Grodzovsky EXPORT_SYMBOL(cancel_work);
352873b4b532SAndrey Grodzovsky 
3529401a8d04STejun Heo /**
353057b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
353157b30ae7STejun Heo  * @dwork: delayed_work to cancel
353209383498STejun Heo  *
3533d185af30SYacine Belkadi  * Kill off a pending delayed_work.
3534d185af30SYacine Belkadi  *
3535d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
3536d185af30SYacine Belkadi  * pending.
3537d185af30SYacine Belkadi  *
3538d185af30SYacine Belkadi  * Note:
3539d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
3540d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
3541d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
354209383498STejun Heo  *
354357b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
354409383498STejun Heo  */
354557b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
354609383498STejun Heo {
3547f72b8792SJens Axboe 	return __cancel_work(&dwork->work, true);
354809383498STejun Heo }
354957b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
355009383498STejun Heo 
355109383498STejun Heo /**
3552401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3553401a8d04STejun Heo  * @dwork: the delayed work cancel
3554401a8d04STejun Heo  *
3555401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
3556401a8d04STejun Heo  *
3557d185af30SYacine Belkadi  * Return:
3558401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
3559401a8d04STejun Heo  */
3560401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
35616e84d644SOleg Nesterov {
356236e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
35636e84d644SOleg Nesterov }
3564f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
35651da177e4SLinus Torvalds 
35660fcb78c2SRolf Eike Beer /**
356731ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3568b6136773SAndrew Morton  * @func: the function to call
3569b6136773SAndrew Morton  *
357031ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
357131ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3572b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
357331ddd871STejun Heo  *
3574d185af30SYacine Belkadi  * Return:
357531ddd871STejun Heo  * 0 on success, -errno on failure.
3576b6136773SAndrew Morton  */
357765f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
357815316ba8SChristoph Lameter {
357915316ba8SChristoph Lameter 	int cpu;
358038f51568SNamhyung Kim 	struct work_struct __percpu *works;
358115316ba8SChristoph Lameter 
3582b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3583b6136773SAndrew Morton 	if (!works)
358415316ba8SChristoph Lameter 		return -ENOMEM;
3585b6136773SAndrew Morton 
3586ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
358793981800STejun Heo 
358815316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
35899bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
35909bfb1839SIngo Molnar 
35919bfb1839SIngo Molnar 		INIT_WORK(work, func);
35928de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
359315316ba8SChristoph Lameter 	}
359493981800STejun Heo 
359593981800STejun Heo 	for_each_online_cpu(cpu)
35968616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
359793981800STejun Heo 
3598ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
3599b6136773SAndrew Morton 	free_percpu(works);
360015316ba8SChristoph Lameter 	return 0;
360115316ba8SChristoph Lameter }
360215316ba8SChristoph Lameter 
3603eef6a7d5SAlan Stern /**
36041fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
36051fa44ecaSJames Bottomley  * @fn:		the function to execute
36061fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
36071fa44ecaSJames Bottomley  *		be available when the work executes)
36081fa44ecaSJames Bottomley  *
36091fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
36101fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
36111fa44ecaSJames Bottomley  *
3612d185af30SYacine Belkadi  * Return:	0 - function was executed
36131fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
36141fa44ecaSJames Bottomley  */
361565f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
36161fa44ecaSJames Bottomley {
36171fa44ecaSJames Bottomley 	if (!in_interrupt()) {
361865f27f38SDavid Howells 		fn(&ew->work);
36191fa44ecaSJames Bottomley 		return 0;
36201fa44ecaSJames Bottomley 	}
36211fa44ecaSJames Bottomley 
362265f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
36231fa44ecaSJames Bottomley 	schedule_work(&ew->work);
36241fa44ecaSJames Bottomley 
36251fa44ecaSJames Bottomley 	return 1;
36261fa44ecaSJames Bottomley }
36271fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
36281fa44ecaSJames Bottomley 
36297a4e344cSTejun Heo /**
36307a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
36317a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
36327a4e344cSTejun Heo  *
36337a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
36347a4e344cSTejun Heo  */
3635513c98d0SDaniel Jordan void free_workqueue_attrs(struct workqueue_attrs *attrs)
36367a4e344cSTejun Heo {
36377a4e344cSTejun Heo 	if (attrs) {
36387a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
36397a4e344cSTejun Heo 		kfree(attrs);
36407a4e344cSTejun Heo 	}
36417a4e344cSTejun Heo }
36427a4e344cSTejun Heo 
36437a4e344cSTejun Heo /**
36447a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
36457a4e344cSTejun Heo  *
36467a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3647d185af30SYacine Belkadi  * return it.
3648d185af30SYacine Belkadi  *
3649d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
36507a4e344cSTejun Heo  */
3651513c98d0SDaniel Jordan struct workqueue_attrs *alloc_workqueue_attrs(void)
36527a4e344cSTejun Heo {
36537a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
36547a4e344cSTejun Heo 
3655be69d00dSThomas Gleixner 	attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
36567a4e344cSTejun Heo 	if (!attrs)
36577a4e344cSTejun Heo 		goto fail;
3658be69d00dSThomas Gleixner 	if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
36597a4e344cSTejun Heo 		goto fail;
36607a4e344cSTejun Heo 
366113e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
36627a4e344cSTejun Heo 	return attrs;
36637a4e344cSTejun Heo fail:
36647a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
36657a4e344cSTejun Heo 	return NULL;
36667a4e344cSTejun Heo }
36677a4e344cSTejun Heo 
366829c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
366929c91e99STejun Heo 				 const struct workqueue_attrs *from)
367029c91e99STejun Heo {
367129c91e99STejun Heo 	to->nice = from->nice;
367229c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
36732865a8fbSShaohua Li 	/*
36742865a8fbSShaohua Li 	 * Unlike hash and equality test, this function doesn't ignore
3675af73f5c9STejun Heo 	 * ->ordered as it is used for both pool and wq attrs.  Instead,
3676af73f5c9STejun Heo 	 * get_unbound_pool() explicitly clears ->ordered after copying.
36772865a8fbSShaohua Li 	 */
3678af73f5c9STejun Heo 	to->ordered = from->ordered;
367929c91e99STejun Heo }
368029c91e99STejun Heo 
368129c91e99STejun Heo /* hash value of the content of @attr */
368229c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
368329c91e99STejun Heo {
368429c91e99STejun Heo 	u32 hash = 0;
368529c91e99STejun Heo 
368629c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
368713e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
368813e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
368929c91e99STejun Heo 	return hash;
369029c91e99STejun Heo }
369129c91e99STejun Heo 
369229c91e99STejun Heo /* content equality test */
369329c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
369429c91e99STejun Heo 			  const struct workqueue_attrs *b)
369529c91e99STejun Heo {
369629c91e99STejun Heo 	if (a->nice != b->nice)
369729c91e99STejun Heo 		return false;
369829c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
369929c91e99STejun Heo 		return false;
370029c91e99STejun Heo 	return true;
370129c91e99STejun Heo }
370229c91e99STejun Heo 
3703*0f36ee24STejun Heo /* Update @attrs with actually available CPUs */
3704*0f36ee24STejun Heo static void wqattrs_actualize_cpumask(struct workqueue_attrs *attrs,
3705*0f36ee24STejun Heo 				      const cpumask_t *unbound_cpumask)
3706*0f36ee24STejun Heo {
3707*0f36ee24STejun Heo 	/*
3708*0f36ee24STejun Heo 	 * Calculate the effective CPU mask of @attrs given @unbound_cpumask. If
3709*0f36ee24STejun Heo 	 * @attrs->cpumask doesn't overlap with @unbound_cpumask, we fallback to
3710*0f36ee24STejun Heo 	 * @unbound_cpumask.
3711*0f36ee24STejun Heo 	 */
3712*0f36ee24STejun Heo 	cpumask_and(attrs->cpumask, attrs->cpumask, unbound_cpumask);
3713*0f36ee24STejun Heo 	if (unlikely(cpumask_empty(attrs->cpumask)))
3714*0f36ee24STejun Heo 		cpumask_copy(attrs->cpumask, unbound_cpumask);
3715*0f36ee24STejun Heo }
3716*0f36ee24STejun Heo 
37177a4e344cSTejun Heo /**
37187a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
37197a4e344cSTejun Heo  * @pool: worker_pool to initialize
37207a4e344cSTejun Heo  *
3721402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3722d185af30SYacine Belkadi  *
3723d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
372429c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
372529c91e99STejun Heo  * on @pool safely to release it.
37267a4e344cSTejun Heo  */
37277a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
37284e1a1f9aSTejun Heo {
3729a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_init(&pool->lock);
373029c91e99STejun Heo 	pool->id = -1;
373129c91e99STejun Heo 	pool->cpu = -1;
3732f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
37334e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
373482607adcSTejun Heo 	pool->watchdog_ts = jiffies;
37354e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
37364e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
37374e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
37384e1a1f9aSTejun Heo 
373932a6c723SKees Cook 	timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
37403f959aa3SValentin Schneider 	INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
37414e1a1f9aSTejun Heo 
374232a6c723SKees Cook 	timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
37434e1a1f9aSTejun Heo 
3744da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
3745e02b9312SValentin Schneider 	INIT_LIST_HEAD(&pool->dying_workers);
37467a4e344cSTejun Heo 
37477cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
374829c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
374929c91e99STejun Heo 	pool->refcnt = 1;
375029c91e99STejun Heo 
375129c91e99STejun Heo 	/* shouldn't fail above this point */
3752be69d00dSThomas Gleixner 	pool->attrs = alloc_workqueue_attrs();
37537a4e344cSTejun Heo 	if (!pool->attrs)
37547a4e344cSTejun Heo 		return -ENOMEM;
37557a4e344cSTejun Heo 	return 0;
37564e1a1f9aSTejun Heo }
37574e1a1f9aSTejun Heo 
3758669de8bdSBart Van Assche #ifdef CONFIG_LOCKDEP
3759669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3760669de8bdSBart Van Assche {
3761669de8bdSBart Van Assche 	char *lock_name;
3762669de8bdSBart Van Assche 
3763669de8bdSBart Van Assche 	lockdep_register_key(&wq->key);
3764669de8bdSBart Van Assche 	lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3765669de8bdSBart Van Assche 	if (!lock_name)
3766669de8bdSBart Van Assche 		lock_name = wq->name;
376769a106c0SQian Cai 
376869a106c0SQian Cai 	wq->lock_name = lock_name;
3769669de8bdSBart Van Assche 	lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3770669de8bdSBart Van Assche }
3771669de8bdSBart Van Assche 
3772669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3773669de8bdSBart Van Assche {
3774669de8bdSBart Van Assche 	lockdep_unregister_key(&wq->key);
3775669de8bdSBart Van Assche }
3776669de8bdSBart Van Assche 
3777669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3778669de8bdSBart Van Assche {
3779669de8bdSBart Van Assche 	if (wq->lock_name != wq->name)
3780669de8bdSBart Van Assche 		kfree(wq->lock_name);
3781669de8bdSBart Van Assche }
3782669de8bdSBart Van Assche #else
3783669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3784669de8bdSBart Van Assche {
3785669de8bdSBart Van Assche }
3786669de8bdSBart Van Assche 
3787669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3788669de8bdSBart Van Assche {
3789669de8bdSBart Van Assche }
3790669de8bdSBart Van Assche 
3791669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3792669de8bdSBart Van Assche {
3793669de8bdSBart Van Assche }
3794669de8bdSBart Van Assche #endif
3795669de8bdSBart Van Assche 
3796e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
3797e2dca7adSTejun Heo {
3798e2dca7adSTejun Heo 	struct workqueue_struct *wq =
3799e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
3800e2dca7adSTejun Heo 
3801669de8bdSBart Van Assche 	wq_free_lockdep(wq);
3802ee1ceef7STejun Heo 	free_percpu(wq->cpu_pwq);
3803e2dca7adSTejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
3804e2dca7adSTejun Heo 	kfree(wq);
3805e2dca7adSTejun Heo }
3806e2dca7adSTejun Heo 
380729c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
380829c91e99STejun Heo {
380929c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
381029c91e99STejun Heo 
38117cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
381229c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
381329c91e99STejun Heo 	kfree(pool);
381429c91e99STejun Heo }
381529c91e99STejun Heo 
381629c91e99STejun Heo /**
381729c91e99STejun Heo  * put_unbound_pool - put a worker_pool
381829c91e99STejun Heo  * @pool: worker_pool to put
381929c91e99STejun Heo  *
382024acfb71SThomas Gleixner  * Put @pool.  If its refcnt reaches zero, it gets destroyed in RCU
3821c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3822c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3823c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
3824a892caccSTejun Heo  *
3825a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
382629c91e99STejun Heo  */
382729c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
382829c91e99STejun Heo {
382960f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
383029c91e99STejun Heo 	struct worker *worker;
38319680540cSYang Yingliang 	LIST_HEAD(cull_list);
3832e02b9312SValentin Schneider 
3833a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3834a892caccSTejun Heo 
3835a892caccSTejun Heo 	if (--pool->refcnt)
383629c91e99STejun Heo 		return;
383729c91e99STejun Heo 
383829c91e99STejun Heo 	/* sanity checks */
383961d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
3840a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
384129c91e99STejun Heo 		return;
384229c91e99STejun Heo 
384329c91e99STejun Heo 	/* release id and unhash */
384429c91e99STejun Heo 	if (pool->id >= 0)
384529c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
384629c91e99STejun Heo 	hash_del(&pool->hash_node);
384729c91e99STejun Heo 
3848c5aa87bbSTejun Heo 	/*
3849692b4825STejun Heo 	 * Become the manager and destroy all workers.  This prevents
3850692b4825STejun Heo 	 * @pool's workers from blocking on attach_mutex.  We're the last
3851692b4825STejun Heo 	 * manager and @pool gets freed with the flag set.
38529ab03be4SValentin Schneider 	 *
38539ab03be4SValentin Schneider 	 * Having a concurrent manager is quite unlikely to happen as we can
38549ab03be4SValentin Schneider 	 * only get here with
38559ab03be4SValentin Schneider 	 *   pwq->refcnt == pool->refcnt == 0
38569ab03be4SValentin Schneider 	 * which implies no work queued to the pool, which implies no worker can
38579ab03be4SValentin Schneider 	 * become the manager. However a worker could have taken the role of
38589ab03be4SValentin Schneider 	 * manager before the refcnts dropped to 0, since maybe_create_worker()
38599ab03be4SValentin Schneider 	 * drops pool->lock
3860c5aa87bbSTejun Heo 	 */
38619ab03be4SValentin Schneider 	while (true) {
38629ab03be4SValentin Schneider 		rcuwait_wait_event(&manager_wait,
38639ab03be4SValentin Schneider 				   !(pool->flags & POOL_MANAGER_ACTIVE),
3864d8bb65abSSebastian Andrzej Siewior 				   TASK_UNINTERRUPTIBLE);
3865e02b9312SValentin Schneider 
3866e02b9312SValentin Schneider 		mutex_lock(&wq_pool_attach_mutex);
38679ab03be4SValentin Schneider 		raw_spin_lock_irq(&pool->lock);
38689ab03be4SValentin Schneider 		if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
3869692b4825STejun Heo 			pool->flags |= POOL_MANAGER_ACTIVE;
38709ab03be4SValentin Schneider 			break;
38719ab03be4SValentin Schneider 		}
38729ab03be4SValentin Schneider 		raw_spin_unlock_irq(&pool->lock);
3873e02b9312SValentin Schneider 		mutex_unlock(&wq_pool_attach_mutex);
38749ab03be4SValentin Schneider 	}
3875692b4825STejun Heo 
38761037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
3877e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
387829c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
3879a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
388060f5a4bcSLai Jiangshan 
3881e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
3882e02b9312SValentin Schneider 
3883e02b9312SValentin Schneider 	if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
388460f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
38851258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
388660f5a4bcSLai Jiangshan 
388760f5a4bcSLai Jiangshan 	if (pool->detach_completion)
388860f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
388960f5a4bcSLai Jiangshan 
389029c91e99STejun Heo 	/* shut down the timers */
389129c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
38923f959aa3SValentin Schneider 	cancel_work_sync(&pool->idle_cull_work);
389329c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
389429c91e99STejun Heo 
389524acfb71SThomas Gleixner 	/* RCU protected to allow dereferences from get_work_pool() */
389625b00775SPaul E. McKenney 	call_rcu(&pool->rcu, rcu_free_pool);
389729c91e99STejun Heo }
389829c91e99STejun Heo 
389929c91e99STejun Heo /**
390029c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
390129c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
390229c91e99STejun Heo  *
390329c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
390429c91e99STejun Heo  * reference count and return it.  If there already is a matching
390529c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
3906d185af30SYacine Belkadi  * create a new one.
3907a892caccSTejun Heo  *
3908a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
3909d185af30SYacine Belkadi  *
3910d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
3911d185af30SYacine Belkadi  * On failure, %NULL.
391229c91e99STejun Heo  */
391329c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
391429c91e99STejun Heo {
391529c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
391629c91e99STejun Heo 	struct worker_pool *pool;
3917fef59c9cSTejun Heo 	int pod;
3918fef59c9cSTejun Heo 	int target_pod = NUMA_NO_NODE;
391929c91e99STejun Heo 
3920a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
392129c91e99STejun Heo 
392229c91e99STejun Heo 	/* do we already have a matching pool? */
392329c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
392429c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
392529c91e99STejun Heo 			pool->refcnt++;
39263fb1823cSLai Jiangshan 			return pool;
392729c91e99STejun Heo 		}
392829c91e99STejun Heo 	}
392929c91e99STejun Heo 
3930fef59c9cSTejun Heo 	/* if cpumask is contained inside a pod, we belong to that pod */
3931fef59c9cSTejun Heo 	if (wq_pod_enabled) {
3932fef59c9cSTejun Heo 		for_each_node(pod) {
3933fef59c9cSTejun Heo 			if (cpumask_subset(attrs->cpumask, wq_pod_cpus[pod])) {
3934fef59c9cSTejun Heo 				target_pod = pod;
3935e2273584SXunlei Pang 				break;
3936e2273584SXunlei Pang 			}
3937e2273584SXunlei Pang 		}
3938e2273584SXunlei Pang 	}
3939e2273584SXunlei Pang 
394029c91e99STejun Heo 	/* nope, create a new one */
3941fef59c9cSTejun Heo 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_pod);
394229c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
394329c91e99STejun Heo 		goto fail;
394429c91e99STejun Heo 
394529c91e99STejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
3946fef59c9cSTejun Heo 	pool->node = target_pod;
394729c91e99STejun Heo 
39482865a8fbSShaohua Li 	/*
3949af73f5c9STejun Heo 	 * ordered isn't a worker_pool attribute, always clear it.  See
39502865a8fbSShaohua Li 	 * 'struct workqueue_attrs' comments for detail.
39512865a8fbSShaohua Li 	 */
3952af73f5c9STejun Heo 	pool->attrs->ordered = false;
39532865a8fbSShaohua Li 
395429c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
395529c91e99STejun Heo 		goto fail;
395629c91e99STejun Heo 
395729c91e99STejun Heo 	/* create and start the initial worker */
39583347fa09STejun Heo 	if (wq_online && !create_worker(pool))
395929c91e99STejun Heo 		goto fail;
396029c91e99STejun Heo 
396129c91e99STejun Heo 	/* install */
396229c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
39633fb1823cSLai Jiangshan 
396429c91e99STejun Heo 	return pool;
396529c91e99STejun Heo fail:
396629c91e99STejun Heo 	if (pool)
396729c91e99STejun Heo 		put_unbound_pool(pool);
396829c91e99STejun Heo 	return NULL;
396929c91e99STejun Heo }
397029c91e99STejun Heo 
39718864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
39728864b4e5STejun Heo {
39738864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
39748864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
39758864b4e5STejun Heo }
39768864b4e5STejun Heo 
39778864b4e5STejun Heo /*
3978967b494eSTejun Heo  * Scheduled on pwq_release_worker by put_pwq() when an unbound pwq hits zero
3979967b494eSTejun Heo  * refcnt and needs to be destroyed.
39808864b4e5STejun Heo  */
3981687a9aa5STejun Heo static void pwq_release_workfn(struct kthread_work *work)
39828864b4e5STejun Heo {
39838864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
3984687a9aa5STejun Heo 						  release_work);
39858864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
39868864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
3987b42b0bddSYang Yingliang 	bool is_last = false;
39888864b4e5STejun Heo 
3989b42b0bddSYang Yingliang 	/*
3990687a9aa5STejun Heo 	 * When @pwq is not linked, it doesn't hold any reference to the
3991b42b0bddSYang Yingliang 	 * @wq, and @wq is invalid to access.
3992b42b0bddSYang Yingliang 	 */
3993b42b0bddSYang Yingliang 	if (!list_empty(&pwq->pwqs_node)) {
39943c25a55dSLai Jiangshan 		mutex_lock(&wq->mutex);
39958864b4e5STejun Heo 		list_del_rcu(&pwq->pwqs_node);
3996bc0caf09STejun Heo 		is_last = list_empty(&wq->pwqs);
39973c25a55dSLai Jiangshan 		mutex_unlock(&wq->mutex);
3998b42b0bddSYang Yingliang 	}
39998864b4e5STejun Heo 
4000687a9aa5STejun Heo 	if (wq->flags & WQ_UNBOUND) {
4001a892caccSTejun Heo 		mutex_lock(&wq_pool_mutex);
40028864b4e5STejun Heo 		put_unbound_pool(pool);
4003a892caccSTejun Heo 		mutex_unlock(&wq_pool_mutex);
4004687a9aa5STejun Heo 	}
4005a892caccSTejun Heo 
400625b00775SPaul E. McKenney 	call_rcu(&pwq->rcu, rcu_free_pwq);
40078864b4e5STejun Heo 
40088864b4e5STejun Heo 	/*
40098864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
4010e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
40118864b4e5STejun Heo 	 */
4012669de8bdSBart Van Assche 	if (is_last) {
4013669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
401425b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
40156029a918STejun Heo 	}
4016669de8bdSBart Van Assche }
40178864b4e5STejun Heo 
40180fbd95aaSTejun Heo /**
4019699ce097STejun Heo  * pwq_adjust_max_active - update a pwq's max_active to the current setting
40200fbd95aaSTejun Heo  * @pwq: target pool_workqueue
40210fbd95aaSTejun Heo  *
4022699ce097STejun Heo  * If @pwq isn't freezing, set @pwq->max_active to the associated
4023f97a4a1aSLai Jiangshan  * workqueue's saved_max_active and activate inactive work items
4024699ce097STejun Heo  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
40250fbd95aaSTejun Heo  */
4026699ce097STejun Heo static void pwq_adjust_max_active(struct pool_workqueue *pwq)
40270fbd95aaSTejun Heo {
4028699ce097STejun Heo 	struct workqueue_struct *wq = pwq->wq;
4029699ce097STejun Heo 	bool freezable = wq->flags & WQ_FREEZABLE;
40303347fa09STejun Heo 	unsigned long flags;
4031699ce097STejun Heo 
4032699ce097STejun Heo 	/* for @wq->saved_max_active */
4033a357fc03SLai Jiangshan 	lockdep_assert_held(&wq->mutex);
4034699ce097STejun Heo 
4035699ce097STejun Heo 	/* fast exit for non-freezable wqs */
4036699ce097STejun Heo 	if (!freezable && pwq->max_active == wq->saved_max_active)
4037699ce097STejun Heo 		return;
4038699ce097STejun Heo 
40393347fa09STejun Heo 	/* this function can be called during early boot w/ irq disabled */
4040a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pwq->pool->lock, flags);
4041699ce097STejun Heo 
404274b414eaSLai Jiangshan 	/*
404374b414eaSLai Jiangshan 	 * During [un]freezing, the caller is responsible for ensuring that
404474b414eaSLai Jiangshan 	 * this function is called at least once after @workqueue_freezing
404574b414eaSLai Jiangshan 	 * is updated and visible.
404674b414eaSLai Jiangshan 	 */
404774b414eaSLai Jiangshan 	if (!freezable || !workqueue_freezing) {
404801341fbdSYunfeng Ye 		bool kick = false;
404901341fbdSYunfeng Ye 
4050699ce097STejun Heo 		pwq->max_active = wq->saved_max_active;
40510fbd95aaSTejun Heo 
4052f97a4a1aSLai Jiangshan 		while (!list_empty(&pwq->inactive_works) &&
405301341fbdSYunfeng Ye 		       pwq->nr_active < pwq->max_active) {
4054f97a4a1aSLai Jiangshan 			pwq_activate_first_inactive(pwq);
405501341fbdSYunfeng Ye 			kick = true;
405601341fbdSYunfeng Ye 		}
4057951a078aSLai Jiangshan 
4058951a078aSLai Jiangshan 		/*
4059951a078aSLai Jiangshan 		 * Need to kick a worker after thawed or an unbound wq's
406001341fbdSYunfeng Ye 		 * max_active is bumped. In realtime scenarios, always kicking a
406101341fbdSYunfeng Ye 		 * worker will cause interference on the isolated cpu cores, so
406201341fbdSYunfeng Ye 		 * let's kick iff work items were activated.
4063951a078aSLai Jiangshan 		 */
406401341fbdSYunfeng Ye 		if (kick)
4065951a078aSLai Jiangshan 			wake_up_worker(pwq->pool);
4066699ce097STejun Heo 	} else {
4067699ce097STejun Heo 		pwq->max_active = 0;
4068699ce097STejun Heo 	}
4069699ce097STejun Heo 
4070a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
40710fbd95aaSTejun Heo }
40720fbd95aaSTejun Heo 
407367dc8325SCai Huoqing /* initialize newly allocated @pwq which is associated with @wq and @pool */
4074f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
4075f147f29eSTejun Heo 		     struct worker_pool *pool)
4076d2c1d404STejun Heo {
4077d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
4078d2c1d404STejun Heo 
4079e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
4080e50aba9aSTejun Heo 
4081d2c1d404STejun Heo 	pwq->pool = pool;
4082d2c1d404STejun Heo 	pwq->wq = wq;
4083d2c1d404STejun Heo 	pwq->flush_color = -1;
40848864b4e5STejun Heo 	pwq->refcnt = 1;
4085f97a4a1aSLai Jiangshan 	INIT_LIST_HEAD(&pwq->inactive_works);
40861befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
4087d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
4088687a9aa5STejun Heo 	kthread_init_work(&pwq->release_work, pwq_release_workfn);
4089f147f29eSTejun Heo }
4090d2c1d404STejun Heo 
4091f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
40921befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
4093f147f29eSTejun Heo {
4094f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
4095f147f29eSTejun Heo 
4096f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
409775ccf595STejun Heo 
40981befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
40991befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
41001befcf30STejun Heo 		return;
41011befcf30STejun Heo 
410229b1cb41SLai Jiangshan 	/* set the matching work_color */
410375ccf595STejun Heo 	pwq->work_color = wq->work_color;
4104983ca25eSTejun Heo 
4105983ca25eSTejun Heo 	/* sync max_active to the current setting */
4106983ca25eSTejun Heo 	pwq_adjust_max_active(pwq);
4107983ca25eSTejun Heo 
4108983ca25eSTejun Heo 	/* link in @pwq */
41099e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
4110df2d5ae4STejun Heo }
41116029a918STejun Heo 
4112f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
4113f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
4114f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
4115f147f29eSTejun Heo {
4116f147f29eSTejun Heo 	struct worker_pool *pool;
4117f147f29eSTejun Heo 	struct pool_workqueue *pwq;
4118f147f29eSTejun Heo 
4119f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
4120f147f29eSTejun Heo 
4121f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
4122f147f29eSTejun Heo 	if (!pool)
4123f147f29eSTejun Heo 		return NULL;
4124f147f29eSTejun Heo 
4125e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
4126f147f29eSTejun Heo 	if (!pwq) {
4127f147f29eSTejun Heo 		put_unbound_pool(pool);
4128f147f29eSTejun Heo 		return NULL;
4129f147f29eSTejun Heo 	}
4130f147f29eSTejun Heo 
4131f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
4132f147f29eSTejun Heo 	return pwq;
4133d2c1d404STejun Heo }
4134d2c1d404STejun Heo 
41354c16bd32STejun Heo /**
4136fef59c9cSTejun Heo  * wq_calc_pod_cpumask - calculate a wq_attrs' cpumask for a pod
4137042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
4138fef59c9cSTejun Heo  * @pod: the target CPU pod
41394c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
41404c16bd32STejun Heo  * @cpumask: outarg, the resulting cpumask
41414c16bd32STejun Heo  *
4142fef59c9cSTejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @pod. If
4143fef59c9cSTejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during calculation.
4144fef59c9cSTejun Heo  * The result is stored in @cpumask.
41454c16bd32STejun Heo  *
4146fef59c9cSTejun Heo  * If pod affinity is not enabled, @attrs->cpumask is always used. If enabled
4147fef59c9cSTejun Heo  * and @pod has online CPUs requested by @attrs, the returned cpumask is the
4148fef59c9cSTejun Heo  * intersection of the possible CPUs of @pod and @attrs->cpumask.
41494c16bd32STejun Heo  *
4150fef59c9cSTejun Heo  * The caller is responsible for ensuring that the cpumask of @pod stays stable.
41514c16bd32STejun Heo  */
4152fef59c9cSTejun Heo static void wq_calc_pod_cpumask(const struct workqueue_attrs *attrs, int pod,
41534c16bd32STejun Heo 				 int cpu_going_down, cpumask_t *cpumask)
41544c16bd32STejun Heo {
4155fef59c9cSTejun Heo 	if (!wq_pod_enabled || attrs->ordered)
41564c16bd32STejun Heo 		goto use_dfl;
41574c16bd32STejun Heo 
4158fef59c9cSTejun Heo 	/* does @pod have any online CPUs @attrs wants? */
4159fef59c9cSTejun Heo 	cpumask_and(cpumask, cpumask_of_node(pod), attrs->cpumask);
41604c16bd32STejun Heo 	if (cpu_going_down >= 0)
41614c16bd32STejun Heo 		cpumask_clear_cpu(cpu_going_down, cpumask);
41624c16bd32STejun Heo 
41634c16bd32STejun Heo 	if (cpumask_empty(cpumask))
41644c16bd32STejun Heo 		goto use_dfl;
41654c16bd32STejun Heo 
4166fef59c9cSTejun Heo 	/* yeap, return possible CPUs in @pod that @attrs wants */
4167fef59c9cSTejun Heo 	cpumask_and(cpumask, attrs->cpumask, wq_pod_cpus[pod]);
41681ad0f0a7SMichael Bringmann 
4169636b927eSTejun Heo 	if (cpumask_empty(cpumask))
41701ad0f0a7SMichael Bringmann 		pr_warn_once("WARNING: workqueue cpumask: online intersect > "
41711ad0f0a7SMichael Bringmann 				"possible intersect\n");
4172636b927eSTejun Heo 	return;
41734c16bd32STejun Heo 
41744c16bd32STejun Heo use_dfl:
41754c16bd32STejun Heo 	cpumask_copy(cpumask, attrs->cpumask);
41764c16bd32STejun Heo }
41774c16bd32STejun Heo 
4178636b927eSTejun Heo /* install @pwq into @wq's cpu_pwq and return the old pwq */
4179636b927eSTejun Heo static struct pool_workqueue *install_unbound_pwq(struct workqueue_struct *wq,
4180636b927eSTejun Heo 					int cpu, struct pool_workqueue *pwq)
41811befcf30STejun Heo {
41821befcf30STejun Heo 	struct pool_workqueue *old_pwq;
41831befcf30STejun Heo 
41845b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
41851befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
41861befcf30STejun Heo 
41871befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
41881befcf30STejun Heo 	link_pwq(pwq);
41891befcf30STejun Heo 
4190636b927eSTejun Heo 	old_pwq = rcu_access_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu));
4191636b927eSTejun Heo 	rcu_assign_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu), pwq);
41921befcf30STejun Heo 	return old_pwq;
41931befcf30STejun Heo }
41941befcf30STejun Heo 
41952d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
41962d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
41972d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
41982d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
4199042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
42002d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
42012d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
42022d5f0764SLai Jiangshan };
42032d5f0764SLai Jiangshan 
42042d5f0764SLai Jiangshan /* free the resources after success or abort */
42052d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
42062d5f0764SLai Jiangshan {
42072d5f0764SLai Jiangshan 	if (ctx) {
4208636b927eSTejun Heo 		int cpu;
42092d5f0764SLai Jiangshan 
4210636b927eSTejun Heo 		for_each_possible_cpu(cpu)
4211636b927eSTejun Heo 			put_pwq_unlocked(ctx->pwq_tbl[cpu]);
42122d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
42132d5f0764SLai Jiangshan 
42142d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
42152d5f0764SLai Jiangshan 
42162d5f0764SLai Jiangshan 		kfree(ctx);
42172d5f0764SLai Jiangshan 	}
42182d5f0764SLai Jiangshan }
42192d5f0764SLai Jiangshan 
42202d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
42212d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
42222d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
422399c621efSLai Jiangshan 		      const struct workqueue_attrs *attrs,
422499c621efSLai Jiangshan 		      const cpumask_var_t unbound_cpumask)
42252d5f0764SLai Jiangshan {
42262d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
42272d5f0764SLai Jiangshan 	struct workqueue_attrs *new_attrs, *tmp_attrs;
4228636b927eSTejun Heo 	int cpu;
42292d5f0764SLai Jiangshan 
42302d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
42312d5f0764SLai Jiangshan 
4232636b927eSTejun Heo 	ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_cpu_ids), GFP_KERNEL);
42332d5f0764SLai Jiangshan 
4234be69d00dSThomas Gleixner 	new_attrs = alloc_workqueue_attrs();
4235be69d00dSThomas Gleixner 	tmp_attrs = alloc_workqueue_attrs();
42362d5f0764SLai Jiangshan 	if (!ctx || !new_attrs || !tmp_attrs)
42372d5f0764SLai Jiangshan 		goto out_free;
42382d5f0764SLai Jiangshan 
4239042f7df1SLai Jiangshan 	/*
42402d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
42412d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
42422d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
42432d5f0764SLai Jiangshan 	 */
4244*0f36ee24STejun Heo 	copy_workqueue_attrs(new_attrs, attrs);
4245*0f36ee24STejun Heo 	wqattrs_actualize_cpumask(new_attrs, unbound_cpumask);
42462d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
42472d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
42482d5f0764SLai Jiangshan 		goto out_free;
42492d5f0764SLai Jiangshan 
4250*0f36ee24STejun Heo 	/*
4251*0f36ee24STejun Heo 	 * We may create multiple pwqs with differing cpumasks. Make a copy of
4252*0f36ee24STejun Heo 	 * @new_attrs which will be modified and used to obtain pools.
4253*0f36ee24STejun Heo 	 */
4254*0f36ee24STejun Heo 	copy_workqueue_attrs(tmp_attrs, new_attrs);
4255*0f36ee24STejun Heo 
4256636b927eSTejun Heo 	for_each_possible_cpu(cpu) {
4257af73f5c9STejun Heo 		if (new_attrs->ordered) {
42582d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
4259636b927eSTejun Heo 			ctx->pwq_tbl[cpu] = ctx->dfl_pwq;
4260636b927eSTejun Heo 		} else {
4261fef59c9cSTejun Heo 			wq_calc_pod_cpumask(new_attrs, cpu_to_node(cpu), -1,
4262636b927eSTejun Heo 					    tmp_attrs->cpumask);
4263636b927eSTejun Heo 			ctx->pwq_tbl[cpu] = alloc_unbound_pwq(wq, tmp_attrs);
4264636b927eSTejun Heo 			if (!ctx->pwq_tbl[cpu])
4265636b927eSTejun Heo 				goto out_free;
42662d5f0764SLai Jiangshan 		}
42672d5f0764SLai Jiangshan 	}
42682d5f0764SLai Jiangshan 
4269042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
4270042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
4271042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
42722d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
4273042f7df1SLai Jiangshan 
42742d5f0764SLai Jiangshan 	ctx->wq = wq;
42752d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
42762d5f0764SLai Jiangshan 	return ctx;
42772d5f0764SLai Jiangshan 
42782d5f0764SLai Jiangshan out_free:
42792d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
42802d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
42812d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
42822d5f0764SLai Jiangshan 	return NULL;
42832d5f0764SLai Jiangshan }
42842d5f0764SLai Jiangshan 
42852d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
42862d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
42872d5f0764SLai Jiangshan {
4288636b927eSTejun Heo 	int cpu;
42892d5f0764SLai Jiangshan 
42902d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
42912d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
42922d5f0764SLai Jiangshan 
42932d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
42942d5f0764SLai Jiangshan 
42952d5f0764SLai Jiangshan 	/* save the previous pwq and install the new one */
4296636b927eSTejun Heo 	for_each_possible_cpu(cpu)
4297636b927eSTejun Heo 		ctx->pwq_tbl[cpu] = install_unbound_pwq(ctx->wq, cpu,
4298636b927eSTejun Heo 							ctx->pwq_tbl[cpu]);
42992d5f0764SLai Jiangshan 
43002d5f0764SLai Jiangshan 	/* @dfl_pwq might not have been used, ensure it's linked */
43012d5f0764SLai Jiangshan 	link_pwq(ctx->dfl_pwq);
43022d5f0764SLai Jiangshan 	swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
43032d5f0764SLai Jiangshan 
43042d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
43052d5f0764SLai Jiangshan }
43062d5f0764SLai Jiangshan 
4307a0111cf6SLai Jiangshan static void apply_wqattrs_lock(void)
4308a0111cf6SLai Jiangshan {
4309a0111cf6SLai Jiangshan 	/* CPUs should stay stable across pwq creations and installations */
4310ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4311a0111cf6SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4312a0111cf6SLai Jiangshan }
4313a0111cf6SLai Jiangshan 
4314a0111cf6SLai Jiangshan static void apply_wqattrs_unlock(void)
4315a0111cf6SLai Jiangshan {
4316a0111cf6SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4317ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4318a0111cf6SLai Jiangshan }
4319a0111cf6SLai Jiangshan 
4320a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4321a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
4322a0111cf6SLai Jiangshan {
4323a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
4324a0111cf6SLai Jiangshan 
4325a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
4326a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4327a0111cf6SLai Jiangshan 		return -EINVAL;
4328a0111cf6SLai Jiangshan 
4329a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
43300a94efb5STejun Heo 	if (!list_empty(&wq->pwqs)) {
43310a94efb5STejun Heo 		if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4332a0111cf6SLai Jiangshan 			return -EINVAL;
4333a0111cf6SLai Jiangshan 
43340a94efb5STejun Heo 		wq->flags &= ~__WQ_ORDERED;
43350a94efb5STejun Heo 	}
43360a94efb5STejun Heo 
433799c621efSLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
43386201171eSwanghaibin 	if (!ctx)
43396201171eSwanghaibin 		return -ENOMEM;
4340a0111cf6SLai Jiangshan 
4341a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
4342a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
4343a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
4344a0111cf6SLai Jiangshan 
43456201171eSwanghaibin 	return 0;
4346a0111cf6SLai Jiangshan }
4347a0111cf6SLai Jiangshan 
43489e8cd2f5STejun Heo /**
43499e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
43509e8cd2f5STejun Heo  * @wq: the target workqueue
43519e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
43529e8cd2f5STejun Heo  *
4353fef59c9cSTejun Heo  * Apply @attrs to an unbound workqueue @wq. Unless disabled, this function maps
4354fef59c9cSTejun Heo  * a separate pwq to each CPU pod with possibles CPUs in @attrs->cpumask so that
4355fef59c9cSTejun Heo  * work items are affine to the pod it was issued on. Older pwqs are released as
4356fef59c9cSTejun Heo  * in-flight work items finish. Note that a work item which repeatedly requeues
4357fef59c9cSTejun Heo  * itself back-to-back will stay on its current pwq.
43589e8cd2f5STejun Heo  *
4359d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
4360d185af30SYacine Belkadi  *
4361ffd8bea8SSebastian Andrzej Siewior  * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
4362509b3204SDaniel Jordan  *
4363d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
43649e8cd2f5STejun Heo  */
4365513c98d0SDaniel Jordan int apply_workqueue_attrs(struct workqueue_struct *wq,
43669e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
43679e8cd2f5STejun Heo {
4368a0111cf6SLai Jiangshan 	int ret;
43699e8cd2f5STejun Heo 
4370509b3204SDaniel Jordan 	lockdep_assert_cpus_held();
4371509b3204SDaniel Jordan 
4372509b3204SDaniel Jordan 	mutex_lock(&wq_pool_mutex);
4373a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
4374509b3204SDaniel Jordan 	mutex_unlock(&wq_pool_mutex);
43752d5f0764SLai Jiangshan 
43762d5f0764SLai Jiangshan 	return ret;
43779e8cd2f5STejun Heo }
43789e8cd2f5STejun Heo 
43794c16bd32STejun Heo /**
4380fef59c9cSTejun Heo  * wq_update_pod - update pod affinity of a wq for CPU hot[un]plug
43814c16bd32STejun Heo  * @wq: the target workqueue
43824cbfd3deSTejun Heo  * @cpu: the CPU to update pool association for
43834cbfd3deSTejun Heo  * @hotplug_cpu: the CPU coming up or going down
43844c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
43854c16bd32STejun Heo  *
43864c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
4387fef59c9cSTejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update pod affinity of
43884c16bd32STejun Heo  * @wq accordingly.
43894c16bd32STejun Heo  *
43904c16bd32STejun Heo  *
4391fef59c9cSTejun Heo  * If pod affinity can't be adjusted due to memory allocation failure, it falls
4392fef59c9cSTejun Heo  * back to @wq->dfl_pwq which may not be optimal but is always correct.
4393fef59c9cSTejun Heo  *
4394fef59c9cSTejun Heo  * Note that when the last allowed CPU of a pod goes offline for a workqueue
4395fef59c9cSTejun Heo  * with a cpumask spanning multiple pods, the workers which were already
4396fef59c9cSTejun Heo  * executing the work items for the workqueue will lose their CPU affinity and
4397fef59c9cSTejun Heo  * may execute on any CPU. This is similar to how per-cpu workqueues behave on
4398fef59c9cSTejun Heo  * CPU_DOWN. If a workqueue user wants strict affinity, it's the user's
4399fef59c9cSTejun Heo  * responsibility to flush the work item from CPU_DOWN_PREPARE.
44004c16bd32STejun Heo  */
4401fef59c9cSTejun Heo static void wq_update_pod(struct workqueue_struct *wq, int cpu,
44024cbfd3deSTejun Heo 			  int hotplug_cpu, bool online)
44034c16bd32STejun Heo {
4404fef59c9cSTejun Heo 	int pod = cpu_to_node(cpu);
44054cbfd3deSTejun Heo 	int off_cpu = online ? -1 : hotplug_cpu;
44064c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
44074c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
44084c16bd32STejun Heo 	cpumask_t *cpumask;
44094c16bd32STejun Heo 
44104c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
44114c16bd32STejun Heo 
4412fef59c9cSTejun Heo 	if (!wq_pod_enabled || !(wq->flags & WQ_UNBOUND) ||
4413af73f5c9STejun Heo 	    wq->unbound_attrs->ordered)
44144c16bd32STejun Heo 		return;
44154c16bd32STejun Heo 
44164c16bd32STejun Heo 	/*
44174c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
44184c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
44194c16bd32STejun Heo 	 * CPU hotplug exclusion.
44204c16bd32STejun Heo 	 */
4421fef59c9cSTejun Heo 	target_attrs = wq_update_pod_attrs_buf;
4422*0f36ee24STejun Heo 	cpumask = wq_update_pod_cpumask_buf;
44234c16bd32STejun Heo 
44244c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
4425*0f36ee24STejun Heo 	wqattrs_actualize_cpumask(target_attrs, wq_unbound_cpumask);
44264c16bd32STejun Heo 
4427636b927eSTejun Heo 	/* nothing to do if the target cpumask matches the current pwq */
4428*0f36ee24STejun Heo 	wq_calc_pod_cpumask(target_attrs, pod, off_cpu, cpumask);
4429636b927eSTejun Heo 	pwq = rcu_dereference_protected(*per_cpu_ptr(wq->cpu_pwq, cpu),
4430636b927eSTejun Heo 					lockdep_is_held(&wq_pool_mutex));
44314c16bd32STejun Heo 	if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
4432f7142ed4SLai Jiangshan 		return;
44334c16bd32STejun Heo 
44344c16bd32STejun Heo 	/* create a new pwq */
4435*0f36ee24STejun Heo 	cpumask_copy(target_attrs->cpumask, cpumask);
44364c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
44374c16bd32STejun Heo 	if (!pwq) {
4438fef59c9cSTejun Heo 		pr_warn("workqueue: allocation failed while updating CPU pod affinity of \"%s\"\n",
44394c16bd32STejun Heo 			wq->name);
444077f300b1SDaeseok Youn 		goto use_dfl_pwq;
44414c16bd32STejun Heo 	}
44424c16bd32STejun Heo 
4443f7142ed4SLai Jiangshan 	/* Install the new pwq. */
44444c16bd32STejun Heo 	mutex_lock(&wq->mutex);
4445636b927eSTejun Heo 	old_pwq = install_unbound_pwq(wq, cpu, pwq);
44464c16bd32STejun Heo 	goto out_unlock;
44474c16bd32STejun Heo 
44484c16bd32STejun Heo use_dfl_pwq:
4449f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
4450a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
44514c16bd32STejun Heo 	get_pwq(wq->dfl_pwq);
4452a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
4453636b927eSTejun Heo 	old_pwq = install_unbound_pwq(wq, cpu, wq->dfl_pwq);
44544c16bd32STejun Heo out_unlock:
44554c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
44564c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
44574c16bd32STejun Heo }
44584c16bd32STejun Heo 
445930cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
44601da177e4SLinus Torvalds {
446149e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
44628a2b7538STejun Heo 	int cpu, ret;
4463e1d8aa9fSFrederic Weisbecker 
4464687a9aa5STejun Heo 	wq->cpu_pwq = alloc_percpu(struct pool_workqueue *);
4465ee1ceef7STejun Heo 	if (!wq->cpu_pwq)
4466687a9aa5STejun Heo 		goto enomem;
446730cdf249STejun Heo 
4468636b927eSTejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
446930cdf249STejun Heo 		for_each_possible_cpu(cpu) {
4470687a9aa5STejun Heo 			struct pool_workqueue **pwq_p =
4471ee1ceef7STejun Heo 				per_cpu_ptr(wq->cpu_pwq, cpu);
4472687a9aa5STejun Heo 			struct worker_pool *pool =
4473687a9aa5STejun Heo 				&(per_cpu_ptr(cpu_worker_pools, cpu)[highpri]);
447430cdf249STejun Heo 
4475687a9aa5STejun Heo 			*pwq_p = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL,
4476687a9aa5STejun Heo 						       pool->node);
4477687a9aa5STejun Heo 			if (!*pwq_p)
4478687a9aa5STejun Heo 				goto enomem;
4479687a9aa5STejun Heo 
4480687a9aa5STejun Heo 			init_pwq(*pwq_p, wq, pool);
4481f147f29eSTejun Heo 
4482f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
4483687a9aa5STejun Heo 			link_pwq(*pwq_p);
4484f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
448530cdf249STejun Heo 		}
448630cdf249STejun Heo 		return 0;
4487509b3204SDaniel Jordan 	}
4488509b3204SDaniel Jordan 
4489ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4490509b3204SDaniel Jordan 	if (wq->flags & __WQ_ORDERED) {
44918a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
44928a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
44938a2b7538STejun Heo 		WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
44948a2b7538STejun Heo 			      wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
44958a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
44969e8cd2f5STejun Heo 	} else {
4497509b3204SDaniel Jordan 		ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
44989e8cd2f5STejun Heo 	}
4499ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4500509b3204SDaniel Jordan 
4501509b3204SDaniel Jordan 	return ret;
4502687a9aa5STejun Heo 
4503687a9aa5STejun Heo enomem:
4504687a9aa5STejun Heo 	if (wq->cpu_pwq) {
4505687a9aa5STejun Heo 		for_each_possible_cpu(cpu)
4506687a9aa5STejun Heo 			kfree(*per_cpu_ptr(wq->cpu_pwq, cpu));
4507687a9aa5STejun Heo 		free_percpu(wq->cpu_pwq);
4508687a9aa5STejun Heo 		wq->cpu_pwq = NULL;
4509687a9aa5STejun Heo 	}
4510687a9aa5STejun Heo 	return -ENOMEM;
45110f900049STejun Heo }
45120f900049STejun Heo 
4513f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
4514f3421797STejun Heo 			       const char *name)
4515b71ab8c2STejun Heo {
4516636b927eSTejun Heo 	if (max_active < 1 || max_active > WQ_MAX_ACTIVE)
4517044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4518636b927eSTejun Heo 			max_active, name, 1, WQ_MAX_ACTIVE);
4519b71ab8c2STejun Heo 
4520636b927eSTejun Heo 	return clamp_val(max_active, 1, WQ_MAX_ACTIVE);
4521b71ab8c2STejun Heo }
4522b71ab8c2STejun Heo 
4523983c7515STejun Heo /*
4524983c7515STejun Heo  * Workqueues which may be used during memory reclaim should have a rescuer
4525983c7515STejun Heo  * to guarantee forward progress.
4526983c7515STejun Heo  */
4527983c7515STejun Heo static int init_rescuer(struct workqueue_struct *wq)
4528983c7515STejun Heo {
4529983c7515STejun Heo 	struct worker *rescuer;
4530b92b36eaSDan Carpenter 	int ret;
4531983c7515STejun Heo 
4532983c7515STejun Heo 	if (!(wq->flags & WQ_MEM_RECLAIM))
4533983c7515STejun Heo 		return 0;
4534983c7515STejun Heo 
4535983c7515STejun Heo 	rescuer = alloc_worker(NUMA_NO_NODE);
45364c0736a7SPetr Mladek 	if (!rescuer) {
45374c0736a7SPetr Mladek 		pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
45384c0736a7SPetr Mladek 		       wq->name);
4539983c7515STejun Heo 		return -ENOMEM;
45404c0736a7SPetr Mladek 	}
4541983c7515STejun Heo 
4542983c7515STejun Heo 	rescuer->rescue_wq = wq;
4543983c7515STejun Heo 	rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name);
4544f187b697SSean Fu 	if (IS_ERR(rescuer->task)) {
4545b92b36eaSDan Carpenter 		ret = PTR_ERR(rescuer->task);
45464c0736a7SPetr Mladek 		pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
45474c0736a7SPetr Mladek 		       wq->name, ERR_PTR(ret));
4548983c7515STejun Heo 		kfree(rescuer);
4549b92b36eaSDan Carpenter 		return ret;
4550983c7515STejun Heo 	}
4551983c7515STejun Heo 
4552983c7515STejun Heo 	wq->rescuer = rescuer;
4553983c7515STejun Heo 	kthread_bind_mask(rescuer->task, cpu_possible_mask);
4554983c7515STejun Heo 	wake_up_process(rescuer->task);
4555983c7515STejun Heo 
4556983c7515STejun Heo 	return 0;
4557983c7515STejun Heo }
4558983c7515STejun Heo 
4559a2775bbcSMathieu Malaterre __printf(1, 4)
4560669de8bdSBart Van Assche struct workqueue_struct *alloc_workqueue(const char *fmt,
456197e37d7bSTejun Heo 					 unsigned int flags,
4562669de8bdSBart Van Assche 					 int max_active, ...)
45633af24433SOleg Nesterov {
4564ecf6881fSTejun Heo 	va_list args;
45653af24433SOleg Nesterov 	struct workqueue_struct *wq;
456649e3cf44STejun Heo 	struct pool_workqueue *pwq;
4567b196be89STejun Heo 
45685c0338c6STejun Heo 	/*
4569fef59c9cSTejun Heo 	 * Unbound && max_active == 1 used to imply ordered, which is no longer
4570fef59c9cSTejun Heo 	 * the case on many machines due to per-pod pools. While
45715c0338c6STejun Heo 	 * alloc_ordered_workqueue() is the right way to create an ordered
4572fef59c9cSTejun Heo 	 * workqueue, keep the previous behavior to avoid subtle breakages.
45735c0338c6STejun Heo 	 */
45745c0338c6STejun Heo 	if ((flags & WQ_UNBOUND) && max_active == 1)
45755c0338c6STejun Heo 		flags |= __WQ_ORDERED;
45765c0338c6STejun Heo 
4577cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
4578cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4579cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
4580cee22a15SViresh Kumar 
4581ecf6881fSTejun Heo 	/* allocate wq and format name */
4582636b927eSTejun Heo 	wq = kzalloc(sizeof(*wq), GFP_KERNEL);
4583b196be89STejun Heo 	if (!wq)
4584d2c1d404STejun Heo 		return NULL;
4585b196be89STejun Heo 
45866029a918STejun Heo 	if (flags & WQ_UNBOUND) {
4587be69d00dSThomas Gleixner 		wq->unbound_attrs = alloc_workqueue_attrs();
45886029a918STejun Heo 		if (!wq->unbound_attrs)
45896029a918STejun Heo 			goto err_free_wq;
45906029a918STejun Heo 	}
45916029a918STejun Heo 
4592669de8bdSBart Van Assche 	va_start(args, max_active);
4593ecf6881fSTejun Heo 	vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4594b196be89STejun Heo 	va_end(args);
45953af24433SOleg Nesterov 
4596d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
4597b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
45983af24433SOleg Nesterov 
4599b196be89STejun Heo 	/* init wq */
460097e37d7bSTejun Heo 	wq->flags = flags;
4601a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
46023c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
4603112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
460430cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
460573f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
460673f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
4607493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
46083af24433SOleg Nesterov 
4609669de8bdSBart Van Assche 	wq_init_lockdep(wq);
4610cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
46113af24433SOleg Nesterov 
461230cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
461382efcab3SBart Van Assche 		goto err_unreg_lockdep;
46141537663fSTejun Heo 
461540c17f75STejun Heo 	if (wq_online && init_rescuer(wq) < 0)
4616d2c1d404STejun Heo 		goto err_destroy;
4617e22bee78STejun Heo 
4618226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4619226223abSTejun Heo 		goto err_destroy;
4620226223abSTejun Heo 
46216af8bf3dSOleg Nesterov 	/*
462268e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
462368e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
462468e13a67SLai Jiangshan 	 * list.
46256af8bf3dSOleg Nesterov 	 */
462668e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4627a0a1a5fdSTejun Heo 
4628a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
462949e3cf44STejun Heo 	for_each_pwq(pwq, wq)
4630699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4631a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4632a0a1a5fdSTejun Heo 
4633e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
4634a0a1a5fdSTejun Heo 
463568e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
46363af24433SOleg Nesterov 
46373af24433SOleg Nesterov 	return wq;
4638d2c1d404STejun Heo 
463982efcab3SBart Van Assche err_unreg_lockdep:
4640009bb421SBart Van Assche 	wq_unregister_lockdep(wq);
4641009bb421SBart Van Assche 	wq_free_lockdep(wq);
464282efcab3SBart Van Assche err_free_wq:
46436029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
46444690c4abSTejun Heo 	kfree(wq);
4645d2c1d404STejun Heo 	return NULL;
4646d2c1d404STejun Heo err_destroy:
4647d2c1d404STejun Heo 	destroy_workqueue(wq);
46484690c4abSTejun Heo 	return NULL;
46491da177e4SLinus Torvalds }
4650669de8bdSBart Van Assche EXPORT_SYMBOL_GPL(alloc_workqueue);
46511da177e4SLinus Torvalds 
4652c29eb853STejun Heo static bool pwq_busy(struct pool_workqueue *pwq)
4653c29eb853STejun Heo {
4654c29eb853STejun Heo 	int i;
4655c29eb853STejun Heo 
4656c29eb853STejun Heo 	for (i = 0; i < WORK_NR_COLORS; i++)
4657c29eb853STejun Heo 		if (pwq->nr_in_flight[i])
4658c29eb853STejun Heo 			return true;
4659c29eb853STejun Heo 
4660c29eb853STejun Heo 	if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4661c29eb853STejun Heo 		return true;
4662f97a4a1aSLai Jiangshan 	if (pwq->nr_active || !list_empty(&pwq->inactive_works))
4663c29eb853STejun Heo 		return true;
4664c29eb853STejun Heo 
4665c29eb853STejun Heo 	return false;
4666c29eb853STejun Heo }
4667c29eb853STejun Heo 
46683af24433SOleg Nesterov /**
46693af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
46703af24433SOleg Nesterov  * @wq: target workqueue
46713af24433SOleg Nesterov  *
46723af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
46733af24433SOleg Nesterov  */
46743af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
46753af24433SOleg Nesterov {
467649e3cf44STejun Heo 	struct pool_workqueue *pwq;
4677636b927eSTejun Heo 	int cpu;
46783af24433SOleg Nesterov 
4679def98c84STejun Heo 	/*
4680def98c84STejun Heo 	 * Remove it from sysfs first so that sanity check failure doesn't
4681def98c84STejun Heo 	 * lead to sysfs name conflicts.
4682def98c84STejun Heo 	 */
4683def98c84STejun Heo 	workqueue_sysfs_unregister(wq);
4684def98c84STejun Heo 
468533e3f0a3SRichard Clark 	/* mark the workqueue destruction is in progress */
468633e3f0a3SRichard Clark 	mutex_lock(&wq->mutex);
468733e3f0a3SRichard Clark 	wq->flags |= __WQ_DESTROYING;
468833e3f0a3SRichard Clark 	mutex_unlock(&wq->mutex);
468933e3f0a3SRichard Clark 
46909c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
46919c5a2ba7STejun Heo 	drain_workqueue(wq);
4692c8efcc25STejun Heo 
4693def98c84STejun Heo 	/* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4694def98c84STejun Heo 	if (wq->rescuer) {
4695def98c84STejun Heo 		struct worker *rescuer = wq->rescuer;
4696def98c84STejun Heo 
4697def98c84STejun Heo 		/* this prevents new queueing */
4698a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
4699def98c84STejun Heo 		wq->rescuer = NULL;
4700a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
4701def98c84STejun Heo 
4702def98c84STejun Heo 		/* rescuer will empty maydays list before exiting */
4703def98c84STejun Heo 		kthread_stop(rescuer->task);
47048efe1223STejun Heo 		kfree(rescuer);
4705def98c84STejun Heo 	}
4706def98c84STejun Heo 
4707c29eb853STejun Heo 	/*
4708c29eb853STejun Heo 	 * Sanity checks - grab all the locks so that we wait for all
4709c29eb853STejun Heo 	 * in-flight operations which may do put_pwq().
4710c29eb853STejun Heo 	 */
4711c29eb853STejun Heo 	mutex_lock(&wq_pool_mutex);
4712b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
471349e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
4714a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
4715c29eb853STejun Heo 		if (WARN_ON(pwq_busy(pwq))) {
47161d9a6159SKefeng Wang 			pr_warn("%s: %s has the following busy pwq\n",
4717e66b39afSTejun Heo 				__func__, wq->name);
4718c29eb853STejun Heo 			show_pwq(pwq);
4719a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pwq->pool->lock);
4720b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
4721c29eb853STejun Heo 			mutex_unlock(&wq_pool_mutex);
472255df0933SImran Khan 			show_one_workqueue(wq);
47236183c009STejun Heo 			return;
472476af4d93STejun Heo 		}
4725a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
472676af4d93STejun Heo 	}
4727b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
47286183c009STejun Heo 
4729a0a1a5fdSTejun Heo 	/*
4730a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
4731a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
4732a0a1a5fdSTejun Heo 	 */
4733e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
473468e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
47353af24433SOleg Nesterov 
47368864b4e5STejun Heo 	/*
4737636b927eSTejun Heo 	 * We're the sole accessor of @wq. Directly access cpu_pwq and dfl_pwq
4738636b927eSTejun Heo 	 * to put the base refs. @wq will be auto-destroyed from the last
4739636b927eSTejun Heo 	 * pwq_put. RCU read lock prevents @wq from going away from under us.
47408864b4e5STejun Heo 	 */
4741636b927eSTejun Heo 	rcu_read_lock();
4742636b927eSTejun Heo 
4743636b927eSTejun Heo 	for_each_possible_cpu(cpu) {
4744636b927eSTejun Heo 		pwq = rcu_access_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu));
4745636b927eSTejun Heo 		RCU_INIT_POINTER(*per_cpu_ptr(wq->cpu_pwq, cpu), NULL);
47464c16bd32STejun Heo 		put_pwq_unlocked(pwq);
47474c16bd32STejun Heo 	}
47484c16bd32STejun Heo 
4749636b927eSTejun Heo 	put_pwq_unlocked(wq->dfl_pwq);
47504c16bd32STejun Heo 	wq->dfl_pwq = NULL;
4751636b927eSTejun Heo 
4752636b927eSTejun Heo 	rcu_read_unlock();
47533af24433SOleg Nesterov }
47543af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
47553af24433SOleg Nesterov 
4756dcd989cbSTejun Heo /**
4757dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
4758dcd989cbSTejun Heo  * @wq: target workqueue
4759dcd989cbSTejun Heo  * @max_active: new max_active value.
4760dcd989cbSTejun Heo  *
4761dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
4762dcd989cbSTejun Heo  *
4763dcd989cbSTejun Heo  * CONTEXT:
4764dcd989cbSTejun Heo  * Don't call from IRQ context.
4765dcd989cbSTejun Heo  */
4766dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4767dcd989cbSTejun Heo {
476849e3cf44STejun Heo 	struct pool_workqueue *pwq;
4769dcd989cbSTejun Heo 
47708719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
47710a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
47728719dceaSTejun Heo 		return;
47738719dceaSTejun Heo 
4774f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4775dcd989cbSTejun Heo 
4776a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4777dcd989cbSTejun Heo 
47780a94efb5STejun Heo 	wq->flags &= ~__WQ_ORDERED;
4779dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4780dcd989cbSTejun Heo 
4781699ce097STejun Heo 	for_each_pwq(pwq, wq)
4782699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4783dcd989cbSTejun Heo 
4784a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4785dcd989cbSTejun Heo }
4786dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4787dcd989cbSTejun Heo 
4788dcd989cbSTejun Heo /**
478927d4ee03SLukas Wunner  * current_work - retrieve %current task's work struct
479027d4ee03SLukas Wunner  *
479127d4ee03SLukas Wunner  * Determine if %current task is a workqueue worker and what it's working on.
479227d4ee03SLukas Wunner  * Useful to find out the context that the %current task is running in.
479327d4ee03SLukas Wunner  *
479427d4ee03SLukas Wunner  * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
479527d4ee03SLukas Wunner  */
479627d4ee03SLukas Wunner struct work_struct *current_work(void)
479727d4ee03SLukas Wunner {
479827d4ee03SLukas Wunner 	struct worker *worker = current_wq_worker();
479927d4ee03SLukas Wunner 
480027d4ee03SLukas Wunner 	return worker ? worker->current_work : NULL;
480127d4ee03SLukas Wunner }
480227d4ee03SLukas Wunner EXPORT_SYMBOL(current_work);
480327d4ee03SLukas Wunner 
480427d4ee03SLukas Wunner /**
4805e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4806e6267616STejun Heo  *
4807e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4808e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4809d185af30SYacine Belkadi  *
4810d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
4811e6267616STejun Heo  */
4812e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4813e6267616STejun Heo {
4814e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4815e6267616STejun Heo 
48166a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
4817e6267616STejun Heo }
4818e6267616STejun Heo 
4819e6267616STejun Heo /**
4820dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4821dcd989cbSTejun Heo  * @cpu: CPU in question
4822dcd989cbSTejun Heo  * @wq: target workqueue
4823dcd989cbSTejun Heo  *
4824dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4825dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4826dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4827dcd989cbSTejun Heo  *
4828d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4829636b927eSTejun Heo  *
4830636b927eSTejun Heo  * With the exception of ordered workqueues, all workqueues have per-cpu
4831636b927eSTejun Heo  * pool_workqueues, each with its own congested state. A workqueue being
4832636b927eSTejun Heo  * congested on one CPU doesn't mean that the workqueue is contested on any
4833636b927eSTejun Heo  * other CPUs.
4834d3251859STejun Heo  *
4835d185af30SYacine Belkadi  * Return:
4836dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4837dcd989cbSTejun Heo  */
4838d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4839dcd989cbSTejun Heo {
48407fb98ea7STejun Heo 	struct pool_workqueue *pwq;
484176af4d93STejun Heo 	bool ret;
484276af4d93STejun Heo 
484324acfb71SThomas Gleixner 	rcu_read_lock();
484424acfb71SThomas Gleixner 	preempt_disable();
48457fb98ea7STejun Heo 
4846d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
4847d3251859STejun Heo 		cpu = smp_processor_id();
4848d3251859STejun Heo 
4849687a9aa5STejun Heo 	pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
4850f97a4a1aSLai Jiangshan 	ret = !list_empty(&pwq->inactive_works);
4851636b927eSTejun Heo 
485224acfb71SThomas Gleixner 	preempt_enable();
485324acfb71SThomas Gleixner 	rcu_read_unlock();
485476af4d93STejun Heo 
485576af4d93STejun Heo 	return ret;
4856dcd989cbSTejun Heo }
4857dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4858dcd989cbSTejun Heo 
4859dcd989cbSTejun Heo /**
4860dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4861dcd989cbSTejun Heo  * @work: the work to be tested
4862dcd989cbSTejun Heo  *
4863dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4864dcd989cbSTejun Heo  * synchronization around this function and the test result is
4865dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4866dcd989cbSTejun Heo  *
4867d185af30SYacine Belkadi  * Return:
4868dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
4869dcd989cbSTejun Heo  */
4870dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4871dcd989cbSTejun Heo {
4872fa1b54e6STejun Heo 	struct worker_pool *pool;
4873dcd989cbSTejun Heo 	unsigned long flags;
4874dcd989cbSTejun Heo 	unsigned int ret = 0;
4875dcd989cbSTejun Heo 
4876dcd989cbSTejun Heo 	if (work_pending(work))
4877dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
4878038366c5SLai Jiangshan 
487924acfb71SThomas Gleixner 	rcu_read_lock();
4880fa1b54e6STejun Heo 	pool = get_work_pool(work);
4881038366c5SLai Jiangshan 	if (pool) {
4882a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pool->lock, flags);
4883c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
4884dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
4885a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pool->lock, flags);
4886038366c5SLai Jiangshan 	}
488724acfb71SThomas Gleixner 	rcu_read_unlock();
4888dcd989cbSTejun Heo 
4889dcd989cbSTejun Heo 	return ret;
4890dcd989cbSTejun Heo }
4891dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
4892dcd989cbSTejun Heo 
48933d1cb205STejun Heo /**
48943d1cb205STejun Heo  * set_worker_desc - set description for the current work item
48953d1cb205STejun Heo  * @fmt: printf-style format string
48963d1cb205STejun Heo  * @...: arguments for the format string
48973d1cb205STejun Heo  *
48983d1cb205STejun Heo  * This function can be called by a running work function to describe what
48993d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
49003d1cb205STejun Heo  * information will be printed out together to help debugging.  The
49013d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
49023d1cb205STejun Heo  */
49033d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
49043d1cb205STejun Heo {
49053d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
49063d1cb205STejun Heo 	va_list args;
49073d1cb205STejun Heo 
49083d1cb205STejun Heo 	if (worker) {
49093d1cb205STejun Heo 		va_start(args, fmt);
49103d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
49113d1cb205STejun Heo 		va_end(args);
49123d1cb205STejun Heo 	}
49133d1cb205STejun Heo }
49145c750d58SSteffen Maier EXPORT_SYMBOL_GPL(set_worker_desc);
49153d1cb205STejun Heo 
49163d1cb205STejun Heo /**
49173d1cb205STejun Heo  * print_worker_info - print out worker information and description
49183d1cb205STejun Heo  * @log_lvl: the log level to use when printing
49193d1cb205STejun Heo  * @task: target task
49203d1cb205STejun Heo  *
49213d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
49223d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
49233d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
49243d1cb205STejun Heo  *
49253d1cb205STejun Heo  * This function can be safely called on any task as long as the
49263d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
49273d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
49283d1cb205STejun Heo  */
49293d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
49303d1cb205STejun Heo {
49313d1cb205STejun Heo 	work_func_t *fn = NULL;
49323d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
49333d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
49343d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
49353d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
49363d1cb205STejun Heo 	struct worker *worker;
49373d1cb205STejun Heo 
49383d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
49393d1cb205STejun Heo 		return;
49403d1cb205STejun Heo 
49413d1cb205STejun Heo 	/*
49423d1cb205STejun Heo 	 * This function is called without any synchronization and @task
49433d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
49443d1cb205STejun Heo 	 */
4945e700591aSPetr Mladek 	worker = kthread_probe_data(task);
49463d1cb205STejun Heo 
49473d1cb205STejun Heo 	/*
49488bf89593STejun Heo 	 * Carefully copy the associated workqueue's workfn, name and desc.
49498bf89593STejun Heo 	 * Keep the original last '\0' in case the original is garbage.
49503d1cb205STejun Heo 	 */
4951fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
4952fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
4953fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
4954fe557319SChristoph Hellwig 	copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
4955fe557319SChristoph Hellwig 	copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
49563d1cb205STejun Heo 
49573d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
4958d75f773cSSakari Ailus 		printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
49598bf89593STejun Heo 		if (strcmp(name, desc))
49603d1cb205STejun Heo 			pr_cont(" (%s)", desc);
49613d1cb205STejun Heo 		pr_cont("\n");
49623d1cb205STejun Heo 	}
49633d1cb205STejun Heo }
49643d1cb205STejun Heo 
49653494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
49663494fc30STejun Heo {
49673494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
49683494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
49693494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
49703494fc30STejun Heo 	pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
49713494fc30STejun Heo }
49723494fc30STejun Heo 
4973c76feb0dSPaul E. McKenney struct pr_cont_work_struct {
4974c76feb0dSPaul E. McKenney 	bool comma;
4975c76feb0dSPaul E. McKenney 	work_func_t func;
4976c76feb0dSPaul E. McKenney 	long ctr;
4977c76feb0dSPaul E. McKenney };
4978c76feb0dSPaul E. McKenney 
4979c76feb0dSPaul E. McKenney static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
4980c76feb0dSPaul E. McKenney {
4981c76feb0dSPaul E. McKenney 	if (!pcwsp->ctr)
4982c76feb0dSPaul E. McKenney 		goto out_record;
4983c76feb0dSPaul E. McKenney 	if (func == pcwsp->func) {
4984c76feb0dSPaul E. McKenney 		pcwsp->ctr++;
4985c76feb0dSPaul E. McKenney 		return;
4986c76feb0dSPaul E. McKenney 	}
4987c76feb0dSPaul E. McKenney 	if (pcwsp->ctr == 1)
4988c76feb0dSPaul E. McKenney 		pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
4989c76feb0dSPaul E. McKenney 	else
4990c76feb0dSPaul E. McKenney 		pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
4991c76feb0dSPaul E. McKenney 	pcwsp->ctr = 0;
4992c76feb0dSPaul E. McKenney out_record:
4993c76feb0dSPaul E. McKenney 	if ((long)func == -1L)
4994c76feb0dSPaul E. McKenney 		return;
4995c76feb0dSPaul E. McKenney 	pcwsp->comma = comma;
4996c76feb0dSPaul E. McKenney 	pcwsp->func = func;
4997c76feb0dSPaul E. McKenney 	pcwsp->ctr = 1;
4998c76feb0dSPaul E. McKenney }
4999c76feb0dSPaul E. McKenney 
5000c76feb0dSPaul E. McKenney static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
50013494fc30STejun Heo {
50023494fc30STejun Heo 	if (work->func == wq_barrier_func) {
50033494fc30STejun Heo 		struct wq_barrier *barr;
50043494fc30STejun Heo 
50053494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
50063494fc30STejun Heo 
5007c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
50083494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
50093494fc30STejun Heo 			task_pid_nr(barr->task));
50103494fc30STejun Heo 	} else {
5011c76feb0dSPaul E. McKenney 		if (!comma)
5012c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5013c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, work->func, pcwsp);
50143494fc30STejun Heo 	}
50153494fc30STejun Heo }
50163494fc30STejun Heo 
50173494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
50183494fc30STejun Heo {
5019c76feb0dSPaul E. McKenney 	struct pr_cont_work_struct pcws = { .ctr = 0, };
50203494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
50213494fc30STejun Heo 	struct work_struct *work;
50223494fc30STejun Heo 	struct worker *worker;
50233494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
50243494fc30STejun Heo 	int bkt;
50253494fc30STejun Heo 
50263494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
50273494fc30STejun Heo 	pr_cont_pool_info(pool);
50283494fc30STejun Heo 
5029e66b39afSTejun Heo 	pr_cont(" active=%d/%d refcnt=%d%s\n",
5030e66b39afSTejun Heo 		pwq->nr_active, pwq->max_active, pwq->refcnt,
50313494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
50323494fc30STejun Heo 
50333494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
50343494fc30STejun Heo 		if (worker->current_pwq == pwq) {
50353494fc30STejun Heo 			has_in_flight = true;
50363494fc30STejun Heo 			break;
50373494fc30STejun Heo 		}
50383494fc30STejun Heo 	}
50393494fc30STejun Heo 	if (has_in_flight) {
50403494fc30STejun Heo 		bool comma = false;
50413494fc30STejun Heo 
50423494fc30STejun Heo 		pr_info("    in-flight:");
50433494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
50443494fc30STejun Heo 			if (worker->current_pwq != pwq)
50453494fc30STejun Heo 				continue;
50463494fc30STejun Heo 
5047d75f773cSSakari Ailus 			pr_cont("%s %d%s:%ps", comma ? "," : "",
50483494fc30STejun Heo 				task_pid_nr(worker->task),
504930ae2fc0STejun Heo 				worker->rescue_wq ? "(RESCUER)" : "",
50503494fc30STejun Heo 				worker->current_func);
50513494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
5052c76feb0dSPaul E. McKenney 				pr_cont_work(false, work, &pcws);
5053c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
50543494fc30STejun Heo 			comma = true;
50553494fc30STejun Heo 		}
50563494fc30STejun Heo 		pr_cont("\n");
50573494fc30STejun Heo 	}
50583494fc30STejun Heo 
50593494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
50603494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
50613494fc30STejun Heo 			has_pending = true;
50623494fc30STejun Heo 			break;
50633494fc30STejun Heo 		}
50643494fc30STejun Heo 	}
50653494fc30STejun Heo 	if (has_pending) {
50663494fc30STejun Heo 		bool comma = false;
50673494fc30STejun Heo 
50683494fc30STejun Heo 		pr_info("    pending:");
50693494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
50703494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
50713494fc30STejun Heo 				continue;
50723494fc30STejun Heo 
5073c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
50743494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
50753494fc30STejun Heo 		}
5076c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
50773494fc30STejun Heo 		pr_cont("\n");
50783494fc30STejun Heo 	}
50793494fc30STejun Heo 
5080f97a4a1aSLai Jiangshan 	if (!list_empty(&pwq->inactive_works)) {
50813494fc30STejun Heo 		bool comma = false;
50823494fc30STejun Heo 
5083f97a4a1aSLai Jiangshan 		pr_info("    inactive:");
5084f97a4a1aSLai Jiangshan 		list_for_each_entry(work, &pwq->inactive_works, entry) {
5085c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
50863494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
50873494fc30STejun Heo 		}
5088c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
50893494fc30STejun Heo 		pr_cont("\n");
50903494fc30STejun Heo 	}
50913494fc30STejun Heo }
50923494fc30STejun Heo 
50933494fc30STejun Heo /**
509455df0933SImran Khan  * show_one_workqueue - dump state of specified workqueue
509555df0933SImran Khan  * @wq: workqueue whose state will be printed
50963494fc30STejun Heo  */
509755df0933SImran Khan void show_one_workqueue(struct workqueue_struct *wq)
50983494fc30STejun Heo {
50993494fc30STejun Heo 	struct pool_workqueue *pwq;
51003494fc30STejun Heo 	bool idle = true;
510155df0933SImran Khan 	unsigned long flags;
51023494fc30STejun Heo 
51033494fc30STejun Heo 	for_each_pwq(pwq, wq) {
5104f97a4a1aSLai Jiangshan 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
51053494fc30STejun Heo 			idle = false;
51063494fc30STejun Heo 			break;
51073494fc30STejun Heo 		}
51083494fc30STejun Heo 	}
510955df0933SImran Khan 	if (idle) /* Nothing to print for idle workqueue */
511055df0933SImran Khan 		return;
51113494fc30STejun Heo 
51123494fc30STejun Heo 	pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
51133494fc30STejun Heo 
51143494fc30STejun Heo 	for_each_pwq(pwq, wq) {
5115a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pwq->pool->lock, flags);
511657116ce1SJohan Hovold 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
511757116ce1SJohan Hovold 			/*
511857116ce1SJohan Hovold 			 * Defer printing to avoid deadlocks in console
511957116ce1SJohan Hovold 			 * drivers that queue work while holding locks
512057116ce1SJohan Hovold 			 * also taken in their write paths.
512157116ce1SJohan Hovold 			 */
512257116ce1SJohan Hovold 			printk_deferred_enter();
51233494fc30STejun Heo 			show_pwq(pwq);
512457116ce1SJohan Hovold 			printk_deferred_exit();
512557116ce1SJohan Hovold 		}
5126a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
512762635ea8SSergey Senozhatsky 		/*
512862635ea8SSergey Senozhatsky 		 * We could be printing a lot from atomic context, e.g.
512955df0933SImran Khan 		 * sysrq-t -> show_all_workqueues(). Avoid triggering
513062635ea8SSergey Senozhatsky 		 * hard lockup.
513162635ea8SSergey Senozhatsky 		 */
513262635ea8SSergey Senozhatsky 		touch_nmi_watchdog();
51333494fc30STejun Heo 	}
513455df0933SImran Khan 
51353494fc30STejun Heo }
51363494fc30STejun Heo 
513755df0933SImran Khan /**
513855df0933SImran Khan  * show_one_worker_pool - dump state of specified worker pool
513955df0933SImran Khan  * @pool: worker pool whose state will be printed
514055df0933SImran Khan  */
514155df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool)
514255df0933SImran Khan {
51433494fc30STejun Heo 	struct worker *worker;
51443494fc30STejun Heo 	bool first = true;
514555df0933SImran Khan 	unsigned long flags;
5146335a42ebSPetr Mladek 	unsigned long hung = 0;
51473494fc30STejun Heo 
5148a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pool->lock, flags);
51493494fc30STejun Heo 	if (pool->nr_workers == pool->nr_idle)
51503494fc30STejun Heo 		goto next_pool;
5151335a42ebSPetr Mladek 
5152335a42ebSPetr Mladek 	/* How long the first pending work is waiting for a worker. */
5153335a42ebSPetr Mladek 	if (!list_empty(&pool->worklist))
5154335a42ebSPetr Mladek 		hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
5155335a42ebSPetr Mladek 
515657116ce1SJohan Hovold 	/*
515757116ce1SJohan Hovold 	 * Defer printing to avoid deadlocks in console drivers that
515857116ce1SJohan Hovold 	 * queue work while holding locks also taken in their write
515957116ce1SJohan Hovold 	 * paths.
516057116ce1SJohan Hovold 	 */
516157116ce1SJohan Hovold 	printk_deferred_enter();
51623494fc30STejun Heo 	pr_info("pool %d:", pool->id);
51633494fc30STejun Heo 	pr_cont_pool_info(pool);
5164335a42ebSPetr Mladek 	pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
51653494fc30STejun Heo 	if (pool->manager)
51663494fc30STejun Heo 		pr_cont(" manager: %d",
51673494fc30STejun Heo 			task_pid_nr(pool->manager->task));
51683494fc30STejun Heo 	list_for_each_entry(worker, &pool->idle_list, entry) {
51693494fc30STejun Heo 		pr_cont(" %s%d", first ? "idle: " : "",
51703494fc30STejun Heo 			task_pid_nr(worker->task));
51713494fc30STejun Heo 		first = false;
51723494fc30STejun Heo 	}
51733494fc30STejun Heo 	pr_cont("\n");
517457116ce1SJohan Hovold 	printk_deferred_exit();
51753494fc30STejun Heo next_pool:
5176a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pool->lock, flags);
517762635ea8SSergey Senozhatsky 	/*
517862635ea8SSergey Senozhatsky 	 * We could be printing a lot from atomic context, e.g.
517955df0933SImran Khan 	 * sysrq-t -> show_all_workqueues(). Avoid triggering
518062635ea8SSergey Senozhatsky 	 * hard lockup.
518162635ea8SSergey Senozhatsky 	 */
518262635ea8SSergey Senozhatsky 	touch_nmi_watchdog();
518355df0933SImran Khan 
51843494fc30STejun Heo }
51853494fc30STejun Heo 
518655df0933SImran Khan /**
518755df0933SImran Khan  * show_all_workqueues - dump workqueue state
518855df0933SImran Khan  *
5189704bc669SJungseung Lee  * Called from a sysrq handler and prints out all busy workqueues and pools.
519055df0933SImran Khan  */
519155df0933SImran Khan void show_all_workqueues(void)
519255df0933SImran Khan {
519355df0933SImran Khan 	struct workqueue_struct *wq;
519455df0933SImran Khan 	struct worker_pool *pool;
519555df0933SImran Khan 	int pi;
519655df0933SImran Khan 
519755df0933SImran Khan 	rcu_read_lock();
519855df0933SImran Khan 
519955df0933SImran Khan 	pr_info("Showing busy workqueues and worker pools:\n");
520055df0933SImran Khan 
520155df0933SImran Khan 	list_for_each_entry_rcu(wq, &workqueues, list)
520255df0933SImran Khan 		show_one_workqueue(wq);
520355df0933SImran Khan 
520455df0933SImran Khan 	for_each_pool(pool, pi)
520555df0933SImran Khan 		show_one_worker_pool(pool);
520655df0933SImran Khan 
520724acfb71SThomas Gleixner 	rcu_read_unlock();
52083494fc30STejun Heo }
52093494fc30STejun Heo 
5210704bc669SJungseung Lee /**
5211704bc669SJungseung Lee  * show_freezable_workqueues - dump freezable workqueue state
5212704bc669SJungseung Lee  *
5213704bc669SJungseung Lee  * Called from try_to_freeze_tasks() and prints out all freezable workqueues
5214704bc669SJungseung Lee  * still busy.
5215704bc669SJungseung Lee  */
5216704bc669SJungseung Lee void show_freezable_workqueues(void)
5217704bc669SJungseung Lee {
5218704bc669SJungseung Lee 	struct workqueue_struct *wq;
5219704bc669SJungseung Lee 
5220704bc669SJungseung Lee 	rcu_read_lock();
5221704bc669SJungseung Lee 
5222704bc669SJungseung Lee 	pr_info("Showing freezable workqueues that are still busy:\n");
5223704bc669SJungseung Lee 
5224704bc669SJungseung Lee 	list_for_each_entry_rcu(wq, &workqueues, list) {
5225704bc669SJungseung Lee 		if (!(wq->flags & WQ_FREEZABLE))
5226704bc669SJungseung Lee 			continue;
5227704bc669SJungseung Lee 		show_one_workqueue(wq);
5228704bc669SJungseung Lee 	}
5229704bc669SJungseung Lee 
5230704bc669SJungseung Lee 	rcu_read_unlock();
5231704bc669SJungseung Lee }
5232704bc669SJungseung Lee 
52336b59808bSTejun Heo /* used to show worker information through /proc/PID/{comm,stat,status} */
52346b59808bSTejun Heo void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
52356b59808bSTejun Heo {
52366b59808bSTejun Heo 	int off;
52376b59808bSTejun Heo 
52386b59808bSTejun Heo 	/* always show the actual comm */
52396b59808bSTejun Heo 	off = strscpy(buf, task->comm, size);
52406b59808bSTejun Heo 	if (off < 0)
52416b59808bSTejun Heo 		return;
52426b59808bSTejun Heo 
5243197f6accSTejun Heo 	/* stabilize PF_WQ_WORKER and worker pool association */
52446b59808bSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
52456b59808bSTejun Heo 
5246197f6accSTejun Heo 	if (task->flags & PF_WQ_WORKER) {
5247197f6accSTejun Heo 		struct worker *worker = kthread_data(task);
5248197f6accSTejun Heo 		struct worker_pool *pool = worker->pool;
52496b59808bSTejun Heo 
52506b59808bSTejun Heo 		if (pool) {
5251a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock_irq(&pool->lock);
52526b59808bSTejun Heo 			/*
5253197f6accSTejun Heo 			 * ->desc tracks information (wq name or
5254197f6accSTejun Heo 			 * set_worker_desc()) for the latest execution.  If
5255197f6accSTejun Heo 			 * current, prepend '+', otherwise '-'.
52566b59808bSTejun Heo 			 */
52576b59808bSTejun Heo 			if (worker->desc[0] != '\0') {
52586b59808bSTejun Heo 				if (worker->current_work)
52596b59808bSTejun Heo 					scnprintf(buf + off, size - off, "+%s",
52606b59808bSTejun Heo 						  worker->desc);
52616b59808bSTejun Heo 				else
52626b59808bSTejun Heo 					scnprintf(buf + off, size - off, "-%s",
52636b59808bSTejun Heo 						  worker->desc);
52646b59808bSTejun Heo 			}
5265a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pool->lock);
52666b59808bSTejun Heo 		}
5267197f6accSTejun Heo 	}
52686b59808bSTejun Heo 
52696b59808bSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
52706b59808bSTejun Heo }
52716b59808bSTejun Heo 
527266448bc2SMathieu Malaterre #ifdef CONFIG_SMP
527366448bc2SMathieu Malaterre 
5274db7bccf4STejun Heo /*
5275db7bccf4STejun Heo  * CPU hotplug.
5276db7bccf4STejun Heo  *
5277e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
5278112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
5279706026c2STejun Heo  * pool which make migrating pending and scheduled works very
5280e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
528194cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
5282e22bee78STejun Heo  * blocked draining impractical.
5283e22bee78STejun Heo  *
528424647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
5285628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
5286628c78e7STejun Heo  * cpu comes back online.
5287db7bccf4STejun Heo  */
5288db7bccf4STejun Heo 
5289e8b3f8dbSLai Jiangshan static void unbind_workers(int cpu)
5290db7bccf4STejun Heo {
52914ce62e9eSTejun Heo 	struct worker_pool *pool;
5292db7bccf4STejun Heo 	struct worker *worker;
5293db7bccf4STejun Heo 
5294f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
52951258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
5296a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
5297e22bee78STejun Heo 
5298f2d5a0eeSTejun Heo 		/*
529992f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
530094cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
530111b45b0bSLai Jiangshan 		 * must be on the cpu.  After this, they may become diasporas.
5302b4ac9384SLai Jiangshan 		 * And the preemption disabled section in their sched callbacks
5303b4ac9384SLai Jiangshan 		 * are guaranteed to see WORKER_UNBOUND since the code here
5304b4ac9384SLai Jiangshan 		 * is on the same cpu.
5305f2d5a0eeSTejun Heo 		 */
5306da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
5307403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
5308db7bccf4STejun Heo 
530924647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
5310f2d5a0eeSTejun Heo 
5311e22bee78STejun Heo 		/*
5312989442d7SLai Jiangshan 		 * The handling of nr_running in sched callbacks are disabled
5313989442d7SLai Jiangshan 		 * now.  Zap nr_running.  After this, nr_running stays zero and
5314989442d7SLai Jiangshan 		 * need_more_worker() and keep_working() are always true as
5315989442d7SLai Jiangshan 		 * long as the worklist is not empty.  This pool now behaves as
5316989442d7SLai Jiangshan 		 * an unbound (in terms of concurrency management) pool which
5317eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
5318e22bee78STejun Heo 		 */
5319bc35f7efSLai Jiangshan 		pool->nr_running = 0;
5320eb283428SLai Jiangshan 
5321eb283428SLai Jiangshan 		/*
5322eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
5323eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
5324eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
5325eb283428SLai Jiangshan 		 */
5326eb283428SLai Jiangshan 		wake_up_worker(pool);
5327989442d7SLai Jiangshan 
5328a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
5329989442d7SLai Jiangshan 
5330793777bcSValentin Schneider 		for_each_pool_worker(worker, pool)
5331793777bcSValentin Schneider 			unbind_worker(worker);
5332989442d7SLai Jiangshan 
5333989442d7SLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
5334eb283428SLai Jiangshan 	}
5335db7bccf4STejun Heo }
5336db7bccf4STejun Heo 
5337bd7c089eSTejun Heo /**
5338bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
5339bd7c089eSTejun Heo  * @pool: pool of interest
5340bd7c089eSTejun Heo  *
5341a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
5342bd7c089eSTejun Heo  */
5343bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
5344bd7c089eSTejun Heo {
5345a9ab775bSTejun Heo 	struct worker *worker;
5346bd7c089eSTejun Heo 
53471258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
5348bd7c089eSTejun Heo 
5349bd7c089eSTejun Heo 	/*
5350a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
5351a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
5352402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
5353a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
5354a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
5355bd7c089eSTejun Heo 	 */
5356c63a2e52SValentin Schneider 	for_each_pool_worker(worker, pool) {
5357c63a2e52SValentin Schneider 		kthread_set_per_cpu(worker->task, pool->cpu);
5358c63a2e52SValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
5359c63a2e52SValentin Schneider 						  pool->attrs->cpumask) < 0);
5360c63a2e52SValentin Schneider 	}
5361a9ab775bSTejun Heo 
5362a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
5363f7c17d26SWanpeng Li 
53643de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
5365a9ab775bSTejun Heo 
5366da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
5367a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
5368a9ab775bSTejun Heo 
5369a9ab775bSTejun Heo 		/*
5370a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
5371a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
5372a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5373a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
5374a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
5375a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
5376a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
5377a9ab775bSTejun Heo 		 *
5378c95491edSMark Rutland 		 * WRITE_ONCE() is necessary because @worker->flags may be
5379a9ab775bSTejun Heo 		 * tested without holding any lock in
53806d25be57SThomas Gleixner 		 * wq_worker_running().  Without it, NOT_RUNNING test may
5381a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
5382a9ab775bSTejun Heo 		 * management operations.
5383bd7c089eSTejun Heo 		 */
5384a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5385a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
5386a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
5387c95491edSMark Rutland 		WRITE_ONCE(worker->flags, worker_flags);
5388bd7c089eSTejun Heo 	}
5389a9ab775bSTejun Heo 
5390a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
5391bd7c089eSTejun Heo }
5392bd7c089eSTejun Heo 
53937dbc725eSTejun Heo /**
53947dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
53957dbc725eSTejun Heo  * @pool: unbound pool of interest
53967dbc725eSTejun Heo  * @cpu: the CPU which is coming up
53977dbc725eSTejun Heo  *
53987dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
53997dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
54007dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
54017dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
54027dbc725eSTejun Heo  */
54037dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
54047dbc725eSTejun Heo {
54057dbc725eSTejun Heo 	static cpumask_t cpumask;
54067dbc725eSTejun Heo 	struct worker *worker;
54077dbc725eSTejun Heo 
54081258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
54097dbc725eSTejun Heo 
54107dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
54117dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
54127dbc725eSTejun Heo 		return;
54137dbc725eSTejun Heo 
54147dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
54157dbc725eSTejun Heo 
54167dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
5417da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
5418d945b5e9SPeter Zijlstra 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
54197dbc725eSTejun Heo }
54207dbc725eSTejun Heo 
54217ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
54221da177e4SLinus Torvalds {
54234ce62e9eSTejun Heo 	struct worker_pool *pool;
54241da177e4SLinus Torvalds 
5425f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
54263ce63377STejun Heo 		if (pool->nr_workers)
54273ce63377STejun Heo 			continue;
5428051e1850SLai Jiangshan 		if (!create_worker(pool))
54297ee681b2SThomas Gleixner 			return -ENOMEM;
54303af24433SOleg Nesterov 	}
54317ee681b2SThomas Gleixner 	return 0;
54327ee681b2SThomas Gleixner }
54331da177e4SLinus Torvalds 
54347ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
54357ee681b2SThomas Gleixner {
54367ee681b2SThomas Gleixner 	struct worker_pool *pool;
54377ee681b2SThomas Gleixner 	struct workqueue_struct *wq;
54387ee681b2SThomas Gleixner 	int pi;
54397ee681b2SThomas Gleixner 
544068e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
54417dbc725eSTejun Heo 
54427dbc725eSTejun Heo 	for_each_pool(pool, pi) {
54431258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
544494cf58bbSTejun Heo 
5445f05b558dSLai Jiangshan 		if (pool->cpu == cpu)
544694cf58bbSTejun Heo 			rebind_workers(pool);
5447f05b558dSLai Jiangshan 		else if (pool->cpu < 0)
54487dbc725eSTejun Heo 			restore_unbound_workers_cpumask(pool, cpu);
544994cf58bbSTejun Heo 
54501258fae7STejun Heo 		mutex_unlock(&wq_pool_attach_mutex);
545194cf58bbSTejun Heo 	}
54527dbc725eSTejun Heo 
5453fef59c9cSTejun Heo 	/* update pod affinity of unbound workqueues */
54544cbfd3deSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
54554cbfd3deSTejun Heo 		int tcpu;
54564cbfd3deSTejun Heo 
54574cbfd3deSTejun Heo 		for_each_possible_cpu(tcpu) {
54584cbfd3deSTejun Heo 			if (cpu_to_node(tcpu) == cpu_to_node(cpu)) {
5459fef59c9cSTejun Heo 				wq_update_pod(wq, tcpu, cpu, true);
54604cbfd3deSTejun Heo 			}
54614cbfd3deSTejun Heo 		}
54624cbfd3deSTejun Heo 	}
54634c16bd32STejun Heo 
546468e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
54657ee681b2SThomas Gleixner 	return 0;
546665758202STejun Heo }
546765758202STejun Heo 
54687ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
546965758202STejun Heo {
54704c16bd32STejun Heo 	struct workqueue_struct *wq;
54718db25e78STejun Heo 
54724c16bd32STejun Heo 	/* unbinding per-cpu workers should happen on the local CPU */
5473e8b3f8dbSLai Jiangshan 	if (WARN_ON(cpu != smp_processor_id()))
5474e8b3f8dbSLai Jiangshan 		return -1;
5475e8b3f8dbSLai Jiangshan 
5476e8b3f8dbSLai Jiangshan 	unbind_workers(cpu);
54774c16bd32STejun Heo 
5478fef59c9cSTejun Heo 	/* update pod affinity of unbound workqueues */
54794c16bd32STejun Heo 	mutex_lock(&wq_pool_mutex);
54804cbfd3deSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
54814cbfd3deSTejun Heo 		int tcpu;
54824cbfd3deSTejun Heo 
54834cbfd3deSTejun Heo 		for_each_possible_cpu(tcpu) {
54844cbfd3deSTejun Heo 			if (cpu_to_node(tcpu) == cpu_to_node(cpu)) {
5485fef59c9cSTejun Heo 				wq_update_pod(wq, tcpu, cpu, false);
54864cbfd3deSTejun Heo 			}
54874cbfd3deSTejun Heo 		}
54884cbfd3deSTejun Heo 	}
54894c16bd32STejun Heo 	mutex_unlock(&wq_pool_mutex);
54904c16bd32STejun Heo 
54917ee681b2SThomas Gleixner 	return 0;
549265758202STejun Heo }
549365758202STejun Heo 
54942d3854a3SRusty Russell struct work_for_cpu {
5495ed48ece2STejun Heo 	struct work_struct work;
54962d3854a3SRusty Russell 	long (*fn)(void *);
54972d3854a3SRusty Russell 	void *arg;
54982d3854a3SRusty Russell 	long ret;
54992d3854a3SRusty Russell };
55002d3854a3SRusty Russell 
5501ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
55022d3854a3SRusty Russell {
5503ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5504ed48ece2STejun Heo 
55052d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
55062d3854a3SRusty Russell }
55072d3854a3SRusty Russell 
55082d3854a3SRusty Russell /**
550922aceb31SAnna-Maria Gleixner  * work_on_cpu - run a function in thread context on a particular cpu
55102d3854a3SRusty Russell  * @cpu: the cpu to run on
55112d3854a3SRusty Russell  * @fn: the function to run
55122d3854a3SRusty Russell  * @arg: the function arg
55132d3854a3SRusty Russell  *
551431ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
55156b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
5516d185af30SYacine Belkadi  *
5517d185af30SYacine Belkadi  * Return: The value @fn returns.
55182d3854a3SRusty Russell  */
5519d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
55202d3854a3SRusty Russell {
5521ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
55222d3854a3SRusty Russell 
5523ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
5524ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
552512997d1aSBjorn Helgaas 	flush_work(&wfc.work);
5526440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
55272d3854a3SRusty Russell 	return wfc.ret;
55282d3854a3SRusty Russell }
55292d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
55300e8d6a93SThomas Gleixner 
55310e8d6a93SThomas Gleixner /**
55320e8d6a93SThomas Gleixner  * work_on_cpu_safe - run a function in thread context on a particular cpu
55330e8d6a93SThomas Gleixner  * @cpu: the cpu to run on
55340e8d6a93SThomas Gleixner  * @fn:  the function to run
55350e8d6a93SThomas Gleixner  * @arg: the function argument
55360e8d6a93SThomas Gleixner  *
55370e8d6a93SThomas Gleixner  * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
55380e8d6a93SThomas Gleixner  * any locks which would prevent @fn from completing.
55390e8d6a93SThomas Gleixner  *
55400e8d6a93SThomas Gleixner  * Return: The value @fn returns.
55410e8d6a93SThomas Gleixner  */
55420e8d6a93SThomas Gleixner long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
55430e8d6a93SThomas Gleixner {
55440e8d6a93SThomas Gleixner 	long ret = -ENODEV;
55450e8d6a93SThomas Gleixner 
5546ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
55470e8d6a93SThomas Gleixner 	if (cpu_online(cpu))
55480e8d6a93SThomas Gleixner 		ret = work_on_cpu(cpu, fn, arg);
5549ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
55500e8d6a93SThomas Gleixner 	return ret;
55510e8d6a93SThomas Gleixner }
55520e8d6a93SThomas Gleixner EXPORT_SYMBOL_GPL(work_on_cpu_safe);
55532d3854a3SRusty Russell #endif /* CONFIG_SMP */
55542d3854a3SRusty Russell 
5555a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
5556e7577c50SRusty Russell 
5557a0a1a5fdSTejun Heo /**
5558a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
5559a0a1a5fdSTejun Heo  *
556058a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
5561f97a4a1aSLai Jiangshan  * workqueues will queue new works to their inactive_works list instead of
5562706026c2STejun Heo  * pool->worklist.
5563a0a1a5fdSTejun Heo  *
5564a0a1a5fdSTejun Heo  * CONTEXT:
5565a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5566a0a1a5fdSTejun Heo  */
5567a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
5568a0a1a5fdSTejun Heo {
556924b8a847STejun Heo 	struct workqueue_struct *wq;
557024b8a847STejun Heo 	struct pool_workqueue *pwq;
5571a0a1a5fdSTejun Heo 
557268e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5573a0a1a5fdSTejun Heo 
55746183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
5575a0a1a5fdSTejun Heo 	workqueue_freezing = true;
5576a0a1a5fdSTejun Heo 
557724b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5578a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5579699ce097STejun Heo 		for_each_pwq(pwq, wq)
5580699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5581a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
5582a1056305STejun Heo 	}
55835bcab335STejun Heo 
558468e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5585a0a1a5fdSTejun Heo }
5586a0a1a5fdSTejun Heo 
5587a0a1a5fdSTejun Heo /**
558858a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
5589a0a1a5fdSTejun Heo  *
5590a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
5591a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
5592a0a1a5fdSTejun Heo  *
5593a0a1a5fdSTejun Heo  * CONTEXT:
559468e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
5595a0a1a5fdSTejun Heo  *
5596d185af30SYacine Belkadi  * Return:
559758a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
559858a69cb4STejun Heo  * is complete.
5599a0a1a5fdSTejun Heo  */
5600a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
5601a0a1a5fdSTejun Heo {
5602a0a1a5fdSTejun Heo 	bool busy = false;
560324b8a847STejun Heo 	struct workqueue_struct *wq;
560424b8a847STejun Heo 	struct pool_workqueue *pwq;
5605a0a1a5fdSTejun Heo 
560668e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5607a0a1a5fdSTejun Heo 
56086183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
5609a0a1a5fdSTejun Heo 
561024b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
561124b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
561224b8a847STejun Heo 			continue;
5613a0a1a5fdSTejun Heo 		/*
5614a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
5615a0a1a5fdSTejun Heo 		 * to peek without lock.
5616a0a1a5fdSTejun Heo 		 */
561724acfb71SThomas Gleixner 		rcu_read_lock();
561824b8a847STejun Heo 		for_each_pwq(pwq, wq) {
56196183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
5620112202d9STejun Heo 			if (pwq->nr_active) {
5621a0a1a5fdSTejun Heo 				busy = true;
562224acfb71SThomas Gleixner 				rcu_read_unlock();
5623a0a1a5fdSTejun Heo 				goto out_unlock;
5624a0a1a5fdSTejun Heo 			}
5625a0a1a5fdSTejun Heo 		}
562624acfb71SThomas Gleixner 		rcu_read_unlock();
5627a0a1a5fdSTejun Heo 	}
5628a0a1a5fdSTejun Heo out_unlock:
562968e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5630a0a1a5fdSTejun Heo 	return busy;
5631a0a1a5fdSTejun Heo }
5632a0a1a5fdSTejun Heo 
5633a0a1a5fdSTejun Heo /**
5634a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
5635a0a1a5fdSTejun Heo  *
5636a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
5637706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
5638a0a1a5fdSTejun Heo  *
5639a0a1a5fdSTejun Heo  * CONTEXT:
5640a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5641a0a1a5fdSTejun Heo  */
5642a0a1a5fdSTejun Heo void thaw_workqueues(void)
5643a0a1a5fdSTejun Heo {
564424b8a847STejun Heo 	struct workqueue_struct *wq;
564524b8a847STejun Heo 	struct pool_workqueue *pwq;
5646a0a1a5fdSTejun Heo 
564768e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5648a0a1a5fdSTejun Heo 
5649a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
5650a0a1a5fdSTejun Heo 		goto out_unlock;
5651a0a1a5fdSTejun Heo 
565274b414eaSLai Jiangshan 	workqueue_freezing = false;
565324b8a847STejun Heo 
565424b8a847STejun Heo 	/* restore max_active and repopulate worklist */
565524b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5656a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5657699ce097STejun Heo 		for_each_pwq(pwq, wq)
5658699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5659a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
566024b8a847STejun Heo 	}
566124b8a847STejun Heo 
5662a0a1a5fdSTejun Heo out_unlock:
566368e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5664a0a1a5fdSTejun Heo }
5665a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
5666a0a1a5fdSTejun Heo 
566799c621efSLai Jiangshan static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
5668042f7df1SLai Jiangshan {
5669042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
5670042f7df1SLai Jiangshan 	int ret = 0;
5671042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
5672042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
5673042f7df1SLai Jiangshan 
5674042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5675042f7df1SLai Jiangshan 
5676042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
5677042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
5678042f7df1SLai Jiangshan 			continue;
5679042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
5680042f7df1SLai Jiangshan 		if (wq->flags & __WQ_ORDERED)
5681042f7df1SLai Jiangshan 			continue;
5682042f7df1SLai Jiangshan 
568399c621efSLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
5684042f7df1SLai Jiangshan 		if (!ctx) {
5685042f7df1SLai Jiangshan 			ret = -ENOMEM;
5686042f7df1SLai Jiangshan 			break;
5687042f7df1SLai Jiangshan 		}
5688042f7df1SLai Jiangshan 
5689042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
5690042f7df1SLai Jiangshan 	}
5691042f7df1SLai Jiangshan 
5692042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
5693042f7df1SLai Jiangshan 		if (!ret)
5694042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
5695042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
5696042f7df1SLai Jiangshan 	}
5697042f7df1SLai Jiangshan 
569899c621efSLai Jiangshan 	if (!ret) {
569999c621efSLai Jiangshan 		mutex_lock(&wq_pool_attach_mutex);
570099c621efSLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
570199c621efSLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
570299c621efSLai Jiangshan 	}
5703042f7df1SLai Jiangshan 	return ret;
5704042f7df1SLai Jiangshan }
5705042f7df1SLai Jiangshan 
5706042f7df1SLai Jiangshan /**
5707042f7df1SLai Jiangshan  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5708042f7df1SLai Jiangshan  *  @cpumask: the cpumask to set
5709042f7df1SLai Jiangshan  *
5710042f7df1SLai Jiangshan  *  The low-level workqueues cpumask is a global cpumask that limits
5711042f7df1SLai Jiangshan  *  the affinity of all unbound workqueues.  This function check the @cpumask
5712042f7df1SLai Jiangshan  *  and apply it to all unbound workqueues and updates all pwqs of them.
5713042f7df1SLai Jiangshan  *
571467dc8325SCai Huoqing  *  Return:	0	- Success
5715042f7df1SLai Jiangshan  *  		-EINVAL	- Invalid @cpumask
5716042f7df1SLai Jiangshan  *  		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
5717042f7df1SLai Jiangshan  */
5718042f7df1SLai Jiangshan int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5719042f7df1SLai Jiangshan {
5720042f7df1SLai Jiangshan 	int ret = -EINVAL;
5721042f7df1SLai Jiangshan 
5722c98a9805STal Shorer 	/*
5723c98a9805STal Shorer 	 * Not excluding isolated cpus on purpose.
5724c98a9805STal Shorer 	 * If the user wishes to include them, we allow that.
5725c98a9805STal Shorer 	 */
5726042f7df1SLai Jiangshan 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
5727042f7df1SLai Jiangshan 	if (!cpumask_empty(cpumask)) {
5728a0111cf6SLai Jiangshan 		apply_wqattrs_lock();
5729d25302e4SMenglong Dong 		if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
5730d25302e4SMenglong Dong 			ret = 0;
5731d25302e4SMenglong Dong 			goto out_unlock;
5732d25302e4SMenglong Dong 		}
5733d25302e4SMenglong Dong 
573499c621efSLai Jiangshan 		ret = workqueue_apply_unbound_cpumask(cpumask);
5735042f7df1SLai Jiangshan 
5736d25302e4SMenglong Dong out_unlock:
5737a0111cf6SLai Jiangshan 		apply_wqattrs_unlock();
5738042f7df1SLai Jiangshan 	}
5739042f7df1SLai Jiangshan 
5740042f7df1SLai Jiangshan 	return ret;
5741042f7df1SLai Jiangshan }
5742042f7df1SLai Jiangshan 
57436ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
57446ba94429SFrederic Weisbecker /*
57456ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
57466ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
57476ba94429SFrederic Weisbecker  * following attributes.
57486ba94429SFrederic Weisbecker  *
57496ba94429SFrederic Weisbecker  *  per_cpu	RO bool	: whether the workqueue is per-cpu or unbound
57506ba94429SFrederic Weisbecker  *  max_active	RW int	: maximum number of in-flight work items
57516ba94429SFrederic Weisbecker  *
57526ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
57536ba94429SFrederic Weisbecker  *
57546ba94429SFrederic Weisbecker  *  nice	RW int	: nice value of the workers
57556ba94429SFrederic Weisbecker  *  cpumask	RW mask	: bitmask of allowed CPUs for the workers
57566ba94429SFrederic Weisbecker  */
57576ba94429SFrederic Weisbecker struct wq_device {
57586ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
57596ba94429SFrederic Weisbecker 	struct device			dev;
57606ba94429SFrederic Weisbecker };
57616ba94429SFrederic Weisbecker 
57626ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
57636ba94429SFrederic Weisbecker {
57646ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
57656ba94429SFrederic Weisbecker 
57666ba94429SFrederic Weisbecker 	return wq_dev->wq;
57676ba94429SFrederic Weisbecker }
57686ba94429SFrederic Weisbecker 
57696ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
57706ba94429SFrederic Weisbecker 			    char *buf)
57716ba94429SFrederic Weisbecker {
57726ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
57736ba94429SFrederic Weisbecker 
57746ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
57756ba94429SFrederic Weisbecker }
57766ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
57776ba94429SFrederic Weisbecker 
57786ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
57796ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
57806ba94429SFrederic Weisbecker {
57816ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
57826ba94429SFrederic Weisbecker 
57836ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
57846ba94429SFrederic Weisbecker }
57856ba94429SFrederic Weisbecker 
57866ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
57876ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
57886ba94429SFrederic Weisbecker 				size_t count)
57896ba94429SFrederic Weisbecker {
57906ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
57916ba94429SFrederic Weisbecker 	int val;
57926ba94429SFrederic Weisbecker 
57936ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
57946ba94429SFrederic Weisbecker 		return -EINVAL;
57956ba94429SFrederic Weisbecker 
57966ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
57976ba94429SFrederic Weisbecker 	return count;
57986ba94429SFrederic Weisbecker }
57996ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
58006ba94429SFrederic Weisbecker 
58016ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
58026ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
58036ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
58046ba94429SFrederic Weisbecker 	NULL,
58056ba94429SFrederic Weisbecker };
58066ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
58076ba94429SFrederic Weisbecker 
58086ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
58096ba94429SFrederic Weisbecker 			    char *buf)
58106ba94429SFrederic Weisbecker {
58116ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
58126ba94429SFrederic Weisbecker 	int written;
58136ba94429SFrederic Weisbecker 
58146ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
58156ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
58166ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
58176ba94429SFrederic Weisbecker 
58186ba94429SFrederic Weisbecker 	return written;
58196ba94429SFrederic Weisbecker }
58206ba94429SFrederic Weisbecker 
58216ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
58226ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
58236ba94429SFrederic Weisbecker {
58246ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
58256ba94429SFrederic Weisbecker 
5826899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5827899a94feSLai Jiangshan 
5828be69d00dSThomas Gleixner 	attrs = alloc_workqueue_attrs();
58296ba94429SFrederic Weisbecker 	if (!attrs)
58306ba94429SFrederic Weisbecker 		return NULL;
58316ba94429SFrederic Weisbecker 
58326ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
58336ba94429SFrederic Weisbecker 	return attrs;
58346ba94429SFrederic Weisbecker }
58356ba94429SFrederic Weisbecker 
58366ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
58376ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
58386ba94429SFrederic Weisbecker {
58396ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
58406ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5841d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5842d4d3e257SLai Jiangshan 
5843d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
58446ba94429SFrederic Weisbecker 
58456ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
58466ba94429SFrederic Weisbecker 	if (!attrs)
5847d4d3e257SLai Jiangshan 		goto out_unlock;
58486ba94429SFrederic Weisbecker 
58496ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
58506ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5851d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
58526ba94429SFrederic Weisbecker 	else
58536ba94429SFrederic Weisbecker 		ret = -EINVAL;
58546ba94429SFrederic Weisbecker 
5855d4d3e257SLai Jiangshan out_unlock:
5856d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
58576ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
58586ba94429SFrederic Weisbecker 	return ret ?: count;
58596ba94429SFrederic Weisbecker }
58606ba94429SFrederic Weisbecker 
58616ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
58626ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
58636ba94429SFrederic Weisbecker {
58646ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
58656ba94429SFrederic Weisbecker 	int written;
58666ba94429SFrederic Weisbecker 
58676ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
58686ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
58696ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
58706ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
58716ba94429SFrederic Weisbecker 	return written;
58726ba94429SFrederic Weisbecker }
58736ba94429SFrederic Weisbecker 
58746ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
58756ba94429SFrederic Weisbecker 				struct device_attribute *attr,
58766ba94429SFrederic Weisbecker 				const char *buf, size_t count)
58776ba94429SFrederic Weisbecker {
58786ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
58796ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5880d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5881d4d3e257SLai Jiangshan 
5882d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
58836ba94429SFrederic Weisbecker 
58846ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
58856ba94429SFrederic Weisbecker 	if (!attrs)
5886d4d3e257SLai Jiangshan 		goto out_unlock;
58876ba94429SFrederic Weisbecker 
58886ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
58896ba94429SFrederic Weisbecker 	if (!ret)
5890d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
58916ba94429SFrederic Weisbecker 
5892d4d3e257SLai Jiangshan out_unlock:
5893d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
58946ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
58956ba94429SFrederic Weisbecker 	return ret ?: count;
58966ba94429SFrederic Weisbecker }
58976ba94429SFrederic Weisbecker 
58986ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
58996ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
59006ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
59016ba94429SFrederic Weisbecker 	__ATTR_NULL,
59026ba94429SFrederic Weisbecker };
59036ba94429SFrederic Weisbecker 
59046ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
59056ba94429SFrederic Weisbecker 	.name				= "workqueue",
59066ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
59076ba94429SFrederic Weisbecker };
59086ba94429SFrederic Weisbecker 
5909b05a7928SFrederic Weisbecker static ssize_t wq_unbound_cpumask_show(struct device *dev,
5910b05a7928SFrederic Weisbecker 		struct device_attribute *attr, char *buf)
5911b05a7928SFrederic Weisbecker {
5912b05a7928SFrederic Weisbecker 	int written;
5913b05a7928SFrederic Weisbecker 
5914042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5915b05a7928SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5916b05a7928SFrederic Weisbecker 			    cpumask_pr_args(wq_unbound_cpumask));
5917042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5918b05a7928SFrederic Weisbecker 
5919b05a7928SFrederic Weisbecker 	return written;
5920b05a7928SFrederic Weisbecker }
5921b05a7928SFrederic Weisbecker 
5922042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
5923042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
5924042f7df1SLai Jiangshan {
5925042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
5926042f7df1SLai Jiangshan 	int ret;
5927042f7df1SLai Jiangshan 
5928042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5929042f7df1SLai Jiangshan 		return -ENOMEM;
5930042f7df1SLai Jiangshan 
5931042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
5932042f7df1SLai Jiangshan 	if (!ret)
5933042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
5934042f7df1SLai Jiangshan 
5935042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
5936042f7df1SLai Jiangshan 	return ret ? ret : count;
5937042f7df1SLai Jiangshan }
5938042f7df1SLai Jiangshan 
5939b05a7928SFrederic Weisbecker static struct device_attribute wq_sysfs_cpumask_attr =
5940042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5941042f7df1SLai Jiangshan 	       wq_unbound_cpumask_store);
5942b05a7928SFrederic Weisbecker 
59436ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
59446ba94429SFrederic Weisbecker {
5945686f6697SGreg Kroah-Hartman 	struct device *dev_root;
5946b05a7928SFrederic Weisbecker 	int err;
5947b05a7928SFrederic Weisbecker 
5948b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
5949b05a7928SFrederic Weisbecker 	if (err)
5950b05a7928SFrederic Weisbecker 		return err;
5951b05a7928SFrederic Weisbecker 
5952686f6697SGreg Kroah-Hartman 	dev_root = bus_get_dev_root(&wq_subsys);
5953686f6697SGreg Kroah-Hartman 	if (dev_root) {
5954686f6697SGreg Kroah-Hartman 		err = device_create_file(dev_root, &wq_sysfs_cpumask_attr);
5955686f6697SGreg Kroah-Hartman 		put_device(dev_root);
5956686f6697SGreg Kroah-Hartman 	}
5957686f6697SGreg Kroah-Hartman 	return err;
59586ba94429SFrederic Weisbecker }
59596ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
59606ba94429SFrederic Weisbecker 
59616ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
59626ba94429SFrederic Weisbecker {
59636ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
59646ba94429SFrederic Weisbecker 
59656ba94429SFrederic Weisbecker 	kfree(wq_dev);
59666ba94429SFrederic Weisbecker }
59676ba94429SFrederic Weisbecker 
59686ba94429SFrederic Weisbecker /**
59696ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
59706ba94429SFrederic Weisbecker  * @wq: the workqueue to register
59716ba94429SFrederic Weisbecker  *
59726ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
59736ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
59746ba94429SFrederic Weisbecker  * which is the preferred method.
59756ba94429SFrederic Weisbecker  *
59766ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
59776ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
59786ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
59796ba94429SFrederic Weisbecker  * attributes.
59806ba94429SFrederic Weisbecker  *
59816ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
59826ba94429SFrederic Weisbecker  */
59836ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
59846ba94429SFrederic Weisbecker {
59856ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
59866ba94429SFrederic Weisbecker 	int ret;
59876ba94429SFrederic Weisbecker 
59886ba94429SFrederic Weisbecker 	/*
5989402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
59906ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
59916ba94429SFrederic Weisbecker 	 * workqueues.
59926ba94429SFrederic Weisbecker 	 */
59930a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
59946ba94429SFrederic Weisbecker 		return -EINVAL;
59956ba94429SFrederic Weisbecker 
59966ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
59976ba94429SFrederic Weisbecker 	if (!wq_dev)
59986ba94429SFrederic Weisbecker 		return -ENOMEM;
59996ba94429SFrederic Weisbecker 
60006ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
60016ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
60026ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
600323217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
60046ba94429SFrederic Weisbecker 
60056ba94429SFrederic Weisbecker 	/*
60066ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
60076ba94429SFrederic Weisbecker 	 * everything is ready.
60086ba94429SFrederic Weisbecker 	 */
60096ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
60106ba94429SFrederic Weisbecker 
60116ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
60126ba94429SFrederic Weisbecker 	if (ret) {
6013537f4146SArvind Yadav 		put_device(&wq_dev->dev);
60146ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
60156ba94429SFrederic Weisbecker 		return ret;
60166ba94429SFrederic Weisbecker 	}
60176ba94429SFrederic Weisbecker 
60186ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
60196ba94429SFrederic Weisbecker 		struct device_attribute *attr;
60206ba94429SFrederic Weisbecker 
60216ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
60226ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
60236ba94429SFrederic Weisbecker 			if (ret) {
60246ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
60256ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
60266ba94429SFrederic Weisbecker 				return ret;
60276ba94429SFrederic Weisbecker 			}
60286ba94429SFrederic Weisbecker 		}
60296ba94429SFrederic Weisbecker 	}
60306ba94429SFrederic Weisbecker 
60316ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
60326ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
60336ba94429SFrederic Weisbecker 	return 0;
60346ba94429SFrederic Weisbecker }
60356ba94429SFrederic Weisbecker 
60366ba94429SFrederic Weisbecker /**
60376ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
60386ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
60396ba94429SFrederic Weisbecker  *
60406ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
60416ba94429SFrederic Weisbecker  */
60426ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
60436ba94429SFrederic Weisbecker {
60446ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
60456ba94429SFrederic Weisbecker 
60466ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
60476ba94429SFrederic Weisbecker 		return;
60486ba94429SFrederic Weisbecker 
60496ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
60506ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
60516ba94429SFrederic Weisbecker }
60526ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
60536ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
60546ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
60556ba94429SFrederic Weisbecker 
605682607adcSTejun Heo /*
605782607adcSTejun Heo  * Workqueue watchdog.
605882607adcSTejun Heo  *
605982607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
606082607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
606182607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
606282607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
606382607adcSTejun Heo  * largely opaque.
606482607adcSTejun Heo  *
606582607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
606682607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
606782607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
606882607adcSTejun Heo  *
606982607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
607082607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
607182607adcSTejun Heo  * corresponding sysfs parameter file.
607282607adcSTejun Heo  */
607382607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
607482607adcSTejun Heo 
607582607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
60765cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
607782607adcSTejun Heo 
607882607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
607982607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
608082607adcSTejun Heo 
6081cd2440d6SPetr Mladek /*
6082cd2440d6SPetr Mladek  * Show workers that might prevent the processing of pending work items.
6083cd2440d6SPetr Mladek  * The only candidates are CPU-bound workers in the running state.
6084cd2440d6SPetr Mladek  * Pending work items should be handled by another idle worker
6085cd2440d6SPetr Mladek  * in all other situations.
6086cd2440d6SPetr Mladek  */
6087cd2440d6SPetr Mladek static void show_cpu_pool_hog(struct worker_pool *pool)
6088cd2440d6SPetr Mladek {
6089cd2440d6SPetr Mladek 	struct worker *worker;
6090cd2440d6SPetr Mladek 	unsigned long flags;
6091cd2440d6SPetr Mladek 	int bkt;
6092cd2440d6SPetr Mladek 
6093cd2440d6SPetr Mladek 	raw_spin_lock_irqsave(&pool->lock, flags);
6094cd2440d6SPetr Mladek 
6095cd2440d6SPetr Mladek 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
6096cd2440d6SPetr Mladek 		if (task_is_running(worker->task)) {
6097cd2440d6SPetr Mladek 			/*
6098cd2440d6SPetr Mladek 			 * Defer printing to avoid deadlocks in console
6099cd2440d6SPetr Mladek 			 * drivers that queue work while holding locks
6100cd2440d6SPetr Mladek 			 * also taken in their write paths.
6101cd2440d6SPetr Mladek 			 */
6102cd2440d6SPetr Mladek 			printk_deferred_enter();
6103cd2440d6SPetr Mladek 
6104cd2440d6SPetr Mladek 			pr_info("pool %d:\n", pool->id);
6105cd2440d6SPetr Mladek 			sched_show_task(worker->task);
6106cd2440d6SPetr Mladek 
6107cd2440d6SPetr Mladek 			printk_deferred_exit();
6108cd2440d6SPetr Mladek 		}
6109cd2440d6SPetr Mladek 	}
6110cd2440d6SPetr Mladek 
6111cd2440d6SPetr Mladek 	raw_spin_unlock_irqrestore(&pool->lock, flags);
6112cd2440d6SPetr Mladek }
6113cd2440d6SPetr Mladek 
6114cd2440d6SPetr Mladek static void show_cpu_pools_hogs(void)
6115cd2440d6SPetr Mladek {
6116cd2440d6SPetr Mladek 	struct worker_pool *pool;
6117cd2440d6SPetr Mladek 	int pi;
6118cd2440d6SPetr Mladek 
6119cd2440d6SPetr Mladek 	pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
6120cd2440d6SPetr Mladek 
6121cd2440d6SPetr Mladek 	rcu_read_lock();
6122cd2440d6SPetr Mladek 
6123cd2440d6SPetr Mladek 	for_each_pool(pool, pi) {
6124cd2440d6SPetr Mladek 		if (pool->cpu_stall)
6125cd2440d6SPetr Mladek 			show_cpu_pool_hog(pool);
6126cd2440d6SPetr Mladek 
6127cd2440d6SPetr Mladek 	}
6128cd2440d6SPetr Mladek 
6129cd2440d6SPetr Mladek 	rcu_read_unlock();
6130cd2440d6SPetr Mladek }
6131cd2440d6SPetr Mladek 
613282607adcSTejun Heo static void wq_watchdog_reset_touched(void)
613382607adcSTejun Heo {
613482607adcSTejun Heo 	int cpu;
613582607adcSTejun Heo 
613682607adcSTejun Heo 	wq_watchdog_touched = jiffies;
613782607adcSTejun Heo 	for_each_possible_cpu(cpu)
613882607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
613982607adcSTejun Heo }
614082607adcSTejun Heo 
61415cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
614282607adcSTejun Heo {
614382607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
614482607adcSTejun Heo 	bool lockup_detected = false;
6145cd2440d6SPetr Mladek 	bool cpu_pool_stall = false;
6146940d71c6SSergey Senozhatsky 	unsigned long now = jiffies;
614782607adcSTejun Heo 	struct worker_pool *pool;
614882607adcSTejun Heo 	int pi;
614982607adcSTejun Heo 
615082607adcSTejun Heo 	if (!thresh)
615182607adcSTejun Heo 		return;
615282607adcSTejun Heo 
615382607adcSTejun Heo 	rcu_read_lock();
615482607adcSTejun Heo 
615582607adcSTejun Heo 	for_each_pool(pool, pi) {
615682607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
615782607adcSTejun Heo 
6158cd2440d6SPetr Mladek 		pool->cpu_stall = false;
615982607adcSTejun Heo 		if (list_empty(&pool->worklist))
616082607adcSTejun Heo 			continue;
616182607adcSTejun Heo 
6162940d71c6SSergey Senozhatsky 		/*
6163940d71c6SSergey Senozhatsky 		 * If a virtual machine is stopped by the host it can look to
6164940d71c6SSergey Senozhatsky 		 * the watchdog like a stall.
6165940d71c6SSergey Senozhatsky 		 */
6166940d71c6SSergey Senozhatsky 		kvm_check_and_clear_guest_paused();
6167940d71c6SSergey Senozhatsky 
616882607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
616989e28ce6SWang Qing 		if (pool->cpu >= 0)
617089e28ce6SWang Qing 			touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
617189e28ce6SWang Qing 		else
617282607adcSTejun Heo 			touched = READ_ONCE(wq_watchdog_touched);
617389e28ce6SWang Qing 		pool_ts = READ_ONCE(pool->watchdog_ts);
617482607adcSTejun Heo 
617582607adcSTejun Heo 		if (time_after(pool_ts, touched))
617682607adcSTejun Heo 			ts = pool_ts;
617782607adcSTejun Heo 		else
617882607adcSTejun Heo 			ts = touched;
617982607adcSTejun Heo 
618082607adcSTejun Heo 		/* did we stall? */
6181940d71c6SSergey Senozhatsky 		if (time_after(now, ts + thresh)) {
618282607adcSTejun Heo 			lockup_detected = true;
6183cd2440d6SPetr Mladek 			if (pool->cpu >= 0) {
6184cd2440d6SPetr Mladek 				pool->cpu_stall = true;
6185cd2440d6SPetr Mladek 				cpu_pool_stall = true;
6186cd2440d6SPetr Mladek 			}
618782607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
618882607adcSTejun Heo 			pr_cont_pool_info(pool);
618982607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
6190940d71c6SSergey Senozhatsky 				jiffies_to_msecs(now - pool_ts) / 1000);
619182607adcSTejun Heo 		}
6192cd2440d6SPetr Mladek 
6193cd2440d6SPetr Mladek 
619482607adcSTejun Heo 	}
619582607adcSTejun Heo 
619682607adcSTejun Heo 	rcu_read_unlock();
619782607adcSTejun Heo 
619882607adcSTejun Heo 	if (lockup_detected)
619955df0933SImran Khan 		show_all_workqueues();
620082607adcSTejun Heo 
6201cd2440d6SPetr Mladek 	if (cpu_pool_stall)
6202cd2440d6SPetr Mladek 		show_cpu_pools_hogs();
6203cd2440d6SPetr Mladek 
620482607adcSTejun Heo 	wq_watchdog_reset_touched();
620582607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
620682607adcSTejun Heo }
620782607adcSTejun Heo 
6208cb9d7fd5SVincent Whitchurch notrace void wq_watchdog_touch(int cpu)
620982607adcSTejun Heo {
621082607adcSTejun Heo 	if (cpu >= 0)
621182607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
621289e28ce6SWang Qing 
621382607adcSTejun Heo 	wq_watchdog_touched = jiffies;
621482607adcSTejun Heo }
621582607adcSTejun Heo 
621682607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
621782607adcSTejun Heo {
621882607adcSTejun Heo 	wq_watchdog_thresh = 0;
621982607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
622082607adcSTejun Heo 
622182607adcSTejun Heo 	if (thresh) {
622282607adcSTejun Heo 		wq_watchdog_thresh = thresh;
622382607adcSTejun Heo 		wq_watchdog_reset_touched();
622482607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
622582607adcSTejun Heo 	}
622682607adcSTejun Heo }
622782607adcSTejun Heo 
622882607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
622982607adcSTejun Heo 					const struct kernel_param *kp)
623082607adcSTejun Heo {
623182607adcSTejun Heo 	unsigned long thresh;
623282607adcSTejun Heo 	int ret;
623382607adcSTejun Heo 
623482607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
623582607adcSTejun Heo 	if (ret)
623682607adcSTejun Heo 		return ret;
623782607adcSTejun Heo 
623882607adcSTejun Heo 	if (system_wq)
623982607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
624082607adcSTejun Heo 	else
624182607adcSTejun Heo 		wq_watchdog_thresh = thresh;
624282607adcSTejun Heo 
624382607adcSTejun Heo 	return 0;
624482607adcSTejun Heo }
624582607adcSTejun Heo 
624682607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
624782607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
624882607adcSTejun Heo 	.get	= param_get_ulong,
624982607adcSTejun Heo };
625082607adcSTejun Heo 
625182607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
625282607adcSTejun Heo 		0644);
625382607adcSTejun Heo 
625482607adcSTejun Heo static void wq_watchdog_init(void)
625582607adcSTejun Heo {
62565cd79d6aSKees Cook 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
625782607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
625882607adcSTejun Heo }
625982607adcSTejun Heo 
626082607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
626182607adcSTejun Heo 
626282607adcSTejun Heo static inline void wq_watchdog_init(void) { }
626382607adcSTejun Heo 
626482607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
626582607adcSTejun Heo 
62663347fa09STejun Heo /**
62673347fa09STejun Heo  * workqueue_init_early - early init for workqueue subsystem
62683347fa09STejun Heo  *
62692930155bSTejun Heo  * This is the first step of three-staged workqueue subsystem initialization and
62702930155bSTejun Heo  * invoked as soon as the bare basics - memory allocation, cpumasks and idr are
62712930155bSTejun Heo  * up. It sets up all the data structures and system workqueues and allows early
62722930155bSTejun Heo  * boot code to create workqueues and queue/cancel work items. Actual work item
62732930155bSTejun Heo  * execution starts only after kthreads can be created and scheduled right
62742930155bSTejun Heo  * before early initcalls.
62753347fa09STejun Heo  */
62762333e829SYu Chen void __init workqueue_init_early(void)
62771da177e4SLinus Torvalds {
62787a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
62797a4e344cSTejun Heo 	int i, cpu;
6280c34056a3STejun Heo 
628110cdb157SLai Jiangshan 	BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
6282e904e6c2STejun Heo 
6283b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
628404d4e665SFrederic Weisbecker 	cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_WQ));
628504d4e665SFrederic Weisbecker 	cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_DOMAIN));
6286b05a7928SFrederic Weisbecker 
6287ace3c549Stiozhang 	if (!cpumask_empty(&wq_cmdline_cpumask))
6288ace3c549Stiozhang 		cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, &wq_cmdline_cpumask);
6289ace3c549Stiozhang 
6290e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6291e904e6c2STejun Heo 
62922930155bSTejun Heo 	wq_update_pod_attrs_buf = alloc_workqueue_attrs();
62932930155bSTejun Heo 	BUG_ON(!wq_update_pod_attrs_buf);
62942930155bSTejun Heo 
6295*0f36ee24STejun Heo 	BUG_ON(!alloc_cpumask_var(&wq_update_pod_cpumask_buf, GFP_KERNEL));
6296*0f36ee24STejun Heo 
6297706026c2STejun Heo 	/* initialize CPU pools */
629829c91e99STejun Heo 	for_each_possible_cpu(cpu) {
62994ce62e9eSTejun Heo 		struct worker_pool *pool;
63008b03ae3cSTejun Heo 
63017a4e344cSTejun Heo 		i = 0;
6302f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
63037a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
6304ec22ca5eSTejun Heo 			pool->cpu = cpu;
63057a4e344cSTejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
63067a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
6307f3f90ad4STejun Heo 			pool->node = cpu_to_node(cpu);
63087a4e344cSTejun Heo 
63099daf9e67STejun Heo 			/* alloc pool ID */
631068e13a67SLai Jiangshan 			mutex_lock(&wq_pool_mutex);
63119daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
631268e13a67SLai Jiangshan 			mutex_unlock(&wq_pool_mutex);
63134ce62e9eSTejun Heo 		}
63148b03ae3cSTejun Heo 	}
63158b03ae3cSTejun Heo 
63168a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
631729c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
631829c91e99STejun Heo 		struct workqueue_attrs *attrs;
631929c91e99STejun Heo 
6320be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
632129c91e99STejun Heo 		attrs->nice = std_nice[i];
632229c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
63238a2b7538STejun Heo 
63248a2b7538STejun Heo 		/*
63258a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
63268a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
63278a2b7538STejun Heo 		 */
6328be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
63298a2b7538STejun Heo 		attrs->nice = std_nice[i];
6330af73f5c9STejun Heo 		attrs->ordered = true;
63318a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
633229c91e99STejun Heo 	}
633329c91e99STejun Heo 
6334d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
63351aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
6336d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
6337f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
6338636b927eSTejun Heo 					    WQ_MAX_ACTIVE);
633924d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
634024d51addSTejun Heo 					      WQ_FREEZABLE, 0);
63410668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
63420668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
63430668106cSViresh Kumar 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
63440668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
63450668106cSViresh Kumar 					      0);
63461aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
63470668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
63480668106cSViresh Kumar 	       !system_power_efficient_wq ||
63490668106cSViresh Kumar 	       !system_freezable_power_efficient_wq);
63503347fa09STejun Heo }
63513347fa09STejun Heo 
6352aa6fde93STejun Heo static void __init wq_cpu_intensive_thresh_init(void)
6353aa6fde93STejun Heo {
6354aa6fde93STejun Heo 	unsigned long thresh;
6355aa6fde93STejun Heo 	unsigned long bogo;
6356aa6fde93STejun Heo 
6357aa6fde93STejun Heo 	/* if the user set it to a specific value, keep it */
6358aa6fde93STejun Heo 	if (wq_cpu_intensive_thresh_us != ULONG_MAX)
6359aa6fde93STejun Heo 		return;
6360aa6fde93STejun Heo 
6361967b494eSTejun Heo 	pwq_release_worker = kthread_create_worker(0, "pool_workqueue_release");
6362967b494eSTejun Heo 	BUG_ON(IS_ERR(pwq_release_worker));
6363967b494eSTejun Heo 
6364aa6fde93STejun Heo 	/*
6365aa6fde93STejun Heo 	 * The default of 10ms is derived from the fact that most modern (as of
6366aa6fde93STejun Heo 	 * 2023) processors can do a lot in 10ms and that it's just below what
6367aa6fde93STejun Heo 	 * most consider human-perceivable. However, the kernel also runs on a
6368aa6fde93STejun Heo 	 * lot slower CPUs including microcontrollers where the threshold is way
6369aa6fde93STejun Heo 	 * too low.
6370aa6fde93STejun Heo 	 *
6371aa6fde93STejun Heo 	 * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
6372aa6fde93STejun Heo 	 * This is by no means accurate but it doesn't have to be. The mechanism
6373aa6fde93STejun Heo 	 * is still useful even when the threshold is fully scaled up. Also, as
6374aa6fde93STejun Heo 	 * the reports would usually be applicable to everyone, some machines
6375aa6fde93STejun Heo 	 * operating on longer thresholds won't significantly diminish their
6376aa6fde93STejun Heo 	 * usefulness.
6377aa6fde93STejun Heo 	 */
6378aa6fde93STejun Heo 	thresh = 10 * USEC_PER_MSEC;
6379aa6fde93STejun Heo 
6380aa6fde93STejun Heo 	/* see init/calibrate.c for lpj -> BogoMIPS calculation */
6381aa6fde93STejun Heo 	bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
6382aa6fde93STejun Heo 	if (bogo < 4000)
6383aa6fde93STejun Heo 		thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
6384aa6fde93STejun Heo 
6385aa6fde93STejun Heo 	pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
6386aa6fde93STejun Heo 		 loops_per_jiffy, bogo, thresh);
6387aa6fde93STejun Heo 
6388aa6fde93STejun Heo 	wq_cpu_intensive_thresh_us = thresh;
6389aa6fde93STejun Heo }
6390aa6fde93STejun Heo 
63913347fa09STejun Heo /**
63923347fa09STejun Heo  * workqueue_init - bring workqueue subsystem fully online
63933347fa09STejun Heo  *
63942930155bSTejun Heo  * This is the second step of three-staged workqueue subsystem initialization
63952930155bSTejun Heo  * and invoked as soon as kthreads can be created and scheduled. Workqueues have
63962930155bSTejun Heo  * been created and work items queued on them, but there are no kworkers
63972930155bSTejun Heo  * executing the work items yet. Populate the worker pools with the initial
63982930155bSTejun Heo  * workers and enable future kworker creations.
63993347fa09STejun Heo  */
64002333e829SYu Chen void __init workqueue_init(void)
64013347fa09STejun Heo {
64022186d9f9STejun Heo 	struct workqueue_struct *wq;
64033347fa09STejun Heo 	struct worker_pool *pool;
64043347fa09STejun Heo 	int cpu, bkt;
64053347fa09STejun Heo 
6406aa6fde93STejun Heo 	wq_cpu_intensive_thresh_init();
6407aa6fde93STejun Heo 
64082186d9f9STejun Heo 	mutex_lock(&wq_pool_mutex);
64092186d9f9STejun Heo 
64102930155bSTejun Heo 	/*
64112930155bSTejun Heo 	 * Per-cpu pools created earlier could be missing node hint. Fix them
64122930155bSTejun Heo 	 * up. Also, create a rescuer for workqueues that requested it.
64132930155bSTejun Heo 	 */
64142186d9f9STejun Heo 	for_each_possible_cpu(cpu) {
64152186d9f9STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
64162186d9f9STejun Heo 			pool->node = cpu_to_node(cpu);
64172186d9f9STejun Heo 		}
64182186d9f9STejun Heo 	}
64192186d9f9STejun Heo 
642040c17f75STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
642140c17f75STejun Heo 		WARN(init_rescuer(wq),
642240c17f75STejun Heo 		     "workqueue: failed to create early rescuer for %s",
642340c17f75STejun Heo 		     wq->name);
642440c17f75STejun Heo 	}
64252186d9f9STejun Heo 
64262186d9f9STejun Heo 	mutex_unlock(&wq_pool_mutex);
64272186d9f9STejun Heo 
64283347fa09STejun Heo 	/* create the initial workers */
64293347fa09STejun Heo 	for_each_online_cpu(cpu) {
64303347fa09STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
64313347fa09STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
64323347fa09STejun Heo 			BUG_ON(!create_worker(pool));
64333347fa09STejun Heo 		}
64343347fa09STejun Heo 	}
64353347fa09STejun Heo 
64363347fa09STejun Heo 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
64373347fa09STejun Heo 		BUG_ON(!create_worker(pool));
64383347fa09STejun Heo 
64393347fa09STejun Heo 	wq_online = true;
644082607adcSTejun Heo 	wq_watchdog_init();
64411da177e4SLinus Torvalds }
6442c4f135d6STetsuo Handa 
64432930155bSTejun Heo /**
64442930155bSTejun Heo  * workqueue_init_topology - initialize CPU pods for unbound workqueues
64452930155bSTejun Heo  *
64462930155bSTejun Heo  * This is the third step of there-staged workqueue subsystem initialization and
64472930155bSTejun Heo  * invoked after SMP and topology information are fully initialized. It
64482930155bSTejun Heo  * initializes the unbound CPU pods accordingly.
64492930155bSTejun Heo  */
64502930155bSTejun Heo void __init workqueue_init_topology(void)
6451a86feae6STejun Heo {
64522930155bSTejun Heo 	struct workqueue_struct *wq;
6453a86feae6STejun Heo 	cpumask_var_t *tbl;
6454a86feae6STejun Heo 	int node, cpu;
6455a86feae6STejun Heo 
6456a86feae6STejun Heo 	if (num_possible_nodes() <= 1)
6457a86feae6STejun Heo 		return;
6458a86feae6STejun Heo 
6459a86feae6STejun Heo 	for_each_possible_cpu(cpu) {
6460a86feae6STejun Heo 		if (WARN_ON(cpu_to_node(cpu) == NUMA_NO_NODE)) {
6461a86feae6STejun Heo 			pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
6462a86feae6STejun Heo 			return;
6463a86feae6STejun Heo 		}
6464a86feae6STejun Heo 	}
6465a86feae6STejun Heo 
64662930155bSTejun Heo 	mutex_lock(&wq_pool_mutex);
6467a86feae6STejun Heo 
6468a86feae6STejun Heo 	/*
6469a86feae6STejun Heo 	 * We want masks of possible CPUs of each node which isn't readily
6470a86feae6STejun Heo 	 * available.  Build one from cpu_to_node() which should have been
6471a86feae6STejun Heo 	 * fully initialized by now.
6472a86feae6STejun Heo 	 */
6473a86feae6STejun Heo 	tbl = kcalloc(nr_node_ids, sizeof(tbl[0]), GFP_KERNEL);
6474a86feae6STejun Heo 	BUG_ON(!tbl);
6475a86feae6STejun Heo 
6476a86feae6STejun Heo 	for_each_node(node)
6477a86feae6STejun Heo 		BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
6478a86feae6STejun Heo 				node_online(node) ? node : NUMA_NO_NODE));
6479a86feae6STejun Heo 
6480a86feae6STejun Heo 	for_each_possible_cpu(cpu) {
6481a86feae6STejun Heo 		node = cpu_to_node(cpu);
6482a86feae6STejun Heo 		cpumask_set_cpu(cpu, tbl[node]);
6483a86feae6STejun Heo 	}
6484a86feae6STejun Heo 
6485a86feae6STejun Heo 	wq_pod_cpus = tbl;
6486a86feae6STejun Heo 	wq_pod_enabled = true;
64872930155bSTejun Heo 
64882930155bSTejun Heo 	/*
64892930155bSTejun Heo 	 * Workqueues allocated earlier would have all CPUs sharing the default
64902930155bSTejun Heo 	 * worker pool. Explicitly call wq_update_pod() on all workqueue and CPU
64912930155bSTejun Heo 	 * combinations to apply per-pod sharing.
64922930155bSTejun Heo 	 */
64932930155bSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
64942930155bSTejun Heo 		for_each_online_cpu(cpu) {
64952930155bSTejun Heo 			wq_update_pod(wq, cpu, cpu, true);
64962930155bSTejun Heo 		}
64972930155bSTejun Heo 	}
64982930155bSTejun Heo 
64992930155bSTejun Heo 	mutex_unlock(&wq_pool_mutex);
6500a86feae6STejun Heo }
6501a86feae6STejun Heo 
650220bdedafSTetsuo Handa void __warn_flushing_systemwide_wq(void)
650320bdedafSTetsuo Handa {
650420bdedafSTetsuo Handa 	pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
650520bdedafSTetsuo Handa 	dump_stack();
650620bdedafSTetsuo Handa }
6507c4f135d6STetsuo Handa EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
6508ace3c549Stiozhang 
6509ace3c549Stiozhang static int __init workqueue_unbound_cpus_setup(char *str)
6510ace3c549Stiozhang {
6511ace3c549Stiozhang 	if (cpulist_parse(str, &wq_cmdline_cpumask) < 0) {
6512ace3c549Stiozhang 		cpumask_clear(&wq_cmdline_cpumask);
6513ace3c549Stiozhang 		pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
6514ace3c549Stiozhang 	}
6515ace3c549Stiozhang 
6516ace3c549Stiozhang 	return 1;
6517ace3c549Stiozhang }
6518ace3c549Stiozhang __setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup);
6519