xref: /openbmc/linux/kernel/workqueue.c (revision 797e8345)
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 <dwmw2@infradead.org>
9e1f8e874SFrancois Cami  *     Andrew Morton
101da177e4SLinus Torvalds  *     Kai Petzke <wpp@marie.physik.tu-berlin.de>
111da177e4SLinus Torvalds  *     Theodore Ts'o <tytso@mit.edu>
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 <tj@kernel.org>
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 	/*
2608864b4e5STejun Heo 	 * Release of unbound pwq is punted to system_wq.  See put_pwq()
2618864b4e5STejun Heo 	 * and pwq_unbound_release_workfn() for details.  pool_workqueue
26224acfb71SThomas Gleixner 	 * itself is also RCU protected so that the first pwq can be
263b09f4fd3SLai Jiangshan 	 * determined without grabbing wq->mutex.
2648864b4e5STejun Heo 	 */
2658864b4e5STejun Heo 	struct work_struct	unbound_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 */
324ee1ceef7STejun Heo 	struct pool_workqueue __percpu *cpu_pwq; /* I: per-cpu pwqs */
3255b95e1afSLai Jiangshan 	struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
3261da177e4SLinus Torvalds };
3271da177e4SLinus Torvalds 
328e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
329e904e6c2STejun Heo 
330bce90380STejun Heo static cpumask_var_t *wq_numa_possible_cpumask;
331bce90380STejun Heo 					/* possible CPUs of each node */
332bce90380STejun Heo 
333616db877STejun Heo /*
334616db877STejun Heo  * Per-cpu work items which run for longer than the following threshold are
335616db877STejun Heo  * automatically considered CPU intensive and excluded from concurrency
336616db877STejun Heo  * management to prevent them from noticeably delaying other per-cpu work items.
337aa6fde93STejun Heo  * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
338aa6fde93STejun Heo  * The actual value is initialized in wq_cpu_intensive_thresh_init().
339616db877STejun Heo  */
340aa6fde93STejun Heo static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
341616db877STejun Heo module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
342616db877STejun Heo 
343d55262c4STejun Heo static bool wq_disable_numa;
344d55262c4STejun Heo module_param_named(disable_numa, wq_disable_numa, bool, 0444);
345d55262c4STejun Heo 
346cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
347552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
348cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
349cee22a15SViresh Kumar 
350863b710bSTejun Heo static bool wq_online;			/* can kworkers be created yet? */
3513347fa09STejun Heo 
352bce90380STejun Heo static bool wq_numa_enabled;		/* unbound NUMA affinity enabled */
353bce90380STejun Heo 
3544c16bd32STejun Heo /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
3554c16bd32STejun Heo static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
3564c16bd32STejun Heo 
35768e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
3581258fae7STejun Heo static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
359a9b8a985SSebastian Andrzej Siewior static DEFINE_RAW_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
360d8bb65abSSebastian Andrzej Siewior /* wait for manager to go away */
361d8bb65abSSebastian Andrzej Siewior static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
3625bcab335STejun Heo 
363e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
36468e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
3657d19c5ceSTejun Heo 
36699c621efSLai Jiangshan /* PL&A: allowable cpus for unbound wqs and work items */
367ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
368ef557180SMike Galbraith 
369ace3c549Stiozhang /* for further constrain wq_unbound_cpumask by cmdline parameter*/
370ace3c549Stiozhang static struct cpumask wq_cmdline_cpumask __initdata;
371ace3c549Stiozhang 
372ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
373ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
374b05a7928SFrederic Weisbecker 
375f303fccbSTejun Heo /*
376f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
377f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
378f303fccbSTejun Heo  * to uncover usages which depend on it.
379f303fccbSTejun Heo  */
380f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
381f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
382f303fccbSTejun Heo #else
383f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
384f303fccbSTejun Heo #endif
385f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
386f303fccbSTejun Heo 
3877d19c5ceSTejun Heo /* the per-cpu worker pools */
38825528213SPeter Zijlstra static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
3897d19c5ceSTejun Heo 
39068e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
3917d19c5ceSTejun Heo 
39268e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
39329c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
39429c91e99STejun Heo 
395c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
39629c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
39729c91e99STejun Heo 
3988a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
3998a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
4008a2b7538STejun Heo 
401d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
402ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
403044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
4041aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
405044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
406d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
407044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
408f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
409044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
41024d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
4110668106cSViresh Kumar struct workqueue_struct *system_power_efficient_wq __read_mostly;
4120668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
4130668106cSViresh Kumar struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
4140668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
415d320c038STejun Heo 
4167d19c5ceSTejun Heo static int worker_thread(void *__worker);
4176ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
418c29eb853STejun Heo static void show_pwq(struct pool_workqueue *pwq);
41955df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool);
4207d19c5ceSTejun Heo 
42197bd2347STejun Heo #define CREATE_TRACE_POINTS
42297bd2347STejun Heo #include <trace/events/workqueue.h>
42397bd2347STejun Heo 
42468e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
42524acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
426f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
42724acfb71SThomas Gleixner 			 "RCU or wq_pool_mutex should be held")
4285bcab335STejun Heo 
4295b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
43024acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
431f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
432f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
43324acfb71SThomas Gleixner 			 "RCU, wq->mutex or wq_pool_mutex should be held")
4345b95e1afSLai Jiangshan 
435f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
436f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
437f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
4387a62c2c8STejun Heo 	     (pool)++)
4394ce62e9eSTejun Heo 
44049e3cf44STejun Heo /**
44117116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
44217116969STejun Heo  * @pool: iteration cursor
443611c92a0STejun Heo  * @pi: integer used for iteration
444fa1b54e6STejun Heo  *
44524acfb71SThomas Gleixner  * This must be called either with wq_pool_mutex held or RCU read
44668e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
44768e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
448fa1b54e6STejun Heo  *
449fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
450fa1b54e6STejun Heo  * ignored.
45117116969STejun Heo  */
452611c92a0STejun Heo #define for_each_pool(pool, pi)						\
453611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
45468e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
455fa1b54e6STejun Heo 		else
45617116969STejun Heo 
45717116969STejun Heo /**
458822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
459822d8405STejun Heo  * @worker: iteration cursor
460822d8405STejun Heo  * @pool: worker_pool to iterate workers of
461822d8405STejun Heo  *
4621258fae7STejun Heo  * This must be called with wq_pool_attach_mutex.
463822d8405STejun Heo  *
464822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
465822d8405STejun Heo  * ignored.
466822d8405STejun Heo  */
467da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
468da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
4691258fae7STejun Heo 		if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
470822d8405STejun Heo 		else
471822d8405STejun Heo 
472822d8405STejun Heo /**
47349e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
47449e3cf44STejun Heo  * @pwq: iteration cursor
47549e3cf44STejun Heo  * @wq: the target workqueue
47676af4d93STejun Heo  *
47724acfb71SThomas Gleixner  * This must be called either with wq->mutex held or RCU read locked.
478794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
479794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
48076af4d93STejun Heo  *
48176af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
48276af4d93STejun Heo  * ignored.
48349e3cf44STejun Heo  */
48449e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
48549e9d1a9SSebastian Andrzej Siewior 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node,		\
4865a644662SJoel Fernandes (Google) 				 lockdep_is_held(&(wq->mutex)))
487f3421797STejun Heo 
488dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
489dc186ad7SThomas Gleixner 
490f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr;
491dc186ad7SThomas Gleixner 
49299777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
49399777288SStanislaw Gruszka {
49499777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
49599777288SStanislaw Gruszka }
49699777288SStanislaw Gruszka 
497b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
498b9fdac7fSDu, Changbin {
499b9fdac7fSDu, Changbin 	struct work_struct *work = addr;
500b9fdac7fSDu, Changbin 
501b9fdac7fSDu, Changbin 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
502b9fdac7fSDu, Changbin }
503b9fdac7fSDu, Changbin 
504dc186ad7SThomas Gleixner /*
505dc186ad7SThomas Gleixner  * fixup_init is called when:
506dc186ad7SThomas Gleixner  * - an active object is initialized
507dc186ad7SThomas Gleixner  */
50802a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
509dc186ad7SThomas Gleixner {
510dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
511dc186ad7SThomas Gleixner 
512dc186ad7SThomas Gleixner 	switch (state) {
513dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
514dc186ad7SThomas Gleixner 		cancel_work_sync(work);
515dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
51602a982a6SDu, Changbin 		return true;
517dc186ad7SThomas Gleixner 	default:
51802a982a6SDu, Changbin 		return false;
519dc186ad7SThomas Gleixner 	}
520dc186ad7SThomas Gleixner }
521dc186ad7SThomas Gleixner 
522dc186ad7SThomas Gleixner /*
523dc186ad7SThomas Gleixner  * fixup_free is called when:
524dc186ad7SThomas Gleixner  * - an active object is freed
525dc186ad7SThomas Gleixner  */
52602a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
527dc186ad7SThomas Gleixner {
528dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
529dc186ad7SThomas Gleixner 
530dc186ad7SThomas Gleixner 	switch (state) {
531dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
532dc186ad7SThomas Gleixner 		cancel_work_sync(work);
533dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
53402a982a6SDu, Changbin 		return true;
535dc186ad7SThomas Gleixner 	default:
53602a982a6SDu, Changbin 		return false;
537dc186ad7SThomas Gleixner 	}
538dc186ad7SThomas Gleixner }
539dc186ad7SThomas Gleixner 
540f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr = {
541dc186ad7SThomas Gleixner 	.name		= "work_struct",
54299777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
543b9fdac7fSDu, Changbin 	.is_static_object = work_is_static_object,
544dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
545dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
546dc186ad7SThomas Gleixner };
547dc186ad7SThomas Gleixner 
548dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
549dc186ad7SThomas Gleixner {
550dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
551dc186ad7SThomas Gleixner }
552dc186ad7SThomas Gleixner 
553dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
554dc186ad7SThomas Gleixner {
555dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
556dc186ad7SThomas Gleixner }
557dc186ad7SThomas Gleixner 
558dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
559dc186ad7SThomas Gleixner {
560dc186ad7SThomas Gleixner 	if (onstack)
561dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
562dc186ad7SThomas Gleixner 	else
563dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
564dc186ad7SThomas Gleixner }
565dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
566dc186ad7SThomas Gleixner 
567dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
568dc186ad7SThomas Gleixner {
569dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
570dc186ad7SThomas Gleixner }
571dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
572dc186ad7SThomas Gleixner 
573ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
574ea2e64f2SThomas Gleixner {
575ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
576ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
577ea2e64f2SThomas Gleixner }
578ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
579ea2e64f2SThomas Gleixner 
580dc186ad7SThomas Gleixner #else
581dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
582dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
583dc186ad7SThomas Gleixner #endif
584dc186ad7SThomas Gleixner 
5854e8b22bdSLi Bin /**
58667dc8325SCai Huoqing  * worker_pool_assign_id - allocate ID and assign it to @pool
5874e8b22bdSLi Bin  * @pool: the pool pointer of interest
5884e8b22bdSLi Bin  *
5894e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
5904e8b22bdSLi Bin  * successfully, -errno on failure.
5914e8b22bdSLi Bin  */
5929daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
5939daf9e67STejun Heo {
5949daf9e67STejun Heo 	int ret;
5959daf9e67STejun Heo 
59668e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5975bcab335STejun Heo 
5984e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
5994e8b22bdSLi Bin 			GFP_KERNEL);
600229641a6STejun Heo 	if (ret >= 0) {
601e68035fbSTejun Heo 		pool->id = ret;
602229641a6STejun Heo 		return 0;
603229641a6STejun Heo 	}
6049daf9e67STejun Heo 	return ret;
6059daf9e67STejun Heo }
6069daf9e67STejun Heo 
60776af4d93STejun Heo /**
608df2d5ae4STejun Heo  * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
609df2d5ae4STejun Heo  * @wq: the target workqueue
610df2d5ae4STejun Heo  * @node: the node ID
611df2d5ae4STejun Heo  *
61224acfb71SThomas Gleixner  * This must be called with any of wq_pool_mutex, wq->mutex or RCU
6135b95e1afSLai Jiangshan  * read locked.
614df2d5ae4STejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
615df2d5ae4STejun Heo  * responsible for guaranteeing that the pwq stays online.
616d185af30SYacine Belkadi  *
617d185af30SYacine Belkadi  * Return: The unbound pool_workqueue for @node.
618df2d5ae4STejun Heo  */
619df2d5ae4STejun Heo static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
620df2d5ae4STejun Heo 						  int node)
621df2d5ae4STejun Heo {
6225b95e1afSLai Jiangshan 	assert_rcu_or_wq_mutex_or_pool_mutex(wq);
623d6e022f1STejun Heo 
624d6e022f1STejun Heo 	/*
625d6e022f1STejun Heo 	 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
626d6e022f1STejun Heo 	 * delayed item is pending.  The plan is to keep CPU -> NODE
627d6e022f1STejun Heo 	 * mapping valid and stable across CPU on/offlines.  Once that
628d6e022f1STejun Heo 	 * happens, this workaround can be removed.
629d6e022f1STejun Heo 	 */
630d6e022f1STejun Heo 	if (unlikely(node == NUMA_NO_NODE))
631d6e022f1STejun Heo 		return wq->dfl_pwq;
632d6e022f1STejun Heo 
633df2d5ae4STejun Heo 	return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
634df2d5ae4STejun Heo }
635df2d5ae4STejun Heo 
63673f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
63773f53c4aSTejun Heo {
63873f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
63973f53c4aSTejun Heo }
64073f53c4aSTejun Heo 
641c4560c2cSLai Jiangshan static int get_work_color(unsigned long work_data)
64273f53c4aSTejun Heo {
643c4560c2cSLai Jiangshan 	return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
64473f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
64573f53c4aSTejun Heo }
64673f53c4aSTejun Heo 
64773f53c4aSTejun Heo static int work_next_color(int color)
64873f53c4aSTejun Heo {
64973f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
650a848e3b6SOleg Nesterov }
651a848e3b6SOleg Nesterov 
6524594bf15SDavid Howells /*
653112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
654112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
6557c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
6567a22ad75STejun Heo  *
657112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
658112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
659bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
660bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
6617a22ad75STejun Heo  *
662112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6637c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
664112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
6657c3eed5cSTejun Heo  * available only while the work item is queued.
666bbb68dfaSTejun Heo  *
667bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
668bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
669bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
670bbb68dfaSTejun Heo  * try to steal the PENDING bit.
6714594bf15SDavid Howells  */
6727a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6737a22ad75STejun Heo 				 unsigned long flags)
6747a22ad75STejun Heo {
6756183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
6767a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
6777a22ad75STejun Heo }
6787a22ad75STejun Heo 
679112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6804690c4abSTejun Heo 			 unsigned long extra_flags)
681365970a1SDavid Howells {
682112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
683112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
684365970a1SDavid Howells }
685365970a1SDavid Howells 
6864468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6874468a00fSLai Jiangshan 					   int pool_id)
6884468a00fSLai Jiangshan {
6894468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6904468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6914468a00fSLai Jiangshan }
6924468a00fSLai Jiangshan 
6937c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6947c3eed5cSTejun Heo 					    int pool_id)
6954d707b9fSOleg Nesterov {
69623657bb1STejun Heo 	/*
69723657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
69823657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
69923657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
70023657bb1STejun Heo 	 * owner.
70123657bb1STejun Heo 	 */
70223657bb1STejun Heo 	smp_wmb();
7037c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
704346c09f8SRoman Pen 	/*
705346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
706346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
707346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
7088bdc6201SLiu Song 	 * reordering can lead to a missed execution on attempt to queue
709346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
710346c09f8SRoman Pen 	 *
711346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
712346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
713346c09f8SRoman Pen 	 *
714346c09f8SRoman Pen 	 * 1  STORE event_indicated
715346c09f8SRoman Pen 	 * 2  queue_work_on() {
716346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
717346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
718346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
719346c09f8SRoman Pen 	 * 6                                 smp_mb()
720346c09f8SRoman Pen 	 * 7                               work->current_func() {
721346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
722346c09f8SRoman Pen 	 *				   }
723346c09f8SRoman Pen 	 *
724346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
725346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
726346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
727346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
728346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
729346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
730346c09f8SRoman Pen 	 * before actual STORE.
731346c09f8SRoman Pen 	 */
732346c09f8SRoman Pen 	smp_mb();
7334d707b9fSOleg Nesterov }
7344d707b9fSOleg Nesterov 
7357a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
736365970a1SDavid Howells {
7377c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
7387c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
7397a22ad75STejun Heo }
7407a22ad75STejun Heo 
741afa4bb77SLinus Torvalds static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
742afa4bb77SLinus Torvalds {
743afa4bb77SLinus Torvalds 	return (struct pool_workqueue *)(data & WORK_STRUCT_WQ_DATA_MASK);
744afa4bb77SLinus Torvalds }
745afa4bb77SLinus Torvalds 
746112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
7477a22ad75STejun Heo {
748e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7497a22ad75STejun Heo 
750112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
751afa4bb77SLinus Torvalds 		return work_struct_pwq(data);
752e120153dSTejun Heo 	else
753e120153dSTejun Heo 		return NULL;
7547a22ad75STejun Heo }
7557a22ad75STejun Heo 
7567c3eed5cSTejun Heo /**
7577c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
7587c3eed5cSTejun Heo  * @work: the work item of interest
7597c3eed5cSTejun Heo  *
76068e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
76124acfb71SThomas Gleixner  * access under RCU read lock.  As such, this function should be
76224acfb71SThomas Gleixner  * called under wq_pool_mutex or inside of a rcu_read_lock() region.
763fa1b54e6STejun Heo  *
764fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
765fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
766fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
767fa1b54e6STejun Heo  * returned pool is and stays online.
768d185af30SYacine Belkadi  *
769d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
7707c3eed5cSTejun Heo  */
7717c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
7727a22ad75STejun Heo {
773e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7747c3eed5cSTejun Heo 	int pool_id;
7757a22ad75STejun Heo 
77668e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
777fa1b54e6STejun Heo 
778112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
779afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool;
7807a22ad75STejun Heo 
7817c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
7827c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
7837a22ad75STejun Heo 		return NULL;
7847a22ad75STejun Heo 
785fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
7867c3eed5cSTejun Heo }
7877c3eed5cSTejun Heo 
7887c3eed5cSTejun Heo /**
7897c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
7907c3eed5cSTejun Heo  * @work: the work item of interest
7917c3eed5cSTejun Heo  *
792d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
7937c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
7947c3eed5cSTejun Heo  */
7957c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
7967c3eed5cSTejun Heo {
79754d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
7987c3eed5cSTejun Heo 
799112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
800afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool->id;
80154d5b7d0SLai Jiangshan 
80254d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
8037c3eed5cSTejun Heo }
8047c3eed5cSTejun Heo 
805bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
806bbb68dfaSTejun Heo {
8077c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
808bbb68dfaSTejun Heo 
8097c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
8107c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
811bbb68dfaSTejun Heo }
812bbb68dfaSTejun Heo 
813bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
814bbb68dfaSTejun Heo {
815bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
816bbb68dfaSTejun Heo 
817112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
818bbb68dfaSTejun Heo }
819bbb68dfaSTejun Heo 
820e22bee78STejun Heo /*
8213270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
8223270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
823d565ed63STejun Heo  * they're being called with pool->lock held.
824e22bee78STejun Heo  */
825e22bee78STejun Heo 
82663d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
827649027d7STejun Heo {
828bc35f7efSLai Jiangshan 	return !pool->nr_running;
829649027d7STejun Heo }
830649027d7STejun Heo 
831e22bee78STejun Heo /*
832e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
833e22bee78STejun Heo  * running workers.
834974271c4STejun Heo  *
835974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
836706026c2STejun Heo  * function will always return %true for unbound pools as long as the
837974271c4STejun Heo  * worklist isn't empty.
838e22bee78STejun Heo  */
83963d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
840e22bee78STejun Heo {
84163d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
842e22bee78STejun Heo }
843e22bee78STejun Heo 
844e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
84563d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
846e22bee78STejun Heo {
84763d95a91STejun Heo 	return pool->nr_idle;
848e22bee78STejun Heo }
849e22bee78STejun Heo 
850e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
85163d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
852e22bee78STejun Heo {
853bc35f7efSLai Jiangshan 	return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
854e22bee78STejun Heo }
855e22bee78STejun Heo 
856e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
85763d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
858e22bee78STejun Heo {
85963d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
860e22bee78STejun Heo }
861e22bee78STejun Heo 
862e22bee78STejun Heo /* Do we have too many workers and should some go away? */
86363d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
864e22bee78STejun Heo {
865692b4825STejun Heo 	bool managing = pool->flags & POOL_MANAGER_ACTIVE;
86663d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
86763d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
868e22bee78STejun Heo 
869e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
870e22bee78STejun Heo }
871e22bee78STejun Heo 
8724690c4abSTejun Heo /**
873e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
874cb444766STejun Heo  * @worker: self
875d302f017STejun Heo  * @flags: flags to set
876d302f017STejun Heo  *
877228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
878d302f017STejun Heo  */
879228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
880d302f017STejun Heo {
881bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
882e22bee78STejun Heo 
883bc8b50c2STejun Heo 	lockdep_assert_held(&pool->lock);
884cb444766STejun Heo 
885228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
886e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
887e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
888bc35f7efSLai Jiangshan 		pool->nr_running--;
889e22bee78STejun Heo 	}
890e22bee78STejun Heo 
891d302f017STejun Heo 	worker->flags |= flags;
892d302f017STejun Heo }
893d302f017STejun Heo 
894d302f017STejun Heo /**
895e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
896cb444766STejun Heo  * @worker: self
897d302f017STejun Heo  * @flags: flags to clear
898d302f017STejun Heo  *
899e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
900d302f017STejun Heo  */
901d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
902d302f017STejun Heo {
90363d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
904e22bee78STejun Heo 	unsigned int oflags = worker->flags;
905e22bee78STejun Heo 
906bc8b50c2STejun Heo 	lockdep_assert_held(&pool->lock);
907cb444766STejun Heo 
908d302f017STejun Heo 	worker->flags &= ~flags;
909e22bee78STejun Heo 
91042c025f3STejun Heo 	/*
91142c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
91242c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
91342c025f3STejun Heo 	 * of multiple flags, not a single flag.
91442c025f3STejun Heo 	 */
915e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
916e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
917bc35f7efSLai Jiangshan 			pool->nr_running++;
918d302f017STejun Heo }
919d302f017STejun Heo 
920*797e8345STejun Heo /* Return the first idle worker.  Called with pool->lock held. */
921*797e8345STejun Heo static struct worker *first_idle_worker(struct worker_pool *pool)
922*797e8345STejun Heo {
923*797e8345STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
924*797e8345STejun Heo 		return NULL;
925*797e8345STejun Heo 
926*797e8345STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
927*797e8345STejun Heo }
928*797e8345STejun Heo 
929*797e8345STejun Heo /**
930*797e8345STejun Heo  * worker_enter_idle - enter idle state
931*797e8345STejun Heo  * @worker: worker which is entering idle state
932*797e8345STejun Heo  *
933*797e8345STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
934*797e8345STejun Heo  * necessary.
935*797e8345STejun Heo  *
936*797e8345STejun Heo  * LOCKING:
937*797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
938*797e8345STejun Heo  */
939*797e8345STejun Heo static void worker_enter_idle(struct worker *worker)
940*797e8345STejun Heo {
941*797e8345STejun Heo 	struct worker_pool *pool = worker->pool;
942*797e8345STejun Heo 
943*797e8345STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
944*797e8345STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
945*797e8345STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
946*797e8345STejun Heo 		return;
947*797e8345STejun Heo 
948*797e8345STejun Heo 	/* can't use worker_set_flags(), also called from create_worker() */
949*797e8345STejun Heo 	worker->flags |= WORKER_IDLE;
950*797e8345STejun Heo 	pool->nr_idle++;
951*797e8345STejun Heo 	worker->last_active = jiffies;
952*797e8345STejun Heo 
953*797e8345STejun Heo 	/* idle_list is LIFO */
954*797e8345STejun Heo 	list_add(&worker->entry, &pool->idle_list);
955*797e8345STejun Heo 
956*797e8345STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
957*797e8345STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
958*797e8345STejun Heo 
959*797e8345STejun Heo 	/* Sanity check nr_running. */
960*797e8345STejun Heo 	WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
961*797e8345STejun Heo }
962*797e8345STejun Heo 
963*797e8345STejun Heo /**
964*797e8345STejun Heo  * worker_leave_idle - leave idle state
965*797e8345STejun Heo  * @worker: worker which is leaving idle state
966*797e8345STejun Heo  *
967*797e8345STejun Heo  * @worker is leaving idle state.  Update stats.
968*797e8345STejun Heo  *
969*797e8345STejun Heo  * LOCKING:
970*797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
971*797e8345STejun Heo  */
972*797e8345STejun Heo static void worker_leave_idle(struct worker *worker)
973*797e8345STejun Heo {
974*797e8345STejun Heo 	struct worker_pool *pool = worker->pool;
975*797e8345STejun Heo 
976*797e8345STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
977*797e8345STejun Heo 		return;
978*797e8345STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
979*797e8345STejun Heo 	pool->nr_idle--;
980*797e8345STejun Heo 	list_del_init(&worker->entry);
981*797e8345STejun Heo }
982*797e8345STejun Heo 
983*797e8345STejun Heo /**
984*797e8345STejun Heo  * find_worker_executing_work - find worker which is executing a work
985*797e8345STejun Heo  * @pool: pool of interest
986*797e8345STejun Heo  * @work: work to find worker for
987*797e8345STejun Heo  *
988*797e8345STejun Heo  * Find a worker which is executing @work on @pool by searching
989*797e8345STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
990*797e8345STejun Heo  * to match, its current execution should match the address of @work and
991*797e8345STejun Heo  * its work function.  This is to avoid unwanted dependency between
992*797e8345STejun Heo  * unrelated work executions through a work item being recycled while still
993*797e8345STejun Heo  * being executed.
994*797e8345STejun Heo  *
995*797e8345STejun Heo  * This is a bit tricky.  A work item may be freed once its execution
996*797e8345STejun Heo  * starts and nothing prevents the freed area from being recycled for
997*797e8345STejun Heo  * another work item.  If the same work item address ends up being reused
998*797e8345STejun Heo  * before the original execution finishes, workqueue will identify the
999*797e8345STejun Heo  * recycled work item as currently executing and make it wait until the
1000*797e8345STejun Heo  * current execution finishes, introducing an unwanted dependency.
1001*797e8345STejun Heo  *
1002*797e8345STejun Heo  * This function checks the work item address and work function to avoid
1003*797e8345STejun Heo  * false positives.  Note that this isn't complete as one may construct a
1004*797e8345STejun Heo  * work function which can introduce dependency onto itself through a
1005*797e8345STejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
1006*797e8345STejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
1007*797e8345STejun Heo  * actually occurs, it should be easy to locate the culprit work function.
1008*797e8345STejun Heo  *
1009*797e8345STejun Heo  * CONTEXT:
1010*797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1011*797e8345STejun Heo  *
1012*797e8345STejun Heo  * Return:
1013*797e8345STejun Heo  * Pointer to worker which is executing @work if found, %NULL
1014*797e8345STejun Heo  * otherwise.
1015*797e8345STejun Heo  */
1016*797e8345STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
1017*797e8345STejun Heo 						 struct work_struct *work)
1018*797e8345STejun Heo {
1019*797e8345STejun Heo 	struct worker *worker;
1020*797e8345STejun Heo 
1021*797e8345STejun Heo 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1022*797e8345STejun Heo 			       (unsigned long)work)
1023*797e8345STejun Heo 		if (worker->current_work == work &&
1024*797e8345STejun Heo 		    worker->current_func == work->func)
1025*797e8345STejun Heo 			return worker;
1026*797e8345STejun Heo 
1027*797e8345STejun Heo 	return NULL;
1028*797e8345STejun Heo }
1029*797e8345STejun Heo 
1030*797e8345STejun Heo /**
1031*797e8345STejun Heo  * move_linked_works - move linked works to a list
1032*797e8345STejun Heo  * @work: start of series of works to be scheduled
1033*797e8345STejun Heo  * @head: target list to append @work to
1034*797e8345STejun Heo  * @nextp: out parameter for nested worklist walking
1035*797e8345STejun Heo  *
1036*797e8345STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
1037*797e8345STejun Heo  * be scheduled starts at @work and includes any consecutive work with
1038*797e8345STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
1039*797e8345STejun Heo  *
1040*797e8345STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
1041*797e8345STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
1042*797e8345STejun Heo  * nested inside outer list_for_each_entry_safe().
1043*797e8345STejun Heo  *
1044*797e8345STejun Heo  * CONTEXT:
1045*797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1046*797e8345STejun Heo  */
1047*797e8345STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1048*797e8345STejun Heo 			      struct work_struct **nextp)
1049*797e8345STejun Heo {
1050*797e8345STejun Heo 	struct work_struct *n;
1051*797e8345STejun Heo 
1052*797e8345STejun Heo 	/*
1053*797e8345STejun Heo 	 * Linked worklist will always end before the end of the list,
1054*797e8345STejun Heo 	 * use NULL for list head.
1055*797e8345STejun Heo 	 */
1056*797e8345STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1057*797e8345STejun Heo 		list_move_tail(&work->entry, head);
1058*797e8345STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1059*797e8345STejun Heo 			break;
1060*797e8345STejun Heo 	}
1061*797e8345STejun Heo 
1062*797e8345STejun Heo 	/*
1063*797e8345STejun Heo 	 * If we're already inside safe list traversal and have moved
1064*797e8345STejun Heo 	 * multiple works to the scheduled queue, the next position
1065*797e8345STejun Heo 	 * needs to be updated.
1066*797e8345STejun Heo 	 */
1067*797e8345STejun Heo 	if (nextp)
1068*797e8345STejun Heo 		*nextp = n;
1069*797e8345STejun Heo }
1070*797e8345STejun Heo 
1071*797e8345STejun Heo /**
1072*797e8345STejun Heo  * wake_up_worker - wake up an idle worker
1073*797e8345STejun Heo  * @pool: worker pool to wake worker from
1074*797e8345STejun Heo  *
1075*797e8345STejun Heo  * Wake up the first idle worker of @pool.
1076*797e8345STejun Heo  *
1077*797e8345STejun Heo  * CONTEXT:
1078*797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1079*797e8345STejun Heo  */
1080*797e8345STejun Heo static void wake_up_worker(struct worker_pool *pool)
1081*797e8345STejun Heo {
1082*797e8345STejun Heo 	struct worker *worker = first_idle_worker(pool);
1083*797e8345STejun Heo 
1084*797e8345STejun Heo 	if (likely(worker))
1085*797e8345STejun Heo 		wake_up_process(worker->task);
1086*797e8345STejun Heo }
1087*797e8345STejun Heo 
108863638450STejun Heo #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
108963638450STejun Heo 
109063638450STejun Heo /*
109163638450STejun Heo  * Concurrency-managed per-cpu work items that hog CPU for longer than
109263638450STejun Heo  * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
109363638450STejun Heo  * which prevents them from stalling other concurrency-managed work items. If a
109463638450STejun Heo  * work function keeps triggering this mechanism, it's likely that the work item
109563638450STejun Heo  * should be using an unbound workqueue instead.
109663638450STejun Heo  *
109763638450STejun Heo  * wq_cpu_intensive_report() tracks work functions which trigger such conditions
109863638450STejun Heo  * and report them so that they can be examined and converted to use unbound
109963638450STejun Heo  * workqueues as appropriate. To avoid flooding the console, each violating work
110063638450STejun Heo  * function is tracked and reported with exponential backoff.
110163638450STejun Heo  */
110263638450STejun Heo #define WCI_MAX_ENTS 128
110363638450STejun Heo 
110463638450STejun Heo struct wci_ent {
110563638450STejun Heo 	work_func_t		func;
110663638450STejun Heo 	atomic64_t		cnt;
110763638450STejun Heo 	struct hlist_node	hash_node;
110863638450STejun Heo };
110963638450STejun Heo 
111063638450STejun Heo static struct wci_ent wci_ents[WCI_MAX_ENTS];
111163638450STejun Heo static int wci_nr_ents;
111263638450STejun Heo static DEFINE_RAW_SPINLOCK(wci_lock);
111363638450STejun Heo static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
111463638450STejun Heo 
111563638450STejun Heo static struct wci_ent *wci_find_ent(work_func_t func)
111663638450STejun Heo {
111763638450STejun Heo 	struct wci_ent *ent;
111863638450STejun Heo 
111963638450STejun Heo 	hash_for_each_possible_rcu(wci_hash, ent, hash_node,
112063638450STejun Heo 				   (unsigned long)func) {
112163638450STejun Heo 		if (ent->func == func)
112263638450STejun Heo 			return ent;
112363638450STejun Heo 	}
112463638450STejun Heo 	return NULL;
112563638450STejun Heo }
112663638450STejun Heo 
112763638450STejun Heo static void wq_cpu_intensive_report(work_func_t func)
112863638450STejun Heo {
112963638450STejun Heo 	struct wci_ent *ent;
113063638450STejun Heo 
113163638450STejun Heo restart:
113263638450STejun Heo 	ent = wci_find_ent(func);
113363638450STejun Heo 	if (ent) {
113463638450STejun Heo 		u64 cnt;
113563638450STejun Heo 
113663638450STejun Heo 		/*
113763638450STejun Heo 		 * Start reporting from the fourth time and back off
113863638450STejun Heo 		 * exponentially.
113963638450STejun Heo 		 */
114063638450STejun Heo 		cnt = atomic64_inc_return_relaxed(&ent->cnt);
114163638450STejun Heo 		if (cnt >= 4 && is_power_of_2(cnt))
114263638450STejun Heo 			printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
114363638450STejun Heo 					ent->func, wq_cpu_intensive_thresh_us,
114463638450STejun Heo 					atomic64_read(&ent->cnt));
114563638450STejun Heo 		return;
114663638450STejun Heo 	}
114763638450STejun Heo 
114863638450STejun Heo 	/*
114963638450STejun Heo 	 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
115063638450STejun Heo 	 * is exhausted, something went really wrong and we probably made enough
115163638450STejun Heo 	 * noise already.
115263638450STejun Heo 	 */
115363638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS)
115463638450STejun Heo 		return;
115563638450STejun Heo 
115663638450STejun Heo 	raw_spin_lock(&wci_lock);
115763638450STejun Heo 
115863638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS) {
115963638450STejun Heo 		raw_spin_unlock(&wci_lock);
116063638450STejun Heo 		return;
116163638450STejun Heo 	}
116263638450STejun Heo 
116363638450STejun Heo 	if (wci_find_ent(func)) {
116463638450STejun Heo 		raw_spin_unlock(&wci_lock);
116563638450STejun Heo 		goto restart;
116663638450STejun Heo 	}
116763638450STejun Heo 
116863638450STejun Heo 	ent = &wci_ents[wci_nr_ents++];
116963638450STejun Heo 	ent->func = func;
117063638450STejun Heo 	atomic64_set(&ent->cnt, 1);
117163638450STejun Heo 	hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
117263638450STejun Heo 
117363638450STejun Heo 	raw_spin_unlock(&wci_lock);
117463638450STejun Heo }
117563638450STejun Heo 
117663638450STejun Heo #else	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
117763638450STejun Heo static void wq_cpu_intensive_report(work_func_t func) {}
117863638450STejun Heo #endif	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
117963638450STejun Heo 
1180c54d5046STejun Heo /**
11811da177e4SLinus Torvalds  * wq_worker_running - a worker is running again
11821da177e4SLinus Torvalds  * @task: task waking up
11831da177e4SLinus Torvalds  *
11841da177e4SLinus Torvalds  * This function is called when a worker returns from schedule()
11851da177e4SLinus Torvalds  */
11861da177e4SLinus Torvalds void wq_worker_running(struct task_struct *task)
11871da177e4SLinus Torvalds {
11881da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
11891da177e4SLinus Torvalds 
1190c8f6219bSZqiang 	if (!READ_ONCE(worker->sleeping))
11911da177e4SLinus Torvalds 		return;
11921da177e4SLinus Torvalds 
11931da177e4SLinus Torvalds 	/*
11941da177e4SLinus Torvalds 	 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
11951da177e4SLinus Torvalds 	 * and the nr_running increment below, we may ruin the nr_running reset
11961da177e4SLinus Torvalds 	 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
11971da177e4SLinus Torvalds 	 * pool. Protect against such race.
11981da177e4SLinus Torvalds 	 */
11991da177e4SLinus Torvalds 	preempt_disable();
12001da177e4SLinus Torvalds 	if (!(worker->flags & WORKER_NOT_RUNNING))
12011da177e4SLinus Torvalds 		worker->pool->nr_running++;
12021da177e4SLinus Torvalds 	preempt_enable();
1203616db877STejun Heo 
1204616db877STejun Heo 	/*
1205616db877STejun Heo 	 * CPU intensive auto-detection cares about how long a work item hogged
1206616db877STejun Heo 	 * CPU without sleeping. Reset the starting timestamp on wakeup.
1207616db877STejun Heo 	 */
1208616db877STejun Heo 	worker->current_at = worker->task->se.sum_exec_runtime;
1209616db877STejun Heo 
1210c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 0);
12111da177e4SLinus Torvalds }
12121da177e4SLinus Torvalds 
12131da177e4SLinus Torvalds /**
12141da177e4SLinus Torvalds  * wq_worker_sleeping - a worker is going to sleep
12151da177e4SLinus Torvalds  * @task: task going to sleep
12161da177e4SLinus Torvalds  *
12171da177e4SLinus Torvalds  * This function is called from schedule() when a busy worker is
12181da177e4SLinus Torvalds  * going to sleep.
12191da177e4SLinus Torvalds  */
12201da177e4SLinus Torvalds void wq_worker_sleeping(struct task_struct *task)
12211da177e4SLinus Torvalds {
12221da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
12231da177e4SLinus Torvalds 	struct worker_pool *pool;
12241da177e4SLinus Torvalds 
12251da177e4SLinus Torvalds 	/*
12261da177e4SLinus Torvalds 	 * Rescuers, which may not have all the fields set up like normal
12271da177e4SLinus Torvalds 	 * workers, also reach here, let's not access anything before
12281da177e4SLinus Torvalds 	 * checking NOT_RUNNING.
12291da177e4SLinus Torvalds 	 */
12301da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING)
12311da177e4SLinus Torvalds 		return;
12321da177e4SLinus Torvalds 
12331da177e4SLinus Torvalds 	pool = worker->pool;
12341da177e4SLinus Torvalds 
12351da177e4SLinus Torvalds 	/* Return if preempted before wq_worker_running() was reached */
1236c8f6219bSZqiang 	if (READ_ONCE(worker->sleeping))
12371da177e4SLinus Torvalds 		return;
12381da177e4SLinus Torvalds 
1239c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 1);
12401da177e4SLinus Torvalds 	raw_spin_lock_irq(&pool->lock);
12411da177e4SLinus Torvalds 
12421da177e4SLinus Torvalds 	/*
12431da177e4SLinus Torvalds 	 * Recheck in case unbind_workers() preempted us. We don't
12441da177e4SLinus Torvalds 	 * want to decrement nr_running after the worker is unbound
12451da177e4SLinus Torvalds 	 * and nr_running has been reset.
12461da177e4SLinus Torvalds 	 */
12471da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING) {
12481da177e4SLinus Torvalds 		raw_spin_unlock_irq(&pool->lock);
12491da177e4SLinus Torvalds 		return;
12501da177e4SLinus Torvalds 	}
12511da177e4SLinus Torvalds 
12521da177e4SLinus Torvalds 	pool->nr_running--;
1253725e8ec5STejun Heo 	if (need_more_worker(pool)) {
1254725e8ec5STejun Heo 		worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
12551da177e4SLinus Torvalds 		wake_up_worker(pool);
1256725e8ec5STejun Heo 	}
12571da177e4SLinus Torvalds 	raw_spin_unlock_irq(&pool->lock);
12581da177e4SLinus Torvalds }
12591da177e4SLinus Torvalds 
12601da177e4SLinus Torvalds /**
1261616db877STejun Heo  * wq_worker_tick - a scheduler tick occurred while a kworker is running
1262616db877STejun Heo  * @task: task currently running
1263616db877STejun Heo  *
1264616db877STejun Heo  * Called from scheduler_tick(). We're in the IRQ context and the current
1265616db877STejun Heo  * worker's fields which follow the 'K' locking rule can be accessed safely.
1266616db877STejun Heo  */
1267616db877STejun Heo void wq_worker_tick(struct task_struct *task)
1268616db877STejun Heo {
1269616db877STejun Heo 	struct worker *worker = kthread_data(task);
1270616db877STejun Heo 	struct pool_workqueue *pwq = worker->current_pwq;
1271616db877STejun Heo 	struct worker_pool *pool = worker->pool;
1272616db877STejun Heo 
1273616db877STejun Heo 	if (!pwq)
1274616db877STejun Heo 		return;
1275616db877STejun Heo 
12768a1dd1e5STejun Heo 	pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
12778a1dd1e5STejun Heo 
127818c8ae81SZqiang 	if (!wq_cpu_intensive_thresh_us)
127918c8ae81SZqiang 		return;
128018c8ae81SZqiang 
1281616db877STejun Heo 	/*
1282616db877STejun Heo 	 * If the current worker is concurrency managed and hogged the CPU for
1283616db877STejun Heo 	 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1284616db877STejun Heo 	 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1285c8f6219bSZqiang 	 *
1286c8f6219bSZqiang 	 * Set @worker->sleeping means that @worker is in the process of
1287c8f6219bSZqiang 	 * switching out voluntarily and won't be contributing to
1288c8f6219bSZqiang 	 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1289c8f6219bSZqiang 	 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1290c8f6219bSZqiang 	 * double decrements. The task is releasing the CPU anyway. Let's skip.
1291c8f6219bSZqiang 	 * We probably want to make this prettier in the future.
1292616db877STejun Heo 	 */
1293c8f6219bSZqiang 	if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1294616db877STejun Heo 	    worker->task->se.sum_exec_runtime - worker->current_at <
1295616db877STejun Heo 	    wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1296616db877STejun Heo 		return;
1297616db877STejun Heo 
1298616db877STejun Heo 	raw_spin_lock(&pool->lock);
1299616db877STejun Heo 
1300616db877STejun Heo 	worker_set_flags(worker, WORKER_CPU_INTENSIVE);
130163638450STejun Heo 	wq_cpu_intensive_report(worker->current_func);
1302616db877STejun Heo 	pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1303616db877STejun Heo 
1304616db877STejun Heo 	if (need_more_worker(pool)) {
1305616db877STejun Heo 		pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1306616db877STejun Heo 		wake_up_worker(pool);
1307616db877STejun Heo 	}
1308616db877STejun Heo 
1309616db877STejun Heo 	raw_spin_unlock(&pool->lock);
1310616db877STejun Heo }
1311616db877STejun Heo 
1312616db877STejun Heo /**
13131da177e4SLinus Torvalds  * wq_worker_last_func - retrieve worker's last work function
13141da177e4SLinus Torvalds  * @task: Task to retrieve last work function of.
13151da177e4SLinus Torvalds  *
13161da177e4SLinus Torvalds  * Determine the last function a worker executed. This is called from
13171da177e4SLinus Torvalds  * the scheduler to get a worker's last known identity.
13181da177e4SLinus Torvalds  *
13191da177e4SLinus Torvalds  * CONTEXT:
13209b41ea72SAndrew Morton  * raw_spin_lock_irq(rq->lock)
13211da177e4SLinus Torvalds  *
13221da177e4SLinus Torvalds  * This function is called during schedule() when a kworker is going
1323f756d5e2SNathan Lynch  * to sleep. It's used by psi to identify aggregation workers during
1324f756d5e2SNathan Lynch  * dequeuing, to allow periodic aggregation to shut-off when that
13251da177e4SLinus Torvalds  * worker is the last task in the system or cgroup to go to sleep.
13261da177e4SLinus Torvalds  *
13271da177e4SLinus Torvalds  * As this function doesn't involve any workqueue-related locking, it
13281da177e4SLinus Torvalds  * only returns stable values when called from inside the scheduler's
13291da177e4SLinus Torvalds  * queuing and dequeuing paths, when @task, which must be a kworker,
13301da177e4SLinus Torvalds  * is guaranteed to not be processing any works.
1331365970a1SDavid Howells  *
1332365970a1SDavid Howells  * Return:
1333365970a1SDavid Howells  * The last work function %current executed as a worker, NULL if it
1334365970a1SDavid Howells  * hasn't executed any work yet.
1335365970a1SDavid Howells  */
1336365970a1SDavid Howells work_func_t wq_worker_last_func(struct task_struct *task)
1337365970a1SDavid Howells {
1338365970a1SDavid Howells 	struct worker *worker = kthread_data(task);
1339365970a1SDavid Howells 
1340365970a1SDavid Howells 	return worker->last_func;
1341365970a1SDavid Howells }
1342365970a1SDavid Howells 
1343d302f017STejun Heo /**
13448864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
13458864b4e5STejun Heo  * @pwq: pool_workqueue to get
13468864b4e5STejun Heo  *
13478864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
13488864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
13498864b4e5STejun Heo  */
13508864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
13518864b4e5STejun Heo {
13528864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
13538864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
13548864b4e5STejun Heo 	pwq->refcnt++;
13558864b4e5STejun Heo }
13568864b4e5STejun Heo 
13578864b4e5STejun Heo /**
13588864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
13598864b4e5STejun Heo  * @pwq: pool_workqueue to put
13608864b4e5STejun Heo  *
13618864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
13628864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
13638864b4e5STejun Heo  */
13648864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
13658864b4e5STejun Heo {
13668864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
13678864b4e5STejun Heo 	if (likely(--pwq->refcnt))
13688864b4e5STejun Heo 		return;
13698864b4e5STejun Heo 	if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
13708864b4e5STejun Heo 		return;
13718864b4e5STejun Heo 	/*
13728864b4e5STejun Heo 	 * @pwq can't be released under pool->lock, bounce to
13738864b4e5STejun Heo 	 * pwq_unbound_release_workfn().  This never recurses on the same
13748864b4e5STejun Heo 	 * pool->lock as this path is taken only for unbound workqueues and
13758864b4e5STejun Heo 	 * the release work item is scheduled on a per-cpu workqueue.  To
13768864b4e5STejun Heo 	 * avoid lockdep warning, unbound pool->locks are given lockdep
13778864b4e5STejun Heo 	 * subclass of 1 in get_unbound_pool().
13788864b4e5STejun Heo 	 */
13798864b4e5STejun Heo 	schedule_work(&pwq->unbound_release_work);
13808864b4e5STejun Heo }
13818864b4e5STejun Heo 
1382dce90d47STejun Heo /**
1383dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1384dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1385dce90d47STejun Heo  *
1386dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1387dce90d47STejun Heo  */
1388dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1389dce90d47STejun Heo {
1390dce90d47STejun Heo 	if (pwq) {
1391dce90d47STejun Heo 		/*
139224acfb71SThomas Gleixner 		 * As both pwqs and pools are RCU protected, the
1393dce90d47STejun Heo 		 * following lock operations are safe.
1394dce90d47STejun Heo 		 */
1395a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
1396dce90d47STejun Heo 		put_pwq(pwq);
1397a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
1398dce90d47STejun Heo 	}
1399dce90d47STejun Heo }
1400dce90d47STejun Heo 
1401f97a4a1aSLai Jiangshan static void pwq_activate_inactive_work(struct work_struct *work)
1402bf4ede01STejun Heo {
1403112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1404bf4ede01STejun Heo 
1405bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
140682607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
140782607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1408112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
1409f97a4a1aSLai Jiangshan 	__clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work));
1410112202d9STejun Heo 	pwq->nr_active++;
1411bf4ede01STejun Heo }
1412bf4ede01STejun Heo 
1413f97a4a1aSLai Jiangshan static void pwq_activate_first_inactive(struct pool_workqueue *pwq)
14143aa62497SLai Jiangshan {
1415f97a4a1aSLai Jiangshan 	struct work_struct *work = list_first_entry(&pwq->inactive_works,
14163aa62497SLai Jiangshan 						    struct work_struct, entry);
14173aa62497SLai Jiangshan 
1418f97a4a1aSLai Jiangshan 	pwq_activate_inactive_work(work);
14193aa62497SLai Jiangshan }
14203aa62497SLai Jiangshan 
1421bf4ede01STejun Heo /**
1422112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1423112202d9STejun Heo  * @pwq: pwq of interest
1424c4560c2cSLai Jiangshan  * @work_data: work_data of work which left the queue
1425bf4ede01STejun Heo  *
1426bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1427112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1428bf4ede01STejun Heo  *
1429bf4ede01STejun Heo  * CONTEXT:
1430a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1431bf4ede01STejun Heo  */
1432c4560c2cSLai Jiangshan static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1433bf4ede01STejun Heo {
1434c4560c2cSLai Jiangshan 	int color = get_work_color(work_data);
1435c4560c2cSLai Jiangshan 
1436018f3a13SLai Jiangshan 	if (!(work_data & WORK_STRUCT_INACTIVE)) {
1437112202d9STejun Heo 		pwq->nr_active--;
1438f97a4a1aSLai Jiangshan 		if (!list_empty(&pwq->inactive_works)) {
1439f97a4a1aSLai Jiangshan 			/* one down, submit an inactive one */
1440112202d9STejun Heo 			if (pwq->nr_active < pwq->max_active)
1441f97a4a1aSLai Jiangshan 				pwq_activate_first_inactive(pwq);
1442bf4ede01STejun Heo 		}
1443018f3a13SLai Jiangshan 	}
1444018f3a13SLai Jiangshan 
1445018f3a13SLai Jiangshan 	pwq->nr_in_flight[color]--;
1446bf4ede01STejun Heo 
1447bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1448112202d9STejun Heo 	if (likely(pwq->flush_color != color))
14498864b4e5STejun Heo 		goto out_put;
1450bf4ede01STejun Heo 
1451bf4ede01STejun Heo 	/* are there still in-flight works? */
1452112202d9STejun Heo 	if (pwq->nr_in_flight[color])
14538864b4e5STejun Heo 		goto out_put;
1454bf4ede01STejun Heo 
1455112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1456112202d9STejun Heo 	pwq->flush_color = -1;
1457bf4ede01STejun Heo 
1458bf4ede01STejun Heo 	/*
1459112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1460bf4ede01STejun Heo 	 * will handle the rest.
1461bf4ede01STejun Heo 	 */
1462112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1463112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
14648864b4e5STejun Heo out_put:
14658864b4e5STejun Heo 	put_pwq(pwq);
1466bf4ede01STejun Heo }
1467bf4ede01STejun Heo 
146836e227d2STejun Heo /**
1469bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
147036e227d2STejun Heo  * @work: work item to steal
147136e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1472bbb68dfaSTejun Heo  * @flags: place to store irq state
147336e227d2STejun Heo  *
147436e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1475d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
147636e227d2STejun Heo  *
1477d185af30SYacine Belkadi  * Return:
14783eb6b31bSMauro Carvalho Chehab  *
14793eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
148036e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
148136e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
148236e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1483bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1484bbb68dfaSTejun Heo  *		for arbitrarily long
14853eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
148636e227d2STejun Heo  *
1487d185af30SYacine Belkadi  * Note:
1488bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1489e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1490e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1491e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1492bbb68dfaSTejun Heo  *
1493bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1494bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1495bbb68dfaSTejun Heo  *
1496e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1497bf4ede01STejun Heo  */
1498bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1499bbb68dfaSTejun Heo 			       unsigned long *flags)
1500bf4ede01STejun Heo {
1501d565ed63STejun Heo 	struct worker_pool *pool;
1502112202d9STejun Heo 	struct pool_workqueue *pwq;
1503bf4ede01STejun Heo 
1504bbb68dfaSTejun Heo 	local_irq_save(*flags);
1505bbb68dfaSTejun Heo 
150636e227d2STejun Heo 	/* try to steal the timer if it exists */
150736e227d2STejun Heo 	if (is_dwork) {
150836e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
150936e227d2STejun Heo 
1510e0aecdd8STejun Heo 		/*
1511e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1512e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1513e0aecdd8STejun Heo 		 * running on the local CPU.
1514e0aecdd8STejun Heo 		 */
151536e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
151636e227d2STejun Heo 			return 1;
151736e227d2STejun Heo 	}
151836e227d2STejun Heo 
151936e227d2STejun Heo 	/* try to claim PENDING the normal way */
1520bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1521bf4ede01STejun Heo 		return 0;
1522bf4ede01STejun Heo 
152324acfb71SThomas Gleixner 	rcu_read_lock();
1524bf4ede01STejun Heo 	/*
1525bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1526bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1527bf4ede01STejun Heo 	 */
1528d565ed63STejun Heo 	pool = get_work_pool(work);
1529d565ed63STejun Heo 	if (!pool)
1530bbb68dfaSTejun Heo 		goto fail;
1531bf4ede01STejun Heo 
1532a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&pool->lock);
1533bf4ede01STejun Heo 	/*
1534112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1535112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1536112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1537112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1538112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
15390b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1540bf4ede01STejun Heo 	 */
1541112202d9STejun Heo 	pwq = get_work_pwq(work);
1542112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1543bf4ede01STejun Heo 		debug_work_deactivate(work);
15443aa62497SLai Jiangshan 
15453aa62497SLai Jiangshan 		/*
1546018f3a13SLai Jiangshan 		 * A cancelable inactive work item must be in the
1547018f3a13SLai Jiangshan 		 * pwq->inactive_works since a queued barrier can't be
1548018f3a13SLai Jiangshan 		 * canceled (see the comments in insert_wq_barrier()).
1549018f3a13SLai Jiangshan 		 *
1550f97a4a1aSLai Jiangshan 		 * An inactive work item cannot be grabbed directly because
1551d812796eSLai Jiangshan 		 * it might have linked barrier work items which, if left
1552f97a4a1aSLai Jiangshan 		 * on the inactive_works list, will confuse pwq->nr_active
155316062836STejun Heo 		 * management later on and cause stall.  Make sure the work
155416062836STejun Heo 		 * item is activated before grabbing.
15553aa62497SLai Jiangshan 		 */
1556f97a4a1aSLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_INACTIVE)
1557f97a4a1aSLai Jiangshan 			pwq_activate_inactive_work(work);
15583aa62497SLai Jiangshan 
1559bf4ede01STejun Heo 		list_del_init(&work->entry);
1560c4560c2cSLai Jiangshan 		pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
156136e227d2STejun Heo 
1562112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
15634468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
15644468a00fSLai Jiangshan 
1565a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock(&pool->lock);
156624acfb71SThomas Gleixner 		rcu_read_unlock();
156736e227d2STejun Heo 		return 1;
1568bf4ede01STejun Heo 	}
1569a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pool->lock);
1570bbb68dfaSTejun Heo fail:
157124acfb71SThomas Gleixner 	rcu_read_unlock();
1572bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1573bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1574bbb68dfaSTejun Heo 		return -ENOENT;
1575bbb68dfaSTejun Heo 	cpu_relax();
157636e227d2STejun Heo 	return -EAGAIN;
1577bf4ede01STejun Heo }
1578bf4ede01STejun Heo 
1579bf4ede01STejun Heo /**
1580706026c2STejun Heo  * insert_work - insert a work into a pool
1581112202d9STejun Heo  * @pwq: pwq @work belongs to
15824690c4abSTejun Heo  * @work: work to insert
15834690c4abSTejun Heo  * @head: insertion point
15844690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
15854690c4abSTejun Heo  *
1586112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1587706026c2STejun Heo  * work_struct flags.
15884690c4abSTejun Heo  *
15894690c4abSTejun Heo  * CONTEXT:
1590a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1591365970a1SDavid Howells  */
1592112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1593112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1594b89deed3SOleg Nesterov {
1595fe089f87STejun Heo 	debug_work_activate(work);
1596e1d8aa9fSFrederic Weisbecker 
1597e89a85d6SWalter Wu 	/* record the work call stack in order to print it in KASAN reports */
1598f70da745SMarco Elver 	kasan_record_aux_stack_noalloc(work);
1599e89a85d6SWalter Wu 
16004690c4abSTejun Heo 	/* we own @work, set data and link */
1601112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
16021a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
16038864b4e5STejun Heo 	get_pwq(pwq);
1604b89deed3SOleg Nesterov }
1605b89deed3SOleg Nesterov 
1606c8efcc25STejun Heo /*
1607c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
16088d03ecfeSTejun Heo  * same workqueue.
1609c8efcc25STejun Heo  */
1610c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1611c8efcc25STejun Heo {
1612c8efcc25STejun Heo 	struct worker *worker;
1613c8efcc25STejun Heo 
16148d03ecfeSTejun Heo 	worker = current_wq_worker();
1615c8efcc25STejun Heo 	/*
1616bf393fd4SBart Van Assche 	 * Return %true iff I'm a worker executing a work item on @wq.  If
16178d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1618c8efcc25STejun Heo 	 */
1619112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1620c8efcc25STejun Heo }
1621c8efcc25STejun Heo 
1622ef557180SMike Galbraith /*
1623ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
1624ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
1625ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
1626ef557180SMike Galbraith  */
1627ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1628ef557180SMike Galbraith {
1629ef557180SMike Galbraith 	int new_cpu;
1630ef557180SMike Galbraith 
1631f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
1632ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1633ef557180SMike Galbraith 			return cpu;
1634a8ec5880SAmmar Faizi 	} else {
1635a8ec5880SAmmar Faizi 		pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
1636f303fccbSTejun Heo 	}
1637f303fccbSTejun Heo 
1638ef557180SMike Galbraith 	if (cpumask_empty(wq_unbound_cpumask))
1639ef557180SMike Galbraith 		return cpu;
1640ef557180SMike Galbraith 
1641ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
1642ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1643ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
1644ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1645ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
1646ef557180SMike Galbraith 			return cpu;
1647ef557180SMike Galbraith 	}
1648ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
1649ef557180SMike Galbraith 
1650ef557180SMike Galbraith 	return new_cpu;
1651ef557180SMike Galbraith }
1652ef557180SMike Galbraith 
1653d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
16541da177e4SLinus Torvalds 			 struct work_struct *work)
16551da177e4SLinus Torvalds {
1656112202d9STejun Heo 	struct pool_workqueue *pwq;
1657fe089f87STejun Heo 	struct worker_pool *last_pool, *pool;
16588a2e8e5dSTejun Heo 	unsigned int work_flags;
1659b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
16608930cabaSTejun Heo 
16618930cabaSTejun Heo 	/*
16628930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
16638930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
16648930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
16658930cabaSTejun Heo 	 * happen with IRQ disabled.
16668930cabaSTejun Heo 	 */
16678e8eb730SFrederic Weisbecker 	lockdep_assert_irqs_disabled();
16681da177e4SLinus Torvalds 
16691e19ffc6STejun Heo 
167033e3f0a3SRichard Clark 	/*
167133e3f0a3SRichard Clark 	 * For a draining wq, only works from the same workqueue are
167233e3f0a3SRichard Clark 	 * allowed. The __WQ_DESTROYING helps to spot the issue that
167333e3f0a3SRichard Clark 	 * queues a new work item to a wq after destroy_workqueue(wq).
167433e3f0a3SRichard Clark 	 */
167533e3f0a3SRichard Clark 	if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
167633e3f0a3SRichard Clark 		     WARN_ON_ONCE(!is_chained_work(wq))))
1677e41e704bSTejun Heo 		return;
167824acfb71SThomas Gleixner 	rcu_read_lock();
16799e8cd2f5STejun Heo retry:
1680aa202f1fSHillf Danton 	/* pwq which will be used unless @work is executing elsewhere */
1681aa202f1fSHillf Danton 	if (wq->flags & WQ_UNBOUND) {
1682df2d5ae4STejun Heo 		if (req_cpu == WORK_CPU_UNBOUND)
1683ef557180SMike Galbraith 			cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1684df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1685aa202f1fSHillf Danton 	} else {
1686aa202f1fSHillf Danton 		if (req_cpu == WORK_CPU_UNBOUND)
1687aa202f1fSHillf Danton 			cpu = raw_smp_processor_id();
1688ee1ceef7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwq, cpu);
1689aa202f1fSHillf Danton 	}
1690f3421797STejun Heo 
1691fe089f87STejun Heo 	pool = pwq->pool;
1692fe089f87STejun Heo 
169318aa9effSTejun Heo 	/*
1694c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1695c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1696c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
169718aa9effSTejun Heo 	 */
1698c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1699fe089f87STejun Heo 	if (last_pool && last_pool != pool) {
170018aa9effSTejun Heo 		struct worker *worker;
170118aa9effSTejun Heo 
1702a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&last_pool->lock);
170318aa9effSTejun Heo 
1704c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
170518aa9effSTejun Heo 
1706112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1707c9178087STejun Heo 			pwq = worker->current_pwq;
1708fe089f87STejun Heo 			pool = pwq->pool;
1709fe089f87STejun Heo 			WARN_ON_ONCE(pool != last_pool);
17108594fadeSLai Jiangshan 		} else {
171118aa9effSTejun Heo 			/* meh... not running there, queue here */
1712a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&last_pool->lock);
1713fe089f87STejun Heo 			raw_spin_lock(&pool->lock);
171418aa9effSTejun Heo 		}
17158930cabaSTejun Heo 	} else {
1716fe089f87STejun Heo 		raw_spin_lock(&pool->lock);
17178930cabaSTejun Heo 	}
1718502ca9d8STejun Heo 
17199e8cd2f5STejun Heo 	/*
17209e8cd2f5STejun Heo 	 * pwq is determined and locked.  For unbound pools, we could have
17219e8cd2f5STejun Heo 	 * raced with pwq release and it could already be dead.  If its
17229e8cd2f5STejun Heo 	 * refcnt is zero, repeat pwq selection.  Note that pwqs never die
1723df2d5ae4STejun Heo 	 * without another pwq replacing it in the numa_pwq_tbl or while
1724df2d5ae4STejun Heo 	 * work items are executing on it, so the retrying is guaranteed to
17259e8cd2f5STejun Heo 	 * make forward-progress.
17269e8cd2f5STejun Heo 	 */
17279e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
17289e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
1729fe089f87STejun Heo 			raw_spin_unlock(&pool->lock);
17309e8cd2f5STejun Heo 			cpu_relax();
17319e8cd2f5STejun Heo 			goto retry;
17329e8cd2f5STejun Heo 		}
17339e8cd2f5STejun Heo 		/* oops */
17349e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
17359e8cd2f5STejun Heo 			  wq->name, cpu);
17369e8cd2f5STejun Heo 	}
17379e8cd2f5STejun Heo 
1738112202d9STejun Heo 	/* pwq determined, queue */
1739112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1740502ca9d8STejun Heo 
174124acfb71SThomas Gleixner 	if (WARN_ON(!list_empty(&work->entry)))
174224acfb71SThomas Gleixner 		goto out;
17431e19ffc6STejun Heo 
1744112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1745112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
17461e19ffc6STejun Heo 
1747112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1748fe089f87STejun Heo 		if (list_empty(&pool->worklist))
1749fe089f87STejun Heo 			pool->watchdog_ts = jiffies;
1750fe089f87STejun Heo 
1751cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1752112202d9STejun Heo 		pwq->nr_active++;
1753fe089f87STejun Heo 		insert_work(pwq, work, &pool->worklist, work_flags);
1754fe089f87STejun Heo 
1755fe089f87STejun Heo 		if (__need_more_worker(pool))
1756fe089f87STejun Heo 			wake_up_worker(pool);
17578a2e8e5dSTejun Heo 	} else {
1758f97a4a1aSLai Jiangshan 		work_flags |= WORK_STRUCT_INACTIVE;
1759fe089f87STejun Heo 		insert_work(pwq, work, &pwq->inactive_works, work_flags);
17608a2e8e5dSTejun Heo 	}
17611e19ffc6STejun Heo 
176224acfb71SThomas Gleixner out:
1763fe089f87STejun Heo 	raw_spin_unlock(&pool->lock);
176424acfb71SThomas Gleixner 	rcu_read_unlock();
17651da177e4SLinus Torvalds }
17661da177e4SLinus Torvalds 
17670fcb78c2SRolf Eike Beer /**
1768c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1769c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1770c1a220e7SZhang Rui  * @wq: workqueue to use
1771c1a220e7SZhang Rui  * @work: work to queue
1772c1a220e7SZhang Rui  *
1773c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1774443378f0SPaul E. McKenney  * can't go away.  Callers that fail to ensure that the specified
1775443378f0SPaul E. McKenney  * CPU cannot go away will execute on a randomly chosen CPU.
1776854f5cc5SPaul E. McKenney  * But note well that callers specifying a CPU that never has been
1777854f5cc5SPaul E. McKenney  * online will get a splat.
1778d185af30SYacine Belkadi  *
1779d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
1780c1a220e7SZhang Rui  */
1781d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1782d4283e93STejun Heo 		   struct work_struct *work)
1783c1a220e7SZhang Rui {
1784d4283e93STejun Heo 	bool ret = false;
17858930cabaSTejun Heo 	unsigned long flags;
17868930cabaSTejun Heo 
17878930cabaSTejun Heo 	local_irq_save(flags);
1788c1a220e7SZhang Rui 
178922df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
17904690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1791d4283e93STejun Heo 		ret = true;
1792c1a220e7SZhang Rui 	}
17938930cabaSTejun Heo 
17948930cabaSTejun Heo 	local_irq_restore(flags);
1795c1a220e7SZhang Rui 	return ret;
1796c1a220e7SZhang Rui }
1797ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1798c1a220e7SZhang Rui 
17998204e0c1SAlexander Duyck /**
18008204e0c1SAlexander Duyck  * workqueue_select_cpu_near - Select a CPU based on NUMA node
18018204e0c1SAlexander Duyck  * @node: NUMA node ID that we want to select a CPU from
18028204e0c1SAlexander Duyck  *
18038204e0c1SAlexander Duyck  * This function will attempt to find a "random" cpu available on a given
18048204e0c1SAlexander Duyck  * node. If there are no CPUs available on the given node it will return
18058204e0c1SAlexander Duyck  * WORK_CPU_UNBOUND indicating that we should just schedule to any
18068204e0c1SAlexander Duyck  * available CPU if we need to schedule this work.
18078204e0c1SAlexander Duyck  */
18088204e0c1SAlexander Duyck static int workqueue_select_cpu_near(int node)
18098204e0c1SAlexander Duyck {
18108204e0c1SAlexander Duyck 	int cpu;
18118204e0c1SAlexander Duyck 
18128204e0c1SAlexander Duyck 	/* No point in doing this if NUMA isn't enabled for workqueues */
18138204e0c1SAlexander Duyck 	if (!wq_numa_enabled)
18148204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
18158204e0c1SAlexander Duyck 
18168204e0c1SAlexander Duyck 	/* Delay binding to CPU if node is not valid or online */
18178204e0c1SAlexander Duyck 	if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
18188204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
18198204e0c1SAlexander Duyck 
18208204e0c1SAlexander Duyck 	/* Use local node/cpu if we are already there */
18218204e0c1SAlexander Duyck 	cpu = raw_smp_processor_id();
18228204e0c1SAlexander Duyck 	if (node == cpu_to_node(cpu))
18238204e0c1SAlexander Duyck 		return cpu;
18248204e0c1SAlexander Duyck 
18258204e0c1SAlexander Duyck 	/* Use "random" otherwise know as "first" online CPU of node */
18268204e0c1SAlexander Duyck 	cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
18278204e0c1SAlexander Duyck 
18288204e0c1SAlexander Duyck 	/* If CPU is valid return that, otherwise just defer */
18298204e0c1SAlexander Duyck 	return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
18308204e0c1SAlexander Duyck }
18318204e0c1SAlexander Duyck 
18328204e0c1SAlexander Duyck /**
18338204e0c1SAlexander Duyck  * queue_work_node - queue work on a "random" cpu for a given NUMA node
18348204e0c1SAlexander Duyck  * @node: NUMA node that we are targeting the work for
18358204e0c1SAlexander Duyck  * @wq: workqueue to use
18368204e0c1SAlexander Duyck  * @work: work to queue
18378204e0c1SAlexander Duyck  *
18388204e0c1SAlexander Duyck  * We queue the work to a "random" CPU within a given NUMA node. The basic
18398204e0c1SAlexander Duyck  * idea here is to provide a way to somehow associate work with a given
18408204e0c1SAlexander Duyck  * NUMA node.
18418204e0c1SAlexander Duyck  *
18428204e0c1SAlexander Duyck  * This function will only make a best effort attempt at getting this onto
18438204e0c1SAlexander Duyck  * the right NUMA node. If no node is requested or the requested node is
18448204e0c1SAlexander Duyck  * offline then we just fall back to standard queue_work behavior.
18458204e0c1SAlexander Duyck  *
18468204e0c1SAlexander Duyck  * Currently the "random" CPU ends up being the first available CPU in the
18478204e0c1SAlexander Duyck  * intersection of cpu_online_mask and the cpumask of the node, unless we
18488204e0c1SAlexander Duyck  * are running on the node. In that case we just use the current CPU.
18498204e0c1SAlexander Duyck  *
18508204e0c1SAlexander Duyck  * Return: %false if @work was already on a queue, %true otherwise.
18518204e0c1SAlexander Duyck  */
18528204e0c1SAlexander Duyck bool queue_work_node(int node, struct workqueue_struct *wq,
18538204e0c1SAlexander Duyck 		     struct work_struct *work)
18548204e0c1SAlexander Duyck {
18558204e0c1SAlexander Duyck 	unsigned long flags;
18568204e0c1SAlexander Duyck 	bool ret = false;
18578204e0c1SAlexander Duyck 
18588204e0c1SAlexander Duyck 	/*
18598204e0c1SAlexander Duyck 	 * This current implementation is specific to unbound workqueues.
18608204e0c1SAlexander Duyck 	 * Specifically we only return the first available CPU for a given
18618204e0c1SAlexander Duyck 	 * node instead of cycling through individual CPUs within the node.
18628204e0c1SAlexander Duyck 	 *
18638204e0c1SAlexander Duyck 	 * If this is used with a per-cpu workqueue then the logic in
18648204e0c1SAlexander Duyck 	 * workqueue_select_cpu_near would need to be updated to allow for
18658204e0c1SAlexander Duyck 	 * some round robin type logic.
18668204e0c1SAlexander Duyck 	 */
18678204e0c1SAlexander Duyck 	WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
18688204e0c1SAlexander Duyck 
18698204e0c1SAlexander Duyck 	local_irq_save(flags);
18708204e0c1SAlexander Duyck 
18718204e0c1SAlexander Duyck 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
18728204e0c1SAlexander Duyck 		int cpu = workqueue_select_cpu_near(node);
18738204e0c1SAlexander Duyck 
18748204e0c1SAlexander Duyck 		__queue_work(cpu, wq, work);
18758204e0c1SAlexander Duyck 		ret = true;
18768204e0c1SAlexander Duyck 	}
18778204e0c1SAlexander Duyck 
18788204e0c1SAlexander Duyck 	local_irq_restore(flags);
18798204e0c1SAlexander Duyck 	return ret;
18808204e0c1SAlexander Duyck }
18818204e0c1SAlexander Duyck EXPORT_SYMBOL_GPL(queue_work_node);
18828204e0c1SAlexander Duyck 
18838c20feb6SKees Cook void delayed_work_timer_fn(struct timer_list *t)
18841da177e4SLinus Torvalds {
18858c20feb6SKees Cook 	struct delayed_work *dwork = from_timer(dwork, t, timer);
18861da177e4SLinus Torvalds 
1887e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
188860c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
18891da177e4SLinus Torvalds }
18901438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
18911da177e4SLinus Torvalds 
18927beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
189352bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
18941da177e4SLinus Torvalds {
18957beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
18967beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
18971da177e4SLinus Torvalds 
1898637fdbaeSTejun Heo 	WARN_ON_ONCE(!wq);
18994b243563SSami Tolvanen 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
1900fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1901fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
19027beb2edfSTejun Heo 
19038852aac2STejun Heo 	/*
19048852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
19058852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
19068852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
19078852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
19088852aac2STejun Heo 	 */
19098852aac2STejun Heo 	if (!delay) {
19108852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
19118852aac2STejun Heo 		return;
19128852aac2STejun Heo 	}
19138852aac2STejun Heo 
191460c057bcSLai Jiangshan 	dwork->wq = wq;
19151265057fSTejun Heo 	dwork->cpu = cpu;
19167beb2edfSTejun Heo 	timer->expires = jiffies + delay;
19177beb2edfSTejun Heo 
1918041bd12eSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
19197beb2edfSTejun Heo 		add_timer_on(timer, cpu);
1920041bd12eSTejun Heo 	else
1921041bd12eSTejun Heo 		add_timer(timer);
19227beb2edfSTejun Heo }
19231da177e4SLinus Torvalds 
19240fcb78c2SRolf Eike Beer /**
19250fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
19260fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
19270fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1928af9997e4SRandy Dunlap  * @dwork: work to queue
19290fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
19300fcb78c2SRolf Eike Beer  *
1931d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
1932715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1933715f1300STejun Heo  * execution.
19340fcb78c2SRolf Eike Beer  */
1935d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
193652bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
19377a6bc1cdSVenkatesh Pallipadi {
193852bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1939d4283e93STejun Heo 	bool ret = false;
19408930cabaSTejun Heo 	unsigned long flags;
19418930cabaSTejun Heo 
19428930cabaSTejun Heo 	/* read the comment in __queue_work() */
19438930cabaSTejun Heo 	local_irq_save(flags);
19447a6bc1cdSVenkatesh Pallipadi 
194522df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
19467beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1947d4283e93STejun Heo 		ret = true;
19487a6bc1cdSVenkatesh Pallipadi 	}
19498930cabaSTejun Heo 
19508930cabaSTejun Heo 	local_irq_restore(flags);
19517a6bc1cdSVenkatesh Pallipadi 	return ret;
19527a6bc1cdSVenkatesh Pallipadi }
1953ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
19541da177e4SLinus Torvalds 
1955c8e55f36STejun Heo /**
19568376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
19578376fe22STejun Heo  * @cpu: CPU number to execute work on
19588376fe22STejun Heo  * @wq: workqueue to use
19598376fe22STejun Heo  * @dwork: work to queue
19608376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
19618376fe22STejun Heo  *
19628376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
19638376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
19648376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
19658376fe22STejun Heo  * current state.
19668376fe22STejun Heo  *
1967d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
19688376fe22STejun Heo  * pending and its timer was modified.
19698376fe22STejun Heo  *
1970e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
19718376fe22STejun Heo  * See try_to_grab_pending() for details.
19728376fe22STejun Heo  */
19738376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
19748376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
19758376fe22STejun Heo {
19768376fe22STejun Heo 	unsigned long flags;
19778376fe22STejun Heo 	int ret;
19788376fe22STejun Heo 
19798376fe22STejun Heo 	do {
19808376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
19818376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
19828376fe22STejun Heo 
19838376fe22STejun Heo 	if (likely(ret >= 0)) {
19848376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
19858376fe22STejun Heo 		local_irq_restore(flags);
19868376fe22STejun Heo 	}
19878376fe22STejun Heo 
19888376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
19898376fe22STejun Heo 	return ret;
19908376fe22STejun Heo }
19918376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
19928376fe22STejun Heo 
199305f0fe6bSTejun Heo static void rcu_work_rcufn(struct rcu_head *rcu)
199405f0fe6bSTejun Heo {
199505f0fe6bSTejun Heo 	struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
199605f0fe6bSTejun Heo 
199705f0fe6bSTejun Heo 	/* read the comment in __queue_work() */
199805f0fe6bSTejun Heo 	local_irq_disable();
199905f0fe6bSTejun Heo 	__queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
200005f0fe6bSTejun Heo 	local_irq_enable();
200105f0fe6bSTejun Heo }
200205f0fe6bSTejun Heo 
200305f0fe6bSTejun Heo /**
200405f0fe6bSTejun Heo  * queue_rcu_work - queue work after a RCU grace period
200505f0fe6bSTejun Heo  * @wq: workqueue to use
200605f0fe6bSTejun Heo  * @rwork: work to queue
200705f0fe6bSTejun Heo  *
200805f0fe6bSTejun Heo  * Return: %false if @rwork was already pending, %true otherwise.  Note
200905f0fe6bSTejun Heo  * that a full RCU grace period is guaranteed only after a %true return.
2010bf393fd4SBart Van Assche  * While @rwork is guaranteed to be executed after a %false return, the
201105f0fe6bSTejun Heo  * execution may happen before a full RCU grace period has passed.
201205f0fe6bSTejun Heo  */
201305f0fe6bSTejun Heo bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
201405f0fe6bSTejun Heo {
201505f0fe6bSTejun Heo 	struct work_struct *work = &rwork->work;
201605f0fe6bSTejun Heo 
201705f0fe6bSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
201805f0fe6bSTejun Heo 		rwork->wq = wq;
2019a7e30c0eSUladzislau Rezki 		call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
202005f0fe6bSTejun Heo 		return true;
202105f0fe6bSTejun Heo 	}
202205f0fe6bSTejun Heo 
202305f0fe6bSTejun Heo 	return false;
202405f0fe6bSTejun Heo }
202505f0fe6bSTejun Heo EXPORT_SYMBOL(queue_rcu_work);
202605f0fe6bSTejun Heo 
2027f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
2028c34056a3STejun Heo {
2029c34056a3STejun Heo 	struct worker *worker;
2030c34056a3STejun Heo 
2031f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
2032c8e55f36STejun Heo 	if (worker) {
2033c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
2034affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
2035da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
2036e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
2037e22bee78STejun Heo 		worker->flags = WORKER_PREP;
2038c8e55f36STejun Heo 	}
2039c34056a3STejun Heo 	return worker;
2040c34056a3STejun Heo }
2041c34056a3STejun Heo 
2042c34056a3STejun Heo /**
20434736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
20444736cbf7SLai Jiangshan  * @worker: worker to be attached
20454736cbf7SLai Jiangshan  * @pool: the target pool
20464736cbf7SLai Jiangshan  *
20474736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
20484736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
20494736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
20504736cbf7SLai Jiangshan  */
20514736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
20524736cbf7SLai Jiangshan 				   struct worker_pool *pool)
20534736cbf7SLai Jiangshan {
20541258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
20554736cbf7SLai Jiangshan 
20564736cbf7SLai Jiangshan 	/*
20571258fae7STejun Heo 	 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
20581258fae7STejun Heo 	 * stable across this function.  See the comments above the flag
20591258fae7STejun Heo 	 * definition for details.
20604736cbf7SLai Jiangshan 	 */
20614736cbf7SLai Jiangshan 	if (pool->flags & POOL_DISASSOCIATED)
20624736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
20635c25b5ffSPeter Zijlstra 	else
20645c25b5ffSPeter Zijlstra 		kthread_set_per_cpu(worker->task, pool->cpu);
20654736cbf7SLai Jiangshan 
2066640f17c8SPeter Zijlstra 	if (worker->rescue_wq)
2067640f17c8SPeter Zijlstra 		set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
2068640f17c8SPeter Zijlstra 
20694736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
2070a2d812a2STejun Heo 	worker->pool = pool;
20714736cbf7SLai Jiangshan 
20721258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
20734736cbf7SLai Jiangshan }
20744736cbf7SLai Jiangshan 
20754736cbf7SLai Jiangshan /**
207660f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
207760f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
207860f5a4bcSLai Jiangshan  *
20794736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
20804736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
20814736cbf7SLai Jiangshan  * other reference to the pool.
208260f5a4bcSLai Jiangshan  */
2083a2d812a2STejun Heo static void worker_detach_from_pool(struct worker *worker)
208460f5a4bcSLai Jiangshan {
2085a2d812a2STejun Heo 	struct worker_pool *pool = worker->pool;
208660f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
208760f5a4bcSLai Jiangshan 
20881258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2089a2d812a2STejun Heo 
20905c25b5ffSPeter Zijlstra 	kthread_set_per_cpu(worker->task, -1);
2091da028469SLai Jiangshan 	list_del(&worker->node);
2092a2d812a2STejun Heo 	worker->pool = NULL;
2093a2d812a2STejun Heo 
2094e02b9312SValentin Schneider 	if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
209560f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
20961258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
209760f5a4bcSLai Jiangshan 
2098b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
2099b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2100b62c0751SLai Jiangshan 
210160f5a4bcSLai Jiangshan 	if (detach_completion)
210260f5a4bcSLai Jiangshan 		complete(detach_completion);
210360f5a4bcSLai Jiangshan }
210460f5a4bcSLai Jiangshan 
210560f5a4bcSLai Jiangshan /**
2106c34056a3STejun Heo  * create_worker - create a new workqueue worker
210763d95a91STejun Heo  * @pool: pool the new worker will belong to
2108c34056a3STejun Heo  *
2109051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
2110c34056a3STejun Heo  *
2111c34056a3STejun Heo  * CONTEXT:
2112c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
2113c34056a3STejun Heo  *
2114d185af30SYacine Belkadi  * Return:
2115c34056a3STejun Heo  * Pointer to the newly created worker.
2116c34056a3STejun Heo  */
2117bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
2118c34056a3STejun Heo {
2119e441b56fSZhen Lei 	struct worker *worker;
2120e441b56fSZhen Lei 	int id;
2121e3c916a4STejun Heo 	char id_buf[16];
2122c34056a3STejun Heo 
21237cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
2124e441b56fSZhen Lei 	id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
21253f0ea0b8SPetr Mladek 	if (id < 0) {
21263f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
21273f0ea0b8SPetr Mladek 			    ERR_PTR(id));
2128e441b56fSZhen Lei 		return NULL;
21293f0ea0b8SPetr Mladek 	}
2130c34056a3STejun Heo 
2131f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
21323f0ea0b8SPetr Mladek 	if (!worker) {
21333f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker\n");
2134c34056a3STejun Heo 		goto fail;
21353f0ea0b8SPetr Mladek 	}
2136c34056a3STejun Heo 
2137c34056a3STejun Heo 	worker->id = id;
2138c34056a3STejun Heo 
213929c91e99STejun Heo 	if (pool->cpu >= 0)
2140e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
2141e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
2142f3421797STejun Heo 	else
2143e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
2144e3c916a4STejun Heo 
2145f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
2146e3c916a4STejun Heo 					      "kworker/%s", id_buf);
21473f0ea0b8SPetr Mladek 	if (IS_ERR(worker->task)) {
214860f54038SPetr Mladek 		if (PTR_ERR(worker->task) == -EINTR) {
214960f54038SPetr Mladek 			pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n",
215060f54038SPetr Mladek 			       id_buf);
215160f54038SPetr Mladek 		} else {
21523f0ea0b8SPetr Mladek 			pr_err_once("workqueue: Failed to create a worker thread: %pe",
21533f0ea0b8SPetr Mladek 				    worker->task);
215460f54038SPetr Mladek 		}
2155c34056a3STejun Heo 		goto fail;
21563f0ea0b8SPetr Mladek 	}
2157c34056a3STejun Heo 
215891151228SOleg Nesterov 	set_user_nice(worker->task, pool->attrs->nice);
215925834c73SPeter Zijlstra 	kthread_bind_mask(worker->task, pool->attrs->cpumask);
216091151228SOleg Nesterov 
2161da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
21624736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
2163822d8405STejun Heo 
2164051e1850SLai Jiangshan 	/* start the newly created worker */
2165a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2166051e1850SLai Jiangshan 	worker->pool->nr_workers++;
2167051e1850SLai Jiangshan 	worker_enter_idle(worker);
2168051e1850SLai Jiangshan 	wake_up_process(worker->task);
2169a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2170051e1850SLai Jiangshan 
2171c34056a3STejun Heo 	return worker;
2172822d8405STejun Heo 
2173c34056a3STejun Heo fail:
2174e441b56fSZhen Lei 	ida_free(&pool->worker_ida, id);
2175c34056a3STejun Heo 	kfree(worker);
2176c34056a3STejun Heo 	return NULL;
2177c34056a3STejun Heo }
2178c34056a3STejun Heo 
2179793777bcSValentin Schneider static void unbind_worker(struct worker *worker)
2180793777bcSValentin Schneider {
2181793777bcSValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2182793777bcSValentin Schneider 
2183793777bcSValentin Schneider 	kthread_set_per_cpu(worker->task, -1);
2184793777bcSValentin Schneider 	if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2185793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2186793777bcSValentin Schneider 	else
2187793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2188793777bcSValentin Schneider }
2189793777bcSValentin Schneider 
2190e02b9312SValentin Schneider static void wake_dying_workers(struct list_head *cull_list)
2191e02b9312SValentin Schneider {
2192e02b9312SValentin Schneider 	struct worker *worker, *tmp;
2193e02b9312SValentin Schneider 
2194e02b9312SValentin Schneider 	list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2195e02b9312SValentin Schneider 		list_del_init(&worker->entry);
2196e02b9312SValentin Schneider 		unbind_worker(worker);
2197e02b9312SValentin Schneider 		/*
2198e02b9312SValentin Schneider 		 * If the worker was somehow already running, then it had to be
2199e02b9312SValentin Schneider 		 * in pool->idle_list when set_worker_dying() happened or we
2200e02b9312SValentin Schneider 		 * wouldn't have gotten here.
2201c34056a3STejun Heo 		 *
2202e02b9312SValentin Schneider 		 * Thus, the worker must either have observed the WORKER_DIE
2203e02b9312SValentin Schneider 		 * flag, or have set its state to TASK_IDLE. Either way, the
2204e02b9312SValentin Schneider 		 * below will be observed by the worker and is safe to do
2205e02b9312SValentin Schneider 		 * outside of pool->lock.
2206e02b9312SValentin Schneider 		 */
2207e02b9312SValentin Schneider 		wake_up_process(worker->task);
2208e02b9312SValentin Schneider 	}
2209e02b9312SValentin Schneider }
2210e02b9312SValentin Schneider 
2211e02b9312SValentin Schneider /**
2212e02b9312SValentin Schneider  * set_worker_dying - Tag a worker for destruction
2213e02b9312SValentin Schneider  * @worker: worker to be destroyed
2214e02b9312SValentin Schneider  * @list: transfer worker away from its pool->idle_list and into list
2215e02b9312SValentin Schneider  *
2216e02b9312SValentin Schneider  * Tag @worker for destruction and adjust @pool stats accordingly.  The worker
2217e02b9312SValentin Schneider  * should be idle.
2218c8e55f36STejun Heo  *
2219c8e55f36STejun Heo  * CONTEXT:
2220a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
2221c34056a3STejun Heo  */
2222e02b9312SValentin Schneider static void set_worker_dying(struct worker *worker, struct list_head *list)
2223c34056a3STejun Heo {
2224bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2225c34056a3STejun Heo 
2226cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
2227e02b9312SValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2228cd549687STejun Heo 
2229c34056a3STejun Heo 	/* sanity check frenzy */
22306183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
223173eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
223273eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
22336183c009STejun Heo 		return;
2234c34056a3STejun Heo 
2235bd7bdd43STejun Heo 	pool->nr_workers--;
2236bd7bdd43STejun Heo 	pool->nr_idle--;
2237c8e55f36STejun Heo 
2238cb444766STejun Heo 	worker->flags |= WORKER_DIE;
2239e02b9312SValentin Schneider 
2240e02b9312SValentin Schneider 	list_move(&worker->entry, list);
2241e02b9312SValentin Schneider 	list_move(&worker->node, &pool->dying_workers);
2242c34056a3STejun Heo }
2243c34056a3STejun Heo 
22443f959aa3SValentin Schneider /**
22453f959aa3SValentin Schneider  * idle_worker_timeout - check if some idle workers can now be deleted.
22463f959aa3SValentin Schneider  * @t: The pool's idle_timer that just expired
22473f959aa3SValentin Schneider  *
22483f959aa3SValentin Schneider  * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
22493f959aa3SValentin Schneider  * worker_leave_idle(), as a worker flicking between idle and active while its
22503f959aa3SValentin Schneider  * pool is at the too_many_workers() tipping point would cause too much timer
22513f959aa3SValentin Schneider  * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
22523f959aa3SValentin Schneider  * it expire and re-evaluate things from there.
22533f959aa3SValentin Schneider  */
225432a6c723SKees Cook static void idle_worker_timeout(struct timer_list *t)
2255e22bee78STejun Heo {
225632a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, idle_timer);
22573f959aa3SValentin Schneider 	bool do_cull = false;
22583f959aa3SValentin Schneider 
22593f959aa3SValentin Schneider 	if (work_pending(&pool->idle_cull_work))
22603f959aa3SValentin Schneider 		return;
22613f959aa3SValentin Schneider 
22623f959aa3SValentin Schneider 	raw_spin_lock_irq(&pool->lock);
22633f959aa3SValentin Schneider 
22643f959aa3SValentin Schneider 	if (too_many_workers(pool)) {
22653f959aa3SValentin Schneider 		struct worker *worker;
22663f959aa3SValentin Schneider 		unsigned long expires;
22673f959aa3SValentin Schneider 
22683f959aa3SValentin Schneider 		/* idle_list is kept in LIFO order, check the last one */
22693f959aa3SValentin Schneider 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
22703f959aa3SValentin Schneider 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
22713f959aa3SValentin Schneider 		do_cull = !time_before(jiffies, expires);
22723f959aa3SValentin Schneider 
22733f959aa3SValentin Schneider 		if (!do_cull)
22743f959aa3SValentin Schneider 			mod_timer(&pool->idle_timer, expires);
22753f959aa3SValentin Schneider 	}
22763f959aa3SValentin Schneider 	raw_spin_unlock_irq(&pool->lock);
22773f959aa3SValentin Schneider 
22783f959aa3SValentin Schneider 	if (do_cull)
22793f959aa3SValentin Schneider 		queue_work(system_unbound_wq, &pool->idle_cull_work);
22803f959aa3SValentin Schneider }
22813f959aa3SValentin Schneider 
22823f959aa3SValentin Schneider /**
22833f959aa3SValentin Schneider  * idle_cull_fn - cull workers that have been idle for too long.
22843f959aa3SValentin Schneider  * @work: the pool's work for handling these idle workers
22853f959aa3SValentin Schneider  *
22863f959aa3SValentin Schneider  * This goes through a pool's idle workers and gets rid of those that have been
22873f959aa3SValentin Schneider  * idle for at least IDLE_WORKER_TIMEOUT seconds.
2288e02b9312SValentin Schneider  *
2289e02b9312SValentin Schneider  * We don't want to disturb isolated CPUs because of a pcpu kworker being
2290e02b9312SValentin Schneider  * culled, so this also resets worker affinity. This requires a sleepable
2291e02b9312SValentin Schneider  * context, hence the split between timer callback and work item.
22923f959aa3SValentin Schneider  */
22933f959aa3SValentin Schneider static void idle_cull_fn(struct work_struct *work)
22943f959aa3SValentin Schneider {
22953f959aa3SValentin Schneider 	struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
22969680540cSYang Yingliang 	LIST_HEAD(cull_list);
2297e22bee78STejun Heo 
2298e02b9312SValentin Schneider 	/*
2299e02b9312SValentin Schneider 	 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2300e02b9312SValentin Schneider 	 * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2301e02b9312SValentin Schneider 	 * path. This is required as a previously-preempted worker could run after
2302e02b9312SValentin Schneider 	 * set_worker_dying() has happened but before wake_dying_workers() did.
2303e02b9312SValentin Schneider 	 */
2304e02b9312SValentin Schneider 	mutex_lock(&wq_pool_attach_mutex);
2305a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2306e22bee78STejun Heo 
23073347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
2308e22bee78STejun Heo 		struct worker *worker;
2309e22bee78STejun Heo 		unsigned long expires;
2310e22bee78STejun Heo 
231163d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
2312e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2313e22bee78STejun Heo 
23143347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
231563d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
23163347fc9fSLai Jiangshan 			break;
2317e22bee78STejun Heo 		}
23183347fc9fSLai Jiangshan 
2319e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
2320e22bee78STejun Heo 	}
2321e22bee78STejun Heo 
2322a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2323e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
2324e02b9312SValentin Schneider 	mutex_unlock(&wq_pool_attach_mutex);
2325e22bee78STejun Heo }
2326e22bee78STejun Heo 
2327493a1724STejun Heo static void send_mayday(struct work_struct *work)
2328e22bee78STejun Heo {
2329112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2330112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
2331493a1724STejun Heo 
23322e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
2333e22bee78STejun Heo 
2334493008a8STejun Heo 	if (!wq->rescuer)
2335493a1724STejun Heo 		return;
2336e22bee78STejun Heo 
2337e22bee78STejun Heo 	/* mayday mayday mayday */
2338493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
233977668c8bSLai Jiangshan 		/*
234077668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
234177668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
234277668c8bSLai Jiangshan 		 * rescuer is done with it.
234377668c8bSLai Jiangshan 		 */
234477668c8bSLai Jiangshan 		get_pwq(pwq);
2345493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
2346e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
2347725e8ec5STejun Heo 		pwq->stats[PWQ_STAT_MAYDAY]++;
2348493a1724STejun Heo 	}
2349e22bee78STejun Heo }
2350e22bee78STejun Heo 
235132a6c723SKees Cook static void pool_mayday_timeout(struct timer_list *t)
2352e22bee78STejun Heo {
235332a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2354e22bee78STejun Heo 	struct work_struct *work;
2355e22bee78STejun Heo 
2356a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2357a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&wq_mayday_lock);		/* for wq->maydays */
2358e22bee78STejun Heo 
235963d95a91STejun Heo 	if (need_to_create_worker(pool)) {
2360e22bee78STejun Heo 		/*
2361e22bee78STejun Heo 		 * We've been trying to create a new worker but
2362e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
2363e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
2364e22bee78STejun Heo 		 * rescuers.
2365e22bee78STejun Heo 		 */
236663d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
2367e22bee78STejun Heo 			send_mayday(work);
2368e22bee78STejun Heo 	}
2369e22bee78STejun Heo 
2370a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&wq_mayday_lock);
2371a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2372e22bee78STejun Heo 
237363d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2374e22bee78STejun Heo }
2375e22bee78STejun Heo 
2376e22bee78STejun Heo /**
2377e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
237863d95a91STejun Heo  * @pool: pool to create a new worker for
2379e22bee78STejun Heo  *
238063d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
2381e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
2382e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
238363d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
2384e22bee78STejun Heo  * possible allocation deadlock.
2385e22bee78STejun Heo  *
2386c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
2387c5aa87bbSTejun Heo  * may_start_working() %true.
2388e22bee78STejun Heo  *
2389e22bee78STejun Heo  * LOCKING:
2390a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2391e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
2392e22bee78STejun Heo  * manager.
2393e22bee78STejun Heo  */
239429187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
2395d565ed63STejun Heo __releases(&pool->lock)
2396d565ed63STejun Heo __acquires(&pool->lock)
2397e22bee78STejun Heo {
2398e22bee78STejun Heo restart:
2399a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
24009f9c2364STejun Heo 
2401e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
240263d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2403e22bee78STejun Heo 
2404e22bee78STejun Heo 	while (true) {
2405051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
2406e22bee78STejun Heo 			break;
2407e22bee78STejun Heo 
2408e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
24099f9c2364STejun Heo 
241063d95a91STejun Heo 		if (!need_to_create_worker(pool))
2411e22bee78STejun Heo 			break;
2412e22bee78STejun Heo 	}
2413e22bee78STejun Heo 
241463d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
2415a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2416051e1850SLai Jiangshan 	/*
2417051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
2418051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
2419051e1850SLai Jiangshan 	 * already become busy.
2420051e1850SLai Jiangshan 	 */
242163d95a91STejun Heo 	if (need_to_create_worker(pool))
2422e22bee78STejun Heo 		goto restart;
2423e22bee78STejun Heo }
2424e22bee78STejun Heo 
2425e22bee78STejun Heo /**
2426e22bee78STejun Heo  * manage_workers - manage worker pool
2427e22bee78STejun Heo  * @worker: self
2428e22bee78STejun Heo  *
2429706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
2430e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2431706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2432e22bee78STejun Heo  *
2433e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2434e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2435e22bee78STejun Heo  * and may_start_working() is true.
2436e22bee78STejun Heo  *
2437e22bee78STejun Heo  * CONTEXT:
2438a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2439e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2440e22bee78STejun Heo  *
2441d185af30SYacine Belkadi  * Return:
244229187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
244329187a9eSTejun Heo  * start processing works, %true if management function was performed and
244429187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
244529187a9eSTejun Heo  * no longer be true.
2446e22bee78STejun Heo  */
2447e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2448e22bee78STejun Heo {
244963d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2450e22bee78STejun Heo 
2451692b4825STejun Heo 	if (pool->flags & POOL_MANAGER_ACTIVE)
245229187a9eSTejun Heo 		return false;
2453692b4825STejun Heo 
2454692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
24552607d7a6STejun Heo 	pool->manager = worker;
2456e22bee78STejun Heo 
245729187a9eSTejun Heo 	maybe_create_worker(pool);
2458e22bee78STejun Heo 
24592607d7a6STejun Heo 	pool->manager = NULL;
2460692b4825STejun Heo 	pool->flags &= ~POOL_MANAGER_ACTIVE;
2461d8bb65abSSebastian Andrzej Siewior 	rcuwait_wake_up(&manager_wait);
246229187a9eSTejun Heo 	return true;
2463e22bee78STejun Heo }
2464e22bee78STejun Heo 
2465a62428c0STejun Heo /**
2466a62428c0STejun Heo  * process_one_work - process single work
2467c34056a3STejun Heo  * @worker: self
2468a62428c0STejun Heo  * @work: work to process
2469a62428c0STejun Heo  *
2470a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2471a62428c0STejun Heo  * process a single work including synchronization against and
2472a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2473a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2474a62428c0STejun Heo  * call this function to process a work.
2475a62428c0STejun Heo  *
2476a62428c0STejun Heo  * CONTEXT:
2477a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
2478a62428c0STejun Heo  */
2479c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2480d565ed63STejun Heo __releases(&pool->lock)
2481d565ed63STejun Heo __acquires(&pool->lock)
24821da177e4SLinus Torvalds {
2483112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2484bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2485c4560c2cSLai Jiangshan 	unsigned long work_data;
24867e11629dSTejun Heo 	struct worker *collision;
24874e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
24884e6045f1SJohannes Berg 	/*
2489a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2490a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2491a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2492a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2493a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
24944e6045f1SJohannes Berg 	 */
24954d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
24964d82a1deSPeter Zijlstra 
24974d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
24984e6045f1SJohannes Berg #endif
2499807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
250085327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2501ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
250225511a47STejun Heo 
25037e11629dSTejun Heo 	/*
25047e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
25057e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
25067e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
25077e11629dSTejun Heo 	 * currently executing one.
25087e11629dSTejun Heo 	 */
2509c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
25107e11629dSTejun Heo 	if (unlikely(collision)) {
25117e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
25127e11629dSTejun Heo 		return;
25137e11629dSTejun Heo 	}
25141da177e4SLinus Torvalds 
25158930cabaSTejun Heo 	/* claim and dequeue */
25161da177e4SLinus Torvalds 	debug_work_deactivate(work);
2517c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2518c34056a3STejun Heo 	worker->current_work = work;
2519a2c1c57bSTejun Heo 	worker->current_func = work->func;
2520112202d9STejun Heo 	worker->current_pwq = pwq;
2521616db877STejun Heo 	worker->current_at = worker->task->se.sum_exec_runtime;
2522c4560c2cSLai Jiangshan 	work_data = *work_data_bits(work);
2523d812796eSLai Jiangshan 	worker->current_color = get_work_color(work_data);
25247a22ad75STejun Heo 
25258bf89593STejun Heo 	/*
25268bf89593STejun Heo 	 * Record wq name for cmdline and debug reporting, may get
25278bf89593STejun Heo 	 * overridden through set_worker_desc().
25288bf89593STejun Heo 	 */
25298bf89593STejun Heo 	strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
25308bf89593STejun Heo 
2531a62428c0STejun Heo 	list_del_init(&work->entry);
2532a62428c0STejun Heo 
2533649027d7STejun Heo 	/*
2534228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
2535228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
2536228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
2537228f1d00SLai Jiangshan 	 * execution of the pending work items.
2538fb0e7bebSTejun Heo 	 */
2539616db877STejun Heo 	if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
2540228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2541fb0e7bebSTejun Heo 
2542974271c4STejun Heo 	/*
2543a489a03eSLai Jiangshan 	 * Wake up another worker if necessary.  The condition is always
2544a489a03eSLai Jiangshan 	 * false for normal per-cpu workers since nr_running would always
2545a489a03eSLai Jiangshan 	 * be >= 1 at this point.  This is used to chain execution of the
2546a489a03eSLai Jiangshan 	 * pending work items for WORKER_NOT_RUNNING workers such as the
2547228f1d00SLai Jiangshan 	 * UNBOUND and CPU_INTENSIVE ones.
2548974271c4STejun Heo 	 */
2549a489a03eSLai Jiangshan 	if (need_more_worker(pool))
255063d95a91STejun Heo 		wake_up_worker(pool);
2551974271c4STejun Heo 
25528930cabaSTejun Heo 	/*
25537c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2554d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
255523657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
255623657bb1STejun Heo 	 * disabled.
25578930cabaSTejun Heo 	 */
25587c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
25591da177e4SLinus Torvalds 
2560a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2561365970a1SDavid Howells 
2562a1d14934SPeter Zijlstra 	lock_map_acquire(&pwq->wq->lockdep_map);
25633295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2564e6f3faa7SPeter Zijlstra 	/*
2565f52be570SPeter Zijlstra 	 * Strictly speaking we should mark the invariant state without holding
2566f52be570SPeter Zijlstra 	 * any locks, that is, before these two lock_map_acquire()'s.
2567e6f3faa7SPeter Zijlstra 	 *
2568e6f3faa7SPeter Zijlstra 	 * However, that would result in:
2569e6f3faa7SPeter Zijlstra 	 *
2570e6f3faa7SPeter Zijlstra 	 *   A(W1)
2571e6f3faa7SPeter Zijlstra 	 *   WFC(C)
2572e6f3faa7SPeter Zijlstra 	 *		A(W1)
2573e6f3faa7SPeter Zijlstra 	 *		C(C)
2574e6f3faa7SPeter Zijlstra 	 *
2575e6f3faa7SPeter Zijlstra 	 * Which would create W1->C->W1 dependencies, even though there is no
2576e6f3faa7SPeter Zijlstra 	 * actual deadlock possible. There are two solutions, using a
2577e6f3faa7SPeter Zijlstra 	 * read-recursive acquire on the work(queue) 'locks', but this will then
2578f52be570SPeter Zijlstra 	 * hit the lockdep limitation on recursive locks, or simply discard
2579e6f3faa7SPeter Zijlstra 	 * these locks.
2580e6f3faa7SPeter Zijlstra 	 *
2581e6f3faa7SPeter Zijlstra 	 * AFAICT there is no possible deadlock scenario between the
2582e6f3faa7SPeter Zijlstra 	 * flush_work() and complete() primitives (except for single-threaded
2583e6f3faa7SPeter Zijlstra 	 * workqueues), so hiding them isn't a problem.
2584e6f3faa7SPeter Zijlstra 	 */
2585f52be570SPeter Zijlstra 	lockdep_invariant_state(true);
2586725e8ec5STejun Heo 	pwq->stats[PWQ_STAT_STARTED]++;
2587e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2588a2c1c57bSTejun Heo 	worker->current_func(work);
2589e36c886aSArjan van de Ven 	/*
2590e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2591e36c886aSArjan van de Ven 	 * point will only record its address.
2592e36c886aSArjan van de Ven 	 */
25931c5da0ecSDaniel Jordan 	trace_workqueue_execute_end(work, worker->current_func);
2594725e8ec5STejun Heo 	pwq->stats[PWQ_STAT_COMPLETED]++;
25953295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2596112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
25971da177e4SLinus Torvalds 
2598d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2599044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2600d75f773cSSakari Ailus 		       "     last function: %ps\n",
2601a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2602a2c1c57bSTejun Heo 		       worker->current_func);
2603d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2604d5abe669SPeter Zijlstra 		dump_stack();
2605d5abe669SPeter Zijlstra 	}
2606d5abe669SPeter Zijlstra 
2607b22ce278STejun Heo 	/*
2608025f50f3SSebastian Andrzej Siewior 	 * The following prevents a kworker from hogging CPU on !PREEMPTION
2609b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
2610b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
2611b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
2612789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
2613789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
2614b22ce278STejun Heo 	 */
2615a7e6425eSPaul E. McKenney 	cond_resched();
2616b22ce278STejun Heo 
2617a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2618a62428c0STejun Heo 
2619616db877STejun Heo 	/*
2620616db877STejun Heo 	 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
2621616db877STejun Heo 	 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
2622616db877STejun Heo 	 * wq_cpu_intensive_thresh_us. Clear it.
2623616db877STejun Heo 	 */
2624fb0e7bebSTejun Heo 	worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2625fb0e7bebSTejun Heo 
26261b69ac6bSJohannes Weiner 	/* tag the worker for identification in schedule() */
26271b69ac6bSJohannes Weiner 	worker->last_func = worker->current_func;
26281b69ac6bSJohannes Weiner 
2629a62428c0STejun Heo 	/* we're done with it, release */
263042f8570fSSasha Levin 	hash_del(&worker->hentry);
2631c34056a3STejun Heo 	worker->current_work = NULL;
2632a2c1c57bSTejun Heo 	worker->current_func = NULL;
2633112202d9STejun Heo 	worker->current_pwq = NULL;
2634d812796eSLai Jiangshan 	worker->current_color = INT_MAX;
2635c4560c2cSLai Jiangshan 	pwq_dec_nr_in_flight(pwq, work_data);
26361da177e4SLinus Torvalds }
26371da177e4SLinus Torvalds 
2638affee4b2STejun Heo /**
2639affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2640affee4b2STejun Heo  * @worker: self
2641affee4b2STejun Heo  *
2642affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2643affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2644affee4b2STejun Heo  * fetches a work from the top and executes it.
2645affee4b2STejun Heo  *
2646affee4b2STejun Heo  * CONTEXT:
2647a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2648affee4b2STejun Heo  * multiple times.
2649affee4b2STejun Heo  */
2650affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
26511da177e4SLinus Torvalds {
2652c0ab017dSTejun Heo 	struct work_struct *work;
2653c0ab017dSTejun Heo 	bool first = true;
2654c0ab017dSTejun Heo 
2655c0ab017dSTejun Heo 	while ((work = list_first_entry_or_null(&worker->scheduled,
2656c0ab017dSTejun Heo 						struct work_struct, entry))) {
2657c0ab017dSTejun Heo 		if (first) {
2658c0ab017dSTejun Heo 			worker->pool->watchdog_ts = jiffies;
2659c0ab017dSTejun Heo 			first = false;
2660c0ab017dSTejun Heo 		}
2661c34056a3STejun Heo 		process_one_work(worker, work);
2662a62428c0STejun Heo 	}
26631da177e4SLinus Torvalds }
26641da177e4SLinus Torvalds 
2665197f6accSTejun Heo static void set_pf_worker(bool val)
2666197f6accSTejun Heo {
2667197f6accSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2668197f6accSTejun Heo 	if (val)
2669197f6accSTejun Heo 		current->flags |= PF_WQ_WORKER;
2670197f6accSTejun Heo 	else
2671197f6accSTejun Heo 		current->flags &= ~PF_WQ_WORKER;
2672197f6accSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
2673197f6accSTejun Heo }
2674197f6accSTejun Heo 
26754690c4abSTejun Heo /**
26764690c4abSTejun Heo  * worker_thread - the worker thread function
2677c34056a3STejun Heo  * @__worker: self
26784690c4abSTejun Heo  *
2679c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2680c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2681c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2682c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2683c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
2684d185af30SYacine Belkadi  *
2685d185af30SYacine Belkadi  * Return: 0
26864690c4abSTejun Heo  */
2687c34056a3STejun Heo static int worker_thread(void *__worker)
26881da177e4SLinus Torvalds {
2689c34056a3STejun Heo 	struct worker *worker = __worker;
2690bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
26911da177e4SLinus Torvalds 
2692e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2693197f6accSTejun Heo 	set_pf_worker(true);
2694c8e55f36STejun Heo woke_up:
2695a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2696affee4b2STejun Heo 
2697a9ab775bSTejun Heo 	/* am I supposed to die? */
2698a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2699a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
2700197f6accSTejun Heo 		set_pf_worker(false);
270160f5a4bcSLai Jiangshan 
270260f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
2703e441b56fSZhen Lei 		ida_free(&pool->worker_ida, worker->id);
2704a2d812a2STejun Heo 		worker_detach_from_pool(worker);
2705e02b9312SValentin Schneider 		WARN_ON_ONCE(!list_empty(&worker->entry));
270660f5a4bcSLai Jiangshan 		kfree(worker);
2707c8e55f36STejun Heo 		return 0;
2708c8e55f36STejun Heo 	}
2709c8e55f36STejun Heo 
2710c8e55f36STejun Heo 	worker_leave_idle(worker);
2711db7bccf4STejun Heo recheck:
2712e22bee78STejun Heo 	/* no more worker necessary? */
271363d95a91STejun Heo 	if (!need_more_worker(pool))
2714e22bee78STejun Heo 		goto sleep;
2715e22bee78STejun Heo 
2716e22bee78STejun Heo 	/* do we need to manage? */
271763d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2718e22bee78STejun Heo 		goto recheck;
2719e22bee78STejun Heo 
2720c8e55f36STejun Heo 	/*
2721c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2722c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2723c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2724c8e55f36STejun Heo 	 */
27256183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2726c8e55f36STejun Heo 
2727e22bee78STejun Heo 	/*
2728a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2729a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2730a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2731a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2732a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2733e22bee78STejun Heo 	 */
2734a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2735e22bee78STejun Heo 
2736e22bee78STejun Heo 	do {
2737affee4b2STejun Heo 		struct work_struct *work =
2738bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2739affee4b2STejun Heo 					 struct work_struct, entry);
2740affee4b2STejun Heo 
2741c8e55f36STejun Heo 		move_linked_works(work, &worker->scheduled, NULL);
2742affee4b2STejun Heo 		process_scheduled_works(worker);
274363d95a91STejun Heo 	} while (keep_working(pool));
2744affee4b2STejun Heo 
2745228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
2746d313dd85STejun Heo sleep:
2747c8e55f36STejun Heo 	/*
2748d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2749d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2750d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2751d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2752d565ed63STejun Heo 	 * event.
2753c8e55f36STejun Heo 	 */
2754c8e55f36STejun Heo 	worker_enter_idle(worker);
2755c5a94a61SPeter Zijlstra 	__set_current_state(TASK_IDLE);
2756a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
27571da177e4SLinus Torvalds 	schedule();
2758c8e55f36STejun Heo 	goto woke_up;
27591da177e4SLinus Torvalds }
27601da177e4SLinus Torvalds 
2761e22bee78STejun Heo /**
2762e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2763111c225aSTejun Heo  * @__rescuer: self
2764e22bee78STejun Heo  *
2765e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2766493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2767e22bee78STejun Heo  *
2768706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2769e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2770e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2771e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2772e22bee78STejun Heo  * the problem rescuer solves.
2773e22bee78STejun Heo  *
2774706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2775706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2776e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2777e22bee78STejun Heo  *
2778e22bee78STejun Heo  * This should happen rarely.
2779d185af30SYacine Belkadi  *
2780d185af30SYacine Belkadi  * Return: 0
2781e22bee78STejun Heo  */
2782111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2783e22bee78STejun Heo {
2784111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2785111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2786e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
27874d595b86SLai Jiangshan 	bool should_stop;
2788e22bee78STejun Heo 
2789e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2790111c225aSTejun Heo 
2791111c225aSTejun Heo 	/*
2792111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2793111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2794111c225aSTejun Heo 	 */
2795197f6accSTejun Heo 	set_pf_worker(true);
2796e22bee78STejun Heo repeat:
2797c5a94a61SPeter Zijlstra 	set_current_state(TASK_IDLE);
27981da177e4SLinus Torvalds 
27994d595b86SLai Jiangshan 	/*
28004d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
28014d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
28024d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
28034d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
28044d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
28054d595b86SLai Jiangshan 	 * list is always empty on exit.
28064d595b86SLai Jiangshan 	 */
28074d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
28081da177e4SLinus Torvalds 
2809493a1724STejun Heo 	/* see whether any pwq is asking for help */
2810a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq_mayday_lock);
2811493a1724STejun Heo 
2812493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2813493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2814493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2815112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2816e22bee78STejun Heo 		struct work_struct *work, *n;
2817e22bee78STejun Heo 
2818e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2819493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2820493a1724STejun Heo 
2821a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
2822e22bee78STejun Heo 
282351697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
282451697d39SLai Jiangshan 
2825a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
2826e22bee78STejun Heo 
2827e22bee78STejun Heo 		/*
2828e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2829e22bee78STejun Heo 		 * process'em.
2830e22bee78STejun Heo 		 */
28310479c8c5STejun Heo 		WARN_ON_ONCE(!list_empty(scheduled));
283282607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
283382607adcSTejun Heo 			if (get_work_pwq(work) == pwq) {
2834e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
2835725e8ec5STejun Heo 				pwq->stats[PWQ_STAT_RESCUED]++;
283682607adcSTejun Heo 			}
283782607adcSTejun Heo 		}
2838e22bee78STejun Heo 
2839008847f6SNeilBrown 		if (!list_empty(scheduled)) {
2840e22bee78STejun Heo 			process_scheduled_works(rescuer);
28417576958aSTejun Heo 
28427576958aSTejun Heo 			/*
2843008847f6SNeilBrown 			 * The above execution of rescued work items could
2844008847f6SNeilBrown 			 * have created more to rescue through
2845f97a4a1aSLai Jiangshan 			 * pwq_activate_first_inactive() or chained
2846008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
2847008847f6SNeilBrown 			 * that such back-to-back work items, which may be
2848008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
2849008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
2850008847f6SNeilBrown 			 */
28514f3f4cf3SLai Jiangshan 			if (pwq->nr_active && need_to_create_worker(pool)) {
2852a9b8a985SSebastian Andrzej Siewior 				raw_spin_lock(&wq_mayday_lock);
2853e66b39afSTejun Heo 				/*
2854e66b39afSTejun Heo 				 * Queue iff we aren't racing destruction
2855e66b39afSTejun Heo 				 * and somebody else hasn't queued it already.
2856e66b39afSTejun Heo 				 */
2857e66b39afSTejun Heo 				if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2858008847f6SNeilBrown 					get_pwq(pwq);
2859e66b39afSTejun Heo 					list_add_tail(&pwq->mayday_node, &wq->maydays);
2860e66b39afSTejun Heo 				}
2861a9b8a985SSebastian Andrzej Siewior 				raw_spin_unlock(&wq_mayday_lock);
2862008847f6SNeilBrown 			}
2863008847f6SNeilBrown 		}
2864008847f6SNeilBrown 
2865008847f6SNeilBrown 		/*
286677668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
286713b1d625SLai Jiangshan 		 * go away while we're still attached to it.
286877668c8bSLai Jiangshan 		 */
286977668c8bSLai Jiangshan 		put_pwq(pwq);
287077668c8bSLai Jiangshan 
287177668c8bSLai Jiangshan 		/*
2872d8ca83e6SLai Jiangshan 		 * Leave this pool.  If need_more_worker() is %true, notify a
28737576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
28747576958aSTejun Heo 		 * and stalling the execution.
28757576958aSTejun Heo 		 */
2876d8ca83e6SLai Jiangshan 		if (need_more_worker(pool))
287763d95a91STejun Heo 			wake_up_worker(pool);
28787576958aSTejun Heo 
2879a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
288013b1d625SLai Jiangshan 
2881a2d812a2STejun Heo 		worker_detach_from_pool(rescuer);
288213b1d625SLai Jiangshan 
2883a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
28841da177e4SLinus Torvalds 	}
28851da177e4SLinus Torvalds 
2886a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq_mayday_lock);
2887493a1724STejun Heo 
28884d595b86SLai Jiangshan 	if (should_stop) {
28894d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
2890197f6accSTejun Heo 		set_pf_worker(false);
28914d595b86SLai Jiangshan 		return 0;
28924d595b86SLai Jiangshan 	}
28934d595b86SLai Jiangshan 
2894111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2895111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2896e22bee78STejun Heo 	schedule();
2897e22bee78STejun Heo 	goto repeat;
28981da177e4SLinus Torvalds }
28991da177e4SLinus Torvalds 
2900fca839c0STejun Heo /**
2901fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
2902fca839c0STejun Heo  * @target_wq: workqueue being flushed
2903fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
2904fca839c0STejun Heo  *
2905fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
2906fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2907fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
2908fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2909fca839c0STejun Heo  * a deadlock.
2910fca839c0STejun Heo  */
2911fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
2912fca839c0STejun Heo 				   struct work_struct *target_work)
2913fca839c0STejun Heo {
2914fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
2915fca839c0STejun Heo 	struct worker *worker;
2916fca839c0STejun Heo 
2917fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
2918fca839c0STejun Heo 		return;
2919fca839c0STejun Heo 
2920fca839c0STejun Heo 	worker = current_wq_worker();
2921fca839c0STejun Heo 
2922fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
2923d75f773cSSakari Ailus 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
2924fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
292523d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
292623d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2927d75f773cSSakari Ailus 		  "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
2928fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
2929fca839c0STejun Heo 		  target_wq->name, target_func);
2930fca839c0STejun Heo }
2931fca839c0STejun Heo 
2932fc2e4d70SOleg Nesterov struct wq_barrier {
2933fc2e4d70SOleg Nesterov 	struct work_struct	work;
2934fc2e4d70SOleg Nesterov 	struct completion	done;
29352607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
2936fc2e4d70SOleg Nesterov };
2937fc2e4d70SOleg Nesterov 
2938fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2939fc2e4d70SOleg Nesterov {
2940fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2941fc2e4d70SOleg Nesterov 	complete(&barr->done);
2942fc2e4d70SOleg Nesterov }
2943fc2e4d70SOleg Nesterov 
29444690c4abSTejun Heo /**
29454690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2946112202d9STejun Heo  * @pwq: pwq to insert barrier into
29474690c4abSTejun Heo  * @barr: wq_barrier to insert
2948affee4b2STejun Heo  * @target: target work to attach @barr to
2949affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
29504690c4abSTejun Heo  *
2951affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2952affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2953affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2954affee4b2STejun Heo  * cpu.
2955affee4b2STejun Heo  *
2956affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2957affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2958affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2959affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2960affee4b2STejun Heo  * after a work with LINKED flag set.
2961affee4b2STejun Heo  *
2962affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2963112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
29644690c4abSTejun Heo  *
29654690c4abSTejun Heo  * CONTEXT:
2966a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
29674690c4abSTejun Heo  */
2968112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2969affee4b2STejun Heo 			      struct wq_barrier *barr,
2970affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2971fc2e4d70SOleg Nesterov {
2972d812796eSLai Jiangshan 	unsigned int work_flags = 0;
2973d812796eSLai Jiangshan 	unsigned int work_color;
2974affee4b2STejun Heo 	struct list_head *head;
2975affee4b2STejun Heo 
2976dc186ad7SThomas Gleixner 	/*
2977d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2978dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2979dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2980dc186ad7SThomas Gleixner 	 * might deadlock.
2981dc186ad7SThomas Gleixner 	 */
2982ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
298322df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
298452fa5bc5SBoqun Feng 
2985fd1a5b04SByungchul Park 	init_completion_map(&barr->done, &target->lockdep_map);
2986fd1a5b04SByungchul Park 
29872607d7a6STejun Heo 	barr->task = current;
298883c22520SOleg Nesterov 
2989018f3a13SLai Jiangshan 	/* The barrier work item does not participate in pwq->nr_active. */
2990018f3a13SLai Jiangshan 	work_flags |= WORK_STRUCT_INACTIVE;
2991018f3a13SLai Jiangshan 
2992affee4b2STejun Heo 	/*
2993affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2994affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2995affee4b2STejun Heo 	 */
2996d812796eSLai Jiangshan 	if (worker) {
2997affee4b2STejun Heo 		head = worker->scheduled.next;
2998d812796eSLai Jiangshan 		work_color = worker->current_color;
2999d812796eSLai Jiangshan 	} else {
3000affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
3001affee4b2STejun Heo 
3002affee4b2STejun Heo 		head = target->entry.next;
3003affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
3004d21cece0SLai Jiangshan 		work_flags |= *bits & WORK_STRUCT_LINKED;
3005d812796eSLai Jiangshan 		work_color = get_work_color(*bits);
3006affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
3007affee4b2STejun Heo 	}
3008affee4b2STejun Heo 
3009d812796eSLai Jiangshan 	pwq->nr_in_flight[work_color]++;
3010d812796eSLai Jiangshan 	work_flags |= work_color_to_flags(work_color);
3011d812796eSLai Jiangshan 
3012d21cece0SLai Jiangshan 	insert_work(pwq, &barr->work, head, work_flags);
3013fc2e4d70SOleg Nesterov }
3014fc2e4d70SOleg Nesterov 
301573f53c4aSTejun Heo /**
3016112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
301773f53c4aSTejun Heo  * @wq: workqueue being flushed
301873f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
301973f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
302073f53c4aSTejun Heo  *
3021112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
302273f53c4aSTejun Heo  *
3023112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
3024112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
3025112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
3026112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
3027112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
302873f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
302973f53c4aSTejun Heo  *
303073f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
303173f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
303273f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
303373f53c4aSTejun Heo  * is returned.
303473f53c4aSTejun Heo  *
3035112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
303673f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
303773f53c4aSTejun Heo  * advanced to @work_color.
303873f53c4aSTejun Heo  *
303973f53c4aSTejun Heo  * CONTEXT:
30403c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
304173f53c4aSTejun Heo  *
3042d185af30SYacine Belkadi  * Return:
304373f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
304473f53c4aSTejun Heo  * otherwise.
304573f53c4aSTejun Heo  */
3046112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
304773f53c4aSTejun Heo 				      int flush_color, int work_color)
30481da177e4SLinus Torvalds {
304973f53c4aSTejun Heo 	bool wait = false;
305049e3cf44STejun Heo 	struct pool_workqueue *pwq;
30511da177e4SLinus Torvalds 
305273f53c4aSTejun Heo 	if (flush_color >= 0) {
30536183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
3054112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
3055dc186ad7SThomas Gleixner 	}
305614441960SOleg Nesterov 
305749e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3058112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
30591da177e4SLinus Torvalds 
3060a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
306173f53c4aSTejun Heo 
306273f53c4aSTejun Heo 		if (flush_color >= 0) {
30636183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
306473f53c4aSTejun Heo 
3065112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
3066112202d9STejun Heo 				pwq->flush_color = flush_color;
3067112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
306873f53c4aSTejun Heo 				wait = true;
30691da177e4SLinus Torvalds 			}
307073f53c4aSTejun Heo 		}
307173f53c4aSTejun Heo 
307273f53c4aSTejun Heo 		if (work_color >= 0) {
30736183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
3074112202d9STejun Heo 			pwq->work_color = work_color;
307573f53c4aSTejun Heo 		}
307673f53c4aSTejun Heo 
3077a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
30781da177e4SLinus Torvalds 	}
30791da177e4SLinus Torvalds 
3080112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
308173f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
308273f53c4aSTejun Heo 
308373f53c4aSTejun Heo 	return wait;
308483c22520SOleg Nesterov }
30851da177e4SLinus Torvalds 
30860fcb78c2SRolf Eike Beer /**
3087c4f135d6STetsuo Handa  * __flush_workqueue - ensure that any scheduled work has run to completion.
30880fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
30891da177e4SLinus Torvalds  *
3090c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
3091c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
30921da177e4SLinus Torvalds  */
3093c4f135d6STetsuo Handa void __flush_workqueue(struct workqueue_struct *wq)
30941da177e4SLinus Torvalds {
309573f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
309673f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
309773f53c4aSTejun Heo 		.flush_color = -1,
3098fd1a5b04SByungchul Park 		.done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
309973f53c4aSTejun Heo 	};
310073f53c4aSTejun Heo 	int next_color;
3101b1f4ec17SOleg Nesterov 
31023347fa09STejun Heo 	if (WARN_ON(!wq_online))
31033347fa09STejun Heo 		return;
31043347fa09STejun Heo 
310587915adcSJohannes Berg 	lock_map_acquire(&wq->lockdep_map);
310687915adcSJohannes Berg 	lock_map_release(&wq->lockdep_map);
310787915adcSJohannes Berg 
31083c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
310973f53c4aSTejun Heo 
311073f53c4aSTejun Heo 	/*
311173f53c4aSTejun Heo 	 * Start-to-wait phase
311273f53c4aSTejun Heo 	 */
311373f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
311473f53c4aSTejun Heo 
311573f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
311673f53c4aSTejun Heo 		/*
311773f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
311873f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
311973f53c4aSTejun Heo 		 * by one.
312073f53c4aSTejun Heo 		 */
31216183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
312273f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
312373f53c4aSTejun Heo 		wq->work_color = next_color;
312473f53c4aSTejun Heo 
312573f53c4aSTejun Heo 		if (!wq->first_flusher) {
312673f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
31276183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
312873f53c4aSTejun Heo 
312973f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
313073f53c4aSTejun Heo 
3131112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
313273f53c4aSTejun Heo 						       wq->work_color)) {
313373f53c4aSTejun Heo 				/* nothing to flush, done */
313473f53c4aSTejun Heo 				wq->flush_color = next_color;
313573f53c4aSTejun Heo 				wq->first_flusher = NULL;
313673f53c4aSTejun Heo 				goto out_unlock;
313773f53c4aSTejun Heo 			}
313873f53c4aSTejun Heo 		} else {
313973f53c4aSTejun Heo 			/* wait in queue */
31406183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
314173f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
3142112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
314373f53c4aSTejun Heo 		}
314473f53c4aSTejun Heo 	} else {
314573f53c4aSTejun Heo 		/*
314673f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
314773f53c4aSTejun Heo 		 * The next flush completion will assign us
314873f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
314973f53c4aSTejun Heo 		 */
315073f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
315173f53c4aSTejun Heo 	}
315273f53c4aSTejun Heo 
3153fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
3154fca839c0STejun Heo 
31553c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
315673f53c4aSTejun Heo 
315773f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
315873f53c4aSTejun Heo 
315973f53c4aSTejun Heo 	/*
316073f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
316173f53c4aSTejun Heo 	 *
316273f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
316373f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
316473f53c4aSTejun Heo 	 */
316500d5d15bSChris Wilson 	if (READ_ONCE(wq->first_flusher) != &this_flusher)
316673f53c4aSTejun Heo 		return;
316773f53c4aSTejun Heo 
31683c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
316973f53c4aSTejun Heo 
31704ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
31714ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
31724ce48b37STejun Heo 		goto out_unlock;
31734ce48b37STejun Heo 
317400d5d15bSChris Wilson 	WRITE_ONCE(wq->first_flusher, NULL);
317573f53c4aSTejun Heo 
31766183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
31776183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
317873f53c4aSTejun Heo 
317973f53c4aSTejun Heo 	while (true) {
318073f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
318173f53c4aSTejun Heo 
318273f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
318373f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
318473f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
318573f53c4aSTejun Heo 				break;
318673f53c4aSTejun Heo 			list_del_init(&next->list);
318773f53c4aSTejun Heo 			complete(&next->done);
318873f53c4aSTejun Heo 		}
318973f53c4aSTejun Heo 
31906183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
319173f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
319273f53c4aSTejun Heo 
319373f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
319473f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
319573f53c4aSTejun Heo 
319673f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
319773f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
319873f53c4aSTejun Heo 			/*
319973f53c4aSTejun Heo 			 * Assign the same color to all overflowed
320073f53c4aSTejun Heo 			 * flushers, advance work_color and append to
320173f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
320273f53c4aSTejun Heo 			 * phase for these overflowed flushers.
320373f53c4aSTejun Heo 			 */
320473f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
320573f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
320673f53c4aSTejun Heo 
320773f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
320873f53c4aSTejun Heo 
320973f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
321073f53c4aSTejun Heo 					      &wq->flusher_queue);
3211112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
321273f53c4aSTejun Heo 		}
321373f53c4aSTejun Heo 
321473f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
32156183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
321673f53c4aSTejun Heo 			break;
321773f53c4aSTejun Heo 		}
321873f53c4aSTejun Heo 
321973f53c4aSTejun Heo 		/*
322073f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
3221112202d9STejun Heo 		 * the new first flusher and arm pwqs.
322273f53c4aSTejun Heo 		 */
32236183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
32246183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
322573f53c4aSTejun Heo 
322673f53c4aSTejun Heo 		list_del_init(&next->list);
322773f53c4aSTejun Heo 		wq->first_flusher = next;
322873f53c4aSTejun Heo 
3229112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
323073f53c4aSTejun Heo 			break;
323173f53c4aSTejun Heo 
323273f53c4aSTejun Heo 		/*
323373f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
323473f53c4aSTejun Heo 		 * flusher and repeat cascading.
323573f53c4aSTejun Heo 		 */
323673f53c4aSTejun Heo 		wq->first_flusher = NULL;
323773f53c4aSTejun Heo 	}
323873f53c4aSTejun Heo 
323973f53c4aSTejun Heo out_unlock:
32403c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
32411da177e4SLinus Torvalds }
3242c4f135d6STetsuo Handa EXPORT_SYMBOL(__flush_workqueue);
32431da177e4SLinus Torvalds 
32449c5a2ba7STejun Heo /**
32459c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
32469c5a2ba7STejun Heo  * @wq: workqueue to drain
32479c5a2ba7STejun Heo  *
32489c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
32499c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
32509c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
3251b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
32529c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
32539c5a2ba7STejun Heo  * takes too long.
32549c5a2ba7STejun Heo  */
32559c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
32569c5a2ba7STejun Heo {
32579c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
325849e3cf44STejun Heo 	struct pool_workqueue *pwq;
32599c5a2ba7STejun Heo 
32609c5a2ba7STejun Heo 	/*
32619c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
32629c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
3263618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
32649c5a2ba7STejun Heo 	 */
326587fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
32669c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
3267618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
326887fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
32699c5a2ba7STejun Heo reflush:
3270c4f135d6STetsuo Handa 	__flush_workqueue(wq);
32719c5a2ba7STejun Heo 
3272b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
327376af4d93STejun Heo 
327449e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3275fa2563e4SThomas Tuttle 		bool drained;
32769c5a2ba7STejun Heo 
3277a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
3278f97a4a1aSLai Jiangshan 		drained = !pwq->nr_active && list_empty(&pwq->inactive_works);
3279a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
3280fa2563e4SThomas Tuttle 
3281fa2563e4SThomas Tuttle 		if (drained)
32829c5a2ba7STejun Heo 			continue;
32839c5a2ba7STejun Heo 
32849c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
32859c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
3286e9ad2eb3SStephen Zhang 			pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3287e9ad2eb3SStephen Zhang 				wq->name, __func__, flush_cnt);
328876af4d93STejun Heo 
3289b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
32909c5a2ba7STejun Heo 		goto reflush;
32919c5a2ba7STejun Heo 	}
32929c5a2ba7STejun Heo 
32939c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
3294618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
329587fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
32969c5a2ba7STejun Heo }
32979c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
32989c5a2ba7STejun Heo 
3299d6e89786SJohannes Berg static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3300d6e89786SJohannes Berg 			     bool from_cancel)
3301baf59022STejun Heo {
3302baf59022STejun Heo 	struct worker *worker = NULL;
3303c9e7cf27STejun Heo 	struct worker_pool *pool;
3304112202d9STejun Heo 	struct pool_workqueue *pwq;
3305baf59022STejun Heo 
3306baf59022STejun Heo 	might_sleep();
3307baf59022STejun Heo 
330824acfb71SThomas Gleixner 	rcu_read_lock();
3309fa1b54e6STejun Heo 	pool = get_work_pool(work);
3310fa1b54e6STejun Heo 	if (!pool) {
331124acfb71SThomas Gleixner 		rcu_read_unlock();
3312fa1b54e6STejun Heo 		return false;
3313fa1b54e6STejun Heo 	}
3314fa1b54e6STejun Heo 
3315a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
33160b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
3317112202d9STejun Heo 	pwq = get_work_pwq(work);
3318112202d9STejun Heo 	if (pwq) {
3319112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
3320baf59022STejun Heo 			goto already_gone;
3321606a5020STejun Heo 	} else {
3322c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
3323baf59022STejun Heo 		if (!worker)
3324baf59022STejun Heo 			goto already_gone;
3325112202d9STejun Heo 		pwq = worker->current_pwq;
3326606a5020STejun Heo 	}
3327baf59022STejun Heo 
3328fca839c0STejun Heo 	check_flush_dependency(pwq->wq, work);
3329fca839c0STejun Heo 
3330112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
3331a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
3332baf59022STejun Heo 
3333e159489bSTejun Heo 	/*
3334a1d14934SPeter Zijlstra 	 * Force a lock recursion deadlock when using flush_work() inside a
3335a1d14934SPeter Zijlstra 	 * single-threaded or rescuer equipped workqueue.
3336a1d14934SPeter Zijlstra 	 *
3337a1d14934SPeter Zijlstra 	 * For single threaded workqueues the deadlock happens when the work
3338a1d14934SPeter Zijlstra 	 * is after the work issuing the flush_work(). For rescuer equipped
3339a1d14934SPeter Zijlstra 	 * workqueues the deadlock happens when the rescuer stalls, blocking
3340a1d14934SPeter Zijlstra 	 * forward progress.
3341e159489bSTejun Heo 	 */
3342d6e89786SJohannes Berg 	if (!from_cancel &&
3343d6e89786SJohannes Berg 	    (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
3344112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
3345112202d9STejun Heo 		lock_map_release(&pwq->wq->lockdep_map);
3346a1d14934SPeter Zijlstra 	}
334724acfb71SThomas Gleixner 	rcu_read_unlock();
3348baf59022STejun Heo 	return true;
3349baf59022STejun Heo already_gone:
3350a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
335124acfb71SThomas Gleixner 	rcu_read_unlock();
3352baf59022STejun Heo 	return false;
3353baf59022STejun Heo }
3354baf59022STejun Heo 
3355d6e89786SJohannes Berg static bool __flush_work(struct work_struct *work, bool from_cancel)
3356d6e89786SJohannes Berg {
3357d6e89786SJohannes Berg 	struct wq_barrier barr;
3358d6e89786SJohannes Berg 
3359d6e89786SJohannes Berg 	if (WARN_ON(!wq_online))
3360d6e89786SJohannes Berg 		return false;
3361d6e89786SJohannes Berg 
33624d43d395STetsuo Handa 	if (WARN_ON(!work->func))
33634d43d395STetsuo Handa 		return false;
33644d43d395STetsuo Handa 
336587915adcSJohannes Berg 	lock_map_acquire(&work->lockdep_map);
336687915adcSJohannes Berg 	lock_map_release(&work->lockdep_map);
336787915adcSJohannes Berg 
3368d6e89786SJohannes Berg 	if (start_flush_work(work, &barr, from_cancel)) {
3369d6e89786SJohannes Berg 		wait_for_completion(&barr.done);
3370d6e89786SJohannes Berg 		destroy_work_on_stack(&barr.work);
3371d6e89786SJohannes Berg 		return true;
3372d6e89786SJohannes Berg 	} else {
3373d6e89786SJohannes Berg 		return false;
3374d6e89786SJohannes Berg 	}
3375d6e89786SJohannes Berg }
3376d6e89786SJohannes Berg 
3377db700897SOleg Nesterov /**
3378401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
3379401a8d04STejun Heo  * @work: the work to flush
3380db700897SOleg Nesterov  *
3381606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
3382606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
3383401a8d04STejun Heo  *
3384d185af30SYacine Belkadi  * Return:
3385401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3386401a8d04STejun Heo  * %false if it was already idle.
3387db700897SOleg Nesterov  */
3388401a8d04STejun Heo bool flush_work(struct work_struct *work)
3389db700897SOleg Nesterov {
3390d6e89786SJohannes Berg 	return __flush_work(work, false);
3391606a5020STejun Heo }
3392db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
3393db700897SOleg Nesterov 
33948603e1b3STejun Heo struct cwt_wait {
3395ac6424b9SIngo Molnar 	wait_queue_entry_t		wait;
33968603e1b3STejun Heo 	struct work_struct	*work;
33978603e1b3STejun Heo };
33988603e1b3STejun Heo 
3399ac6424b9SIngo Molnar static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
34008603e1b3STejun Heo {
34018603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
34028603e1b3STejun Heo 
34038603e1b3STejun Heo 	if (cwait->work != key)
34048603e1b3STejun Heo 		return 0;
34058603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
34068603e1b3STejun Heo }
34078603e1b3STejun Heo 
340836e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3409401a8d04STejun Heo {
34108603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3411bbb68dfaSTejun Heo 	unsigned long flags;
34121f1f642eSOleg Nesterov 	int ret;
34131f1f642eSOleg Nesterov 
34141f1f642eSOleg Nesterov 	do {
3415bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
3416bbb68dfaSTejun Heo 		/*
34178603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
34188603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
34198603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
34208603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
34218603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
34228603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
34238603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
34248603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
34258603e1b3STejun Heo 		 * we're hogging the CPU.
34268603e1b3STejun Heo 		 *
34278603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
34288603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
34298603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
34308603e1b3STejun Heo 		 * wait and wakeup.
3431bbb68dfaSTejun Heo 		 */
34328603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
34338603e1b3STejun Heo 			struct cwt_wait cwait;
34348603e1b3STejun Heo 
34358603e1b3STejun Heo 			init_wait(&cwait.wait);
34368603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
34378603e1b3STejun Heo 			cwait.work = work;
34388603e1b3STejun Heo 
34398603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
34408603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
34418603e1b3STejun Heo 			if (work_is_canceling(work))
34428603e1b3STejun Heo 				schedule();
34438603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
34448603e1b3STejun Heo 		}
34451f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
34461f1f642eSOleg Nesterov 
3447bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
3448bbb68dfaSTejun Heo 	mark_work_canceling(work);
3449bbb68dfaSTejun Heo 	local_irq_restore(flags);
3450bbb68dfaSTejun Heo 
34513347fa09STejun Heo 	/*
34523347fa09STejun Heo 	 * This allows canceling during early boot.  We know that @work
34533347fa09STejun Heo 	 * isn't executing.
34543347fa09STejun Heo 	 */
34553347fa09STejun Heo 	if (wq_online)
3456d6e89786SJohannes Berg 		__flush_work(work, true);
34573347fa09STejun Heo 
34587a22ad75STejun Heo 	clear_work_data(work);
34598603e1b3STejun Heo 
34608603e1b3STejun Heo 	/*
34618603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
34628603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
34638603e1b3STejun Heo 	 * visible there.
34648603e1b3STejun Heo 	 */
34658603e1b3STejun Heo 	smp_mb();
34668603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
34678603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
34688603e1b3STejun Heo 
34691f1f642eSOleg Nesterov 	return ret;
34701f1f642eSOleg Nesterov }
34711f1f642eSOleg Nesterov 
34726e84d644SOleg Nesterov /**
3473401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
3474401a8d04STejun Heo  * @work: the work to cancel
34756e84d644SOleg Nesterov  *
3476401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
3477401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
3478401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
3479401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
34801f1f642eSOleg Nesterov  *
3481401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
3482401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
34836e84d644SOleg Nesterov  *
3484401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
34856e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
3486401a8d04STejun Heo  *
3487d185af30SYacine Belkadi  * Return:
3488401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
34896e84d644SOleg Nesterov  */
3490401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
34916e84d644SOleg Nesterov {
349236e227d2STejun Heo 	return __cancel_work_timer(work, false);
3493b89deed3SOleg Nesterov }
349428e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
3495b89deed3SOleg Nesterov 
34966e84d644SOleg Nesterov /**
3497401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
3498401a8d04STejun Heo  * @dwork: the delayed work to flush
34996e84d644SOleg Nesterov  *
3500401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
3501401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
3502401a8d04STejun Heo  * considers the last queueing instance of @dwork.
35031f1f642eSOleg Nesterov  *
3504d185af30SYacine Belkadi  * Return:
3505401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3506401a8d04STejun Heo  * %false if it was already idle.
35076e84d644SOleg Nesterov  */
3508401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
3509401a8d04STejun Heo {
35108930cabaSTejun Heo 	local_irq_disable();
3511401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
351260c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
35138930cabaSTejun Heo 	local_irq_enable();
3514401a8d04STejun Heo 	return flush_work(&dwork->work);
3515401a8d04STejun Heo }
3516401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3517401a8d04STejun Heo 
351805f0fe6bSTejun Heo /**
351905f0fe6bSTejun Heo  * flush_rcu_work - wait for a rwork to finish executing the last queueing
352005f0fe6bSTejun Heo  * @rwork: the rcu work to flush
352105f0fe6bSTejun Heo  *
352205f0fe6bSTejun Heo  * Return:
352305f0fe6bSTejun Heo  * %true if flush_rcu_work() waited for the work to finish execution,
352405f0fe6bSTejun Heo  * %false if it was already idle.
352505f0fe6bSTejun Heo  */
352605f0fe6bSTejun Heo bool flush_rcu_work(struct rcu_work *rwork)
352705f0fe6bSTejun Heo {
352805f0fe6bSTejun Heo 	if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
352905f0fe6bSTejun Heo 		rcu_barrier();
353005f0fe6bSTejun Heo 		flush_work(&rwork->work);
353105f0fe6bSTejun Heo 		return true;
353205f0fe6bSTejun Heo 	} else {
353305f0fe6bSTejun Heo 		return flush_work(&rwork->work);
353405f0fe6bSTejun Heo 	}
353505f0fe6bSTejun Heo }
353605f0fe6bSTejun Heo EXPORT_SYMBOL(flush_rcu_work);
353705f0fe6bSTejun Heo 
3538f72b8792SJens Axboe static bool __cancel_work(struct work_struct *work, bool is_dwork)
3539f72b8792SJens Axboe {
3540f72b8792SJens Axboe 	unsigned long flags;
3541f72b8792SJens Axboe 	int ret;
3542f72b8792SJens Axboe 
3543f72b8792SJens Axboe 	do {
3544f72b8792SJens Axboe 		ret = try_to_grab_pending(work, is_dwork, &flags);
3545f72b8792SJens Axboe 	} while (unlikely(ret == -EAGAIN));
3546f72b8792SJens Axboe 
3547f72b8792SJens Axboe 	if (unlikely(ret < 0))
3548f72b8792SJens Axboe 		return false;
3549f72b8792SJens Axboe 
3550f72b8792SJens Axboe 	set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3551f72b8792SJens Axboe 	local_irq_restore(flags);
3552f72b8792SJens Axboe 	return ret;
3553f72b8792SJens Axboe }
3554f72b8792SJens Axboe 
355573b4b532SAndrey Grodzovsky /*
355673b4b532SAndrey Grodzovsky  * See cancel_delayed_work()
355773b4b532SAndrey Grodzovsky  */
355873b4b532SAndrey Grodzovsky bool cancel_work(struct work_struct *work)
355973b4b532SAndrey Grodzovsky {
356073b4b532SAndrey Grodzovsky 	return __cancel_work(work, false);
356173b4b532SAndrey Grodzovsky }
356273b4b532SAndrey Grodzovsky EXPORT_SYMBOL(cancel_work);
356373b4b532SAndrey Grodzovsky 
3564401a8d04STejun Heo /**
356557b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
356657b30ae7STejun Heo  * @dwork: delayed_work to cancel
356709383498STejun Heo  *
3568d185af30SYacine Belkadi  * Kill off a pending delayed_work.
3569d185af30SYacine Belkadi  *
3570d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
3571d185af30SYacine Belkadi  * pending.
3572d185af30SYacine Belkadi  *
3573d185af30SYacine Belkadi  * Note:
3574d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
3575d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
3576d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
357709383498STejun Heo  *
357857b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
357909383498STejun Heo  */
358057b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
358109383498STejun Heo {
3582f72b8792SJens Axboe 	return __cancel_work(&dwork->work, true);
358309383498STejun Heo }
358457b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
358509383498STejun Heo 
358609383498STejun Heo /**
3587401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3588401a8d04STejun Heo  * @dwork: the delayed work cancel
3589401a8d04STejun Heo  *
3590401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
3591401a8d04STejun Heo  *
3592d185af30SYacine Belkadi  * Return:
3593401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
3594401a8d04STejun Heo  */
3595401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
35966e84d644SOleg Nesterov {
359736e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
35986e84d644SOleg Nesterov }
3599f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
36001da177e4SLinus Torvalds 
36010fcb78c2SRolf Eike Beer /**
360231ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3603b6136773SAndrew Morton  * @func: the function to call
3604b6136773SAndrew Morton  *
360531ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
360631ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3607b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
360831ddd871STejun Heo  *
3609d185af30SYacine Belkadi  * Return:
361031ddd871STejun Heo  * 0 on success, -errno on failure.
3611b6136773SAndrew Morton  */
361265f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
361315316ba8SChristoph Lameter {
361415316ba8SChristoph Lameter 	int cpu;
361538f51568SNamhyung Kim 	struct work_struct __percpu *works;
361615316ba8SChristoph Lameter 
3617b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3618b6136773SAndrew Morton 	if (!works)
361915316ba8SChristoph Lameter 		return -ENOMEM;
3620b6136773SAndrew Morton 
3621ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
362293981800STejun Heo 
362315316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
36249bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
36259bfb1839SIngo Molnar 
36269bfb1839SIngo Molnar 		INIT_WORK(work, func);
36278de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
362815316ba8SChristoph Lameter 	}
362993981800STejun Heo 
363093981800STejun Heo 	for_each_online_cpu(cpu)
36318616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
363293981800STejun Heo 
3633ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
3634b6136773SAndrew Morton 	free_percpu(works);
363515316ba8SChristoph Lameter 	return 0;
363615316ba8SChristoph Lameter }
363715316ba8SChristoph Lameter 
3638eef6a7d5SAlan Stern /**
36391fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
36401fa44ecaSJames Bottomley  * @fn:		the function to execute
36411fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
36421fa44ecaSJames Bottomley  *		be available when the work executes)
36431fa44ecaSJames Bottomley  *
36441fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
36451fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
36461fa44ecaSJames Bottomley  *
3647d185af30SYacine Belkadi  * Return:	0 - function was executed
36481fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
36491fa44ecaSJames Bottomley  */
365065f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
36511fa44ecaSJames Bottomley {
36521fa44ecaSJames Bottomley 	if (!in_interrupt()) {
365365f27f38SDavid Howells 		fn(&ew->work);
36541fa44ecaSJames Bottomley 		return 0;
36551fa44ecaSJames Bottomley 	}
36561fa44ecaSJames Bottomley 
365765f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
36581fa44ecaSJames Bottomley 	schedule_work(&ew->work);
36591fa44ecaSJames Bottomley 
36601fa44ecaSJames Bottomley 	return 1;
36611fa44ecaSJames Bottomley }
36621fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
36631fa44ecaSJames Bottomley 
36647a4e344cSTejun Heo /**
36657a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
36667a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
36677a4e344cSTejun Heo  *
36687a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
36697a4e344cSTejun Heo  */
3670513c98d0SDaniel Jordan void free_workqueue_attrs(struct workqueue_attrs *attrs)
36717a4e344cSTejun Heo {
36727a4e344cSTejun Heo 	if (attrs) {
36737a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
36747a4e344cSTejun Heo 		kfree(attrs);
36757a4e344cSTejun Heo 	}
36767a4e344cSTejun Heo }
36777a4e344cSTejun Heo 
36787a4e344cSTejun Heo /**
36797a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
36807a4e344cSTejun Heo  *
36817a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3682d185af30SYacine Belkadi  * return it.
3683d185af30SYacine Belkadi  *
3684d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
36857a4e344cSTejun Heo  */
3686513c98d0SDaniel Jordan struct workqueue_attrs *alloc_workqueue_attrs(void)
36877a4e344cSTejun Heo {
36887a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
36897a4e344cSTejun Heo 
3690be69d00dSThomas Gleixner 	attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
36917a4e344cSTejun Heo 	if (!attrs)
36927a4e344cSTejun Heo 		goto fail;
3693be69d00dSThomas Gleixner 	if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
36947a4e344cSTejun Heo 		goto fail;
36957a4e344cSTejun Heo 
369613e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
36977a4e344cSTejun Heo 	return attrs;
36987a4e344cSTejun Heo fail:
36997a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
37007a4e344cSTejun Heo 	return NULL;
37017a4e344cSTejun Heo }
37027a4e344cSTejun Heo 
370329c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
370429c91e99STejun Heo 				 const struct workqueue_attrs *from)
370529c91e99STejun Heo {
370629c91e99STejun Heo 	to->nice = from->nice;
370729c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
37082865a8fbSShaohua Li 	/*
37092865a8fbSShaohua Li 	 * Unlike hash and equality test, this function doesn't ignore
37102865a8fbSShaohua Li 	 * ->no_numa as it is used for both pool and wq attrs.  Instead,
37112865a8fbSShaohua Li 	 * get_unbound_pool() explicitly clears ->no_numa after copying.
37122865a8fbSShaohua Li 	 */
37132865a8fbSShaohua Li 	to->no_numa = from->no_numa;
371429c91e99STejun Heo }
371529c91e99STejun Heo 
371629c91e99STejun Heo /* hash value of the content of @attr */
371729c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
371829c91e99STejun Heo {
371929c91e99STejun Heo 	u32 hash = 0;
372029c91e99STejun Heo 
372129c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
372213e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
372313e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
372429c91e99STejun Heo 	return hash;
372529c91e99STejun Heo }
372629c91e99STejun Heo 
372729c91e99STejun Heo /* content equality test */
372829c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
372929c91e99STejun Heo 			  const struct workqueue_attrs *b)
373029c91e99STejun Heo {
373129c91e99STejun Heo 	if (a->nice != b->nice)
373229c91e99STejun Heo 		return false;
373329c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
373429c91e99STejun Heo 		return false;
373529c91e99STejun Heo 	return true;
373629c91e99STejun Heo }
373729c91e99STejun Heo 
37387a4e344cSTejun Heo /**
37397a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
37407a4e344cSTejun Heo  * @pool: worker_pool to initialize
37417a4e344cSTejun Heo  *
3742402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3743d185af30SYacine Belkadi  *
3744d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
374529c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
374629c91e99STejun Heo  * on @pool safely to release it.
37477a4e344cSTejun Heo  */
37487a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
37494e1a1f9aSTejun Heo {
3750a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_init(&pool->lock);
375129c91e99STejun Heo 	pool->id = -1;
375229c91e99STejun Heo 	pool->cpu = -1;
3753f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
37544e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
375582607adcSTejun Heo 	pool->watchdog_ts = jiffies;
37564e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
37574e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
37584e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
37594e1a1f9aSTejun Heo 
376032a6c723SKees Cook 	timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
37613f959aa3SValentin Schneider 	INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
37624e1a1f9aSTejun Heo 
376332a6c723SKees Cook 	timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
37644e1a1f9aSTejun Heo 
3765da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
3766e02b9312SValentin Schneider 	INIT_LIST_HEAD(&pool->dying_workers);
37677a4e344cSTejun Heo 
37687cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
376929c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
377029c91e99STejun Heo 	pool->refcnt = 1;
377129c91e99STejun Heo 
377229c91e99STejun Heo 	/* shouldn't fail above this point */
3773be69d00dSThomas Gleixner 	pool->attrs = alloc_workqueue_attrs();
37747a4e344cSTejun Heo 	if (!pool->attrs)
37757a4e344cSTejun Heo 		return -ENOMEM;
37767a4e344cSTejun Heo 	return 0;
37774e1a1f9aSTejun Heo }
37784e1a1f9aSTejun Heo 
3779669de8bdSBart Van Assche #ifdef CONFIG_LOCKDEP
3780669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3781669de8bdSBart Van Assche {
3782669de8bdSBart Van Assche 	char *lock_name;
3783669de8bdSBart Van Assche 
3784669de8bdSBart Van Assche 	lockdep_register_key(&wq->key);
3785669de8bdSBart Van Assche 	lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3786669de8bdSBart Van Assche 	if (!lock_name)
3787669de8bdSBart Van Assche 		lock_name = wq->name;
378869a106c0SQian Cai 
378969a106c0SQian Cai 	wq->lock_name = lock_name;
3790669de8bdSBart Van Assche 	lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3791669de8bdSBart Van Assche }
3792669de8bdSBart Van Assche 
3793669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3794669de8bdSBart Van Assche {
3795669de8bdSBart Van Assche 	lockdep_unregister_key(&wq->key);
3796669de8bdSBart Van Assche }
3797669de8bdSBart Van Assche 
3798669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3799669de8bdSBart Van Assche {
3800669de8bdSBart Van Assche 	if (wq->lock_name != wq->name)
3801669de8bdSBart Van Assche 		kfree(wq->lock_name);
3802669de8bdSBart Van Assche }
3803669de8bdSBart Van Assche #else
3804669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3805669de8bdSBart Van Assche {
3806669de8bdSBart Van Assche }
3807669de8bdSBart Van Assche 
3808669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3809669de8bdSBart Van Assche {
3810669de8bdSBart Van Assche }
3811669de8bdSBart Van Assche 
3812669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3813669de8bdSBart Van Assche {
3814669de8bdSBart Van Assche }
3815669de8bdSBart Van Assche #endif
3816669de8bdSBart Van Assche 
3817e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
3818e2dca7adSTejun Heo {
3819e2dca7adSTejun Heo 	struct workqueue_struct *wq =
3820e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
3821e2dca7adSTejun Heo 
3822669de8bdSBart Van Assche 	wq_free_lockdep(wq);
3823669de8bdSBart Van Assche 
3824e2dca7adSTejun Heo 	if (!(wq->flags & WQ_UNBOUND))
3825ee1ceef7STejun Heo 		free_percpu(wq->cpu_pwq);
3826e2dca7adSTejun Heo 	else
3827e2dca7adSTejun Heo 		free_workqueue_attrs(wq->unbound_attrs);
3828e2dca7adSTejun Heo 
3829e2dca7adSTejun Heo 	kfree(wq);
3830e2dca7adSTejun Heo }
3831e2dca7adSTejun Heo 
383229c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
383329c91e99STejun Heo {
383429c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
383529c91e99STejun Heo 
38367cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
383729c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
383829c91e99STejun Heo 	kfree(pool);
383929c91e99STejun Heo }
384029c91e99STejun Heo 
384129c91e99STejun Heo /**
384229c91e99STejun Heo  * put_unbound_pool - put a worker_pool
384329c91e99STejun Heo  * @pool: worker_pool to put
384429c91e99STejun Heo  *
384524acfb71SThomas Gleixner  * Put @pool.  If its refcnt reaches zero, it gets destroyed in RCU
3846c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3847c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3848c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
3849a892caccSTejun Heo  *
3850a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
385129c91e99STejun Heo  */
385229c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
385329c91e99STejun Heo {
385460f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
385529c91e99STejun Heo 	struct worker *worker;
38569680540cSYang Yingliang 	LIST_HEAD(cull_list);
3857e02b9312SValentin Schneider 
3858a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3859a892caccSTejun Heo 
3860a892caccSTejun Heo 	if (--pool->refcnt)
386129c91e99STejun Heo 		return;
386229c91e99STejun Heo 
386329c91e99STejun Heo 	/* sanity checks */
386461d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
3865a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
386629c91e99STejun Heo 		return;
386729c91e99STejun Heo 
386829c91e99STejun Heo 	/* release id and unhash */
386929c91e99STejun Heo 	if (pool->id >= 0)
387029c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
387129c91e99STejun Heo 	hash_del(&pool->hash_node);
387229c91e99STejun Heo 
3873c5aa87bbSTejun Heo 	/*
3874692b4825STejun Heo 	 * Become the manager and destroy all workers.  This prevents
3875692b4825STejun Heo 	 * @pool's workers from blocking on attach_mutex.  We're the last
3876692b4825STejun Heo 	 * manager and @pool gets freed with the flag set.
38779ab03be4SValentin Schneider 	 *
38789ab03be4SValentin Schneider 	 * Having a concurrent manager is quite unlikely to happen as we can
38799ab03be4SValentin Schneider 	 * only get here with
38809ab03be4SValentin Schneider 	 *   pwq->refcnt == pool->refcnt == 0
38819ab03be4SValentin Schneider 	 * which implies no work queued to the pool, which implies no worker can
38829ab03be4SValentin Schneider 	 * become the manager. However a worker could have taken the role of
38839ab03be4SValentin Schneider 	 * manager before the refcnts dropped to 0, since maybe_create_worker()
38849ab03be4SValentin Schneider 	 * drops pool->lock
3885c5aa87bbSTejun Heo 	 */
38869ab03be4SValentin Schneider 	while (true) {
38879ab03be4SValentin Schneider 		rcuwait_wait_event(&manager_wait,
38889ab03be4SValentin Schneider 				   !(pool->flags & POOL_MANAGER_ACTIVE),
3889d8bb65abSSebastian Andrzej Siewior 				   TASK_UNINTERRUPTIBLE);
3890e02b9312SValentin Schneider 
3891e02b9312SValentin Schneider 		mutex_lock(&wq_pool_attach_mutex);
38929ab03be4SValentin Schneider 		raw_spin_lock_irq(&pool->lock);
38939ab03be4SValentin Schneider 		if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
3894692b4825STejun Heo 			pool->flags |= POOL_MANAGER_ACTIVE;
38959ab03be4SValentin Schneider 			break;
38969ab03be4SValentin Schneider 		}
38979ab03be4SValentin Schneider 		raw_spin_unlock_irq(&pool->lock);
3898e02b9312SValentin Schneider 		mutex_unlock(&wq_pool_attach_mutex);
38999ab03be4SValentin Schneider 	}
3900692b4825STejun Heo 
39011037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
3902e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
390329c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
3904a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
390560f5a4bcSLai Jiangshan 
3906e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
3907e02b9312SValentin Schneider 
3908e02b9312SValentin Schneider 	if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
390960f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
39101258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
391160f5a4bcSLai Jiangshan 
391260f5a4bcSLai Jiangshan 	if (pool->detach_completion)
391360f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
391460f5a4bcSLai Jiangshan 
391529c91e99STejun Heo 	/* shut down the timers */
391629c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
39173f959aa3SValentin Schneider 	cancel_work_sync(&pool->idle_cull_work);
391829c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
391929c91e99STejun Heo 
392024acfb71SThomas Gleixner 	/* RCU protected to allow dereferences from get_work_pool() */
392125b00775SPaul E. McKenney 	call_rcu(&pool->rcu, rcu_free_pool);
392229c91e99STejun Heo }
392329c91e99STejun Heo 
392429c91e99STejun Heo /**
392529c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
392629c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
392729c91e99STejun Heo  *
392829c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
392929c91e99STejun Heo  * reference count and return it.  If there already is a matching
393029c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
3931d185af30SYacine Belkadi  * create a new one.
3932a892caccSTejun Heo  *
3933a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
3934d185af30SYacine Belkadi  *
3935d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
3936d185af30SYacine Belkadi  * On failure, %NULL.
393729c91e99STejun Heo  */
393829c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
393929c91e99STejun Heo {
394029c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
394129c91e99STejun Heo 	struct worker_pool *pool;
3942f3f90ad4STejun Heo 	int node;
3943e2273584SXunlei Pang 	int target_node = NUMA_NO_NODE;
394429c91e99STejun Heo 
3945a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
394629c91e99STejun Heo 
394729c91e99STejun Heo 	/* do we already have a matching pool? */
394829c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
394929c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
395029c91e99STejun Heo 			pool->refcnt++;
39513fb1823cSLai Jiangshan 			return pool;
395229c91e99STejun Heo 		}
395329c91e99STejun Heo 	}
395429c91e99STejun Heo 
3955e2273584SXunlei Pang 	/* if cpumask is contained inside a NUMA node, we belong to that node */
3956e2273584SXunlei Pang 	if (wq_numa_enabled) {
3957e2273584SXunlei Pang 		for_each_node(node) {
3958e2273584SXunlei Pang 			if (cpumask_subset(attrs->cpumask,
3959e2273584SXunlei Pang 					   wq_numa_possible_cpumask[node])) {
3960e2273584SXunlei Pang 				target_node = node;
3961e2273584SXunlei Pang 				break;
3962e2273584SXunlei Pang 			}
3963e2273584SXunlei Pang 		}
3964e2273584SXunlei Pang 	}
3965e2273584SXunlei Pang 
396629c91e99STejun Heo 	/* nope, create a new one */
3967e2273584SXunlei Pang 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
396829c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
396929c91e99STejun Heo 		goto fail;
397029c91e99STejun Heo 
39718864b4e5STejun Heo 	lockdep_set_subclass(&pool->lock, 1);	/* see put_pwq() */
397229c91e99STejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
3973e2273584SXunlei Pang 	pool->node = target_node;
397429c91e99STejun Heo 
39752865a8fbSShaohua Li 	/*
39762865a8fbSShaohua Li 	 * no_numa isn't a worker_pool attribute, always clear it.  See
39772865a8fbSShaohua Li 	 * 'struct workqueue_attrs' comments for detail.
39782865a8fbSShaohua Li 	 */
39792865a8fbSShaohua Li 	pool->attrs->no_numa = false;
39802865a8fbSShaohua Li 
398129c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
398229c91e99STejun Heo 		goto fail;
398329c91e99STejun Heo 
398429c91e99STejun Heo 	/* create and start the initial worker */
39853347fa09STejun Heo 	if (wq_online && !create_worker(pool))
398629c91e99STejun Heo 		goto fail;
398729c91e99STejun Heo 
398829c91e99STejun Heo 	/* install */
398929c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
39903fb1823cSLai Jiangshan 
399129c91e99STejun Heo 	return pool;
399229c91e99STejun Heo fail:
399329c91e99STejun Heo 	if (pool)
399429c91e99STejun Heo 		put_unbound_pool(pool);
399529c91e99STejun Heo 	return NULL;
399629c91e99STejun Heo }
399729c91e99STejun Heo 
39988864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
39998864b4e5STejun Heo {
40008864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
40018864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
40028864b4e5STejun Heo }
40038864b4e5STejun Heo 
40048864b4e5STejun Heo /*
40058864b4e5STejun Heo  * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
40068864b4e5STejun Heo  * and needs to be destroyed.
40078864b4e5STejun Heo  */
40088864b4e5STejun Heo static void pwq_unbound_release_workfn(struct work_struct *work)
40098864b4e5STejun Heo {
40108864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
40118864b4e5STejun Heo 						  unbound_release_work);
40128864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
40138864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
4014b42b0bddSYang Yingliang 	bool is_last = false;
40158864b4e5STejun Heo 
4016b42b0bddSYang Yingliang 	/*
4017b42b0bddSYang Yingliang 	 * when @pwq is not linked, it doesn't hold any reference to the
4018b42b0bddSYang Yingliang 	 * @wq, and @wq is invalid to access.
4019b42b0bddSYang Yingliang 	 */
4020b42b0bddSYang Yingliang 	if (!list_empty(&pwq->pwqs_node)) {
40218864b4e5STejun Heo 		if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
40228864b4e5STejun Heo 			return;
40238864b4e5STejun Heo 
40243c25a55dSLai Jiangshan 		mutex_lock(&wq->mutex);
40258864b4e5STejun Heo 		list_del_rcu(&pwq->pwqs_node);
4026bc0caf09STejun Heo 		is_last = list_empty(&wq->pwqs);
40273c25a55dSLai Jiangshan 		mutex_unlock(&wq->mutex);
4028b42b0bddSYang Yingliang 	}
40298864b4e5STejun Heo 
4030a892caccSTejun Heo 	mutex_lock(&wq_pool_mutex);
40318864b4e5STejun Heo 	put_unbound_pool(pool);
4032a892caccSTejun Heo 	mutex_unlock(&wq_pool_mutex);
4033a892caccSTejun Heo 
403425b00775SPaul E. McKenney 	call_rcu(&pwq->rcu, rcu_free_pwq);
40358864b4e5STejun Heo 
40368864b4e5STejun Heo 	/*
40378864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
4038e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
40398864b4e5STejun Heo 	 */
4040669de8bdSBart Van Assche 	if (is_last) {
4041669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
404225b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
40436029a918STejun Heo 	}
4044669de8bdSBart Van Assche }
40458864b4e5STejun Heo 
40460fbd95aaSTejun Heo /**
4047699ce097STejun Heo  * pwq_adjust_max_active - update a pwq's max_active to the current setting
40480fbd95aaSTejun Heo  * @pwq: target pool_workqueue
40490fbd95aaSTejun Heo  *
4050699ce097STejun Heo  * If @pwq isn't freezing, set @pwq->max_active to the associated
4051f97a4a1aSLai Jiangshan  * workqueue's saved_max_active and activate inactive work items
4052699ce097STejun Heo  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
40530fbd95aaSTejun Heo  */
4054699ce097STejun Heo static void pwq_adjust_max_active(struct pool_workqueue *pwq)
40550fbd95aaSTejun Heo {
4056699ce097STejun Heo 	struct workqueue_struct *wq = pwq->wq;
4057699ce097STejun Heo 	bool freezable = wq->flags & WQ_FREEZABLE;
40583347fa09STejun Heo 	unsigned long flags;
4059699ce097STejun Heo 
4060699ce097STejun Heo 	/* for @wq->saved_max_active */
4061a357fc03SLai Jiangshan 	lockdep_assert_held(&wq->mutex);
4062699ce097STejun Heo 
4063699ce097STejun Heo 	/* fast exit for non-freezable wqs */
4064699ce097STejun Heo 	if (!freezable && pwq->max_active == wq->saved_max_active)
4065699ce097STejun Heo 		return;
4066699ce097STejun Heo 
40673347fa09STejun Heo 	/* this function can be called during early boot w/ irq disabled */
4068a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pwq->pool->lock, flags);
4069699ce097STejun Heo 
407074b414eaSLai Jiangshan 	/*
407174b414eaSLai Jiangshan 	 * During [un]freezing, the caller is responsible for ensuring that
407274b414eaSLai Jiangshan 	 * this function is called at least once after @workqueue_freezing
407374b414eaSLai Jiangshan 	 * is updated and visible.
407474b414eaSLai Jiangshan 	 */
407574b414eaSLai Jiangshan 	if (!freezable || !workqueue_freezing) {
407601341fbdSYunfeng Ye 		bool kick = false;
407701341fbdSYunfeng Ye 
4078699ce097STejun Heo 		pwq->max_active = wq->saved_max_active;
40790fbd95aaSTejun Heo 
4080f97a4a1aSLai Jiangshan 		while (!list_empty(&pwq->inactive_works) &&
408101341fbdSYunfeng Ye 		       pwq->nr_active < pwq->max_active) {
4082f97a4a1aSLai Jiangshan 			pwq_activate_first_inactive(pwq);
408301341fbdSYunfeng Ye 			kick = true;
408401341fbdSYunfeng Ye 		}
4085951a078aSLai Jiangshan 
4086951a078aSLai Jiangshan 		/*
4087951a078aSLai Jiangshan 		 * Need to kick a worker after thawed or an unbound wq's
408801341fbdSYunfeng Ye 		 * max_active is bumped. In realtime scenarios, always kicking a
408901341fbdSYunfeng Ye 		 * worker will cause interference on the isolated cpu cores, so
409001341fbdSYunfeng Ye 		 * let's kick iff work items were activated.
4091951a078aSLai Jiangshan 		 */
409201341fbdSYunfeng Ye 		if (kick)
4093951a078aSLai Jiangshan 			wake_up_worker(pwq->pool);
4094699ce097STejun Heo 	} else {
4095699ce097STejun Heo 		pwq->max_active = 0;
4096699ce097STejun Heo 	}
4097699ce097STejun Heo 
4098a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
40990fbd95aaSTejun Heo }
41000fbd95aaSTejun Heo 
410167dc8325SCai Huoqing /* initialize newly allocated @pwq which is associated with @wq and @pool */
4102f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
4103f147f29eSTejun Heo 		     struct worker_pool *pool)
4104d2c1d404STejun Heo {
4105d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
4106d2c1d404STejun Heo 
4107e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
4108e50aba9aSTejun Heo 
4109d2c1d404STejun Heo 	pwq->pool = pool;
4110d2c1d404STejun Heo 	pwq->wq = wq;
4111d2c1d404STejun Heo 	pwq->flush_color = -1;
41128864b4e5STejun Heo 	pwq->refcnt = 1;
4113f97a4a1aSLai Jiangshan 	INIT_LIST_HEAD(&pwq->inactive_works);
41141befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
4115d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
41168864b4e5STejun Heo 	INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
4117f147f29eSTejun Heo }
4118d2c1d404STejun Heo 
4119f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
41201befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
4121f147f29eSTejun Heo {
4122f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
4123f147f29eSTejun Heo 
4124f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
412575ccf595STejun Heo 
41261befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
41271befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
41281befcf30STejun Heo 		return;
41291befcf30STejun Heo 
413029b1cb41SLai Jiangshan 	/* set the matching work_color */
413175ccf595STejun Heo 	pwq->work_color = wq->work_color;
4132983ca25eSTejun Heo 
4133983ca25eSTejun Heo 	/* sync max_active to the current setting */
4134983ca25eSTejun Heo 	pwq_adjust_max_active(pwq);
4135983ca25eSTejun Heo 
4136983ca25eSTejun Heo 	/* link in @pwq */
41379e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
4138df2d5ae4STejun Heo }
41396029a918STejun Heo 
4140f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
4141f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
4142f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
4143f147f29eSTejun Heo {
4144f147f29eSTejun Heo 	struct worker_pool *pool;
4145f147f29eSTejun Heo 	struct pool_workqueue *pwq;
4146f147f29eSTejun Heo 
4147f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
4148f147f29eSTejun Heo 
4149f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
4150f147f29eSTejun Heo 	if (!pool)
4151f147f29eSTejun Heo 		return NULL;
4152f147f29eSTejun Heo 
4153e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
4154f147f29eSTejun Heo 	if (!pwq) {
4155f147f29eSTejun Heo 		put_unbound_pool(pool);
4156f147f29eSTejun Heo 		return NULL;
4157f147f29eSTejun Heo 	}
4158f147f29eSTejun Heo 
4159f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
4160f147f29eSTejun Heo 	return pwq;
4161d2c1d404STejun Heo }
4162d2c1d404STejun Heo 
41634c16bd32STejun Heo /**
416430186c6fSGong Zhaogang  * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
4165042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
41664c16bd32STejun Heo  * @node: the target NUMA node
41674c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
41684c16bd32STejun Heo  * @cpumask: outarg, the resulting cpumask
41694c16bd32STejun Heo  *
41704c16bd32STejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @node.  If
41714c16bd32STejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during
4172d185af30SYacine Belkadi  * calculation.  The result is stored in @cpumask.
41734c16bd32STejun Heo  *
41744c16bd32STejun Heo  * If NUMA affinity is not enabled, @attrs->cpumask is always used.  If
41754c16bd32STejun Heo  * enabled and @node has online CPUs requested by @attrs, the returned
41764c16bd32STejun Heo  * cpumask is the intersection of the possible CPUs of @node and
41774c16bd32STejun Heo  * @attrs->cpumask.
41784c16bd32STejun Heo  *
41794c16bd32STejun Heo  * The caller is responsible for ensuring that the cpumask of @node stays
41804c16bd32STejun Heo  * stable.
4181d185af30SYacine Belkadi  *
4182d185af30SYacine Belkadi  * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
4183d185af30SYacine Belkadi  * %false if equal.
41844c16bd32STejun Heo  */
41854c16bd32STejun Heo static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
41864c16bd32STejun Heo 				 int cpu_going_down, cpumask_t *cpumask)
41874c16bd32STejun Heo {
4188d55262c4STejun Heo 	if (!wq_numa_enabled || attrs->no_numa)
41894c16bd32STejun Heo 		goto use_dfl;
41904c16bd32STejun Heo 
41914c16bd32STejun Heo 	/* does @node have any online CPUs @attrs wants? */
41924c16bd32STejun Heo 	cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
41934c16bd32STejun Heo 	if (cpu_going_down >= 0)
41944c16bd32STejun Heo 		cpumask_clear_cpu(cpu_going_down, cpumask);
41954c16bd32STejun Heo 
41964c16bd32STejun Heo 	if (cpumask_empty(cpumask))
41974c16bd32STejun Heo 		goto use_dfl;
41984c16bd32STejun Heo 
41994c16bd32STejun Heo 	/* yeap, return possible CPUs in @node that @attrs wants */
42004c16bd32STejun Heo 	cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
42011ad0f0a7SMichael Bringmann 
42021ad0f0a7SMichael Bringmann 	if (cpumask_empty(cpumask)) {
42031ad0f0a7SMichael Bringmann 		pr_warn_once("WARNING: workqueue cpumask: online intersect > "
42041ad0f0a7SMichael Bringmann 				"possible intersect\n");
42051ad0f0a7SMichael Bringmann 		return false;
42061ad0f0a7SMichael Bringmann 	}
42071ad0f0a7SMichael Bringmann 
42084c16bd32STejun Heo 	return !cpumask_equal(cpumask, attrs->cpumask);
42094c16bd32STejun Heo 
42104c16bd32STejun Heo use_dfl:
42114c16bd32STejun Heo 	cpumask_copy(cpumask, attrs->cpumask);
42124c16bd32STejun Heo 	return false;
42134c16bd32STejun Heo }
42144c16bd32STejun Heo 
42151befcf30STejun Heo /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
42161befcf30STejun Heo static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
42171befcf30STejun Heo 						   int node,
42181befcf30STejun Heo 						   struct pool_workqueue *pwq)
42191befcf30STejun Heo {
42201befcf30STejun Heo 	struct pool_workqueue *old_pwq;
42211befcf30STejun Heo 
42225b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
42231befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
42241befcf30STejun Heo 
42251befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
42261befcf30STejun Heo 	link_pwq(pwq);
42271befcf30STejun Heo 
42281befcf30STejun Heo 	old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
42291befcf30STejun Heo 	rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
42301befcf30STejun Heo 	return old_pwq;
42311befcf30STejun Heo }
42321befcf30STejun Heo 
42332d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
42342d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
42352d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
42362d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
4237042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
42382d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
42392d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
42402d5f0764SLai Jiangshan };
42412d5f0764SLai Jiangshan 
42422d5f0764SLai Jiangshan /* free the resources after success or abort */
42432d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
42442d5f0764SLai Jiangshan {
42452d5f0764SLai Jiangshan 	if (ctx) {
42462d5f0764SLai Jiangshan 		int node;
42472d5f0764SLai Jiangshan 
42482d5f0764SLai Jiangshan 		for_each_node(node)
42492d5f0764SLai Jiangshan 			put_pwq_unlocked(ctx->pwq_tbl[node]);
42502d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
42512d5f0764SLai Jiangshan 
42522d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
42532d5f0764SLai Jiangshan 
42542d5f0764SLai Jiangshan 		kfree(ctx);
42552d5f0764SLai Jiangshan 	}
42562d5f0764SLai Jiangshan }
42572d5f0764SLai Jiangshan 
42582d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
42592d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
42602d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
426199c621efSLai Jiangshan 		      const struct workqueue_attrs *attrs,
426299c621efSLai Jiangshan 		      const cpumask_var_t unbound_cpumask)
42632d5f0764SLai Jiangshan {
42642d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
42652d5f0764SLai Jiangshan 	struct workqueue_attrs *new_attrs, *tmp_attrs;
42662d5f0764SLai Jiangshan 	int node;
42672d5f0764SLai Jiangshan 
42682d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
42692d5f0764SLai Jiangshan 
4270acafe7e3SKees Cook 	ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_node_ids), GFP_KERNEL);
42712d5f0764SLai Jiangshan 
4272be69d00dSThomas Gleixner 	new_attrs = alloc_workqueue_attrs();
4273be69d00dSThomas Gleixner 	tmp_attrs = alloc_workqueue_attrs();
42742d5f0764SLai Jiangshan 	if (!ctx || !new_attrs || !tmp_attrs)
42752d5f0764SLai Jiangshan 		goto out_free;
42762d5f0764SLai Jiangshan 
4277042f7df1SLai Jiangshan 	/*
427899c621efSLai Jiangshan 	 * Calculate the attrs of the default pwq with unbound_cpumask
427999c621efSLai Jiangshan 	 * which is wq_unbound_cpumask or to set to wq_unbound_cpumask.
4280042f7df1SLai Jiangshan 	 * If the user configured cpumask doesn't overlap with the
4281042f7df1SLai Jiangshan 	 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
4282042f7df1SLai Jiangshan 	 */
42832d5f0764SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
428499c621efSLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, unbound_cpumask);
4285042f7df1SLai Jiangshan 	if (unlikely(cpumask_empty(new_attrs->cpumask)))
428699c621efSLai Jiangshan 		cpumask_copy(new_attrs->cpumask, unbound_cpumask);
42872d5f0764SLai Jiangshan 
42882d5f0764SLai Jiangshan 	/*
42892d5f0764SLai Jiangshan 	 * We may create multiple pwqs with differing cpumasks.  Make a
42902d5f0764SLai Jiangshan 	 * copy of @new_attrs which will be modified and used to obtain
42912d5f0764SLai Jiangshan 	 * pools.
42922d5f0764SLai Jiangshan 	 */
42932d5f0764SLai Jiangshan 	copy_workqueue_attrs(tmp_attrs, new_attrs);
42942d5f0764SLai Jiangshan 
42952d5f0764SLai Jiangshan 	/*
42962d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
42972d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
42982d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
42992d5f0764SLai Jiangshan 	 */
43002d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
43012d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
43022d5f0764SLai Jiangshan 		goto out_free;
43032d5f0764SLai Jiangshan 
43042d5f0764SLai Jiangshan 	for_each_node(node) {
4305042f7df1SLai Jiangshan 		if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
43062d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
43072d5f0764SLai Jiangshan 			if (!ctx->pwq_tbl[node])
43082d5f0764SLai Jiangshan 				goto out_free;
43092d5f0764SLai Jiangshan 		} else {
43102d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
43112d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = ctx->dfl_pwq;
43122d5f0764SLai Jiangshan 		}
43132d5f0764SLai Jiangshan 	}
43142d5f0764SLai Jiangshan 
4315042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
4316042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
4317042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
43182d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
4319042f7df1SLai Jiangshan 
43202d5f0764SLai Jiangshan 	ctx->wq = wq;
43212d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
43222d5f0764SLai Jiangshan 	return ctx;
43232d5f0764SLai Jiangshan 
43242d5f0764SLai Jiangshan out_free:
43252d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
43262d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
43272d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
43282d5f0764SLai Jiangshan 	return NULL;
43292d5f0764SLai Jiangshan }
43302d5f0764SLai Jiangshan 
43312d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
43322d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
43332d5f0764SLai Jiangshan {
43342d5f0764SLai Jiangshan 	int node;
43352d5f0764SLai Jiangshan 
43362d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
43372d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
43382d5f0764SLai Jiangshan 
43392d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
43402d5f0764SLai Jiangshan 
43412d5f0764SLai Jiangshan 	/* save the previous pwq and install the new one */
43422d5f0764SLai Jiangshan 	for_each_node(node)
43432d5f0764SLai Jiangshan 		ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
43442d5f0764SLai Jiangshan 							  ctx->pwq_tbl[node]);
43452d5f0764SLai Jiangshan 
43462d5f0764SLai Jiangshan 	/* @dfl_pwq might not have been used, ensure it's linked */
43472d5f0764SLai Jiangshan 	link_pwq(ctx->dfl_pwq);
43482d5f0764SLai Jiangshan 	swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
43492d5f0764SLai Jiangshan 
43502d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
43512d5f0764SLai Jiangshan }
43522d5f0764SLai Jiangshan 
4353a0111cf6SLai Jiangshan static void apply_wqattrs_lock(void)
4354a0111cf6SLai Jiangshan {
4355a0111cf6SLai Jiangshan 	/* CPUs should stay stable across pwq creations and installations */
4356ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4357a0111cf6SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4358a0111cf6SLai Jiangshan }
4359a0111cf6SLai Jiangshan 
4360a0111cf6SLai Jiangshan static void apply_wqattrs_unlock(void)
4361a0111cf6SLai Jiangshan {
4362a0111cf6SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4363ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4364a0111cf6SLai Jiangshan }
4365a0111cf6SLai Jiangshan 
4366a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4367a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
4368a0111cf6SLai Jiangshan {
4369a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
4370a0111cf6SLai Jiangshan 
4371a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
4372a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4373a0111cf6SLai Jiangshan 		return -EINVAL;
4374a0111cf6SLai Jiangshan 
4375a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
43760a94efb5STejun Heo 	if (!list_empty(&wq->pwqs)) {
43770a94efb5STejun Heo 		if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4378a0111cf6SLai Jiangshan 			return -EINVAL;
4379a0111cf6SLai Jiangshan 
43800a94efb5STejun Heo 		wq->flags &= ~__WQ_ORDERED;
43810a94efb5STejun Heo 	}
43820a94efb5STejun Heo 
438399c621efSLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
43846201171eSwanghaibin 	if (!ctx)
43856201171eSwanghaibin 		return -ENOMEM;
4386a0111cf6SLai Jiangshan 
4387a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
4388a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
4389a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
4390a0111cf6SLai Jiangshan 
43916201171eSwanghaibin 	return 0;
4392a0111cf6SLai Jiangshan }
4393a0111cf6SLai Jiangshan 
43949e8cd2f5STejun Heo /**
43959e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
43969e8cd2f5STejun Heo  * @wq: the target workqueue
43979e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
43989e8cd2f5STejun Heo  *
43994c16bd32STejun Heo  * Apply @attrs to an unbound workqueue @wq.  Unless disabled, on NUMA
44004c16bd32STejun Heo  * machines, this function maps a separate pwq to each NUMA node with
44014c16bd32STejun Heo  * possibles CPUs in @attrs->cpumask so that work items are affine to the
44024c16bd32STejun Heo  * NUMA node it was issued on.  Older pwqs are released as in-flight work
44034c16bd32STejun Heo  * items finish.  Note that a work item which repeatedly requeues itself
44044c16bd32STejun Heo  * back-to-back will stay on its current pwq.
44059e8cd2f5STejun Heo  *
4406d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
4407d185af30SYacine Belkadi  *
4408ffd8bea8SSebastian Andrzej Siewior  * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
4409509b3204SDaniel Jordan  *
4410d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
44119e8cd2f5STejun Heo  */
4412513c98d0SDaniel Jordan int apply_workqueue_attrs(struct workqueue_struct *wq,
44139e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
44149e8cd2f5STejun Heo {
4415a0111cf6SLai Jiangshan 	int ret;
44169e8cd2f5STejun Heo 
4417509b3204SDaniel Jordan 	lockdep_assert_cpus_held();
4418509b3204SDaniel Jordan 
4419509b3204SDaniel Jordan 	mutex_lock(&wq_pool_mutex);
4420a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
4421509b3204SDaniel Jordan 	mutex_unlock(&wq_pool_mutex);
44222d5f0764SLai Jiangshan 
44232d5f0764SLai Jiangshan 	return ret;
44249e8cd2f5STejun Heo }
44259e8cd2f5STejun Heo 
44264c16bd32STejun Heo /**
44274c16bd32STejun Heo  * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
44284c16bd32STejun Heo  * @wq: the target workqueue
44294c16bd32STejun Heo  * @cpu: the CPU coming up or going down
44304c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
44314c16bd32STejun Heo  *
44324c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
44334c16bd32STejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update NUMA affinity of
44344c16bd32STejun Heo  * @wq accordingly.
44354c16bd32STejun Heo  *
44364c16bd32STejun Heo  * If NUMA affinity can't be adjusted due to memory allocation failure, it
44374c16bd32STejun Heo  * falls back to @wq->dfl_pwq which may not be optimal but is always
44384c16bd32STejun Heo  * correct.
44394c16bd32STejun Heo  *
44404c16bd32STejun Heo  * Note that when the last allowed CPU of a NUMA node goes offline for a
44414c16bd32STejun Heo  * workqueue with a cpumask spanning multiple nodes, the workers which were
44424c16bd32STejun Heo  * already executing the work items for the workqueue will lose their CPU
44434c16bd32STejun Heo  * affinity and may execute on any CPU.  This is similar to how per-cpu
44444c16bd32STejun Heo  * workqueues behave on CPU_DOWN.  If a workqueue user wants strict
44454c16bd32STejun Heo  * affinity, it's the user's responsibility to flush the work item from
44464c16bd32STejun Heo  * CPU_DOWN_PREPARE.
44474c16bd32STejun Heo  */
44484c16bd32STejun Heo static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
44494c16bd32STejun Heo 				   bool online)
44504c16bd32STejun Heo {
44514c16bd32STejun Heo 	int node = cpu_to_node(cpu);
44524c16bd32STejun Heo 	int cpu_off = online ? -1 : cpu;
44534c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
44544c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
44554c16bd32STejun Heo 	cpumask_t *cpumask;
44564c16bd32STejun Heo 
44574c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
44584c16bd32STejun Heo 
4459f7142ed4SLai Jiangshan 	if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
4460f7142ed4SLai Jiangshan 	    wq->unbound_attrs->no_numa)
44614c16bd32STejun Heo 		return;
44624c16bd32STejun Heo 
44634c16bd32STejun Heo 	/*
44644c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
44654c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
44664c16bd32STejun Heo 	 * CPU hotplug exclusion.
44674c16bd32STejun Heo 	 */
44684c16bd32STejun Heo 	target_attrs = wq_update_unbound_numa_attrs_buf;
44694c16bd32STejun Heo 	cpumask = target_attrs->cpumask;
44704c16bd32STejun Heo 
44714c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
44724c16bd32STejun Heo 	pwq = unbound_pwq_by_node(wq, node);
44734c16bd32STejun Heo 
44744c16bd32STejun Heo 	/*
44754c16bd32STejun Heo 	 * Let's determine what needs to be done.  If the target cpumask is
4476042f7df1SLai Jiangshan 	 * different from the default pwq's, we need to compare it to @pwq's
4477042f7df1SLai Jiangshan 	 * and create a new one if they don't match.  If the target cpumask
4478042f7df1SLai Jiangshan 	 * equals the default pwq's, the default pwq should be used.
44794c16bd32STejun Heo 	 */
4480042f7df1SLai Jiangshan 	if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
44814c16bd32STejun Heo 		if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
4482f7142ed4SLai Jiangshan 			return;
44834c16bd32STejun Heo 	} else {
44844c16bd32STejun Heo 		goto use_dfl_pwq;
44854c16bd32STejun Heo 	}
44864c16bd32STejun Heo 
44874c16bd32STejun Heo 	/* create a new pwq */
44884c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
44894c16bd32STejun Heo 	if (!pwq) {
44902d916033SFabian Frederick 		pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
44914c16bd32STejun Heo 			wq->name);
449277f300b1SDaeseok Youn 		goto use_dfl_pwq;
44934c16bd32STejun Heo 	}
44944c16bd32STejun Heo 
4495f7142ed4SLai Jiangshan 	/* Install the new pwq. */
44964c16bd32STejun Heo 	mutex_lock(&wq->mutex);
44974c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, pwq);
44984c16bd32STejun Heo 	goto out_unlock;
44994c16bd32STejun Heo 
45004c16bd32STejun Heo use_dfl_pwq:
4501f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
4502a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
45034c16bd32STejun Heo 	get_pwq(wq->dfl_pwq);
4504a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
45054c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
45064c16bd32STejun Heo out_unlock:
45074c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
45084c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
45094c16bd32STejun Heo }
45104c16bd32STejun Heo 
451130cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
45121da177e4SLinus Torvalds {
451349e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
45148a2b7538STejun Heo 	int cpu, ret;
4515e1d8aa9fSFrederic Weisbecker 
451630cdf249STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
4517ee1ceef7STejun Heo 		wq->cpu_pwq = alloc_percpu(struct pool_workqueue);
4518ee1ceef7STejun Heo 		if (!wq->cpu_pwq)
451930cdf249STejun Heo 			return -ENOMEM;
452030cdf249STejun Heo 
452130cdf249STejun Heo 		for_each_possible_cpu(cpu) {
45227fb98ea7STejun Heo 			struct pool_workqueue *pwq =
4523ee1ceef7STejun Heo 				per_cpu_ptr(wq->cpu_pwq, cpu);
45247a62c2c8STejun Heo 			struct worker_pool *cpu_pools =
4525f02ae73aSTejun Heo 				per_cpu(cpu_worker_pools, cpu);
452630cdf249STejun Heo 
4527f147f29eSTejun Heo 			init_pwq(pwq, wq, &cpu_pools[highpri]);
4528f147f29eSTejun Heo 
4529f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
45301befcf30STejun Heo 			link_pwq(pwq);
4531f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
453230cdf249STejun Heo 		}
453330cdf249STejun Heo 		return 0;
4534509b3204SDaniel Jordan 	}
4535509b3204SDaniel Jordan 
4536ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4537509b3204SDaniel Jordan 	if (wq->flags & __WQ_ORDERED) {
45388a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
45398a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
45408a2b7538STejun Heo 		WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
45418a2b7538STejun Heo 			      wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
45428a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
45439e8cd2f5STejun Heo 	} else {
4544509b3204SDaniel Jordan 		ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
45459e8cd2f5STejun Heo 	}
4546ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4547509b3204SDaniel Jordan 
4548509b3204SDaniel Jordan 	return ret;
45490f900049STejun Heo }
45500f900049STejun Heo 
4551f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
4552f3421797STejun Heo 			       const char *name)
4553b71ab8c2STejun Heo {
4554f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
4555f3421797STejun Heo 
4556f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
4557044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4558f3421797STejun Heo 			max_active, name, 1, lim);
4559b71ab8c2STejun Heo 
4560f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
4561b71ab8c2STejun Heo }
4562b71ab8c2STejun Heo 
4563983c7515STejun Heo /*
4564983c7515STejun Heo  * Workqueues which may be used during memory reclaim should have a rescuer
4565983c7515STejun Heo  * to guarantee forward progress.
4566983c7515STejun Heo  */
4567983c7515STejun Heo static int init_rescuer(struct workqueue_struct *wq)
4568983c7515STejun Heo {
4569983c7515STejun Heo 	struct worker *rescuer;
4570b92b36eaSDan Carpenter 	int ret;
4571983c7515STejun Heo 
4572983c7515STejun Heo 	if (!(wq->flags & WQ_MEM_RECLAIM))
4573983c7515STejun Heo 		return 0;
4574983c7515STejun Heo 
4575983c7515STejun Heo 	rescuer = alloc_worker(NUMA_NO_NODE);
45764c0736a7SPetr Mladek 	if (!rescuer) {
45774c0736a7SPetr Mladek 		pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
45784c0736a7SPetr Mladek 		       wq->name);
4579983c7515STejun Heo 		return -ENOMEM;
45804c0736a7SPetr Mladek 	}
4581983c7515STejun Heo 
4582983c7515STejun Heo 	rescuer->rescue_wq = wq;
4583983c7515STejun Heo 	rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name);
4584f187b697SSean Fu 	if (IS_ERR(rescuer->task)) {
4585b92b36eaSDan Carpenter 		ret = PTR_ERR(rescuer->task);
45864c0736a7SPetr Mladek 		pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
45874c0736a7SPetr Mladek 		       wq->name, ERR_PTR(ret));
4588983c7515STejun Heo 		kfree(rescuer);
4589b92b36eaSDan Carpenter 		return ret;
4590983c7515STejun Heo 	}
4591983c7515STejun Heo 
4592983c7515STejun Heo 	wq->rescuer = rescuer;
4593983c7515STejun Heo 	kthread_bind_mask(rescuer->task, cpu_possible_mask);
4594983c7515STejun Heo 	wake_up_process(rescuer->task);
4595983c7515STejun Heo 
4596983c7515STejun Heo 	return 0;
4597983c7515STejun Heo }
4598983c7515STejun Heo 
4599a2775bbcSMathieu Malaterre __printf(1, 4)
4600669de8bdSBart Van Assche struct workqueue_struct *alloc_workqueue(const char *fmt,
460197e37d7bSTejun Heo 					 unsigned int flags,
4602669de8bdSBart Van Assche 					 int max_active, ...)
46033af24433SOleg Nesterov {
4604df2d5ae4STejun Heo 	size_t tbl_size = 0;
4605ecf6881fSTejun Heo 	va_list args;
46063af24433SOleg Nesterov 	struct workqueue_struct *wq;
460749e3cf44STejun Heo 	struct pool_workqueue *pwq;
4608b196be89STejun Heo 
46095c0338c6STejun Heo 	/*
46105c0338c6STejun Heo 	 * Unbound && max_active == 1 used to imply ordered, which is no
46115c0338c6STejun Heo 	 * longer the case on NUMA machines due to per-node pools.  While
46125c0338c6STejun Heo 	 * alloc_ordered_workqueue() is the right way to create an ordered
46135c0338c6STejun Heo 	 * workqueue, keep the previous behavior to avoid subtle breakages
46145c0338c6STejun Heo 	 * on NUMA.
46155c0338c6STejun Heo 	 */
46165c0338c6STejun Heo 	if ((flags & WQ_UNBOUND) && max_active == 1)
46175c0338c6STejun Heo 		flags |= __WQ_ORDERED;
46185c0338c6STejun Heo 
4619cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
4620cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4621cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
4622cee22a15SViresh Kumar 
4623ecf6881fSTejun Heo 	/* allocate wq and format name */
4624df2d5ae4STejun Heo 	if (flags & WQ_UNBOUND)
4625ddcb57e2SLai Jiangshan 		tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
4626df2d5ae4STejun Heo 
4627df2d5ae4STejun Heo 	wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
4628b196be89STejun Heo 	if (!wq)
4629d2c1d404STejun Heo 		return NULL;
4630b196be89STejun Heo 
46316029a918STejun Heo 	if (flags & WQ_UNBOUND) {
4632be69d00dSThomas Gleixner 		wq->unbound_attrs = alloc_workqueue_attrs();
46336029a918STejun Heo 		if (!wq->unbound_attrs)
46346029a918STejun Heo 			goto err_free_wq;
46356029a918STejun Heo 	}
46366029a918STejun Heo 
4637669de8bdSBart Van Assche 	va_start(args, max_active);
4638ecf6881fSTejun Heo 	vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4639b196be89STejun Heo 	va_end(args);
46403af24433SOleg Nesterov 
4641d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
4642b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
46433af24433SOleg Nesterov 
4644b196be89STejun Heo 	/* init wq */
464597e37d7bSTejun Heo 	wq->flags = flags;
4646a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
46473c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
4648112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
464930cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
465073f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
465173f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
4652493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
46533af24433SOleg Nesterov 
4654669de8bdSBart Van Assche 	wq_init_lockdep(wq);
4655cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
46563af24433SOleg Nesterov 
465730cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
465882efcab3SBart Van Assche 		goto err_unreg_lockdep;
46591537663fSTejun Heo 
466040c17f75STejun Heo 	if (wq_online && init_rescuer(wq) < 0)
4661d2c1d404STejun Heo 		goto err_destroy;
4662e22bee78STejun Heo 
4663226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4664226223abSTejun Heo 		goto err_destroy;
4665226223abSTejun Heo 
46666af8bf3dSOleg Nesterov 	/*
466768e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
466868e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
466968e13a67SLai Jiangshan 	 * list.
46706af8bf3dSOleg Nesterov 	 */
467168e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4672a0a1a5fdSTejun Heo 
4673a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
467449e3cf44STejun Heo 	for_each_pwq(pwq, wq)
4675699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4676a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4677a0a1a5fdSTejun Heo 
4678e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
4679a0a1a5fdSTejun Heo 
468068e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
46813af24433SOleg Nesterov 
46823af24433SOleg Nesterov 	return wq;
4683d2c1d404STejun Heo 
468482efcab3SBart Van Assche err_unreg_lockdep:
4685009bb421SBart Van Assche 	wq_unregister_lockdep(wq);
4686009bb421SBart Van Assche 	wq_free_lockdep(wq);
468782efcab3SBart Van Assche err_free_wq:
46886029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
46894690c4abSTejun Heo 	kfree(wq);
4690d2c1d404STejun Heo 	return NULL;
4691d2c1d404STejun Heo err_destroy:
4692d2c1d404STejun Heo 	destroy_workqueue(wq);
46934690c4abSTejun Heo 	return NULL;
46941da177e4SLinus Torvalds }
4695669de8bdSBart Van Assche EXPORT_SYMBOL_GPL(alloc_workqueue);
46961da177e4SLinus Torvalds 
4697c29eb853STejun Heo static bool pwq_busy(struct pool_workqueue *pwq)
4698c29eb853STejun Heo {
4699c29eb853STejun Heo 	int i;
4700c29eb853STejun Heo 
4701c29eb853STejun Heo 	for (i = 0; i < WORK_NR_COLORS; i++)
4702c29eb853STejun Heo 		if (pwq->nr_in_flight[i])
4703c29eb853STejun Heo 			return true;
4704c29eb853STejun Heo 
4705c29eb853STejun Heo 	if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4706c29eb853STejun Heo 		return true;
4707f97a4a1aSLai Jiangshan 	if (pwq->nr_active || !list_empty(&pwq->inactive_works))
4708c29eb853STejun Heo 		return true;
4709c29eb853STejun Heo 
4710c29eb853STejun Heo 	return false;
4711c29eb853STejun Heo }
4712c29eb853STejun Heo 
47133af24433SOleg Nesterov /**
47143af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
47153af24433SOleg Nesterov  * @wq: target workqueue
47163af24433SOleg Nesterov  *
47173af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
47183af24433SOleg Nesterov  */
47193af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
47203af24433SOleg Nesterov {
472149e3cf44STejun Heo 	struct pool_workqueue *pwq;
47224c16bd32STejun Heo 	int node;
47233af24433SOleg Nesterov 
4724def98c84STejun Heo 	/*
4725def98c84STejun Heo 	 * Remove it from sysfs first so that sanity check failure doesn't
4726def98c84STejun Heo 	 * lead to sysfs name conflicts.
4727def98c84STejun Heo 	 */
4728def98c84STejun Heo 	workqueue_sysfs_unregister(wq);
4729def98c84STejun Heo 
473033e3f0a3SRichard Clark 	/* mark the workqueue destruction is in progress */
473133e3f0a3SRichard Clark 	mutex_lock(&wq->mutex);
473233e3f0a3SRichard Clark 	wq->flags |= __WQ_DESTROYING;
473333e3f0a3SRichard Clark 	mutex_unlock(&wq->mutex);
473433e3f0a3SRichard Clark 
47359c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
47369c5a2ba7STejun Heo 	drain_workqueue(wq);
4737c8efcc25STejun Heo 
4738def98c84STejun Heo 	/* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4739def98c84STejun Heo 	if (wq->rescuer) {
4740def98c84STejun Heo 		struct worker *rescuer = wq->rescuer;
4741def98c84STejun Heo 
4742def98c84STejun Heo 		/* this prevents new queueing */
4743a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
4744def98c84STejun Heo 		wq->rescuer = NULL;
4745a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
4746def98c84STejun Heo 
4747def98c84STejun Heo 		/* rescuer will empty maydays list before exiting */
4748def98c84STejun Heo 		kthread_stop(rescuer->task);
47498efe1223STejun Heo 		kfree(rescuer);
4750def98c84STejun Heo 	}
4751def98c84STejun Heo 
4752c29eb853STejun Heo 	/*
4753c29eb853STejun Heo 	 * Sanity checks - grab all the locks so that we wait for all
4754c29eb853STejun Heo 	 * in-flight operations which may do put_pwq().
4755c29eb853STejun Heo 	 */
4756c29eb853STejun Heo 	mutex_lock(&wq_pool_mutex);
4757b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
475849e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
4759a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
4760c29eb853STejun Heo 		if (WARN_ON(pwq_busy(pwq))) {
47611d9a6159SKefeng Wang 			pr_warn("%s: %s has the following busy pwq\n",
4762e66b39afSTejun Heo 				__func__, wq->name);
4763c29eb853STejun Heo 			show_pwq(pwq);
4764a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pwq->pool->lock);
4765b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
4766c29eb853STejun Heo 			mutex_unlock(&wq_pool_mutex);
476755df0933SImran Khan 			show_one_workqueue(wq);
47686183c009STejun Heo 			return;
476976af4d93STejun Heo 		}
4770a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
477176af4d93STejun Heo 	}
4772b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
47736183c009STejun Heo 
4774a0a1a5fdSTejun Heo 	/*
4775a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
4776a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
4777a0a1a5fdSTejun Heo 	 */
4778e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
477968e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
47803af24433SOleg Nesterov 
47818864b4e5STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
4782669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
478329c91e99STejun Heo 		/*
47848864b4e5STejun Heo 		 * The base ref is never dropped on per-cpu pwqs.  Directly
4785e2dca7adSTejun Heo 		 * schedule RCU free.
478629c91e99STejun Heo 		 */
478725b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
47888864b4e5STejun Heo 	} else {
47898864b4e5STejun Heo 		/*
47908864b4e5STejun Heo 		 * We're the sole accessor of @wq at this point.  Directly
47914c16bd32STejun Heo 		 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
47924c16bd32STejun Heo 		 * @wq will be freed when the last pwq is released.
47938864b4e5STejun Heo 		 */
47944c16bd32STejun Heo 		for_each_node(node) {
47954c16bd32STejun Heo 			pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
47964c16bd32STejun Heo 			RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
47974c16bd32STejun Heo 			put_pwq_unlocked(pwq);
47984c16bd32STejun Heo 		}
47994c16bd32STejun Heo 
48004c16bd32STejun Heo 		/*
48014c16bd32STejun Heo 		 * Put dfl_pwq.  @wq may be freed any time after dfl_pwq is
48024c16bd32STejun Heo 		 * put.  Don't access it afterwards.
48034c16bd32STejun Heo 		 */
48044c16bd32STejun Heo 		pwq = wq->dfl_pwq;
48054c16bd32STejun Heo 		wq->dfl_pwq = NULL;
4806dce90d47STejun Heo 		put_pwq_unlocked(pwq);
480729c91e99STejun Heo 	}
48083af24433SOleg Nesterov }
48093af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
48103af24433SOleg Nesterov 
4811dcd989cbSTejun Heo /**
4812dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
4813dcd989cbSTejun Heo  * @wq: target workqueue
4814dcd989cbSTejun Heo  * @max_active: new max_active value.
4815dcd989cbSTejun Heo  *
4816dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
4817dcd989cbSTejun Heo  *
4818dcd989cbSTejun Heo  * CONTEXT:
4819dcd989cbSTejun Heo  * Don't call from IRQ context.
4820dcd989cbSTejun Heo  */
4821dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4822dcd989cbSTejun Heo {
482349e3cf44STejun Heo 	struct pool_workqueue *pwq;
4824dcd989cbSTejun Heo 
48258719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
48260a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
48278719dceaSTejun Heo 		return;
48288719dceaSTejun Heo 
4829f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4830dcd989cbSTejun Heo 
4831a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4832dcd989cbSTejun Heo 
48330a94efb5STejun Heo 	wq->flags &= ~__WQ_ORDERED;
4834dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4835dcd989cbSTejun Heo 
4836699ce097STejun Heo 	for_each_pwq(pwq, wq)
4837699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4838dcd989cbSTejun Heo 
4839a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4840dcd989cbSTejun Heo }
4841dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4842dcd989cbSTejun Heo 
4843dcd989cbSTejun Heo /**
484427d4ee03SLukas Wunner  * current_work - retrieve %current task's work struct
484527d4ee03SLukas Wunner  *
484627d4ee03SLukas Wunner  * Determine if %current task is a workqueue worker and what it's working on.
484727d4ee03SLukas Wunner  * Useful to find out the context that the %current task is running in.
484827d4ee03SLukas Wunner  *
484927d4ee03SLukas Wunner  * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
485027d4ee03SLukas Wunner  */
485127d4ee03SLukas Wunner struct work_struct *current_work(void)
485227d4ee03SLukas Wunner {
485327d4ee03SLukas Wunner 	struct worker *worker = current_wq_worker();
485427d4ee03SLukas Wunner 
485527d4ee03SLukas Wunner 	return worker ? worker->current_work : NULL;
485627d4ee03SLukas Wunner }
485727d4ee03SLukas Wunner EXPORT_SYMBOL(current_work);
485827d4ee03SLukas Wunner 
485927d4ee03SLukas Wunner /**
4860e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4861e6267616STejun Heo  *
4862e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4863e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4864d185af30SYacine Belkadi  *
4865d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
4866e6267616STejun Heo  */
4867e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4868e6267616STejun Heo {
4869e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4870e6267616STejun Heo 
48716a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
4872e6267616STejun Heo }
4873e6267616STejun Heo 
4874e6267616STejun Heo /**
4875dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4876dcd989cbSTejun Heo  * @cpu: CPU in question
4877dcd989cbSTejun Heo  * @wq: target workqueue
4878dcd989cbSTejun Heo  *
4879dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4880dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4881dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4882dcd989cbSTejun Heo  *
4883d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4884d3251859STejun Heo  * Note that both per-cpu and unbound workqueues may be associated with
4885d3251859STejun Heo  * multiple pool_workqueues which have separate congested states.  A
4886d3251859STejun Heo  * workqueue being congested on one CPU doesn't mean the workqueue is also
4887d3251859STejun Heo  * contested on other CPUs / NUMA nodes.
4888d3251859STejun Heo  *
4889d185af30SYacine Belkadi  * Return:
4890dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4891dcd989cbSTejun Heo  */
4892d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4893dcd989cbSTejun Heo {
48947fb98ea7STejun Heo 	struct pool_workqueue *pwq;
489576af4d93STejun Heo 	bool ret;
489676af4d93STejun Heo 
489724acfb71SThomas Gleixner 	rcu_read_lock();
489824acfb71SThomas Gleixner 	preempt_disable();
48997fb98ea7STejun Heo 
4900d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
4901d3251859STejun Heo 		cpu = smp_processor_id();
4902d3251859STejun Heo 
49037fb98ea7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
4904ee1ceef7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwq, cpu);
49057fb98ea7STejun Heo 	else
4906df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4907dcd989cbSTejun Heo 
4908f97a4a1aSLai Jiangshan 	ret = !list_empty(&pwq->inactive_works);
490924acfb71SThomas Gleixner 	preempt_enable();
491024acfb71SThomas Gleixner 	rcu_read_unlock();
491176af4d93STejun Heo 
491276af4d93STejun Heo 	return ret;
4913dcd989cbSTejun Heo }
4914dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4915dcd989cbSTejun Heo 
4916dcd989cbSTejun Heo /**
4917dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4918dcd989cbSTejun Heo  * @work: the work to be tested
4919dcd989cbSTejun Heo  *
4920dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4921dcd989cbSTejun Heo  * synchronization around this function and the test result is
4922dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4923dcd989cbSTejun Heo  *
4924d185af30SYacine Belkadi  * Return:
4925dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
4926dcd989cbSTejun Heo  */
4927dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4928dcd989cbSTejun Heo {
4929fa1b54e6STejun Heo 	struct worker_pool *pool;
4930dcd989cbSTejun Heo 	unsigned long flags;
4931dcd989cbSTejun Heo 	unsigned int ret = 0;
4932dcd989cbSTejun Heo 
4933dcd989cbSTejun Heo 	if (work_pending(work))
4934dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
4935038366c5SLai Jiangshan 
493624acfb71SThomas Gleixner 	rcu_read_lock();
4937fa1b54e6STejun Heo 	pool = get_work_pool(work);
4938038366c5SLai Jiangshan 	if (pool) {
4939a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pool->lock, flags);
4940c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
4941dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
4942a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pool->lock, flags);
4943038366c5SLai Jiangshan 	}
494424acfb71SThomas Gleixner 	rcu_read_unlock();
4945dcd989cbSTejun Heo 
4946dcd989cbSTejun Heo 	return ret;
4947dcd989cbSTejun Heo }
4948dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
4949dcd989cbSTejun Heo 
49503d1cb205STejun Heo /**
49513d1cb205STejun Heo  * set_worker_desc - set description for the current work item
49523d1cb205STejun Heo  * @fmt: printf-style format string
49533d1cb205STejun Heo  * @...: arguments for the format string
49543d1cb205STejun Heo  *
49553d1cb205STejun Heo  * This function can be called by a running work function to describe what
49563d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
49573d1cb205STejun Heo  * information will be printed out together to help debugging.  The
49583d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
49593d1cb205STejun Heo  */
49603d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
49613d1cb205STejun Heo {
49623d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
49633d1cb205STejun Heo 	va_list args;
49643d1cb205STejun Heo 
49653d1cb205STejun Heo 	if (worker) {
49663d1cb205STejun Heo 		va_start(args, fmt);
49673d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
49683d1cb205STejun Heo 		va_end(args);
49693d1cb205STejun Heo 	}
49703d1cb205STejun Heo }
49715c750d58SSteffen Maier EXPORT_SYMBOL_GPL(set_worker_desc);
49723d1cb205STejun Heo 
49733d1cb205STejun Heo /**
49743d1cb205STejun Heo  * print_worker_info - print out worker information and description
49753d1cb205STejun Heo  * @log_lvl: the log level to use when printing
49763d1cb205STejun Heo  * @task: target task
49773d1cb205STejun Heo  *
49783d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
49793d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
49803d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
49813d1cb205STejun Heo  *
49823d1cb205STejun Heo  * This function can be safely called on any task as long as the
49833d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
49843d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
49853d1cb205STejun Heo  */
49863d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
49873d1cb205STejun Heo {
49883d1cb205STejun Heo 	work_func_t *fn = NULL;
49893d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
49903d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
49913d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
49923d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
49933d1cb205STejun Heo 	struct worker *worker;
49943d1cb205STejun Heo 
49953d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
49963d1cb205STejun Heo 		return;
49973d1cb205STejun Heo 
49983d1cb205STejun Heo 	/*
49993d1cb205STejun Heo 	 * This function is called without any synchronization and @task
50003d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
50013d1cb205STejun Heo 	 */
5002e700591aSPetr Mladek 	worker = kthread_probe_data(task);
50033d1cb205STejun Heo 
50043d1cb205STejun Heo 	/*
50058bf89593STejun Heo 	 * Carefully copy the associated workqueue's workfn, name and desc.
50068bf89593STejun Heo 	 * Keep the original last '\0' in case the original is garbage.
50073d1cb205STejun Heo 	 */
5008fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
5009fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
5010fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
5011fe557319SChristoph Hellwig 	copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
5012fe557319SChristoph Hellwig 	copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
50133d1cb205STejun Heo 
50143d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
5015d75f773cSSakari Ailus 		printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
50168bf89593STejun Heo 		if (strcmp(name, desc))
50173d1cb205STejun Heo 			pr_cont(" (%s)", desc);
50183d1cb205STejun Heo 		pr_cont("\n");
50193d1cb205STejun Heo 	}
50203d1cb205STejun Heo }
50213d1cb205STejun Heo 
50223494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
50233494fc30STejun Heo {
50243494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
50253494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
50263494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
50273494fc30STejun Heo 	pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
50283494fc30STejun Heo }
50293494fc30STejun Heo 
5030c76feb0dSPaul E. McKenney struct pr_cont_work_struct {
5031c76feb0dSPaul E. McKenney 	bool comma;
5032c76feb0dSPaul E. McKenney 	work_func_t func;
5033c76feb0dSPaul E. McKenney 	long ctr;
5034c76feb0dSPaul E. McKenney };
5035c76feb0dSPaul E. McKenney 
5036c76feb0dSPaul E. McKenney static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
5037c76feb0dSPaul E. McKenney {
5038c76feb0dSPaul E. McKenney 	if (!pcwsp->ctr)
5039c76feb0dSPaul E. McKenney 		goto out_record;
5040c76feb0dSPaul E. McKenney 	if (func == pcwsp->func) {
5041c76feb0dSPaul E. McKenney 		pcwsp->ctr++;
5042c76feb0dSPaul E. McKenney 		return;
5043c76feb0dSPaul E. McKenney 	}
5044c76feb0dSPaul E. McKenney 	if (pcwsp->ctr == 1)
5045c76feb0dSPaul E. McKenney 		pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
5046c76feb0dSPaul E. McKenney 	else
5047c76feb0dSPaul E. McKenney 		pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
5048c76feb0dSPaul E. McKenney 	pcwsp->ctr = 0;
5049c76feb0dSPaul E. McKenney out_record:
5050c76feb0dSPaul E. McKenney 	if ((long)func == -1L)
5051c76feb0dSPaul E. McKenney 		return;
5052c76feb0dSPaul E. McKenney 	pcwsp->comma = comma;
5053c76feb0dSPaul E. McKenney 	pcwsp->func = func;
5054c76feb0dSPaul E. McKenney 	pcwsp->ctr = 1;
5055c76feb0dSPaul E. McKenney }
5056c76feb0dSPaul E. McKenney 
5057c76feb0dSPaul E. McKenney static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
50583494fc30STejun Heo {
50593494fc30STejun Heo 	if (work->func == wq_barrier_func) {
50603494fc30STejun Heo 		struct wq_barrier *barr;
50613494fc30STejun Heo 
50623494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
50633494fc30STejun Heo 
5064c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
50653494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
50663494fc30STejun Heo 			task_pid_nr(barr->task));
50673494fc30STejun Heo 	} else {
5068c76feb0dSPaul E. McKenney 		if (!comma)
5069c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5070c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, work->func, pcwsp);
50713494fc30STejun Heo 	}
50723494fc30STejun Heo }
50733494fc30STejun Heo 
50743494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
50753494fc30STejun Heo {
5076c76feb0dSPaul E. McKenney 	struct pr_cont_work_struct pcws = { .ctr = 0, };
50773494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
50783494fc30STejun Heo 	struct work_struct *work;
50793494fc30STejun Heo 	struct worker *worker;
50803494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
50813494fc30STejun Heo 	int bkt;
50823494fc30STejun Heo 
50833494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
50843494fc30STejun Heo 	pr_cont_pool_info(pool);
50853494fc30STejun Heo 
5086e66b39afSTejun Heo 	pr_cont(" active=%d/%d refcnt=%d%s\n",
5087e66b39afSTejun Heo 		pwq->nr_active, pwq->max_active, pwq->refcnt,
50883494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
50893494fc30STejun Heo 
50903494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
50913494fc30STejun Heo 		if (worker->current_pwq == pwq) {
50923494fc30STejun Heo 			has_in_flight = true;
50933494fc30STejun Heo 			break;
50943494fc30STejun Heo 		}
50953494fc30STejun Heo 	}
50963494fc30STejun Heo 	if (has_in_flight) {
50973494fc30STejun Heo 		bool comma = false;
50983494fc30STejun Heo 
50993494fc30STejun Heo 		pr_info("    in-flight:");
51003494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
51013494fc30STejun Heo 			if (worker->current_pwq != pwq)
51023494fc30STejun Heo 				continue;
51033494fc30STejun Heo 
5104d75f773cSSakari Ailus 			pr_cont("%s %d%s:%ps", comma ? "," : "",
51053494fc30STejun Heo 				task_pid_nr(worker->task),
510630ae2fc0STejun Heo 				worker->rescue_wq ? "(RESCUER)" : "",
51073494fc30STejun Heo 				worker->current_func);
51083494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
5109c76feb0dSPaul E. McKenney 				pr_cont_work(false, work, &pcws);
5110c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
51113494fc30STejun Heo 			comma = true;
51123494fc30STejun Heo 		}
51133494fc30STejun Heo 		pr_cont("\n");
51143494fc30STejun Heo 	}
51153494fc30STejun Heo 
51163494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
51173494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
51183494fc30STejun Heo 			has_pending = true;
51193494fc30STejun Heo 			break;
51203494fc30STejun Heo 		}
51213494fc30STejun Heo 	}
51223494fc30STejun Heo 	if (has_pending) {
51233494fc30STejun Heo 		bool comma = false;
51243494fc30STejun Heo 
51253494fc30STejun Heo 		pr_info("    pending:");
51263494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
51273494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
51283494fc30STejun Heo 				continue;
51293494fc30STejun Heo 
5130c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
51313494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
51323494fc30STejun Heo 		}
5133c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
51343494fc30STejun Heo 		pr_cont("\n");
51353494fc30STejun Heo 	}
51363494fc30STejun Heo 
5137f97a4a1aSLai Jiangshan 	if (!list_empty(&pwq->inactive_works)) {
51383494fc30STejun Heo 		bool comma = false;
51393494fc30STejun Heo 
5140f97a4a1aSLai Jiangshan 		pr_info("    inactive:");
5141f97a4a1aSLai Jiangshan 		list_for_each_entry(work, &pwq->inactive_works, entry) {
5142c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
51433494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
51443494fc30STejun Heo 		}
5145c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
51463494fc30STejun Heo 		pr_cont("\n");
51473494fc30STejun Heo 	}
51483494fc30STejun Heo }
51493494fc30STejun Heo 
51503494fc30STejun Heo /**
515155df0933SImran Khan  * show_one_workqueue - dump state of specified workqueue
515255df0933SImran Khan  * @wq: workqueue whose state will be printed
51533494fc30STejun Heo  */
515455df0933SImran Khan void show_one_workqueue(struct workqueue_struct *wq)
51553494fc30STejun Heo {
51563494fc30STejun Heo 	struct pool_workqueue *pwq;
51573494fc30STejun Heo 	bool idle = true;
515855df0933SImran Khan 	unsigned long flags;
51593494fc30STejun Heo 
51603494fc30STejun Heo 	for_each_pwq(pwq, wq) {
5161f97a4a1aSLai Jiangshan 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
51623494fc30STejun Heo 			idle = false;
51633494fc30STejun Heo 			break;
51643494fc30STejun Heo 		}
51653494fc30STejun Heo 	}
516655df0933SImran Khan 	if (idle) /* Nothing to print for idle workqueue */
516755df0933SImran Khan 		return;
51683494fc30STejun Heo 
51693494fc30STejun Heo 	pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
51703494fc30STejun Heo 
51713494fc30STejun Heo 	for_each_pwq(pwq, wq) {
5172a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pwq->pool->lock, flags);
517357116ce1SJohan Hovold 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
517457116ce1SJohan Hovold 			/*
517557116ce1SJohan Hovold 			 * Defer printing to avoid deadlocks in console
517657116ce1SJohan Hovold 			 * drivers that queue work while holding locks
517757116ce1SJohan Hovold 			 * also taken in their write paths.
517857116ce1SJohan Hovold 			 */
517957116ce1SJohan Hovold 			printk_deferred_enter();
51803494fc30STejun Heo 			show_pwq(pwq);
518157116ce1SJohan Hovold 			printk_deferred_exit();
518257116ce1SJohan Hovold 		}
5183a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
518462635ea8SSergey Senozhatsky 		/*
518562635ea8SSergey Senozhatsky 		 * We could be printing a lot from atomic context, e.g.
518655df0933SImran Khan 		 * sysrq-t -> show_all_workqueues(). Avoid triggering
518762635ea8SSergey Senozhatsky 		 * hard lockup.
518862635ea8SSergey Senozhatsky 		 */
518962635ea8SSergey Senozhatsky 		touch_nmi_watchdog();
51903494fc30STejun Heo 	}
519155df0933SImran Khan 
51923494fc30STejun Heo }
51933494fc30STejun Heo 
519455df0933SImran Khan /**
519555df0933SImran Khan  * show_one_worker_pool - dump state of specified worker pool
519655df0933SImran Khan  * @pool: worker pool whose state will be printed
519755df0933SImran Khan  */
519855df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool)
519955df0933SImran Khan {
52003494fc30STejun Heo 	struct worker *worker;
52013494fc30STejun Heo 	bool first = true;
520255df0933SImran Khan 	unsigned long flags;
5203335a42ebSPetr Mladek 	unsigned long hung = 0;
52043494fc30STejun Heo 
5205a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pool->lock, flags);
52063494fc30STejun Heo 	if (pool->nr_workers == pool->nr_idle)
52073494fc30STejun Heo 		goto next_pool;
5208335a42ebSPetr Mladek 
5209335a42ebSPetr Mladek 	/* How long the first pending work is waiting for a worker. */
5210335a42ebSPetr Mladek 	if (!list_empty(&pool->worklist))
5211335a42ebSPetr Mladek 		hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
5212335a42ebSPetr Mladek 
521357116ce1SJohan Hovold 	/*
521457116ce1SJohan Hovold 	 * Defer printing to avoid deadlocks in console drivers that
521557116ce1SJohan Hovold 	 * queue work while holding locks also taken in their write
521657116ce1SJohan Hovold 	 * paths.
521757116ce1SJohan Hovold 	 */
521857116ce1SJohan Hovold 	printk_deferred_enter();
52193494fc30STejun Heo 	pr_info("pool %d:", pool->id);
52203494fc30STejun Heo 	pr_cont_pool_info(pool);
5221335a42ebSPetr Mladek 	pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
52223494fc30STejun Heo 	if (pool->manager)
52233494fc30STejun Heo 		pr_cont(" manager: %d",
52243494fc30STejun Heo 			task_pid_nr(pool->manager->task));
52253494fc30STejun Heo 	list_for_each_entry(worker, &pool->idle_list, entry) {
52263494fc30STejun Heo 		pr_cont(" %s%d", first ? "idle: " : "",
52273494fc30STejun Heo 			task_pid_nr(worker->task));
52283494fc30STejun Heo 		first = false;
52293494fc30STejun Heo 	}
52303494fc30STejun Heo 	pr_cont("\n");
523157116ce1SJohan Hovold 	printk_deferred_exit();
52323494fc30STejun Heo next_pool:
5233a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pool->lock, flags);
523462635ea8SSergey Senozhatsky 	/*
523562635ea8SSergey Senozhatsky 	 * We could be printing a lot from atomic context, e.g.
523655df0933SImran Khan 	 * sysrq-t -> show_all_workqueues(). Avoid triggering
523762635ea8SSergey Senozhatsky 	 * hard lockup.
523862635ea8SSergey Senozhatsky 	 */
523962635ea8SSergey Senozhatsky 	touch_nmi_watchdog();
524055df0933SImran Khan 
52413494fc30STejun Heo }
52423494fc30STejun Heo 
524355df0933SImran Khan /**
524455df0933SImran Khan  * show_all_workqueues - dump workqueue state
524555df0933SImran Khan  *
5246704bc669SJungseung Lee  * Called from a sysrq handler and prints out all busy workqueues and pools.
524755df0933SImran Khan  */
524855df0933SImran Khan void show_all_workqueues(void)
524955df0933SImran Khan {
525055df0933SImran Khan 	struct workqueue_struct *wq;
525155df0933SImran Khan 	struct worker_pool *pool;
525255df0933SImran Khan 	int pi;
525355df0933SImran Khan 
525455df0933SImran Khan 	rcu_read_lock();
525555df0933SImran Khan 
525655df0933SImran Khan 	pr_info("Showing busy workqueues and worker pools:\n");
525755df0933SImran Khan 
525855df0933SImran Khan 	list_for_each_entry_rcu(wq, &workqueues, list)
525955df0933SImran Khan 		show_one_workqueue(wq);
526055df0933SImran Khan 
526155df0933SImran Khan 	for_each_pool(pool, pi)
526255df0933SImran Khan 		show_one_worker_pool(pool);
526355df0933SImran Khan 
526424acfb71SThomas Gleixner 	rcu_read_unlock();
52653494fc30STejun Heo }
52663494fc30STejun Heo 
5267704bc669SJungseung Lee /**
5268704bc669SJungseung Lee  * show_freezable_workqueues - dump freezable workqueue state
5269704bc669SJungseung Lee  *
5270704bc669SJungseung Lee  * Called from try_to_freeze_tasks() and prints out all freezable workqueues
5271704bc669SJungseung Lee  * still busy.
5272704bc669SJungseung Lee  */
5273704bc669SJungseung Lee void show_freezable_workqueues(void)
5274704bc669SJungseung Lee {
5275704bc669SJungseung Lee 	struct workqueue_struct *wq;
5276704bc669SJungseung Lee 
5277704bc669SJungseung Lee 	rcu_read_lock();
5278704bc669SJungseung Lee 
5279704bc669SJungseung Lee 	pr_info("Showing freezable workqueues that are still busy:\n");
5280704bc669SJungseung Lee 
5281704bc669SJungseung Lee 	list_for_each_entry_rcu(wq, &workqueues, list) {
5282704bc669SJungseung Lee 		if (!(wq->flags & WQ_FREEZABLE))
5283704bc669SJungseung Lee 			continue;
5284704bc669SJungseung Lee 		show_one_workqueue(wq);
5285704bc669SJungseung Lee 	}
5286704bc669SJungseung Lee 
5287704bc669SJungseung Lee 	rcu_read_unlock();
5288704bc669SJungseung Lee }
5289704bc669SJungseung Lee 
52906b59808bSTejun Heo /* used to show worker information through /proc/PID/{comm,stat,status} */
52916b59808bSTejun Heo void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
52926b59808bSTejun Heo {
52936b59808bSTejun Heo 	int off;
52946b59808bSTejun Heo 
52956b59808bSTejun Heo 	/* always show the actual comm */
52966b59808bSTejun Heo 	off = strscpy(buf, task->comm, size);
52976b59808bSTejun Heo 	if (off < 0)
52986b59808bSTejun Heo 		return;
52996b59808bSTejun Heo 
5300197f6accSTejun Heo 	/* stabilize PF_WQ_WORKER and worker pool association */
53016b59808bSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
53026b59808bSTejun Heo 
5303197f6accSTejun Heo 	if (task->flags & PF_WQ_WORKER) {
5304197f6accSTejun Heo 		struct worker *worker = kthread_data(task);
5305197f6accSTejun Heo 		struct worker_pool *pool = worker->pool;
53066b59808bSTejun Heo 
53076b59808bSTejun Heo 		if (pool) {
5308a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock_irq(&pool->lock);
53096b59808bSTejun Heo 			/*
5310197f6accSTejun Heo 			 * ->desc tracks information (wq name or
5311197f6accSTejun Heo 			 * set_worker_desc()) for the latest execution.  If
5312197f6accSTejun Heo 			 * current, prepend '+', otherwise '-'.
53136b59808bSTejun Heo 			 */
53146b59808bSTejun Heo 			if (worker->desc[0] != '\0') {
53156b59808bSTejun Heo 				if (worker->current_work)
53166b59808bSTejun Heo 					scnprintf(buf + off, size - off, "+%s",
53176b59808bSTejun Heo 						  worker->desc);
53186b59808bSTejun Heo 				else
53196b59808bSTejun Heo 					scnprintf(buf + off, size - off, "-%s",
53206b59808bSTejun Heo 						  worker->desc);
53216b59808bSTejun Heo 			}
5322a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pool->lock);
53236b59808bSTejun Heo 		}
5324197f6accSTejun Heo 	}
53256b59808bSTejun Heo 
53266b59808bSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
53276b59808bSTejun Heo }
53286b59808bSTejun Heo 
532966448bc2SMathieu Malaterre #ifdef CONFIG_SMP
533066448bc2SMathieu Malaterre 
5331db7bccf4STejun Heo /*
5332db7bccf4STejun Heo  * CPU hotplug.
5333db7bccf4STejun Heo  *
5334e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
5335112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
5336706026c2STejun Heo  * pool which make migrating pending and scheduled works very
5337e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
533894cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
5339e22bee78STejun Heo  * blocked draining impractical.
5340e22bee78STejun Heo  *
534124647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
5342628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
5343628c78e7STejun Heo  * cpu comes back online.
5344db7bccf4STejun Heo  */
5345db7bccf4STejun Heo 
5346e8b3f8dbSLai Jiangshan static void unbind_workers(int cpu)
5347db7bccf4STejun Heo {
53484ce62e9eSTejun Heo 	struct worker_pool *pool;
5349db7bccf4STejun Heo 	struct worker *worker;
5350db7bccf4STejun Heo 
5351f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
53521258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
5353a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
5354e22bee78STejun Heo 
5355f2d5a0eeSTejun Heo 		/*
535692f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
535794cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
535811b45b0bSLai Jiangshan 		 * must be on the cpu.  After this, they may become diasporas.
5359b4ac9384SLai Jiangshan 		 * And the preemption disabled section in their sched callbacks
5360b4ac9384SLai Jiangshan 		 * are guaranteed to see WORKER_UNBOUND since the code here
5361b4ac9384SLai Jiangshan 		 * is on the same cpu.
5362f2d5a0eeSTejun Heo 		 */
5363da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
5364403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
5365db7bccf4STejun Heo 
536624647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
5367f2d5a0eeSTejun Heo 
5368e22bee78STejun Heo 		/*
5369989442d7SLai Jiangshan 		 * The handling of nr_running in sched callbacks are disabled
5370989442d7SLai Jiangshan 		 * now.  Zap nr_running.  After this, nr_running stays zero and
5371989442d7SLai Jiangshan 		 * need_more_worker() and keep_working() are always true as
5372989442d7SLai Jiangshan 		 * long as the worklist is not empty.  This pool now behaves as
5373989442d7SLai Jiangshan 		 * an unbound (in terms of concurrency management) pool which
5374eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
5375e22bee78STejun Heo 		 */
5376bc35f7efSLai Jiangshan 		pool->nr_running = 0;
5377eb283428SLai Jiangshan 
5378eb283428SLai Jiangshan 		/*
5379eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
5380eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
5381eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
5382eb283428SLai Jiangshan 		 */
5383eb283428SLai Jiangshan 		wake_up_worker(pool);
5384989442d7SLai Jiangshan 
5385a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
5386989442d7SLai Jiangshan 
5387793777bcSValentin Schneider 		for_each_pool_worker(worker, pool)
5388793777bcSValentin Schneider 			unbind_worker(worker);
5389989442d7SLai Jiangshan 
5390989442d7SLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
5391eb283428SLai Jiangshan 	}
5392db7bccf4STejun Heo }
5393db7bccf4STejun Heo 
5394bd7c089eSTejun Heo /**
5395bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
5396bd7c089eSTejun Heo  * @pool: pool of interest
5397bd7c089eSTejun Heo  *
5398a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
5399bd7c089eSTejun Heo  */
5400bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
5401bd7c089eSTejun Heo {
5402a9ab775bSTejun Heo 	struct worker *worker;
5403bd7c089eSTejun Heo 
54041258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
5405bd7c089eSTejun Heo 
5406bd7c089eSTejun Heo 	/*
5407a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
5408a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
5409402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
5410a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
5411a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
5412bd7c089eSTejun Heo 	 */
5413c63a2e52SValentin Schneider 	for_each_pool_worker(worker, pool) {
5414c63a2e52SValentin Schneider 		kthread_set_per_cpu(worker->task, pool->cpu);
5415c63a2e52SValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
5416c63a2e52SValentin Schneider 						  pool->attrs->cpumask) < 0);
5417c63a2e52SValentin Schneider 	}
5418a9ab775bSTejun Heo 
5419a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
5420f7c17d26SWanpeng Li 
54213de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
5422a9ab775bSTejun Heo 
5423da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
5424a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
5425a9ab775bSTejun Heo 
5426a9ab775bSTejun Heo 		/*
5427a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
5428a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
5429a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5430a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
5431a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
5432a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
5433a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
5434a9ab775bSTejun Heo 		 *
5435c95491edSMark Rutland 		 * WRITE_ONCE() is necessary because @worker->flags may be
5436a9ab775bSTejun Heo 		 * tested without holding any lock in
54376d25be57SThomas Gleixner 		 * wq_worker_running().  Without it, NOT_RUNNING test may
5438a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
5439a9ab775bSTejun Heo 		 * management operations.
5440bd7c089eSTejun Heo 		 */
5441a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5442a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
5443a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
5444c95491edSMark Rutland 		WRITE_ONCE(worker->flags, worker_flags);
5445bd7c089eSTejun Heo 	}
5446a9ab775bSTejun Heo 
5447a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
5448bd7c089eSTejun Heo }
5449bd7c089eSTejun Heo 
54507dbc725eSTejun Heo /**
54517dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
54527dbc725eSTejun Heo  * @pool: unbound pool of interest
54537dbc725eSTejun Heo  * @cpu: the CPU which is coming up
54547dbc725eSTejun Heo  *
54557dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
54567dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
54577dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
54587dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
54597dbc725eSTejun Heo  */
54607dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
54617dbc725eSTejun Heo {
54627dbc725eSTejun Heo 	static cpumask_t cpumask;
54637dbc725eSTejun Heo 	struct worker *worker;
54647dbc725eSTejun Heo 
54651258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
54667dbc725eSTejun Heo 
54677dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
54687dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
54697dbc725eSTejun Heo 		return;
54707dbc725eSTejun Heo 
54717dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
54727dbc725eSTejun Heo 
54737dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
5474da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
5475d945b5e9SPeter Zijlstra 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
54767dbc725eSTejun Heo }
54777dbc725eSTejun Heo 
54787ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
54791da177e4SLinus Torvalds {
54804ce62e9eSTejun Heo 	struct worker_pool *pool;
54811da177e4SLinus Torvalds 
5482f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
54833ce63377STejun Heo 		if (pool->nr_workers)
54843ce63377STejun Heo 			continue;
5485051e1850SLai Jiangshan 		if (!create_worker(pool))
54867ee681b2SThomas Gleixner 			return -ENOMEM;
54873af24433SOleg Nesterov 	}
54887ee681b2SThomas Gleixner 	return 0;
54897ee681b2SThomas Gleixner }
54901da177e4SLinus Torvalds 
54917ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
54927ee681b2SThomas Gleixner {
54937ee681b2SThomas Gleixner 	struct worker_pool *pool;
54947ee681b2SThomas Gleixner 	struct workqueue_struct *wq;
54957ee681b2SThomas Gleixner 	int pi;
54967ee681b2SThomas Gleixner 
549768e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
54987dbc725eSTejun Heo 
54997dbc725eSTejun Heo 	for_each_pool(pool, pi) {
55001258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
550194cf58bbSTejun Heo 
5502f05b558dSLai Jiangshan 		if (pool->cpu == cpu)
550394cf58bbSTejun Heo 			rebind_workers(pool);
5504f05b558dSLai Jiangshan 		else if (pool->cpu < 0)
55057dbc725eSTejun Heo 			restore_unbound_workers_cpumask(pool, cpu);
550694cf58bbSTejun Heo 
55071258fae7STejun Heo 		mutex_unlock(&wq_pool_attach_mutex);
550894cf58bbSTejun Heo 	}
55097dbc725eSTejun Heo 
55104c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
55114c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
55124c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, true);
55134c16bd32STejun Heo 
551468e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
55157ee681b2SThomas Gleixner 	return 0;
551665758202STejun Heo }
551765758202STejun Heo 
55187ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
551965758202STejun Heo {
55204c16bd32STejun Heo 	struct workqueue_struct *wq;
55218db25e78STejun Heo 
55224c16bd32STejun Heo 	/* unbinding per-cpu workers should happen on the local CPU */
5523e8b3f8dbSLai Jiangshan 	if (WARN_ON(cpu != smp_processor_id()))
5524e8b3f8dbSLai Jiangshan 		return -1;
5525e8b3f8dbSLai Jiangshan 
5526e8b3f8dbSLai Jiangshan 	unbind_workers(cpu);
55274c16bd32STejun Heo 
55284c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
55294c16bd32STejun Heo 	mutex_lock(&wq_pool_mutex);
55304c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
55314c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, false);
55324c16bd32STejun Heo 	mutex_unlock(&wq_pool_mutex);
55334c16bd32STejun Heo 
55347ee681b2SThomas Gleixner 	return 0;
553565758202STejun Heo }
553665758202STejun Heo 
55372d3854a3SRusty Russell struct work_for_cpu {
5538ed48ece2STejun Heo 	struct work_struct work;
55392d3854a3SRusty Russell 	long (*fn)(void *);
55402d3854a3SRusty Russell 	void *arg;
55412d3854a3SRusty Russell 	long ret;
55422d3854a3SRusty Russell };
55432d3854a3SRusty Russell 
5544ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
55452d3854a3SRusty Russell {
5546ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5547ed48ece2STejun Heo 
55482d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
55492d3854a3SRusty Russell }
55502d3854a3SRusty Russell 
55512d3854a3SRusty Russell /**
555222aceb31SAnna-Maria Gleixner  * work_on_cpu - run a function in thread context on a particular cpu
55532d3854a3SRusty Russell  * @cpu: the cpu to run on
55542d3854a3SRusty Russell  * @fn: the function to run
55552d3854a3SRusty Russell  * @arg: the function arg
55562d3854a3SRusty Russell  *
555731ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
55586b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
5559d185af30SYacine Belkadi  *
5560d185af30SYacine Belkadi  * Return: The value @fn returns.
55612d3854a3SRusty Russell  */
5562d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
55632d3854a3SRusty Russell {
5564ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
55652d3854a3SRusty Russell 
5566ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
5567ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
556812997d1aSBjorn Helgaas 	flush_work(&wfc.work);
5569440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
55702d3854a3SRusty Russell 	return wfc.ret;
55712d3854a3SRusty Russell }
55722d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
55730e8d6a93SThomas Gleixner 
55740e8d6a93SThomas Gleixner /**
55750e8d6a93SThomas Gleixner  * work_on_cpu_safe - run a function in thread context on a particular cpu
55760e8d6a93SThomas Gleixner  * @cpu: the cpu to run on
55770e8d6a93SThomas Gleixner  * @fn:  the function to run
55780e8d6a93SThomas Gleixner  * @arg: the function argument
55790e8d6a93SThomas Gleixner  *
55800e8d6a93SThomas Gleixner  * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
55810e8d6a93SThomas Gleixner  * any locks which would prevent @fn from completing.
55820e8d6a93SThomas Gleixner  *
55830e8d6a93SThomas Gleixner  * Return: The value @fn returns.
55840e8d6a93SThomas Gleixner  */
55850e8d6a93SThomas Gleixner long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
55860e8d6a93SThomas Gleixner {
55870e8d6a93SThomas Gleixner 	long ret = -ENODEV;
55880e8d6a93SThomas Gleixner 
5589ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
55900e8d6a93SThomas Gleixner 	if (cpu_online(cpu))
55910e8d6a93SThomas Gleixner 		ret = work_on_cpu(cpu, fn, arg);
5592ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
55930e8d6a93SThomas Gleixner 	return ret;
55940e8d6a93SThomas Gleixner }
55950e8d6a93SThomas Gleixner EXPORT_SYMBOL_GPL(work_on_cpu_safe);
55962d3854a3SRusty Russell #endif /* CONFIG_SMP */
55972d3854a3SRusty Russell 
5598a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
5599e7577c50SRusty Russell 
5600a0a1a5fdSTejun Heo /**
5601a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
5602a0a1a5fdSTejun Heo  *
560358a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
5604f97a4a1aSLai Jiangshan  * workqueues will queue new works to their inactive_works list instead of
5605706026c2STejun Heo  * pool->worklist.
5606a0a1a5fdSTejun Heo  *
5607a0a1a5fdSTejun Heo  * CONTEXT:
5608a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5609a0a1a5fdSTejun Heo  */
5610a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
5611a0a1a5fdSTejun Heo {
561224b8a847STejun Heo 	struct workqueue_struct *wq;
561324b8a847STejun Heo 	struct pool_workqueue *pwq;
5614a0a1a5fdSTejun Heo 
561568e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5616a0a1a5fdSTejun Heo 
56176183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
5618a0a1a5fdSTejun Heo 	workqueue_freezing = true;
5619a0a1a5fdSTejun Heo 
562024b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5621a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5622699ce097STejun Heo 		for_each_pwq(pwq, wq)
5623699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5624a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
5625a1056305STejun Heo 	}
56265bcab335STejun Heo 
562768e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5628a0a1a5fdSTejun Heo }
5629a0a1a5fdSTejun Heo 
5630a0a1a5fdSTejun Heo /**
563158a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
5632a0a1a5fdSTejun Heo  *
5633a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
5634a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
5635a0a1a5fdSTejun Heo  *
5636a0a1a5fdSTejun Heo  * CONTEXT:
563768e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
5638a0a1a5fdSTejun Heo  *
5639d185af30SYacine Belkadi  * Return:
564058a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
564158a69cb4STejun Heo  * is complete.
5642a0a1a5fdSTejun Heo  */
5643a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
5644a0a1a5fdSTejun Heo {
5645a0a1a5fdSTejun Heo 	bool busy = false;
564624b8a847STejun Heo 	struct workqueue_struct *wq;
564724b8a847STejun Heo 	struct pool_workqueue *pwq;
5648a0a1a5fdSTejun Heo 
564968e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5650a0a1a5fdSTejun Heo 
56516183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
5652a0a1a5fdSTejun Heo 
565324b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
565424b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
565524b8a847STejun Heo 			continue;
5656a0a1a5fdSTejun Heo 		/*
5657a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
5658a0a1a5fdSTejun Heo 		 * to peek without lock.
5659a0a1a5fdSTejun Heo 		 */
566024acfb71SThomas Gleixner 		rcu_read_lock();
566124b8a847STejun Heo 		for_each_pwq(pwq, wq) {
56626183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
5663112202d9STejun Heo 			if (pwq->nr_active) {
5664a0a1a5fdSTejun Heo 				busy = true;
566524acfb71SThomas Gleixner 				rcu_read_unlock();
5666a0a1a5fdSTejun Heo 				goto out_unlock;
5667a0a1a5fdSTejun Heo 			}
5668a0a1a5fdSTejun Heo 		}
566924acfb71SThomas Gleixner 		rcu_read_unlock();
5670a0a1a5fdSTejun Heo 	}
5671a0a1a5fdSTejun Heo out_unlock:
567268e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5673a0a1a5fdSTejun Heo 	return busy;
5674a0a1a5fdSTejun Heo }
5675a0a1a5fdSTejun Heo 
5676a0a1a5fdSTejun Heo /**
5677a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
5678a0a1a5fdSTejun Heo  *
5679a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
5680706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
5681a0a1a5fdSTejun Heo  *
5682a0a1a5fdSTejun Heo  * CONTEXT:
5683a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5684a0a1a5fdSTejun Heo  */
5685a0a1a5fdSTejun Heo void thaw_workqueues(void)
5686a0a1a5fdSTejun Heo {
568724b8a847STejun Heo 	struct workqueue_struct *wq;
568824b8a847STejun Heo 	struct pool_workqueue *pwq;
5689a0a1a5fdSTejun Heo 
569068e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5691a0a1a5fdSTejun Heo 
5692a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
5693a0a1a5fdSTejun Heo 		goto out_unlock;
5694a0a1a5fdSTejun Heo 
569574b414eaSLai Jiangshan 	workqueue_freezing = false;
569624b8a847STejun Heo 
569724b8a847STejun Heo 	/* restore max_active and repopulate worklist */
569824b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5699a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5700699ce097STejun Heo 		for_each_pwq(pwq, wq)
5701699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5702a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
570324b8a847STejun Heo 	}
570424b8a847STejun Heo 
5705a0a1a5fdSTejun Heo out_unlock:
570668e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5707a0a1a5fdSTejun Heo }
5708a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
5709a0a1a5fdSTejun Heo 
571099c621efSLai Jiangshan static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
5711042f7df1SLai Jiangshan {
5712042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
5713042f7df1SLai Jiangshan 	int ret = 0;
5714042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
5715042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
5716042f7df1SLai Jiangshan 
5717042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5718042f7df1SLai Jiangshan 
5719042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
5720042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
5721042f7df1SLai Jiangshan 			continue;
5722042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
5723042f7df1SLai Jiangshan 		if (wq->flags & __WQ_ORDERED)
5724042f7df1SLai Jiangshan 			continue;
5725042f7df1SLai Jiangshan 
572699c621efSLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
5727042f7df1SLai Jiangshan 		if (!ctx) {
5728042f7df1SLai Jiangshan 			ret = -ENOMEM;
5729042f7df1SLai Jiangshan 			break;
5730042f7df1SLai Jiangshan 		}
5731042f7df1SLai Jiangshan 
5732042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
5733042f7df1SLai Jiangshan 	}
5734042f7df1SLai Jiangshan 
5735042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
5736042f7df1SLai Jiangshan 		if (!ret)
5737042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
5738042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
5739042f7df1SLai Jiangshan 	}
5740042f7df1SLai Jiangshan 
574199c621efSLai Jiangshan 	if (!ret) {
574299c621efSLai Jiangshan 		mutex_lock(&wq_pool_attach_mutex);
574399c621efSLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
574499c621efSLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
574599c621efSLai Jiangshan 	}
5746042f7df1SLai Jiangshan 	return ret;
5747042f7df1SLai Jiangshan }
5748042f7df1SLai Jiangshan 
5749042f7df1SLai Jiangshan /**
5750042f7df1SLai Jiangshan  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5751042f7df1SLai Jiangshan  *  @cpumask: the cpumask to set
5752042f7df1SLai Jiangshan  *
5753042f7df1SLai Jiangshan  *  The low-level workqueues cpumask is a global cpumask that limits
5754042f7df1SLai Jiangshan  *  the affinity of all unbound workqueues.  This function check the @cpumask
5755042f7df1SLai Jiangshan  *  and apply it to all unbound workqueues and updates all pwqs of them.
5756042f7df1SLai Jiangshan  *
575767dc8325SCai Huoqing  *  Return:	0	- Success
5758042f7df1SLai Jiangshan  *  		-EINVAL	- Invalid @cpumask
5759042f7df1SLai Jiangshan  *  		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
5760042f7df1SLai Jiangshan  */
5761042f7df1SLai Jiangshan int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5762042f7df1SLai Jiangshan {
5763042f7df1SLai Jiangshan 	int ret = -EINVAL;
5764042f7df1SLai Jiangshan 
5765c98a9805STal Shorer 	/*
5766c98a9805STal Shorer 	 * Not excluding isolated cpus on purpose.
5767c98a9805STal Shorer 	 * If the user wishes to include them, we allow that.
5768c98a9805STal Shorer 	 */
5769042f7df1SLai Jiangshan 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
5770042f7df1SLai Jiangshan 	if (!cpumask_empty(cpumask)) {
5771a0111cf6SLai Jiangshan 		apply_wqattrs_lock();
5772d25302e4SMenglong Dong 		if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
5773d25302e4SMenglong Dong 			ret = 0;
5774d25302e4SMenglong Dong 			goto out_unlock;
5775d25302e4SMenglong Dong 		}
5776d25302e4SMenglong Dong 
577799c621efSLai Jiangshan 		ret = workqueue_apply_unbound_cpumask(cpumask);
5778042f7df1SLai Jiangshan 
5779d25302e4SMenglong Dong out_unlock:
5780a0111cf6SLai Jiangshan 		apply_wqattrs_unlock();
5781042f7df1SLai Jiangshan 	}
5782042f7df1SLai Jiangshan 
5783042f7df1SLai Jiangshan 	return ret;
5784042f7df1SLai Jiangshan }
5785042f7df1SLai Jiangshan 
57866ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
57876ba94429SFrederic Weisbecker /*
57886ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
57896ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
57906ba94429SFrederic Weisbecker  * following attributes.
57916ba94429SFrederic Weisbecker  *
57926ba94429SFrederic Weisbecker  *  per_cpu	RO bool	: whether the workqueue is per-cpu or unbound
57936ba94429SFrederic Weisbecker  *  max_active	RW int	: maximum number of in-flight work items
57946ba94429SFrederic Weisbecker  *
57956ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
57966ba94429SFrederic Weisbecker  *
57979a19b463SWang Long  *  pool_ids	RO int	: the associated pool IDs for each node
57986ba94429SFrederic Weisbecker  *  nice	RW int	: nice value of the workers
57996ba94429SFrederic Weisbecker  *  cpumask	RW mask	: bitmask of allowed CPUs for the workers
58009a19b463SWang Long  *  numa	RW bool	: whether enable NUMA affinity
58016ba94429SFrederic Weisbecker  */
58026ba94429SFrederic Weisbecker struct wq_device {
58036ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
58046ba94429SFrederic Weisbecker 	struct device			dev;
58056ba94429SFrederic Weisbecker };
58066ba94429SFrederic Weisbecker 
58076ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
58086ba94429SFrederic Weisbecker {
58096ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
58106ba94429SFrederic Weisbecker 
58116ba94429SFrederic Weisbecker 	return wq_dev->wq;
58126ba94429SFrederic Weisbecker }
58136ba94429SFrederic Weisbecker 
58146ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
58156ba94429SFrederic Weisbecker 			    char *buf)
58166ba94429SFrederic Weisbecker {
58176ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
58186ba94429SFrederic Weisbecker 
58196ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
58206ba94429SFrederic Weisbecker }
58216ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
58226ba94429SFrederic Weisbecker 
58236ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
58246ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
58256ba94429SFrederic Weisbecker {
58266ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
58276ba94429SFrederic Weisbecker 
58286ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
58296ba94429SFrederic Weisbecker }
58306ba94429SFrederic Weisbecker 
58316ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
58326ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
58336ba94429SFrederic Weisbecker 				size_t count)
58346ba94429SFrederic Weisbecker {
58356ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
58366ba94429SFrederic Weisbecker 	int val;
58376ba94429SFrederic Weisbecker 
58386ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
58396ba94429SFrederic Weisbecker 		return -EINVAL;
58406ba94429SFrederic Weisbecker 
58416ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
58426ba94429SFrederic Weisbecker 	return count;
58436ba94429SFrederic Weisbecker }
58446ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
58456ba94429SFrederic Weisbecker 
58466ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
58476ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
58486ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
58496ba94429SFrederic Weisbecker 	NULL,
58506ba94429SFrederic Weisbecker };
58516ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
58526ba94429SFrederic Weisbecker 
58536ba94429SFrederic Weisbecker static ssize_t wq_pool_ids_show(struct device *dev,
58546ba94429SFrederic Weisbecker 				struct device_attribute *attr, char *buf)
58556ba94429SFrederic Weisbecker {
58566ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
58576ba94429SFrederic Weisbecker 	const char *delim = "";
58586ba94429SFrederic Weisbecker 	int node, written = 0;
58596ba94429SFrederic Weisbecker 
5860ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
586124acfb71SThomas Gleixner 	rcu_read_lock();
58626ba94429SFrederic Weisbecker 	for_each_node(node) {
58636ba94429SFrederic Weisbecker 		written += scnprintf(buf + written, PAGE_SIZE - written,
58646ba94429SFrederic Weisbecker 				     "%s%d:%d", delim, node,
58656ba94429SFrederic Weisbecker 				     unbound_pwq_by_node(wq, node)->pool->id);
58666ba94429SFrederic Weisbecker 		delim = " ";
58676ba94429SFrederic Weisbecker 	}
58686ba94429SFrederic Weisbecker 	written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
586924acfb71SThomas Gleixner 	rcu_read_unlock();
5870ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
58716ba94429SFrederic Weisbecker 
58726ba94429SFrederic Weisbecker 	return written;
58736ba94429SFrederic Weisbecker }
58746ba94429SFrederic Weisbecker 
58756ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
58766ba94429SFrederic Weisbecker 			    char *buf)
58776ba94429SFrederic Weisbecker {
58786ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
58796ba94429SFrederic Weisbecker 	int written;
58806ba94429SFrederic Weisbecker 
58816ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
58826ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
58836ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
58846ba94429SFrederic Weisbecker 
58856ba94429SFrederic Weisbecker 	return written;
58866ba94429SFrederic Weisbecker }
58876ba94429SFrederic Weisbecker 
58886ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
58896ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
58906ba94429SFrederic Weisbecker {
58916ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
58926ba94429SFrederic Weisbecker 
5893899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5894899a94feSLai Jiangshan 
5895be69d00dSThomas Gleixner 	attrs = alloc_workqueue_attrs();
58966ba94429SFrederic Weisbecker 	if (!attrs)
58976ba94429SFrederic Weisbecker 		return NULL;
58986ba94429SFrederic Weisbecker 
58996ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
59006ba94429SFrederic Weisbecker 	return attrs;
59016ba94429SFrederic Weisbecker }
59026ba94429SFrederic Weisbecker 
59036ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
59046ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
59056ba94429SFrederic Weisbecker {
59066ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
59076ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5908d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5909d4d3e257SLai Jiangshan 
5910d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
59116ba94429SFrederic Weisbecker 
59126ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
59136ba94429SFrederic Weisbecker 	if (!attrs)
5914d4d3e257SLai Jiangshan 		goto out_unlock;
59156ba94429SFrederic Weisbecker 
59166ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
59176ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5918d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
59196ba94429SFrederic Weisbecker 	else
59206ba94429SFrederic Weisbecker 		ret = -EINVAL;
59216ba94429SFrederic Weisbecker 
5922d4d3e257SLai Jiangshan out_unlock:
5923d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
59246ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
59256ba94429SFrederic Weisbecker 	return ret ?: count;
59266ba94429SFrederic Weisbecker }
59276ba94429SFrederic Weisbecker 
59286ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
59296ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
59306ba94429SFrederic Weisbecker {
59316ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
59326ba94429SFrederic Weisbecker 	int written;
59336ba94429SFrederic Weisbecker 
59346ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
59356ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
59366ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
59376ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
59386ba94429SFrederic Weisbecker 	return written;
59396ba94429SFrederic Weisbecker }
59406ba94429SFrederic Weisbecker 
59416ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
59426ba94429SFrederic Weisbecker 				struct device_attribute *attr,
59436ba94429SFrederic Weisbecker 				const char *buf, size_t count)
59446ba94429SFrederic Weisbecker {
59456ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
59466ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5947d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5948d4d3e257SLai Jiangshan 
5949d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
59506ba94429SFrederic Weisbecker 
59516ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
59526ba94429SFrederic Weisbecker 	if (!attrs)
5953d4d3e257SLai Jiangshan 		goto out_unlock;
59546ba94429SFrederic Weisbecker 
59556ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
59566ba94429SFrederic Weisbecker 	if (!ret)
5957d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
59586ba94429SFrederic Weisbecker 
5959d4d3e257SLai Jiangshan out_unlock:
5960d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
59616ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
59626ba94429SFrederic Weisbecker 	return ret ?: count;
59636ba94429SFrederic Weisbecker }
59646ba94429SFrederic Weisbecker 
59656ba94429SFrederic Weisbecker static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
59666ba94429SFrederic Weisbecker 			    char *buf)
59676ba94429SFrederic Weisbecker {
59686ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
59696ba94429SFrederic Weisbecker 	int written;
59706ba94429SFrederic Weisbecker 
59716ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
59726ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n",
59736ba94429SFrederic Weisbecker 			    !wq->unbound_attrs->no_numa);
59746ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
59756ba94429SFrederic Weisbecker 
59766ba94429SFrederic Weisbecker 	return written;
59776ba94429SFrederic Weisbecker }
59786ba94429SFrederic Weisbecker 
59796ba94429SFrederic Weisbecker static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
59806ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
59816ba94429SFrederic Weisbecker {
59826ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
59836ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5984d4d3e257SLai Jiangshan 	int v, ret = -ENOMEM;
5985d4d3e257SLai Jiangshan 
5986d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
59876ba94429SFrederic Weisbecker 
59886ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
59896ba94429SFrederic Weisbecker 	if (!attrs)
5990d4d3e257SLai Jiangshan 		goto out_unlock;
59916ba94429SFrederic Weisbecker 
59926ba94429SFrederic Weisbecker 	ret = -EINVAL;
59936ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &v) == 1) {
59946ba94429SFrederic Weisbecker 		attrs->no_numa = !v;
5995d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
59966ba94429SFrederic Weisbecker 	}
59976ba94429SFrederic Weisbecker 
5998d4d3e257SLai Jiangshan out_unlock:
5999d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
60006ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
60016ba94429SFrederic Weisbecker 	return ret ?: count;
60026ba94429SFrederic Weisbecker }
60036ba94429SFrederic Weisbecker 
60046ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
60056ba94429SFrederic Weisbecker 	__ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
60066ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
60076ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
60086ba94429SFrederic Weisbecker 	__ATTR(numa, 0644, wq_numa_show, wq_numa_store),
60096ba94429SFrederic Weisbecker 	__ATTR_NULL,
60106ba94429SFrederic Weisbecker };
60116ba94429SFrederic Weisbecker 
60126ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
60136ba94429SFrederic Weisbecker 	.name				= "workqueue",
60146ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
60156ba94429SFrederic Weisbecker };
60166ba94429SFrederic Weisbecker 
6017b05a7928SFrederic Weisbecker static ssize_t wq_unbound_cpumask_show(struct device *dev,
6018b05a7928SFrederic Weisbecker 		struct device_attribute *attr, char *buf)
6019b05a7928SFrederic Weisbecker {
6020b05a7928SFrederic Weisbecker 	int written;
6021b05a7928SFrederic Weisbecker 
6022042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
6023b05a7928SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
6024b05a7928SFrederic Weisbecker 			    cpumask_pr_args(wq_unbound_cpumask));
6025042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
6026b05a7928SFrederic Weisbecker 
6027b05a7928SFrederic Weisbecker 	return written;
6028b05a7928SFrederic Weisbecker }
6029b05a7928SFrederic Weisbecker 
6030042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
6031042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
6032042f7df1SLai Jiangshan {
6033042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
6034042f7df1SLai Jiangshan 	int ret;
6035042f7df1SLai Jiangshan 
6036042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
6037042f7df1SLai Jiangshan 		return -ENOMEM;
6038042f7df1SLai Jiangshan 
6039042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
6040042f7df1SLai Jiangshan 	if (!ret)
6041042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
6042042f7df1SLai Jiangshan 
6043042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
6044042f7df1SLai Jiangshan 	return ret ? ret : count;
6045042f7df1SLai Jiangshan }
6046042f7df1SLai Jiangshan 
6047b05a7928SFrederic Weisbecker static struct device_attribute wq_sysfs_cpumask_attr =
6048042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
6049042f7df1SLai Jiangshan 	       wq_unbound_cpumask_store);
6050b05a7928SFrederic Weisbecker 
60516ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
60526ba94429SFrederic Weisbecker {
6053686f6697SGreg Kroah-Hartman 	struct device *dev_root;
6054b05a7928SFrederic Weisbecker 	int err;
6055b05a7928SFrederic Weisbecker 
6056b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
6057b05a7928SFrederic Weisbecker 	if (err)
6058b05a7928SFrederic Weisbecker 		return err;
6059b05a7928SFrederic Weisbecker 
6060686f6697SGreg Kroah-Hartman 	dev_root = bus_get_dev_root(&wq_subsys);
6061686f6697SGreg Kroah-Hartman 	if (dev_root) {
6062686f6697SGreg Kroah-Hartman 		err = device_create_file(dev_root, &wq_sysfs_cpumask_attr);
6063686f6697SGreg Kroah-Hartman 		put_device(dev_root);
6064686f6697SGreg Kroah-Hartman 	}
6065686f6697SGreg Kroah-Hartman 	return err;
60666ba94429SFrederic Weisbecker }
60676ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
60686ba94429SFrederic Weisbecker 
60696ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
60706ba94429SFrederic Weisbecker {
60716ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
60726ba94429SFrederic Weisbecker 
60736ba94429SFrederic Weisbecker 	kfree(wq_dev);
60746ba94429SFrederic Weisbecker }
60756ba94429SFrederic Weisbecker 
60766ba94429SFrederic Weisbecker /**
60776ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
60786ba94429SFrederic Weisbecker  * @wq: the workqueue to register
60796ba94429SFrederic Weisbecker  *
60806ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
60816ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
60826ba94429SFrederic Weisbecker  * which is the preferred method.
60836ba94429SFrederic Weisbecker  *
60846ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
60856ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
60866ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
60876ba94429SFrederic Weisbecker  * attributes.
60886ba94429SFrederic Weisbecker  *
60896ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
60906ba94429SFrederic Weisbecker  */
60916ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
60926ba94429SFrederic Weisbecker {
60936ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
60946ba94429SFrederic Weisbecker 	int ret;
60956ba94429SFrederic Weisbecker 
60966ba94429SFrederic Weisbecker 	/*
6097402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
60986ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
60996ba94429SFrederic Weisbecker 	 * workqueues.
61006ba94429SFrederic Weisbecker 	 */
61010a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
61026ba94429SFrederic Weisbecker 		return -EINVAL;
61036ba94429SFrederic Weisbecker 
61046ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
61056ba94429SFrederic Weisbecker 	if (!wq_dev)
61066ba94429SFrederic Weisbecker 		return -ENOMEM;
61076ba94429SFrederic Weisbecker 
61086ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
61096ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
61106ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
611123217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
61126ba94429SFrederic Weisbecker 
61136ba94429SFrederic Weisbecker 	/*
61146ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
61156ba94429SFrederic Weisbecker 	 * everything is ready.
61166ba94429SFrederic Weisbecker 	 */
61176ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
61186ba94429SFrederic Weisbecker 
61196ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
61206ba94429SFrederic Weisbecker 	if (ret) {
6121537f4146SArvind Yadav 		put_device(&wq_dev->dev);
61226ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
61236ba94429SFrederic Weisbecker 		return ret;
61246ba94429SFrederic Weisbecker 	}
61256ba94429SFrederic Weisbecker 
61266ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
61276ba94429SFrederic Weisbecker 		struct device_attribute *attr;
61286ba94429SFrederic Weisbecker 
61296ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
61306ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
61316ba94429SFrederic Weisbecker 			if (ret) {
61326ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
61336ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
61346ba94429SFrederic Weisbecker 				return ret;
61356ba94429SFrederic Weisbecker 			}
61366ba94429SFrederic Weisbecker 		}
61376ba94429SFrederic Weisbecker 	}
61386ba94429SFrederic Weisbecker 
61396ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
61406ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
61416ba94429SFrederic Weisbecker 	return 0;
61426ba94429SFrederic Weisbecker }
61436ba94429SFrederic Weisbecker 
61446ba94429SFrederic Weisbecker /**
61456ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
61466ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
61476ba94429SFrederic Weisbecker  *
61486ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
61496ba94429SFrederic Weisbecker  */
61506ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
61516ba94429SFrederic Weisbecker {
61526ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
61536ba94429SFrederic Weisbecker 
61546ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
61556ba94429SFrederic Weisbecker 		return;
61566ba94429SFrederic Weisbecker 
61576ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
61586ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
61596ba94429SFrederic Weisbecker }
61606ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
61616ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
61626ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
61636ba94429SFrederic Weisbecker 
616482607adcSTejun Heo /*
616582607adcSTejun Heo  * Workqueue watchdog.
616682607adcSTejun Heo  *
616782607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
616882607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
616982607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
617082607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
617182607adcSTejun Heo  * largely opaque.
617282607adcSTejun Heo  *
617382607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
617482607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
617582607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
617682607adcSTejun Heo  *
617782607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
617882607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
617982607adcSTejun Heo  * corresponding sysfs parameter file.
618082607adcSTejun Heo  */
618182607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
618282607adcSTejun Heo 
618382607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
61845cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
618582607adcSTejun Heo 
618682607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
618782607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
618882607adcSTejun Heo 
6189cd2440d6SPetr Mladek /*
6190cd2440d6SPetr Mladek  * Show workers that might prevent the processing of pending work items.
6191cd2440d6SPetr Mladek  * The only candidates are CPU-bound workers in the running state.
6192cd2440d6SPetr Mladek  * Pending work items should be handled by another idle worker
6193cd2440d6SPetr Mladek  * in all other situations.
6194cd2440d6SPetr Mladek  */
6195cd2440d6SPetr Mladek static void show_cpu_pool_hog(struct worker_pool *pool)
6196cd2440d6SPetr Mladek {
6197cd2440d6SPetr Mladek 	struct worker *worker;
6198cd2440d6SPetr Mladek 	unsigned long flags;
6199cd2440d6SPetr Mladek 	int bkt;
6200cd2440d6SPetr Mladek 
6201cd2440d6SPetr Mladek 	raw_spin_lock_irqsave(&pool->lock, flags);
6202cd2440d6SPetr Mladek 
6203cd2440d6SPetr Mladek 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
6204cd2440d6SPetr Mladek 		if (task_is_running(worker->task)) {
6205cd2440d6SPetr Mladek 			/*
6206cd2440d6SPetr Mladek 			 * Defer printing to avoid deadlocks in console
6207cd2440d6SPetr Mladek 			 * drivers that queue work while holding locks
6208cd2440d6SPetr Mladek 			 * also taken in their write paths.
6209cd2440d6SPetr Mladek 			 */
6210cd2440d6SPetr Mladek 			printk_deferred_enter();
6211cd2440d6SPetr Mladek 
6212cd2440d6SPetr Mladek 			pr_info("pool %d:\n", pool->id);
6213cd2440d6SPetr Mladek 			sched_show_task(worker->task);
6214cd2440d6SPetr Mladek 
6215cd2440d6SPetr Mladek 			printk_deferred_exit();
6216cd2440d6SPetr Mladek 		}
6217cd2440d6SPetr Mladek 	}
6218cd2440d6SPetr Mladek 
6219cd2440d6SPetr Mladek 	raw_spin_unlock_irqrestore(&pool->lock, flags);
6220cd2440d6SPetr Mladek }
6221cd2440d6SPetr Mladek 
6222cd2440d6SPetr Mladek static void show_cpu_pools_hogs(void)
6223cd2440d6SPetr Mladek {
6224cd2440d6SPetr Mladek 	struct worker_pool *pool;
6225cd2440d6SPetr Mladek 	int pi;
6226cd2440d6SPetr Mladek 
6227cd2440d6SPetr Mladek 	pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
6228cd2440d6SPetr Mladek 
6229cd2440d6SPetr Mladek 	rcu_read_lock();
6230cd2440d6SPetr Mladek 
6231cd2440d6SPetr Mladek 	for_each_pool(pool, pi) {
6232cd2440d6SPetr Mladek 		if (pool->cpu_stall)
6233cd2440d6SPetr Mladek 			show_cpu_pool_hog(pool);
6234cd2440d6SPetr Mladek 
6235cd2440d6SPetr Mladek 	}
6236cd2440d6SPetr Mladek 
6237cd2440d6SPetr Mladek 	rcu_read_unlock();
6238cd2440d6SPetr Mladek }
6239cd2440d6SPetr Mladek 
624082607adcSTejun Heo static void wq_watchdog_reset_touched(void)
624182607adcSTejun Heo {
624282607adcSTejun Heo 	int cpu;
624382607adcSTejun Heo 
624482607adcSTejun Heo 	wq_watchdog_touched = jiffies;
624582607adcSTejun Heo 	for_each_possible_cpu(cpu)
624682607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
624782607adcSTejun Heo }
624882607adcSTejun Heo 
62495cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
625082607adcSTejun Heo {
625182607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
625282607adcSTejun Heo 	bool lockup_detected = false;
6253cd2440d6SPetr Mladek 	bool cpu_pool_stall = false;
6254940d71c6SSergey Senozhatsky 	unsigned long now = jiffies;
625582607adcSTejun Heo 	struct worker_pool *pool;
625682607adcSTejun Heo 	int pi;
625782607adcSTejun Heo 
625882607adcSTejun Heo 	if (!thresh)
625982607adcSTejun Heo 		return;
626082607adcSTejun Heo 
626182607adcSTejun Heo 	rcu_read_lock();
626282607adcSTejun Heo 
626382607adcSTejun Heo 	for_each_pool(pool, pi) {
626482607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
626582607adcSTejun Heo 
6266cd2440d6SPetr Mladek 		pool->cpu_stall = false;
626782607adcSTejun Heo 		if (list_empty(&pool->worklist))
626882607adcSTejun Heo 			continue;
626982607adcSTejun Heo 
6270940d71c6SSergey Senozhatsky 		/*
6271940d71c6SSergey Senozhatsky 		 * If a virtual machine is stopped by the host it can look to
6272940d71c6SSergey Senozhatsky 		 * the watchdog like a stall.
6273940d71c6SSergey Senozhatsky 		 */
6274940d71c6SSergey Senozhatsky 		kvm_check_and_clear_guest_paused();
6275940d71c6SSergey Senozhatsky 
627682607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
627789e28ce6SWang Qing 		if (pool->cpu >= 0)
627889e28ce6SWang Qing 			touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
627989e28ce6SWang Qing 		else
628082607adcSTejun Heo 			touched = READ_ONCE(wq_watchdog_touched);
628189e28ce6SWang Qing 		pool_ts = READ_ONCE(pool->watchdog_ts);
628282607adcSTejun Heo 
628382607adcSTejun Heo 		if (time_after(pool_ts, touched))
628482607adcSTejun Heo 			ts = pool_ts;
628582607adcSTejun Heo 		else
628682607adcSTejun Heo 			ts = touched;
628782607adcSTejun Heo 
628882607adcSTejun Heo 		/* did we stall? */
6289940d71c6SSergey Senozhatsky 		if (time_after(now, ts + thresh)) {
629082607adcSTejun Heo 			lockup_detected = true;
6291cd2440d6SPetr Mladek 			if (pool->cpu >= 0) {
6292cd2440d6SPetr Mladek 				pool->cpu_stall = true;
6293cd2440d6SPetr Mladek 				cpu_pool_stall = true;
6294cd2440d6SPetr Mladek 			}
629582607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
629682607adcSTejun Heo 			pr_cont_pool_info(pool);
629782607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
6298940d71c6SSergey Senozhatsky 				jiffies_to_msecs(now - pool_ts) / 1000);
629982607adcSTejun Heo 		}
6300cd2440d6SPetr Mladek 
6301cd2440d6SPetr Mladek 
630282607adcSTejun Heo 	}
630382607adcSTejun Heo 
630482607adcSTejun Heo 	rcu_read_unlock();
630582607adcSTejun Heo 
630682607adcSTejun Heo 	if (lockup_detected)
630755df0933SImran Khan 		show_all_workqueues();
630882607adcSTejun Heo 
6309cd2440d6SPetr Mladek 	if (cpu_pool_stall)
6310cd2440d6SPetr Mladek 		show_cpu_pools_hogs();
6311cd2440d6SPetr Mladek 
631282607adcSTejun Heo 	wq_watchdog_reset_touched();
631382607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
631482607adcSTejun Heo }
631582607adcSTejun Heo 
6316cb9d7fd5SVincent Whitchurch notrace void wq_watchdog_touch(int cpu)
631782607adcSTejun Heo {
631882607adcSTejun Heo 	if (cpu >= 0)
631982607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
632089e28ce6SWang Qing 
632182607adcSTejun Heo 	wq_watchdog_touched = jiffies;
632282607adcSTejun Heo }
632382607adcSTejun Heo 
632482607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
632582607adcSTejun Heo {
632682607adcSTejun Heo 	wq_watchdog_thresh = 0;
632782607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
632882607adcSTejun Heo 
632982607adcSTejun Heo 	if (thresh) {
633082607adcSTejun Heo 		wq_watchdog_thresh = thresh;
633182607adcSTejun Heo 		wq_watchdog_reset_touched();
633282607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
633382607adcSTejun Heo 	}
633482607adcSTejun Heo }
633582607adcSTejun Heo 
633682607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
633782607adcSTejun Heo 					const struct kernel_param *kp)
633882607adcSTejun Heo {
633982607adcSTejun Heo 	unsigned long thresh;
634082607adcSTejun Heo 	int ret;
634182607adcSTejun Heo 
634282607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
634382607adcSTejun Heo 	if (ret)
634482607adcSTejun Heo 		return ret;
634582607adcSTejun Heo 
634682607adcSTejun Heo 	if (system_wq)
634782607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
634882607adcSTejun Heo 	else
634982607adcSTejun Heo 		wq_watchdog_thresh = thresh;
635082607adcSTejun Heo 
635182607adcSTejun Heo 	return 0;
635282607adcSTejun Heo }
635382607adcSTejun Heo 
635482607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
635582607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
635682607adcSTejun Heo 	.get	= param_get_ulong,
635782607adcSTejun Heo };
635882607adcSTejun Heo 
635982607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
636082607adcSTejun Heo 		0644);
636182607adcSTejun Heo 
636282607adcSTejun Heo static void wq_watchdog_init(void)
636382607adcSTejun Heo {
63645cd79d6aSKees Cook 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
636582607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
636682607adcSTejun Heo }
636782607adcSTejun Heo 
636882607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
636982607adcSTejun Heo 
637082607adcSTejun Heo static inline void wq_watchdog_init(void) { }
637182607adcSTejun Heo 
637282607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
637382607adcSTejun Heo 
6374bce90380STejun Heo static void __init wq_numa_init(void)
6375bce90380STejun Heo {
6376bce90380STejun Heo 	cpumask_var_t *tbl;
6377bce90380STejun Heo 	int node, cpu;
6378bce90380STejun Heo 
6379bce90380STejun Heo 	if (num_possible_nodes() <= 1)
6380bce90380STejun Heo 		return;
6381bce90380STejun Heo 
6382d55262c4STejun Heo 	if (wq_disable_numa) {
6383d55262c4STejun Heo 		pr_info("workqueue: NUMA affinity support disabled\n");
6384d55262c4STejun Heo 		return;
6385d55262c4STejun Heo 	}
6386d55262c4STejun Heo 
6387f728c4a9SZhen Lei 	for_each_possible_cpu(cpu) {
6388f728c4a9SZhen Lei 		if (WARN_ON(cpu_to_node(cpu) == NUMA_NO_NODE)) {
6389f728c4a9SZhen Lei 			pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
6390f728c4a9SZhen Lei 			return;
6391f728c4a9SZhen Lei 		}
6392f728c4a9SZhen Lei 	}
6393f728c4a9SZhen Lei 
6394be69d00dSThomas Gleixner 	wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs();
63954c16bd32STejun Heo 	BUG_ON(!wq_update_unbound_numa_attrs_buf);
63964c16bd32STejun Heo 
6397bce90380STejun Heo 	/*
6398bce90380STejun Heo 	 * We want masks of possible CPUs of each node which isn't readily
6399bce90380STejun Heo 	 * available.  Build one from cpu_to_node() which should have been
6400bce90380STejun Heo 	 * fully initialized by now.
6401bce90380STejun Heo 	 */
64026396bb22SKees Cook 	tbl = kcalloc(nr_node_ids, sizeof(tbl[0]), GFP_KERNEL);
6403bce90380STejun Heo 	BUG_ON(!tbl);
6404bce90380STejun Heo 
6405bce90380STejun Heo 	for_each_node(node)
64065a6024f1SYasuaki Ishimatsu 		BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
64071be0c25dSTejun Heo 				node_online(node) ? node : NUMA_NO_NODE));
6408bce90380STejun Heo 
6409bce90380STejun Heo 	for_each_possible_cpu(cpu) {
6410bce90380STejun Heo 		node = cpu_to_node(cpu);
6411bce90380STejun Heo 		cpumask_set_cpu(cpu, tbl[node]);
6412bce90380STejun Heo 	}
6413bce90380STejun Heo 
6414bce90380STejun Heo 	wq_numa_possible_cpumask = tbl;
6415bce90380STejun Heo 	wq_numa_enabled = true;
6416bce90380STejun Heo }
6417bce90380STejun Heo 
64183347fa09STejun Heo /**
64193347fa09STejun Heo  * workqueue_init_early - early init for workqueue subsystem
64203347fa09STejun Heo  *
64213347fa09STejun Heo  * This is the first half of two-staged workqueue subsystem initialization
64223347fa09STejun Heo  * and invoked as soon as the bare basics - memory allocation, cpumasks and
64233347fa09STejun Heo  * idr are up.  It sets up all the data structures and system workqueues
64243347fa09STejun Heo  * and allows early boot code to create workqueues and queue/cancel work
64253347fa09STejun Heo  * items.  Actual work item execution starts only after kthreads can be
64263347fa09STejun Heo  * created and scheduled right before early initcalls.
64273347fa09STejun Heo  */
64282333e829SYu Chen void __init workqueue_init_early(void)
64291da177e4SLinus Torvalds {
64307a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
64317a4e344cSTejun Heo 	int i, cpu;
6432c34056a3STejun Heo 
643310cdb157SLai Jiangshan 	BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
6434e904e6c2STejun Heo 
6435b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
643604d4e665SFrederic Weisbecker 	cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_WQ));
643704d4e665SFrederic Weisbecker 	cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_DOMAIN));
6438b05a7928SFrederic Weisbecker 
6439ace3c549Stiozhang 	if (!cpumask_empty(&wq_cmdline_cpumask))
6440ace3c549Stiozhang 		cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, &wq_cmdline_cpumask);
6441ace3c549Stiozhang 
6442e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6443e904e6c2STejun Heo 
6444706026c2STejun Heo 	/* initialize CPU pools */
644529c91e99STejun Heo 	for_each_possible_cpu(cpu) {
64464ce62e9eSTejun Heo 		struct worker_pool *pool;
64478b03ae3cSTejun Heo 
64487a4e344cSTejun Heo 		i = 0;
6449f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
64507a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
6451ec22ca5eSTejun Heo 			pool->cpu = cpu;
64527a4e344cSTejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
64537a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
6454f3f90ad4STejun Heo 			pool->node = cpu_to_node(cpu);
64557a4e344cSTejun Heo 
64569daf9e67STejun Heo 			/* alloc pool ID */
645768e13a67SLai Jiangshan 			mutex_lock(&wq_pool_mutex);
64589daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
645968e13a67SLai Jiangshan 			mutex_unlock(&wq_pool_mutex);
64604ce62e9eSTejun Heo 		}
64618b03ae3cSTejun Heo 	}
64628b03ae3cSTejun Heo 
64638a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
646429c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
646529c91e99STejun Heo 		struct workqueue_attrs *attrs;
646629c91e99STejun Heo 
6467be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
646829c91e99STejun Heo 		attrs->nice = std_nice[i];
646929c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
64708a2b7538STejun Heo 
64718a2b7538STejun Heo 		/*
64728a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
64738a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
64748a2b7538STejun Heo 		 * Turn off NUMA so that dfl_pwq is used for all nodes.
64758a2b7538STejun Heo 		 */
6476be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
64778a2b7538STejun Heo 		attrs->nice = std_nice[i];
64788a2b7538STejun Heo 		attrs->no_numa = true;
64798a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
648029c91e99STejun Heo 	}
648129c91e99STejun Heo 
6482d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
64831aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
6484d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
6485f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
6486f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
648724d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
648824d51addSTejun Heo 					      WQ_FREEZABLE, 0);
64890668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
64900668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
64910668106cSViresh Kumar 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
64920668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
64930668106cSViresh Kumar 					      0);
64941aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
64950668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
64960668106cSViresh Kumar 	       !system_power_efficient_wq ||
64970668106cSViresh Kumar 	       !system_freezable_power_efficient_wq);
64983347fa09STejun Heo }
64993347fa09STejun Heo 
6500aa6fde93STejun Heo static void __init wq_cpu_intensive_thresh_init(void)
6501aa6fde93STejun Heo {
6502aa6fde93STejun Heo 	unsigned long thresh;
6503aa6fde93STejun Heo 	unsigned long bogo;
6504aa6fde93STejun Heo 
6505aa6fde93STejun Heo 	/* if the user set it to a specific value, keep it */
6506aa6fde93STejun Heo 	if (wq_cpu_intensive_thresh_us != ULONG_MAX)
6507aa6fde93STejun Heo 		return;
6508aa6fde93STejun Heo 
6509aa6fde93STejun Heo 	/*
6510aa6fde93STejun Heo 	 * The default of 10ms is derived from the fact that most modern (as of
6511aa6fde93STejun Heo 	 * 2023) processors can do a lot in 10ms and that it's just below what
6512aa6fde93STejun Heo 	 * most consider human-perceivable. However, the kernel also runs on a
6513aa6fde93STejun Heo 	 * lot slower CPUs including microcontrollers where the threshold is way
6514aa6fde93STejun Heo 	 * too low.
6515aa6fde93STejun Heo 	 *
6516aa6fde93STejun Heo 	 * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
6517aa6fde93STejun Heo 	 * This is by no means accurate but it doesn't have to be. The mechanism
6518aa6fde93STejun Heo 	 * is still useful even when the threshold is fully scaled up. Also, as
6519aa6fde93STejun Heo 	 * the reports would usually be applicable to everyone, some machines
6520aa6fde93STejun Heo 	 * operating on longer thresholds won't significantly diminish their
6521aa6fde93STejun Heo 	 * usefulness.
6522aa6fde93STejun Heo 	 */
6523aa6fde93STejun Heo 	thresh = 10 * USEC_PER_MSEC;
6524aa6fde93STejun Heo 
6525aa6fde93STejun Heo 	/* see init/calibrate.c for lpj -> BogoMIPS calculation */
6526aa6fde93STejun Heo 	bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
6527aa6fde93STejun Heo 	if (bogo < 4000)
6528aa6fde93STejun Heo 		thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
6529aa6fde93STejun Heo 
6530aa6fde93STejun Heo 	pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
6531aa6fde93STejun Heo 		 loops_per_jiffy, bogo, thresh);
6532aa6fde93STejun Heo 
6533aa6fde93STejun Heo 	wq_cpu_intensive_thresh_us = thresh;
6534aa6fde93STejun Heo }
6535aa6fde93STejun Heo 
65363347fa09STejun Heo /**
65373347fa09STejun Heo  * workqueue_init - bring workqueue subsystem fully online
65383347fa09STejun Heo  *
65393347fa09STejun Heo  * This is the latter half of two-staged workqueue subsystem initialization
65403347fa09STejun Heo  * and invoked as soon as kthreads can be created and scheduled.
65413347fa09STejun Heo  * Workqueues have been created and work items queued on them, but there
65423347fa09STejun Heo  * are no kworkers executing the work items yet.  Populate the worker pools
65433347fa09STejun Heo  * with the initial workers and enable future kworker creations.
65443347fa09STejun Heo  */
65452333e829SYu Chen void __init workqueue_init(void)
65463347fa09STejun Heo {
65472186d9f9STejun Heo 	struct workqueue_struct *wq;
65483347fa09STejun Heo 	struct worker_pool *pool;
65493347fa09STejun Heo 	int cpu, bkt;
65503347fa09STejun Heo 
6551aa6fde93STejun Heo 	wq_cpu_intensive_thresh_init();
6552aa6fde93STejun Heo 
65532186d9f9STejun Heo 	/*
65542186d9f9STejun Heo 	 * It'd be simpler to initialize NUMA in workqueue_init_early() but
65552186d9f9STejun Heo 	 * CPU to node mapping may not be available that early on some
65562186d9f9STejun Heo 	 * archs such as power and arm64.  As per-cpu pools created
65572186d9f9STejun Heo 	 * previously could be missing node hint and unbound pools NUMA
65582186d9f9STejun Heo 	 * affinity, fix them up.
655940c17f75STejun Heo 	 *
656040c17f75STejun Heo 	 * Also, while iterating workqueues, create rescuers if requested.
65612186d9f9STejun Heo 	 */
65622186d9f9STejun Heo 	wq_numa_init();
65632186d9f9STejun Heo 
65642186d9f9STejun Heo 	mutex_lock(&wq_pool_mutex);
65652186d9f9STejun Heo 
65662186d9f9STejun Heo 	for_each_possible_cpu(cpu) {
65672186d9f9STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
65682186d9f9STejun Heo 			pool->node = cpu_to_node(cpu);
65692186d9f9STejun Heo 		}
65702186d9f9STejun Heo 	}
65712186d9f9STejun Heo 
657240c17f75STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
65732186d9f9STejun Heo 		wq_update_unbound_numa(wq, smp_processor_id(), true);
657440c17f75STejun Heo 		WARN(init_rescuer(wq),
657540c17f75STejun Heo 		     "workqueue: failed to create early rescuer for %s",
657640c17f75STejun Heo 		     wq->name);
657740c17f75STejun Heo 	}
65782186d9f9STejun Heo 
65792186d9f9STejun Heo 	mutex_unlock(&wq_pool_mutex);
65802186d9f9STejun Heo 
65813347fa09STejun Heo 	/* create the initial workers */
65823347fa09STejun Heo 	for_each_online_cpu(cpu) {
65833347fa09STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
65843347fa09STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
65853347fa09STejun Heo 			BUG_ON(!create_worker(pool));
65863347fa09STejun Heo 		}
65873347fa09STejun Heo 	}
65883347fa09STejun Heo 
65893347fa09STejun Heo 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
65903347fa09STejun Heo 		BUG_ON(!create_worker(pool));
65913347fa09STejun Heo 
65923347fa09STejun Heo 	wq_online = true;
659382607adcSTejun Heo 	wq_watchdog_init();
65941da177e4SLinus Torvalds }
6595c4f135d6STetsuo Handa 
659620bdedafSTetsuo Handa void __warn_flushing_systemwide_wq(void)
659720bdedafSTetsuo Handa {
659820bdedafSTetsuo Handa 	pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
659920bdedafSTetsuo Handa 	dump_stack();
660020bdedafSTetsuo Handa }
6601c4f135d6STetsuo Handa EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
6602ace3c549Stiozhang 
6603ace3c549Stiozhang static int __init workqueue_unbound_cpus_setup(char *str)
6604ace3c549Stiozhang {
6605ace3c549Stiozhang 	if (cpulist_parse(str, &wq_cmdline_cpumask) < 0) {
6606ace3c549Stiozhang 		cpumask_clear(&wq_cmdline_cpumask);
6607ace3c549Stiozhang 		pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
6608ace3c549Stiozhang 	}
6609ace3c549Stiozhang 
6610ace3c549Stiozhang 	return 1;
6611ace3c549Stiozhang }
6612ace3c549Stiozhang __setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup);
6613