xref: /openbmc/linux/kernel/workqueue.c (revision d32fd6bb9f2bc8178cdd65ebec1ad670a8bfa241)
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 
111a99d7274SGreg Kroah-Hartman 	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 */
2148639ecebSTejun Heo 	PWQ_STAT_REPATRIATED,	/* unbound workers brought back into scope */
215725e8ec5STejun Heo 	PWQ_STAT_MAYDAY,	/* maydays to rescuer */
216725e8ec5STejun Heo 	PWQ_STAT_RESCUED,	/* linked work items executed by rescuer */
217725e8ec5STejun Heo 
218725e8ec5STejun Heo 	PWQ_NR_STATS,
219725e8ec5STejun Heo };
220725e8ec5STejun Heo 
221725e8ec5STejun Heo /*
222112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
223112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
224112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
225112202d9STejun Heo  * number of flag bits.
2261da177e4SLinus Torvalds  */
227112202d9STejun Heo struct pool_workqueue {
228bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
2294690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
23073f53c4aSTejun Heo 	int			work_color;	/* L: current color */
23173f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
2328864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
23373f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
23473f53c4aSTejun Heo 						/* L: nr of in_flight works */
235018f3a13SLai Jiangshan 
236018f3a13SLai Jiangshan 	/*
237018f3a13SLai Jiangshan 	 * nr_active management and WORK_STRUCT_INACTIVE:
238018f3a13SLai Jiangshan 	 *
239018f3a13SLai Jiangshan 	 * When pwq->nr_active >= max_active, new work item is queued to
240018f3a13SLai Jiangshan 	 * pwq->inactive_works instead of pool->worklist and marked with
241018f3a13SLai Jiangshan 	 * WORK_STRUCT_INACTIVE.
242018f3a13SLai Jiangshan 	 *
2436741dd3fSGreg Kroah-Hartman 	 * All work items marked with WORK_STRUCT_INACTIVE do not participate
2446741dd3fSGreg Kroah-Hartman 	 * in pwq->nr_active and all work items in pwq->inactive_works are
2456741dd3fSGreg Kroah-Hartman 	 * marked with WORK_STRUCT_INACTIVE.  But not all WORK_STRUCT_INACTIVE
2466741dd3fSGreg Kroah-Hartman 	 * work items are in pwq->inactive_works.  Some of them are ready to
2476741dd3fSGreg Kroah-Hartman 	 * run in pool->worklist or worker->scheduled.  Those work itmes are
2486741dd3fSGreg Kroah-Hartman 	 * only struct wq_barrier which is used for flush_work() and should
2496741dd3fSGreg Kroah-Hartman 	 * not participate in pwq->nr_active.  For non-barrier work item, it
2506741dd3fSGreg Kroah-Hartman 	 * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
251018f3a13SLai Jiangshan 	 */
2521e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
253d8354f26SGreg Kroah-Hartman 	int			max_active;	/* L: max active works */
254f97a4a1aSLai Jiangshan 	struct list_head	inactive_works;	/* L: inactive works */
2553c25a55dSLai Jiangshan 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
2562e109a28STejun Heo 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
2578864b4e5STejun Heo 
258725e8ec5STejun Heo 	u64			stats[PWQ_NR_STATS];
259725e8ec5STejun Heo 
2608864b4e5STejun Heo 	/*
261967b494eSTejun Heo 	 * Release of unbound pwq is punted to a kthread_worker. See put_pwq()
262687a9aa5STejun Heo 	 * and pwq_release_workfn() for details. pool_workqueue itself is also
263687a9aa5STejun Heo 	 * RCU protected so that the first pwq can be determined without
264967b494eSTejun Heo 	 * grabbing wq->mutex.
2658864b4e5STejun Heo 	 */
266687a9aa5STejun Heo 	struct kthread_work	release_work;
2678864b4e5STejun Heo 	struct rcu_head		rcu;
268e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2691da177e4SLinus Torvalds 
2701da177e4SLinus Torvalds /*
27173f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
27273f53c4aSTejun Heo  */
27373f53c4aSTejun Heo struct wq_flusher {
2743c25a55dSLai Jiangshan 	struct list_head	list;		/* WQ: list of flushers */
2753c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: flush color waiting for */
27673f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
27773f53c4aSTejun Heo };
2781da177e4SLinus Torvalds 
279226223abSTejun Heo struct wq_device;
280226223abSTejun Heo 
28173f53c4aSTejun Heo /*
282c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
283c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
2841da177e4SLinus Torvalds  */
2851da177e4SLinus Torvalds struct workqueue_struct {
2863c25a55dSLai Jiangshan 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
287e2dca7adSTejun Heo 	struct list_head	list;		/* PR: list of all workqueues */
28873f53c4aSTejun Heo 
2893c25a55dSLai Jiangshan 	struct mutex		mutex;		/* protects this wq */
2903c25a55dSLai Jiangshan 	int			work_color;	/* WQ: current work color */
2913c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: current flush color */
292112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
2933c25a55dSLai Jiangshan 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
2943c25a55dSLai Jiangshan 	struct list_head	flusher_queue;	/* WQ: flush waiters */
2953c25a55dSLai Jiangshan 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
29673f53c4aSTejun Heo 
2972e109a28STejun Heo 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
29830ae2fc0STejun Heo 	struct worker		*rescuer;	/* MD: rescue worker */
299e22bee78STejun Heo 
30087fc741eSLai Jiangshan 	int			nr_drainers;	/* WQ: drain in progress */
301d8354f26SGreg Kroah-Hartman 	int			saved_max_active; /* WQ: saved pwq max_active */
302226223abSTejun Heo 
3035b95e1afSLai Jiangshan 	struct workqueue_attrs	*unbound_attrs;	/* PW: only for unbound wqs */
304f3c11cb2SGreg Kroah-Hartman 	struct pool_workqueue	*dfl_pwq;	/* PW: only for unbound wqs */
3056029a918STejun Heo 
306226223abSTejun Heo #ifdef CONFIG_SYSFS
307226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
308226223abSTejun Heo #endif
3094e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
310669de8bdSBart Van Assche 	char			*lock_name;
311669de8bdSBart Van Assche 	struct lock_class_key	key;
3124e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
3134e6045f1SJohannes Berg #endif
314ecf6881fSTejun Heo 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
3152728fd2fSTejun Heo 
316e2dca7adSTejun Heo 	/*
31724acfb71SThomas Gleixner 	 * Destruction of workqueue_struct is RCU protected to allow walking
31824acfb71SThomas Gleixner 	 * the workqueues list without grabbing wq_pool_mutex.
319e2dca7adSTejun Heo 	 * This is used to dump all workqueues from sysrq.
320e2dca7adSTejun Heo 	 */
321e2dca7adSTejun Heo 	struct rcu_head		rcu;
322e2dca7adSTejun Heo 
3232728fd2fSTejun Heo 	/* hot fields used during command issue, aligned to cacheline */
3242728fd2fSTejun Heo 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
325636b927eSTejun Heo 	struct pool_workqueue __percpu __rcu **cpu_pwq; /* I: per-cpu pwqs */
3261da177e4SLinus Torvalds };
3271da177e4SLinus Torvalds 
328e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
329e904e6c2STejun Heo 
33084193c07STejun Heo /*
33184193c07STejun Heo  * Each pod type describes how CPUs should be grouped for unbound workqueues.
33284193c07STejun Heo  * See the comment above workqueue_attrs->affn_scope.
33384193c07STejun Heo  */
33484193c07STejun Heo struct wq_pod_type {
33584193c07STejun Heo 	int			nr_pods;	/* number of pods */
33684193c07STejun Heo 	cpumask_var_t		*pod_cpus;	/* pod -> cpus */
33784193c07STejun Heo 	int			*pod_node;	/* pod -> node */
33884193c07STejun Heo 	int			*cpu_pod;	/* cpu -> pod */
33984193c07STejun Heo };
34084193c07STejun Heo 
34184193c07STejun Heo static struct wq_pod_type wq_pod_types[WQ_AFFN_NR_TYPES];
342523a301eSTejun Heo static enum wq_affn_scope wq_affn_dfl = WQ_AFFN_CACHE;
34363c5484eSTejun Heo 
34463c5484eSTejun Heo static const char *wq_affn_names[WQ_AFFN_NR_TYPES] = {
345523a301eSTejun Heo 	[WQ_AFFN_DFL]			= "default",
34663c5484eSTejun Heo 	[WQ_AFFN_CPU]			= "cpu",
34763c5484eSTejun Heo 	[WQ_AFFN_SMT]			= "smt",
34863c5484eSTejun Heo 	[WQ_AFFN_CACHE]			= "cache",
34963c5484eSTejun Heo 	[WQ_AFFN_NUMA]			= "numa",
35063c5484eSTejun Heo 	[WQ_AFFN_SYSTEM]		= "system",
35163c5484eSTejun Heo };
352bce90380STejun Heo 
353616db877STejun Heo /*
354616db877STejun Heo  * Per-cpu work items which run for longer than the following threshold are
355616db877STejun Heo  * automatically considered CPU intensive and excluded from concurrency
356616db877STejun Heo  * management to prevent them from noticeably delaying other per-cpu work items.
357aa6fde93STejun Heo  * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
358aa6fde93STejun Heo  * The actual value is initialized in wq_cpu_intensive_thresh_init().
359616db877STejun Heo  */
360aa6fde93STejun Heo static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
361616db877STejun Heo module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
362616db877STejun Heo 
363cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
364552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
365cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
366cee22a15SViresh Kumar 
367863b710bSTejun Heo static bool wq_online;			/* can kworkers be created yet? */
3683347fa09STejun Heo 
369fef59c9cSTejun Heo /* buf for wq_update_unbound_pod_attrs(), protected by CPU hotplug exclusion */
370fef59c9cSTejun Heo static struct workqueue_attrs *wq_update_pod_attrs_buf;
3714c16bd32STejun Heo 
37268e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
3731258fae7STejun Heo static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
374a9b8a985SSebastian Andrzej Siewior static DEFINE_RAW_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
375d8bb65abSSebastian Andrzej Siewior /* wait for manager to go away */
376d8bb65abSSebastian Andrzej Siewior static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
3775bcab335STejun Heo 
378e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
37968e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
3807d19c5ceSTejun Heo 
38199c621efSLai Jiangshan /* PL&A: allowable cpus for unbound wqs and work items */
382ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
383ef557180SMike Galbraith 
384ace3c549Stiozhang /* for further constrain wq_unbound_cpumask by cmdline parameter*/
385ace3c549Stiozhang static struct cpumask wq_cmdline_cpumask __initdata;
386ace3c549Stiozhang 
387ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
388ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
389b05a7928SFrederic Weisbecker 
390f303fccbSTejun Heo /*
391f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
392f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
393f303fccbSTejun Heo  * to uncover usages which depend on it.
394f303fccbSTejun Heo  */
395f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
396f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
397f303fccbSTejun Heo #else
398f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
399f303fccbSTejun Heo #endif
400f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
401f303fccbSTejun Heo 
4027d19c5ceSTejun Heo /* the per-cpu worker pools */
40325528213SPeter Zijlstra static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
4047d19c5ceSTejun Heo 
40568e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
4067d19c5ceSTejun Heo 
40768e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
40829c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
40929c91e99STejun Heo 
410c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
41129c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
41229c91e99STejun Heo 
4138a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
4148a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
4158a2b7538STejun Heo 
416967b494eSTejun Heo /*
417967b494eSTejun Heo  * I: kthread_worker to release pwq's. pwq release needs to be bounced to a
418967b494eSTejun Heo  * process context while holding a pool lock. Bounce to a dedicated kthread
419967b494eSTejun Heo  * worker to avoid A-A deadlocks.
420967b494eSTejun Heo  */
421967b494eSTejun Heo static struct kthread_worker *pwq_release_worker;
422967b494eSTejun Heo 
423d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
424ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
425044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
4261aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
427044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
428d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
429044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
430f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
431044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
43224d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
4330668106cSViresh Kumar struct workqueue_struct *system_power_efficient_wq __read_mostly;
4340668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
4350668106cSViresh Kumar struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
4360668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
437d320c038STejun Heo 
4387d19c5ceSTejun Heo static int worker_thread(void *__worker);
4396ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
440c29eb853STejun Heo static void show_pwq(struct pool_workqueue *pwq);
44155df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool);
4427d19c5ceSTejun Heo 
44397bd2347STejun Heo #define CREATE_TRACE_POINTS
44497bd2347STejun Heo #include <trace/events/workqueue.h>
44597bd2347STejun Heo 
44668e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
44724acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
448f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
44924acfb71SThomas Gleixner 			 "RCU or wq_pool_mutex should be held")
4505bcab335STejun Heo 
4515b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
45224acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
453f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
454f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
45524acfb71SThomas Gleixner 			 "RCU, wq->mutex or wq_pool_mutex should be held")
4565b95e1afSLai Jiangshan 
457f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
458f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
459f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
4607a62c2c8STejun Heo 	     (pool)++)
4614ce62e9eSTejun Heo 
46249e3cf44STejun Heo /**
46317116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
46417116969STejun Heo  * @pool: iteration cursor
465611c92a0STejun Heo  * @pi: integer used for iteration
466fa1b54e6STejun Heo  *
46724acfb71SThomas Gleixner  * This must be called either with wq_pool_mutex held or RCU read
46868e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
46968e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
470fa1b54e6STejun Heo  *
471fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
472fa1b54e6STejun Heo  * ignored.
47317116969STejun Heo  */
474611c92a0STejun Heo #define for_each_pool(pool, pi)						\
475611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
47668e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
477fa1b54e6STejun Heo 		else
47817116969STejun Heo 
47917116969STejun Heo /**
480822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
481822d8405STejun Heo  * @worker: iteration cursor
482822d8405STejun Heo  * @pool: worker_pool to iterate workers of
483822d8405STejun Heo  *
4841258fae7STejun Heo  * This must be called with wq_pool_attach_mutex.
485822d8405STejun Heo  *
486822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
487822d8405STejun Heo  * ignored.
488822d8405STejun Heo  */
489da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
490da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
4911258fae7STejun Heo 		if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
492822d8405STejun Heo 		else
493822d8405STejun Heo 
494822d8405STejun Heo /**
49549e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
49649e3cf44STejun Heo  * @pwq: iteration cursor
49749e3cf44STejun Heo  * @wq: the target workqueue
49876af4d93STejun Heo  *
49924acfb71SThomas Gleixner  * This must be called either with wq->mutex held or RCU read locked.
500794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
501794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
50276af4d93STejun Heo  *
50376af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
50476af4d93STejun Heo  * ignored.
50549e3cf44STejun Heo  */
50649e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
50749e9d1a9SSebastian Andrzej Siewior 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node,		\
5085a644662SJoel Fernandes (Google) 				 lockdep_is_held(&(wq->mutex)))
509f3421797STejun Heo 
510dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
511dc186ad7SThomas Gleixner 
512f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr;
513dc186ad7SThomas Gleixner 
work_debug_hint(void * addr)51499777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
51599777288SStanislaw Gruszka {
51699777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
51799777288SStanislaw Gruszka }
51899777288SStanislaw Gruszka 
work_is_static_object(void * addr)519b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
520b9fdac7fSDu, Changbin {
521b9fdac7fSDu, Changbin 	struct work_struct *work = addr;
522b9fdac7fSDu, Changbin 
523b9fdac7fSDu, Changbin 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
524b9fdac7fSDu, Changbin }
525b9fdac7fSDu, Changbin 
526dc186ad7SThomas Gleixner /*
527dc186ad7SThomas Gleixner  * fixup_init is called when:
528dc186ad7SThomas Gleixner  * - an active object is initialized
529dc186ad7SThomas Gleixner  */
work_fixup_init(void * addr,enum debug_obj_state state)53002a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
531dc186ad7SThomas Gleixner {
532dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
533dc186ad7SThomas Gleixner 
534dc186ad7SThomas Gleixner 	switch (state) {
535dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
536dc186ad7SThomas Gleixner 		cancel_work_sync(work);
537dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
53802a982a6SDu, Changbin 		return true;
539dc186ad7SThomas Gleixner 	default:
54002a982a6SDu, Changbin 		return false;
541dc186ad7SThomas Gleixner 	}
542dc186ad7SThomas Gleixner }
543dc186ad7SThomas Gleixner 
544dc186ad7SThomas Gleixner /*
545dc186ad7SThomas Gleixner  * fixup_free is called when:
546dc186ad7SThomas Gleixner  * - an active object is freed
547dc186ad7SThomas Gleixner  */
work_fixup_free(void * addr,enum debug_obj_state state)54802a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
549dc186ad7SThomas Gleixner {
550dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
551dc186ad7SThomas Gleixner 
552dc186ad7SThomas Gleixner 	switch (state) {
553dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
554dc186ad7SThomas Gleixner 		cancel_work_sync(work);
555dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
55602a982a6SDu, Changbin 		return true;
557dc186ad7SThomas Gleixner 	default:
55802a982a6SDu, Changbin 		return false;
559dc186ad7SThomas Gleixner 	}
560dc186ad7SThomas Gleixner }
561dc186ad7SThomas Gleixner 
562f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr = {
563dc186ad7SThomas Gleixner 	.name		= "work_struct",
56499777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
565b9fdac7fSDu, Changbin 	.is_static_object = work_is_static_object,
566dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
567dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
568dc186ad7SThomas Gleixner };
569dc186ad7SThomas Gleixner 
debug_work_activate(struct work_struct * work)570dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
571dc186ad7SThomas Gleixner {
572dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
573dc186ad7SThomas Gleixner }
574dc186ad7SThomas Gleixner 
debug_work_deactivate(struct work_struct * work)575dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
576dc186ad7SThomas Gleixner {
577dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
578dc186ad7SThomas Gleixner }
579dc186ad7SThomas Gleixner 
__init_work(struct work_struct * work,int onstack)580dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
581dc186ad7SThomas Gleixner {
582dc186ad7SThomas Gleixner 	if (onstack)
583dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
584dc186ad7SThomas Gleixner 	else
585dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
586dc186ad7SThomas Gleixner }
587dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
588dc186ad7SThomas Gleixner 
destroy_work_on_stack(struct work_struct * work)589dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
590dc186ad7SThomas Gleixner {
591dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
592dc186ad7SThomas Gleixner }
593dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
594dc186ad7SThomas Gleixner 
destroy_delayed_work_on_stack(struct delayed_work * work)595ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
596ea2e64f2SThomas Gleixner {
597ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
598ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
599ea2e64f2SThomas Gleixner }
600ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
601ea2e64f2SThomas Gleixner 
602dc186ad7SThomas Gleixner #else
debug_work_activate(struct work_struct * work)603dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
debug_work_deactivate(struct work_struct * work)604dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
605dc186ad7SThomas Gleixner #endif
606dc186ad7SThomas Gleixner 
6074e8b22bdSLi Bin /**
60867dc8325SCai Huoqing  * worker_pool_assign_id - allocate ID and assign it to @pool
6094e8b22bdSLi Bin  * @pool: the pool pointer of interest
6104e8b22bdSLi Bin  *
6114e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
6124e8b22bdSLi Bin  * successfully, -errno on failure.
6134e8b22bdSLi Bin  */
worker_pool_assign_id(struct worker_pool * pool)6149daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
6159daf9e67STejun Heo {
6169daf9e67STejun Heo 	int ret;
6179daf9e67STejun Heo 
61868e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
6195bcab335STejun Heo 
6204e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
6214e8b22bdSLi Bin 			GFP_KERNEL);
622229641a6STejun Heo 	if (ret >= 0) {
623e68035fbSTejun Heo 		pool->id = ret;
624229641a6STejun Heo 		return 0;
625229641a6STejun Heo 	}
6269daf9e67STejun Heo 	return ret;
6279daf9e67STejun Heo }
6289daf9e67STejun Heo 
work_color_to_flags(int color)62973f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
63073f53c4aSTejun Heo {
63173f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
63273f53c4aSTejun Heo }
63373f53c4aSTejun Heo 
get_work_color(unsigned long work_data)634c4560c2cSLai Jiangshan static int get_work_color(unsigned long work_data)
63573f53c4aSTejun Heo {
636c4560c2cSLai Jiangshan 	return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
63773f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
63873f53c4aSTejun Heo }
63973f53c4aSTejun Heo 
work_next_color(int color)64073f53c4aSTejun Heo static int work_next_color(int color)
64173f53c4aSTejun Heo {
64273f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
643a848e3b6SOleg Nesterov }
644a848e3b6SOleg Nesterov 
6454594bf15SDavid Howells /*
646112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
647112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
6487c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
6497a22ad75STejun Heo  *
650112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
651112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
652bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
653bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
6547a22ad75STejun Heo  *
655112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6567c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
657112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
6587c3eed5cSTejun Heo  * available only while the work item is queued.
659bbb68dfaSTejun Heo  *
660bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
661bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
662bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
663bbb68dfaSTejun Heo  * try to steal the PENDING bit.
6644594bf15SDavid Howells  */
set_work_data(struct work_struct * work,unsigned long data,unsigned long flags)6657a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6667a22ad75STejun Heo 				 unsigned long flags)
6677a22ad75STejun Heo {
6686183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
6697a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
6707a22ad75STejun Heo }
6717a22ad75STejun Heo 
set_work_pwq(struct work_struct * work,struct pool_workqueue * pwq,unsigned long extra_flags)672112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6734690c4abSTejun Heo 			 unsigned long extra_flags)
674365970a1SDavid Howells {
675112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
676112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
677365970a1SDavid Howells }
678365970a1SDavid Howells 
set_work_pool_and_keep_pending(struct work_struct * work,int pool_id)6794468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6804468a00fSLai Jiangshan 					   int pool_id)
6814468a00fSLai Jiangshan {
6824468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6834468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6844468a00fSLai Jiangshan }
6854468a00fSLai Jiangshan 
set_work_pool_and_clear_pending(struct work_struct * work,int pool_id)6867c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6877c3eed5cSTejun Heo 					    int pool_id)
6884d707b9fSOleg Nesterov {
68923657bb1STejun Heo 	/*
69023657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
69123657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
69223657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
69323657bb1STejun Heo 	 * owner.
69423657bb1STejun Heo 	 */
69523657bb1STejun Heo 	smp_wmb();
6967c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
697346c09f8SRoman Pen 	/*
698346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
699346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
700346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
7018bdc6201SLiu Song 	 * reordering can lead to a missed execution on attempt to queue
702346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
703346c09f8SRoman Pen 	 *
704346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
705346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
706346c09f8SRoman Pen 	 *
707346c09f8SRoman Pen 	 * 1  STORE event_indicated
708346c09f8SRoman Pen 	 * 2  queue_work_on() {
709346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
710346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
711346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
712346c09f8SRoman Pen 	 * 6                                 smp_mb()
713346c09f8SRoman Pen 	 * 7                               work->current_func() {
714346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
715346c09f8SRoman Pen 	 *				   }
716346c09f8SRoman Pen 	 *
717346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
718346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
719346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
720346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
721346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
722346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
723346c09f8SRoman Pen 	 * before actual STORE.
724346c09f8SRoman Pen 	 */
725346c09f8SRoman Pen 	smp_mb();
7264d707b9fSOleg Nesterov }
7274d707b9fSOleg Nesterov 
clear_work_data(struct work_struct * work)7287a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
729365970a1SDavid Howells {
7307c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
7317c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
7327a22ad75STejun Heo }
7337a22ad75STejun Heo 
work_struct_pwq(unsigned long data)734afa4bb77SLinus Torvalds static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
735afa4bb77SLinus Torvalds {
736afa4bb77SLinus Torvalds 	return (struct pool_workqueue *)(data & WORK_STRUCT_WQ_DATA_MASK);
737afa4bb77SLinus Torvalds }
738afa4bb77SLinus Torvalds 
get_work_pwq(struct work_struct * work)739112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
7407a22ad75STejun Heo {
741e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7427a22ad75STejun Heo 
743112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
744afa4bb77SLinus Torvalds 		return work_struct_pwq(data);
745e120153dSTejun Heo 	else
746e120153dSTejun Heo 		return NULL;
7477a22ad75STejun Heo }
7487a22ad75STejun Heo 
7497c3eed5cSTejun Heo /**
7507c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
7517c3eed5cSTejun Heo  * @work: the work item of interest
7527c3eed5cSTejun Heo  *
75368e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
75424acfb71SThomas Gleixner  * access under RCU read lock.  As such, this function should be
75524acfb71SThomas Gleixner  * called under wq_pool_mutex or inside of a rcu_read_lock() region.
756fa1b54e6STejun Heo  *
757fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
758fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
759fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
760fa1b54e6STejun Heo  * returned pool is and stays online.
761d185af30SYacine Belkadi  *
762d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
7637c3eed5cSTejun Heo  */
get_work_pool(struct work_struct * work)7647c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
7657a22ad75STejun Heo {
766e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7677c3eed5cSTejun Heo 	int pool_id;
7687a22ad75STejun Heo 
76968e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
770fa1b54e6STejun Heo 
771112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
772afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool;
7737a22ad75STejun Heo 
7747c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
7757c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
7767a22ad75STejun Heo 		return NULL;
7777a22ad75STejun Heo 
778fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
7797c3eed5cSTejun Heo }
7807c3eed5cSTejun Heo 
7817c3eed5cSTejun Heo /**
7827c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
7837c3eed5cSTejun Heo  * @work: the work item of interest
7847c3eed5cSTejun Heo  *
785d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
7867c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
7877c3eed5cSTejun Heo  */
get_work_pool_id(struct work_struct * work)7887c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
7897c3eed5cSTejun Heo {
79054d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
7917c3eed5cSTejun Heo 
792112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
793afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool->id;
79454d5b7d0SLai Jiangshan 
79554d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
7967c3eed5cSTejun Heo }
7977c3eed5cSTejun Heo 
mark_work_canceling(struct work_struct * work)798bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
799bbb68dfaSTejun Heo {
8007c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
801bbb68dfaSTejun Heo 
8027c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
8037c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
804bbb68dfaSTejun Heo }
805bbb68dfaSTejun Heo 
work_is_canceling(struct work_struct * work)806bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
807bbb68dfaSTejun Heo {
808bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
809bbb68dfaSTejun Heo 
810112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
811bbb68dfaSTejun Heo }
812bbb68dfaSTejun Heo 
813e22bee78STejun Heo /*
8143270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
8153270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
816d565ed63STejun Heo  * they're being called with pool->lock held.
817e22bee78STejun Heo  */
818e22bee78STejun Heo 
819e22bee78STejun Heo /*
820e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
821e22bee78STejun Heo  * running workers.
822974271c4STejun Heo  *
823974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
824706026c2STejun Heo  * function will always return %true for unbound pools as long as the
825974271c4STejun Heo  * worklist isn't empty.
826e22bee78STejun Heo  */
need_more_worker(struct worker_pool * pool)82763d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
828e22bee78STejun Heo {
8290219a352STejun Heo 	return !list_empty(&pool->worklist) && !pool->nr_running;
830e22bee78STejun Heo }
831e22bee78STejun Heo 
832e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
may_start_working(struct worker_pool * pool)83363d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
834e22bee78STejun Heo {
83563d95a91STejun Heo 	return pool->nr_idle;
836e22bee78STejun Heo }
837e22bee78STejun Heo 
838e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
keep_working(struct worker_pool * pool)83963d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
840e22bee78STejun Heo {
841bc35f7efSLai Jiangshan 	return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
842e22bee78STejun Heo }
843e22bee78STejun Heo 
844e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
need_to_create_worker(struct worker_pool * pool)84563d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
846e22bee78STejun Heo {
84763d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
848e22bee78STejun Heo }
849e22bee78STejun Heo 
850e22bee78STejun Heo /* Do we have too many workers and should some go away? */
too_many_workers(struct worker_pool * pool)85163d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
852e22bee78STejun Heo {
853692b4825STejun Heo 	bool managing = pool->flags & POOL_MANAGER_ACTIVE;
85463d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
85563d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
856e22bee78STejun Heo 
857e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
858e22bee78STejun Heo }
859e22bee78STejun Heo 
8604690c4abSTejun Heo /**
861e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
862cb444766STejun Heo  * @worker: self
863d302f017STejun Heo  * @flags: flags to set
864d302f017STejun Heo  *
865228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
866d302f017STejun Heo  */
worker_set_flags(struct worker * worker,unsigned int flags)867228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
868d302f017STejun Heo {
869bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
870e22bee78STejun Heo 
871bc8b50c2STejun Heo 	lockdep_assert_held(&pool->lock);
872cb444766STejun Heo 
873228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
874e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
875e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
876bc35f7efSLai Jiangshan 		pool->nr_running--;
877e22bee78STejun Heo 	}
878e22bee78STejun Heo 
879d302f017STejun Heo 	worker->flags |= flags;
880d302f017STejun Heo }
881d302f017STejun Heo 
882d302f017STejun Heo /**
883e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
884cb444766STejun Heo  * @worker: self
885d302f017STejun Heo  * @flags: flags to clear
886d302f017STejun Heo  *
887e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
888d302f017STejun Heo  */
worker_clr_flags(struct worker * worker,unsigned int flags)889d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
890d302f017STejun Heo {
89163d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
892e22bee78STejun Heo 	unsigned int oflags = worker->flags;
893e22bee78STejun Heo 
894bc8b50c2STejun Heo 	lockdep_assert_held(&pool->lock);
895cb444766STejun Heo 
896d302f017STejun Heo 	worker->flags &= ~flags;
897e22bee78STejun Heo 
89842c025f3STejun Heo 	/*
89942c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
90042c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
90142c025f3STejun Heo 	 * of multiple flags, not a single flag.
90242c025f3STejun Heo 	 */
903e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
904e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
905bc35f7efSLai Jiangshan 			pool->nr_running++;
906d302f017STejun Heo }
907d302f017STejun Heo 
908797e8345STejun Heo /* Return the first idle worker.  Called with pool->lock held. */
first_idle_worker(struct worker_pool * pool)909797e8345STejun Heo static struct worker *first_idle_worker(struct worker_pool *pool)
910797e8345STejun Heo {
911797e8345STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
912797e8345STejun Heo 		return NULL;
913797e8345STejun Heo 
914797e8345STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
915797e8345STejun Heo }
916797e8345STejun Heo 
917797e8345STejun Heo /**
918797e8345STejun Heo  * worker_enter_idle - enter idle state
919797e8345STejun Heo  * @worker: worker which is entering idle state
920797e8345STejun Heo  *
921797e8345STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
922797e8345STejun Heo  * necessary.
923797e8345STejun Heo  *
924797e8345STejun Heo  * LOCKING:
925797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
926797e8345STejun Heo  */
worker_enter_idle(struct worker * worker)927797e8345STejun Heo static void worker_enter_idle(struct worker *worker)
928797e8345STejun Heo {
929797e8345STejun Heo 	struct worker_pool *pool = worker->pool;
930797e8345STejun Heo 
931797e8345STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
932797e8345STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
933797e8345STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
934797e8345STejun Heo 		return;
935797e8345STejun Heo 
936797e8345STejun Heo 	/* can't use worker_set_flags(), also called from create_worker() */
937797e8345STejun Heo 	worker->flags |= WORKER_IDLE;
938797e8345STejun Heo 	pool->nr_idle++;
939797e8345STejun Heo 	worker->last_active = jiffies;
940797e8345STejun Heo 
941797e8345STejun Heo 	/* idle_list is LIFO */
942797e8345STejun Heo 	list_add(&worker->entry, &pool->idle_list);
943797e8345STejun Heo 
944797e8345STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
945797e8345STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
946797e8345STejun Heo 
947797e8345STejun Heo 	/* Sanity check nr_running. */
948797e8345STejun Heo 	WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
949797e8345STejun Heo }
950797e8345STejun Heo 
951797e8345STejun Heo /**
952797e8345STejun Heo  * worker_leave_idle - leave idle state
953797e8345STejun Heo  * @worker: worker which is leaving idle state
954797e8345STejun Heo  *
955797e8345STejun Heo  * @worker is leaving idle state.  Update stats.
956797e8345STejun Heo  *
957797e8345STejun Heo  * LOCKING:
958797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
959797e8345STejun Heo  */
worker_leave_idle(struct worker * worker)960797e8345STejun Heo static void worker_leave_idle(struct worker *worker)
961797e8345STejun Heo {
962797e8345STejun Heo 	struct worker_pool *pool = worker->pool;
963797e8345STejun Heo 
964797e8345STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
965797e8345STejun Heo 		return;
966797e8345STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
967797e8345STejun Heo 	pool->nr_idle--;
968797e8345STejun Heo 	list_del_init(&worker->entry);
969797e8345STejun Heo }
970797e8345STejun Heo 
971797e8345STejun Heo /**
972797e8345STejun Heo  * find_worker_executing_work - find worker which is executing a work
973797e8345STejun Heo  * @pool: pool of interest
974797e8345STejun Heo  * @work: work to find worker for
975797e8345STejun Heo  *
976797e8345STejun Heo  * Find a worker which is executing @work on @pool by searching
977797e8345STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
978797e8345STejun Heo  * to match, its current execution should match the address of @work and
979797e8345STejun Heo  * its work function.  This is to avoid unwanted dependency between
980797e8345STejun Heo  * unrelated work executions through a work item being recycled while still
981797e8345STejun Heo  * being executed.
982797e8345STejun Heo  *
983797e8345STejun Heo  * This is a bit tricky.  A work item may be freed once its execution
984797e8345STejun Heo  * starts and nothing prevents the freed area from being recycled for
985797e8345STejun Heo  * another work item.  If the same work item address ends up being reused
986797e8345STejun Heo  * before the original execution finishes, workqueue will identify the
987797e8345STejun Heo  * recycled work item as currently executing and make it wait until the
988797e8345STejun Heo  * current execution finishes, introducing an unwanted dependency.
989797e8345STejun Heo  *
990797e8345STejun Heo  * This function checks the work item address and work function to avoid
991797e8345STejun Heo  * false positives.  Note that this isn't complete as one may construct a
992797e8345STejun Heo  * work function which can introduce dependency onto itself through a
993797e8345STejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
994797e8345STejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
995797e8345STejun Heo  * actually occurs, it should be easy to locate the culprit work function.
996797e8345STejun Heo  *
997797e8345STejun Heo  * CONTEXT:
998797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
999797e8345STejun Heo  *
1000797e8345STejun Heo  * Return:
1001797e8345STejun Heo  * Pointer to worker which is executing @work if found, %NULL
1002797e8345STejun Heo  * otherwise.
1003797e8345STejun Heo  */
find_worker_executing_work(struct worker_pool * pool,struct work_struct * work)1004797e8345STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
1005797e8345STejun Heo 						 struct work_struct *work)
1006797e8345STejun Heo {
1007797e8345STejun Heo 	struct worker *worker;
1008797e8345STejun Heo 
1009797e8345STejun Heo 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1010797e8345STejun Heo 			       (unsigned long)work)
1011797e8345STejun Heo 		if (worker->current_work == work &&
1012797e8345STejun Heo 		    worker->current_func == work->func)
1013797e8345STejun Heo 			return worker;
1014797e8345STejun Heo 
1015797e8345STejun Heo 	return NULL;
1016797e8345STejun Heo }
1017797e8345STejun Heo 
1018797e8345STejun Heo /**
1019797e8345STejun Heo  * move_linked_works - move linked works to a list
1020797e8345STejun Heo  * @work: start of series of works to be scheduled
1021797e8345STejun Heo  * @head: target list to append @work to
1022797e8345STejun Heo  * @nextp: out parameter for nested worklist walking
1023797e8345STejun Heo  *
1024873eaca6STejun Heo  * Schedule linked works starting from @work to @head. Work series to be
1025873eaca6STejun Heo  * scheduled starts at @work and includes any consecutive work with
1026873eaca6STejun Heo  * WORK_STRUCT_LINKED set in its predecessor. See assign_work() for details on
1027873eaca6STejun Heo  * @nextp.
1028797e8345STejun Heo  *
1029797e8345STejun Heo  * CONTEXT:
1030797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1031797e8345STejun Heo  */
move_linked_works(struct work_struct * work,struct list_head * head,struct work_struct ** nextp)1032797e8345STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1033797e8345STejun Heo 			      struct work_struct **nextp)
1034797e8345STejun Heo {
1035797e8345STejun Heo 	struct work_struct *n;
1036797e8345STejun Heo 
1037797e8345STejun Heo 	/*
1038797e8345STejun Heo 	 * Linked worklist will always end before the end of the list,
1039797e8345STejun Heo 	 * use NULL for list head.
1040797e8345STejun Heo 	 */
1041797e8345STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1042797e8345STejun Heo 		list_move_tail(&work->entry, head);
1043797e8345STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1044797e8345STejun Heo 			break;
1045797e8345STejun Heo 	}
1046797e8345STejun Heo 
1047797e8345STejun Heo 	/*
1048797e8345STejun Heo 	 * If we're already inside safe list traversal and have moved
1049797e8345STejun Heo 	 * multiple works to the scheduled queue, the next position
1050797e8345STejun Heo 	 * needs to be updated.
1051797e8345STejun Heo 	 */
1052797e8345STejun Heo 	if (nextp)
1053797e8345STejun Heo 		*nextp = n;
1054797e8345STejun Heo }
1055797e8345STejun Heo 
1056797e8345STejun Heo /**
1057873eaca6STejun Heo  * assign_work - assign a work item and its linked work items to a worker
1058873eaca6STejun Heo  * @work: work to assign
1059873eaca6STejun Heo  * @worker: worker to assign to
1060873eaca6STejun Heo  * @nextp: out parameter for nested worklist walking
1061873eaca6STejun Heo  *
1062873eaca6STejun Heo  * Assign @work and its linked work items to @worker. If @work is already being
1063873eaca6STejun Heo  * executed by another worker in the same pool, it'll be punted there.
1064873eaca6STejun Heo  *
1065873eaca6STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of the last
1066873eaca6STejun Heo  * scheduled work. This allows assign_work() to be nested inside
1067873eaca6STejun Heo  * list_for_each_entry_safe().
1068873eaca6STejun Heo  *
1069873eaca6STejun Heo  * Returns %true if @work was successfully assigned to @worker. %false if @work
1070873eaca6STejun Heo  * was punted to another worker already executing it.
1071873eaca6STejun Heo  */
assign_work(struct work_struct * work,struct worker * worker,struct work_struct ** nextp)1072873eaca6STejun Heo static bool assign_work(struct work_struct *work, struct worker *worker,
1073873eaca6STejun Heo 			struct work_struct **nextp)
1074873eaca6STejun Heo {
1075873eaca6STejun Heo 	struct worker_pool *pool = worker->pool;
1076873eaca6STejun Heo 	struct worker *collision;
1077873eaca6STejun Heo 
1078873eaca6STejun Heo 	lockdep_assert_held(&pool->lock);
1079873eaca6STejun Heo 
1080873eaca6STejun Heo 	/*
1081873eaca6STejun Heo 	 * A single work shouldn't be executed concurrently by multiple workers.
1082873eaca6STejun Heo 	 * __queue_work() ensures that @work doesn't jump to a different pool
1083873eaca6STejun Heo 	 * while still running in the previous pool. Here, we should ensure that
1084873eaca6STejun Heo 	 * @work is not executed concurrently by multiple workers from the same
1085873eaca6STejun Heo 	 * pool. Check whether anyone is already processing the work. If so,
1086873eaca6STejun Heo 	 * defer the work to the currently executing one.
1087873eaca6STejun Heo 	 */
1088873eaca6STejun Heo 	collision = find_worker_executing_work(pool, work);
1089873eaca6STejun Heo 	if (unlikely(collision)) {
1090873eaca6STejun Heo 		move_linked_works(work, &collision->scheduled, nextp);
1091873eaca6STejun Heo 		return false;
1092873eaca6STejun Heo 	}
1093873eaca6STejun Heo 
1094873eaca6STejun Heo 	move_linked_works(work, &worker->scheduled, nextp);
1095873eaca6STejun Heo 	return true;
1096873eaca6STejun Heo }
1097873eaca6STejun Heo 
1098873eaca6STejun Heo /**
10990219a352STejun Heo  * kick_pool - wake up an idle worker if necessary
11000219a352STejun Heo  * @pool: pool to kick
1101797e8345STejun Heo  *
11020219a352STejun Heo  * @pool may have pending work items. Wake up worker if necessary. Returns
11030219a352STejun Heo  * whether a worker was woken up.
1104797e8345STejun Heo  */
kick_pool(struct worker_pool * pool)11050219a352STejun Heo static bool kick_pool(struct worker_pool *pool)
1106797e8345STejun Heo {
1107797e8345STejun Heo 	struct worker *worker = first_idle_worker(pool);
11088639ecebSTejun Heo 	struct task_struct *p;
1109797e8345STejun Heo 
11100219a352STejun Heo 	lockdep_assert_held(&pool->lock);
11110219a352STejun Heo 
11120219a352STejun Heo 	if (!need_more_worker(pool) || !worker)
11130219a352STejun Heo 		return false;
11140219a352STejun Heo 
11158639ecebSTejun Heo 	p = worker->task;
11168639ecebSTejun Heo 
11178639ecebSTejun Heo #ifdef CONFIG_SMP
11188639ecebSTejun Heo 	/*
11198639ecebSTejun Heo 	 * Idle @worker is about to execute @work and waking up provides an
11208639ecebSTejun Heo 	 * opportunity to migrate @worker at a lower cost by setting the task's
11218639ecebSTejun Heo 	 * wake_cpu field. Let's see if we want to move @worker to improve
11228639ecebSTejun Heo 	 * execution locality.
11238639ecebSTejun Heo 	 *
11248639ecebSTejun Heo 	 * We're waking the worker that went idle the latest and there's some
11258639ecebSTejun Heo 	 * chance that @worker is marked idle but hasn't gone off CPU yet. If
11268639ecebSTejun Heo 	 * so, setting the wake_cpu won't do anything. As this is a best-effort
11278639ecebSTejun Heo 	 * optimization and the race window is narrow, let's leave as-is for
11288639ecebSTejun Heo 	 * now. If this becomes pronounced, we can skip over workers which are
11298639ecebSTejun Heo 	 * still on cpu when picking an idle worker.
11308639ecebSTejun Heo 	 *
11318639ecebSTejun Heo 	 * If @pool has non-strict affinity, @worker might have ended up outside
11328639ecebSTejun Heo 	 * its affinity scope. Repatriate.
11338639ecebSTejun Heo 	 */
11348639ecebSTejun Heo 	if (!pool->attrs->affn_strict &&
11358639ecebSTejun Heo 	    !cpumask_test_cpu(p->wake_cpu, pool->attrs->__pod_cpumask)) {
11368639ecebSTejun Heo 		struct work_struct *work = list_first_entry(&pool->worklist,
11378639ecebSTejun Heo 						struct work_struct, entry);
1138c57824d4SSven Schnelle 		int wake_cpu = cpumask_any_and_distribute(pool->attrs->__pod_cpumask,
1139c57824d4SSven Schnelle 							  cpu_online_mask);
1140c57824d4SSven Schnelle 		if (wake_cpu < nr_cpu_ids) {
1141c57824d4SSven Schnelle 			p->wake_cpu = wake_cpu;
11428639ecebSTejun Heo 			get_work_pwq(work)->stats[PWQ_STAT_REPATRIATED]++;
11438639ecebSTejun Heo 		}
1144c57824d4SSven Schnelle 	}
11458639ecebSTejun Heo #endif
11468639ecebSTejun Heo 	wake_up_process(p);
11470219a352STejun Heo 	return true;
1148797e8345STejun Heo }
1149797e8345STejun Heo 
115063638450STejun Heo #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
115163638450STejun Heo 
115263638450STejun Heo /*
115363638450STejun Heo  * Concurrency-managed per-cpu work items that hog CPU for longer than
115463638450STejun Heo  * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
115563638450STejun Heo  * which prevents them from stalling other concurrency-managed work items. If a
115663638450STejun Heo  * work function keeps triggering this mechanism, it's likely that the work item
115763638450STejun Heo  * should be using an unbound workqueue instead.
115863638450STejun Heo  *
115963638450STejun Heo  * wq_cpu_intensive_report() tracks work functions which trigger such conditions
116063638450STejun Heo  * and report them so that they can be examined and converted to use unbound
116163638450STejun Heo  * workqueues as appropriate. To avoid flooding the console, each violating work
116263638450STejun Heo  * function is tracked and reported with exponential backoff.
116363638450STejun Heo  */
116463638450STejun Heo #define WCI_MAX_ENTS 128
116563638450STejun Heo 
116663638450STejun Heo struct wci_ent {
116763638450STejun Heo 	work_func_t		func;
116863638450STejun Heo 	atomic64_t		cnt;
116963638450STejun Heo 	struct hlist_node	hash_node;
117063638450STejun Heo };
117163638450STejun Heo 
117263638450STejun Heo static struct wci_ent wci_ents[WCI_MAX_ENTS];
117363638450STejun Heo static int wci_nr_ents;
117463638450STejun Heo static DEFINE_RAW_SPINLOCK(wci_lock);
117563638450STejun Heo static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
117663638450STejun Heo 
wci_find_ent(work_func_t func)117763638450STejun Heo static struct wci_ent *wci_find_ent(work_func_t func)
117863638450STejun Heo {
117963638450STejun Heo 	struct wci_ent *ent;
118063638450STejun Heo 
118163638450STejun Heo 	hash_for_each_possible_rcu(wci_hash, ent, hash_node,
118263638450STejun Heo 				   (unsigned long)func) {
118363638450STejun Heo 		if (ent->func == func)
118463638450STejun Heo 			return ent;
118563638450STejun Heo 	}
118663638450STejun Heo 	return NULL;
118763638450STejun Heo }
118863638450STejun Heo 
wq_cpu_intensive_report(work_func_t func)118963638450STejun Heo static void wq_cpu_intensive_report(work_func_t func)
119063638450STejun Heo {
119163638450STejun Heo 	struct wci_ent *ent;
119263638450STejun Heo 
119363638450STejun Heo restart:
119463638450STejun Heo 	ent = wci_find_ent(func);
119563638450STejun Heo 	if (ent) {
119663638450STejun Heo 		u64 cnt;
119763638450STejun Heo 
119863638450STejun Heo 		/*
119963638450STejun Heo 		 * Start reporting from the fourth time and back off
120063638450STejun Heo 		 * exponentially.
120163638450STejun Heo 		 */
120263638450STejun Heo 		cnt = atomic64_inc_return_relaxed(&ent->cnt);
120363638450STejun Heo 		if (cnt >= 4 && is_power_of_2(cnt))
120463638450STejun Heo 			printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
120563638450STejun Heo 					ent->func, wq_cpu_intensive_thresh_us,
120663638450STejun Heo 					atomic64_read(&ent->cnt));
120763638450STejun Heo 		return;
120863638450STejun Heo 	}
120963638450STejun Heo 
121063638450STejun Heo 	/*
121163638450STejun Heo 	 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
121263638450STejun Heo 	 * is exhausted, something went really wrong and we probably made enough
121363638450STejun Heo 	 * noise already.
121463638450STejun Heo 	 */
121563638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS)
121663638450STejun Heo 		return;
121763638450STejun Heo 
121863638450STejun Heo 	raw_spin_lock(&wci_lock);
121963638450STejun Heo 
122063638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS) {
122163638450STejun Heo 		raw_spin_unlock(&wci_lock);
122263638450STejun Heo 		return;
122363638450STejun Heo 	}
122463638450STejun Heo 
122563638450STejun Heo 	if (wci_find_ent(func)) {
122663638450STejun Heo 		raw_spin_unlock(&wci_lock);
122763638450STejun Heo 		goto restart;
122863638450STejun Heo 	}
122963638450STejun Heo 
123063638450STejun Heo 	ent = &wci_ents[wci_nr_ents++];
123163638450STejun Heo 	ent->func = func;
123263638450STejun Heo 	atomic64_set(&ent->cnt, 1);
123363638450STejun Heo 	hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
123463638450STejun Heo 
123563638450STejun Heo 	raw_spin_unlock(&wci_lock);
123663638450STejun Heo }
123763638450STejun Heo 
123863638450STejun Heo #else	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
wq_cpu_intensive_report(work_func_t func)123963638450STejun Heo static void wq_cpu_intensive_report(work_func_t func) {}
124063638450STejun Heo #endif	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
124163638450STejun Heo 
1242c54d5046STejun Heo /**
12431da177e4SLinus Torvalds  * wq_worker_running - a worker is running again
12441da177e4SLinus Torvalds  * @task: task waking up
12451da177e4SLinus Torvalds  *
12461da177e4SLinus Torvalds  * This function is called when a worker returns from schedule()
12471da177e4SLinus Torvalds  */
wq_worker_running(struct task_struct * task)12481da177e4SLinus Torvalds void wq_worker_running(struct task_struct *task)
12491da177e4SLinus Torvalds {
12501da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
12511da177e4SLinus Torvalds 
1252c8f6219bSZqiang 	if (!READ_ONCE(worker->sleeping))
12531da177e4SLinus Torvalds 		return;
12541da177e4SLinus Torvalds 
12551da177e4SLinus Torvalds 	/*
12561da177e4SLinus Torvalds 	 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
12571da177e4SLinus Torvalds 	 * and the nr_running increment below, we may ruin the nr_running reset
12581da177e4SLinus Torvalds 	 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
12591da177e4SLinus Torvalds 	 * pool. Protect against such race.
12601da177e4SLinus Torvalds 	 */
12611da177e4SLinus Torvalds 	preempt_disable();
12621da177e4SLinus Torvalds 	if (!(worker->flags & WORKER_NOT_RUNNING))
12631da177e4SLinus Torvalds 		worker->pool->nr_running++;
12641da177e4SLinus Torvalds 	preempt_enable();
1265616db877STejun Heo 
1266616db877STejun Heo 	/*
1267616db877STejun Heo 	 * CPU intensive auto-detection cares about how long a work item hogged
1268616db877STejun Heo 	 * CPU without sleeping. Reset the starting timestamp on wakeup.
1269616db877STejun Heo 	 */
1270616db877STejun Heo 	worker->current_at = worker->task->se.sum_exec_runtime;
1271616db877STejun Heo 
1272c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 0);
12731da177e4SLinus Torvalds }
12741da177e4SLinus Torvalds 
12751da177e4SLinus Torvalds /**
12761da177e4SLinus Torvalds  * wq_worker_sleeping - a worker is going to sleep
12771da177e4SLinus Torvalds  * @task: task going to sleep
12781da177e4SLinus Torvalds  *
12791da177e4SLinus Torvalds  * This function is called from schedule() when a busy worker is
12801da177e4SLinus Torvalds  * going to sleep.
12811da177e4SLinus Torvalds  */
wq_worker_sleeping(struct task_struct * task)12821da177e4SLinus Torvalds void wq_worker_sleeping(struct task_struct *task)
12831da177e4SLinus Torvalds {
12841da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
12851da177e4SLinus Torvalds 	struct worker_pool *pool;
12861da177e4SLinus Torvalds 
12871da177e4SLinus Torvalds 	/*
12881da177e4SLinus Torvalds 	 * Rescuers, which may not have all the fields set up like normal
12891da177e4SLinus Torvalds 	 * workers, also reach here, let's not access anything before
12901da177e4SLinus Torvalds 	 * checking NOT_RUNNING.
12911da177e4SLinus Torvalds 	 */
12921da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING)
12931da177e4SLinus Torvalds 		return;
12941da177e4SLinus Torvalds 
12951da177e4SLinus Torvalds 	pool = worker->pool;
12961da177e4SLinus Torvalds 
12971da177e4SLinus Torvalds 	/* Return if preempted before wq_worker_running() was reached */
1298c8f6219bSZqiang 	if (READ_ONCE(worker->sleeping))
12991da177e4SLinus Torvalds 		return;
13001da177e4SLinus Torvalds 
1301c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 1);
13021da177e4SLinus Torvalds 	raw_spin_lock_irq(&pool->lock);
13031da177e4SLinus Torvalds 
13041da177e4SLinus Torvalds 	/*
13051da177e4SLinus Torvalds 	 * Recheck in case unbind_workers() preempted us. We don't
13061da177e4SLinus Torvalds 	 * want to decrement nr_running after the worker is unbound
13071da177e4SLinus Torvalds 	 * and nr_running has been reset.
13081da177e4SLinus Torvalds 	 */
13091da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING) {
13101da177e4SLinus Torvalds 		raw_spin_unlock_irq(&pool->lock);
13111da177e4SLinus Torvalds 		return;
13121da177e4SLinus Torvalds 	}
13131da177e4SLinus Torvalds 
13141da177e4SLinus Torvalds 	pool->nr_running--;
13150219a352STejun Heo 	if (kick_pool(pool))
1316725e8ec5STejun Heo 		worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
13170219a352STejun Heo 
13181da177e4SLinus Torvalds 	raw_spin_unlock_irq(&pool->lock);
13191da177e4SLinus Torvalds }
13201da177e4SLinus Torvalds 
13211da177e4SLinus Torvalds /**
1322616db877STejun Heo  * wq_worker_tick - a scheduler tick occurred while a kworker is running
1323616db877STejun Heo  * @task: task currently running
1324616db877STejun Heo  *
1325616db877STejun Heo  * Called from scheduler_tick(). We're in the IRQ context and the current
1326616db877STejun Heo  * worker's fields which follow the 'K' locking rule can be accessed safely.
1327616db877STejun Heo  */
wq_worker_tick(struct task_struct * task)1328616db877STejun Heo void wq_worker_tick(struct task_struct *task)
1329616db877STejun Heo {
1330616db877STejun Heo 	struct worker *worker = kthread_data(task);
1331616db877STejun Heo 	struct pool_workqueue *pwq = worker->current_pwq;
1332616db877STejun Heo 	struct worker_pool *pool = worker->pool;
1333616db877STejun Heo 
1334616db877STejun Heo 	if (!pwq)
1335616db877STejun Heo 		return;
1336616db877STejun Heo 
13378a1dd1e5STejun Heo 	pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
13388a1dd1e5STejun Heo 
133918c8ae81SZqiang 	if (!wq_cpu_intensive_thresh_us)
134018c8ae81SZqiang 		return;
134118c8ae81SZqiang 
1342616db877STejun Heo 	/*
1343616db877STejun Heo 	 * If the current worker is concurrency managed and hogged the CPU for
1344616db877STejun Heo 	 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1345616db877STejun Heo 	 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1346c8f6219bSZqiang 	 *
1347c8f6219bSZqiang 	 * Set @worker->sleeping means that @worker is in the process of
1348c8f6219bSZqiang 	 * switching out voluntarily and won't be contributing to
1349c8f6219bSZqiang 	 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1350c8f6219bSZqiang 	 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1351c8f6219bSZqiang 	 * double decrements. The task is releasing the CPU anyway. Let's skip.
1352c8f6219bSZqiang 	 * We probably want to make this prettier in the future.
1353616db877STejun Heo 	 */
1354c8f6219bSZqiang 	if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1355616db877STejun Heo 	    worker->task->se.sum_exec_runtime - worker->current_at <
1356616db877STejun Heo 	    wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1357616db877STejun Heo 		return;
1358616db877STejun Heo 
1359616db877STejun Heo 	raw_spin_lock(&pool->lock);
1360616db877STejun Heo 
1361616db877STejun Heo 	worker_set_flags(worker, WORKER_CPU_INTENSIVE);
136263638450STejun Heo 	wq_cpu_intensive_report(worker->current_func);
1363616db877STejun Heo 	pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1364616db877STejun Heo 
13650219a352STejun Heo 	if (kick_pool(pool))
1366616db877STejun Heo 		pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1367616db877STejun Heo 
1368616db877STejun Heo 	raw_spin_unlock(&pool->lock);
1369616db877STejun Heo }
1370616db877STejun Heo 
1371616db877STejun Heo /**
13721da177e4SLinus Torvalds  * wq_worker_last_func - retrieve worker's last work function
13731da177e4SLinus Torvalds  * @task: Task to retrieve last work function of.
13741da177e4SLinus Torvalds  *
13751da177e4SLinus Torvalds  * Determine the last function a worker executed. This is called from
13761da177e4SLinus Torvalds  * the scheduler to get a worker's last known identity.
13771da177e4SLinus Torvalds  *
13781da177e4SLinus Torvalds  * CONTEXT:
13799b41ea72SAndrew Morton  * raw_spin_lock_irq(rq->lock)
13801da177e4SLinus Torvalds  *
13811da177e4SLinus Torvalds  * This function is called during schedule() when a kworker is going
1382f756d5e2SNathan Lynch  * to sleep. It's used by psi to identify aggregation workers during
1383f756d5e2SNathan Lynch  * dequeuing, to allow periodic aggregation to shut-off when that
13841da177e4SLinus Torvalds  * worker is the last task in the system or cgroup to go to sleep.
13851da177e4SLinus Torvalds  *
13861da177e4SLinus Torvalds  * As this function doesn't involve any workqueue-related locking, it
13871da177e4SLinus Torvalds  * only returns stable values when called from inside the scheduler's
13881da177e4SLinus Torvalds  * queuing and dequeuing paths, when @task, which must be a kworker,
13891da177e4SLinus Torvalds  * is guaranteed to not be processing any works.
1390365970a1SDavid Howells  *
1391365970a1SDavid Howells  * Return:
1392365970a1SDavid Howells  * The last work function %current executed as a worker, NULL if it
1393365970a1SDavid Howells  * hasn't executed any work yet.
1394365970a1SDavid Howells  */
wq_worker_last_func(struct task_struct * task)1395365970a1SDavid Howells work_func_t wq_worker_last_func(struct task_struct *task)
1396365970a1SDavid Howells {
1397365970a1SDavid Howells 	struct worker *worker = kthread_data(task);
1398365970a1SDavid Howells 
1399365970a1SDavid Howells 	return worker->last_func;
1400365970a1SDavid Howells }
1401365970a1SDavid Howells 
1402d302f017STejun Heo /**
14038864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
14048864b4e5STejun Heo  * @pwq: pool_workqueue to get
14058864b4e5STejun Heo  *
14068864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
14078864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
14088864b4e5STejun Heo  */
get_pwq(struct pool_workqueue * pwq)14098864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
14108864b4e5STejun Heo {
14118864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
14128864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
14138864b4e5STejun Heo 	pwq->refcnt++;
14148864b4e5STejun Heo }
14158864b4e5STejun Heo 
14168864b4e5STejun Heo /**
14178864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
14188864b4e5STejun Heo  * @pwq: pool_workqueue to put
14198864b4e5STejun Heo  *
14208864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
14218864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
14228864b4e5STejun Heo  */
put_pwq(struct pool_workqueue * pwq)14238864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
14248864b4e5STejun Heo {
14258864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
14268864b4e5STejun Heo 	if (likely(--pwq->refcnt))
14278864b4e5STejun Heo 		return;
14288864b4e5STejun Heo 	/*
1429967b494eSTejun Heo 	 * @pwq can't be released under pool->lock, bounce to a dedicated
1430967b494eSTejun Heo 	 * kthread_worker to avoid A-A deadlocks.
14318864b4e5STejun Heo 	 */
1432687a9aa5STejun Heo 	kthread_queue_work(pwq_release_worker, &pwq->release_work);
14338864b4e5STejun Heo }
14348864b4e5STejun Heo 
1435dce90d47STejun Heo /**
1436dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1437dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1438dce90d47STejun Heo  *
1439dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1440dce90d47STejun Heo  */
put_pwq_unlocked(struct pool_workqueue * pwq)1441dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1442dce90d47STejun Heo {
1443dce90d47STejun Heo 	if (pwq) {
1444dce90d47STejun Heo 		/*
144524acfb71SThomas Gleixner 		 * As both pwqs and pools are RCU protected, the
1446dce90d47STejun Heo 		 * following lock operations are safe.
1447dce90d47STejun Heo 		 */
1448a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
1449dce90d47STejun Heo 		put_pwq(pwq);
1450a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
1451dce90d47STejun Heo 	}
1452dce90d47STejun Heo }
1453dce90d47STejun Heo 
pwq_activate_inactive_work(struct work_struct * work)1454957578ecSGreg Kroah-Hartman static void pwq_activate_inactive_work(struct work_struct *work)
1455bf4ede01STejun Heo {
1456957578ecSGreg Kroah-Hartman 	struct pool_workqueue *pwq = get_work_pwq(work);
1457957578ecSGreg Kroah-Hartman 
1458bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
145982607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
146082607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1461112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
14625debbff9SGreg Kroah-Hartman 	__clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work));
1463112202d9STejun Heo 	pwq->nr_active++;
1464bf4ede01STejun Heo }
1465bf4ede01STejun Heo 
pwq_activate_first_inactive(struct pool_workqueue * pwq)14665debbff9SGreg Kroah-Hartman static void pwq_activate_first_inactive(struct pool_workqueue *pwq)
14673aa62497SLai Jiangshan {
14685debbff9SGreg Kroah-Hartman 	struct work_struct *work = list_first_entry(&pwq->inactive_works,
14693aa62497SLai Jiangshan 						    struct work_struct, entry);
14703aa62497SLai Jiangshan 
1471957578ecSGreg Kroah-Hartman 	pwq_activate_inactive_work(work);
14723aa62497SLai Jiangshan }
14733aa62497SLai Jiangshan 
1474bf4ede01STejun Heo /**
1475112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1476112202d9STejun Heo  * @pwq: pwq of interest
1477c4560c2cSLai Jiangshan  * @work_data: work_data of work which left the queue
1478bf4ede01STejun Heo  *
1479bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1480112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1481bf4ede01STejun Heo  *
1482bf4ede01STejun Heo  * CONTEXT:
1483a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1484bf4ede01STejun Heo  */
pwq_dec_nr_in_flight(struct pool_workqueue * pwq,unsigned long work_data)1485c4560c2cSLai Jiangshan static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1486bf4ede01STejun Heo {
1487c4560c2cSLai Jiangshan 	int color = get_work_color(work_data);
1488c4560c2cSLai Jiangshan 
14895debbff9SGreg Kroah-Hartman 	if (!(work_data & WORK_STRUCT_INACTIVE)) {
14905debbff9SGreg Kroah-Hartman 		pwq->nr_active--;
14915debbff9SGreg Kroah-Hartman 		if (!list_empty(&pwq->inactive_works)) {
14925debbff9SGreg Kroah-Hartman 			/* one down, submit an inactive one */
1493d8354f26SGreg Kroah-Hartman 			if (pwq->nr_active < pwq->max_active)
14945debbff9SGreg Kroah-Hartman 				pwq_activate_first_inactive(pwq);
14955debbff9SGreg Kroah-Hartman 		}
14965debbff9SGreg Kroah-Hartman 	}
1497018f3a13SLai Jiangshan 
1498018f3a13SLai Jiangshan 	pwq->nr_in_flight[color]--;
1499bf4ede01STejun Heo 
1500bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1501112202d9STejun Heo 	if (likely(pwq->flush_color != color))
15028864b4e5STejun Heo 		goto out_put;
1503bf4ede01STejun Heo 
1504bf4ede01STejun Heo 	/* are there still in-flight works? */
1505112202d9STejun Heo 	if (pwq->nr_in_flight[color])
15068864b4e5STejun Heo 		goto out_put;
1507bf4ede01STejun Heo 
1508112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1509112202d9STejun Heo 	pwq->flush_color = -1;
1510bf4ede01STejun Heo 
1511bf4ede01STejun Heo 	/*
1512112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1513bf4ede01STejun Heo 	 * will handle the rest.
1514bf4ede01STejun Heo 	 */
1515112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1516112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
15178864b4e5STejun Heo out_put:
15188864b4e5STejun Heo 	put_pwq(pwq);
1519bf4ede01STejun Heo }
1520bf4ede01STejun Heo 
152136e227d2STejun Heo /**
1522bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
152336e227d2STejun Heo  * @work: work item to steal
152436e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1525bbb68dfaSTejun Heo  * @flags: place to store irq state
152636e227d2STejun Heo  *
152736e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1528d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
152936e227d2STejun Heo  *
1530d185af30SYacine Belkadi  * Return:
15313eb6b31bSMauro Carvalho Chehab  *
15323eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
153336e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
153436e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
153536e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1536bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1537bbb68dfaSTejun Heo  *		for arbitrarily long
15383eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
153936e227d2STejun Heo  *
1540d185af30SYacine Belkadi  * Note:
1541bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1542e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1543e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1544e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1545bbb68dfaSTejun Heo  *
1546bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1547bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1548bbb68dfaSTejun Heo  *
1549e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1550bf4ede01STejun Heo  */
try_to_grab_pending(struct work_struct * work,bool is_dwork,unsigned long * flags)1551bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1552bbb68dfaSTejun Heo 			       unsigned long *flags)
1553bf4ede01STejun Heo {
1554d565ed63STejun Heo 	struct worker_pool *pool;
1555112202d9STejun Heo 	struct pool_workqueue *pwq;
1556bf4ede01STejun Heo 
1557bbb68dfaSTejun Heo 	local_irq_save(*flags);
1558bbb68dfaSTejun Heo 
155936e227d2STejun Heo 	/* try to steal the timer if it exists */
156036e227d2STejun Heo 	if (is_dwork) {
156136e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
156236e227d2STejun Heo 
1563e0aecdd8STejun Heo 		/*
1564e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1565e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1566e0aecdd8STejun Heo 		 * running on the local CPU.
1567e0aecdd8STejun Heo 		 */
156836e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
156936e227d2STejun Heo 			return 1;
157036e227d2STejun Heo 	}
157136e227d2STejun Heo 
157236e227d2STejun Heo 	/* try to claim PENDING the normal way */
1573bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1574bf4ede01STejun Heo 		return 0;
1575bf4ede01STejun Heo 
157624acfb71SThomas Gleixner 	rcu_read_lock();
1577bf4ede01STejun Heo 	/*
1578bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1579bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1580bf4ede01STejun Heo 	 */
1581d565ed63STejun Heo 	pool = get_work_pool(work);
1582d565ed63STejun Heo 	if (!pool)
1583bbb68dfaSTejun Heo 		goto fail;
1584bf4ede01STejun Heo 
1585a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&pool->lock);
1586bf4ede01STejun Heo 	/*
1587112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1588112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1589112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1590112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1591112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
15920b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1593bf4ede01STejun Heo 	 */
1594112202d9STejun Heo 	pwq = get_work_pwq(work);
1595112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1596bf4ede01STejun Heo 		debug_work_deactivate(work);
15973aa62497SLai Jiangshan 
15983aa62497SLai Jiangshan 		/*
1599018f3a13SLai Jiangshan 		 * A cancelable inactive work item must be in the
1600018f3a13SLai Jiangshan 		 * pwq->inactive_works since a queued barrier can't be
1601018f3a13SLai Jiangshan 		 * canceled (see the comments in insert_wq_barrier()).
1602018f3a13SLai Jiangshan 		 *
1603f97a4a1aSLai Jiangshan 		 * An inactive work item cannot be grabbed directly because
1604d812796eSLai Jiangshan 		 * it might have linked barrier work items which, if left
1605f97a4a1aSLai Jiangshan 		 * on the inactive_works list, will confuse pwq->nr_active
160616062836STejun Heo 		 * management later on and cause stall.  Make sure the work
160716062836STejun Heo 		 * item is activated before grabbing.
16083aa62497SLai Jiangshan 		 */
1609957578ecSGreg Kroah-Hartman 		if (*work_data_bits(work) & WORK_STRUCT_INACTIVE)
1610957578ecSGreg Kroah-Hartman 			pwq_activate_inactive_work(work);
16113aa62497SLai Jiangshan 
1612bf4ede01STejun Heo 		list_del_init(&work->entry);
1613c4560c2cSLai Jiangshan 		pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
161436e227d2STejun Heo 
1615112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
16164468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
16174468a00fSLai Jiangshan 
1618a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock(&pool->lock);
161924acfb71SThomas Gleixner 		rcu_read_unlock();
162036e227d2STejun Heo 		return 1;
1621bf4ede01STejun Heo 	}
1622a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pool->lock);
1623bbb68dfaSTejun Heo fail:
162424acfb71SThomas Gleixner 	rcu_read_unlock();
1625bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1626bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1627bbb68dfaSTejun Heo 		return -ENOENT;
1628bbb68dfaSTejun Heo 	cpu_relax();
162936e227d2STejun Heo 	return -EAGAIN;
1630bf4ede01STejun Heo }
1631bf4ede01STejun Heo 
1632bf4ede01STejun Heo /**
1633706026c2STejun Heo  * insert_work - insert a work into a pool
1634112202d9STejun Heo  * @pwq: pwq @work belongs to
16354690c4abSTejun Heo  * @work: work to insert
16364690c4abSTejun Heo  * @head: insertion point
16374690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
16384690c4abSTejun Heo  *
1639112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1640706026c2STejun Heo  * work_struct flags.
16414690c4abSTejun Heo  *
16424690c4abSTejun Heo  * CONTEXT:
1643a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1644365970a1SDavid Howells  */
insert_work(struct pool_workqueue * pwq,struct work_struct * work,struct list_head * head,unsigned int extra_flags)1645112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1646112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1647b89deed3SOleg Nesterov {
1648fe089f87STejun Heo 	debug_work_activate(work);
1649e1d8aa9fSFrederic Weisbecker 
1650e89a85d6SWalter Wu 	/* record the work call stack in order to print it in KASAN reports */
1651f70da745SMarco Elver 	kasan_record_aux_stack_noalloc(work);
1652e89a85d6SWalter Wu 
16534690c4abSTejun Heo 	/* we own @work, set data and link */
1654112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
16551a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
16568864b4e5STejun Heo 	get_pwq(pwq);
1657b89deed3SOleg Nesterov }
1658b89deed3SOleg Nesterov 
1659c8efcc25STejun Heo /*
1660c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
16618d03ecfeSTejun Heo  * same workqueue.
1662c8efcc25STejun Heo  */
is_chained_work(struct workqueue_struct * wq)1663c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1664c8efcc25STejun Heo {
1665c8efcc25STejun Heo 	struct worker *worker;
1666c8efcc25STejun Heo 
16678d03ecfeSTejun Heo 	worker = current_wq_worker();
1668c8efcc25STejun Heo 	/*
1669bf393fd4SBart Van Assche 	 * Return %true iff I'm a worker executing a work item on @wq.  If
16708d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1671c8efcc25STejun Heo 	 */
1672112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1673c8efcc25STejun Heo }
1674c8efcc25STejun Heo 
1675ef557180SMike Galbraith /*
1676ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
1677ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
1678ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
1679ef557180SMike Galbraith  */
wq_select_unbound_cpu(int cpu)1680ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1681ef557180SMike Galbraith {
1682ef557180SMike Galbraith 	int new_cpu;
1683ef557180SMike Galbraith 
1684f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
1685ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1686ef557180SMike Galbraith 			return cpu;
1687a8ec5880SAmmar Faizi 	} else {
1688a8ec5880SAmmar Faizi 		pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
1689f303fccbSTejun Heo 	}
1690f303fccbSTejun Heo 
1691ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
1692ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1693ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
1694ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1695ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
1696ef557180SMike Galbraith 			return cpu;
1697ef557180SMike Galbraith 	}
1698ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
1699ef557180SMike Galbraith 
1700ef557180SMike Galbraith 	return new_cpu;
1701ef557180SMike Galbraith }
1702ef557180SMike Galbraith 
__queue_work(int cpu,struct workqueue_struct * wq,struct work_struct * work)1703d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
17041da177e4SLinus Torvalds 			 struct work_struct *work)
17051da177e4SLinus Torvalds {
1706112202d9STejun Heo 	struct pool_workqueue *pwq;
1707fe089f87STejun Heo 	struct worker_pool *last_pool, *pool;
17088a2e8e5dSTejun Heo 	unsigned int work_flags;
1709b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
17108930cabaSTejun Heo 
17118930cabaSTejun Heo 	/*
17128930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
17138930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
17148930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
17158930cabaSTejun Heo 	 * happen with IRQ disabled.
17168930cabaSTejun Heo 	 */
17178e8eb730SFrederic Weisbecker 	lockdep_assert_irqs_disabled();
17181da177e4SLinus Torvalds 
17191e19ffc6STejun Heo 
172033e3f0a3SRichard Clark 	/*
172133e3f0a3SRichard Clark 	 * For a draining wq, only works from the same workqueue are
172233e3f0a3SRichard Clark 	 * allowed. The __WQ_DESTROYING helps to spot the issue that
172333e3f0a3SRichard Clark 	 * queues a new work item to a wq after destroy_workqueue(wq).
172433e3f0a3SRichard Clark 	 */
172533e3f0a3SRichard Clark 	if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
172633e3f0a3SRichard Clark 		     WARN_ON_ONCE(!is_chained_work(wq))))
1727e41e704bSTejun Heo 		return;
172824acfb71SThomas Gleixner 	rcu_read_lock();
17299e8cd2f5STejun Heo retry:
1730aa202f1fSHillf Danton 	/* pwq which will be used unless @work is executing elsewhere */
1731636b927eSTejun Heo 	if (req_cpu == WORK_CPU_UNBOUND) {
1732636b927eSTejun Heo 		if (wq->flags & WQ_UNBOUND)
1733ef557180SMike Galbraith 			cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1734636b927eSTejun Heo 		else
1735aa202f1fSHillf Danton 			cpu = raw_smp_processor_id();
1736aa202f1fSHillf Danton 	}
1737f3421797STejun Heo 
1738636b927eSTejun Heo 	pwq = rcu_dereference(*per_cpu_ptr(wq->cpu_pwq, cpu));
1739fe089f87STejun Heo 	pool = pwq->pool;
1740fe089f87STejun Heo 
174118aa9effSTejun Heo 	/*
1742c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1743c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1744c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
174518aa9effSTejun Heo 	 */
1746c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1747fe089f87STejun Heo 	if (last_pool && last_pool != pool) {
174818aa9effSTejun Heo 		struct worker *worker;
174918aa9effSTejun Heo 
1750a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&last_pool->lock);
175118aa9effSTejun Heo 
1752c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
175318aa9effSTejun Heo 
1754112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1755c9178087STejun Heo 			pwq = worker->current_pwq;
1756fe089f87STejun Heo 			pool = pwq->pool;
1757fe089f87STejun Heo 			WARN_ON_ONCE(pool != last_pool);
17588594fadeSLai Jiangshan 		} else {
175918aa9effSTejun Heo 			/* meh... not running there, queue here */
1760a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&last_pool->lock);
1761fe089f87STejun Heo 			raw_spin_lock(&pool->lock);
176218aa9effSTejun Heo 		}
17638930cabaSTejun Heo 	} else {
1764fe089f87STejun Heo 		raw_spin_lock(&pool->lock);
17658930cabaSTejun Heo 	}
1766502ca9d8STejun Heo 
17679e8cd2f5STejun Heo 	/*
1768636b927eSTejun Heo 	 * pwq is determined and locked. For unbound pools, we could have raced
1769636b927eSTejun Heo 	 * with pwq release and it could already be dead. If its refcnt is zero,
1770636b927eSTejun Heo 	 * repeat pwq selection. Note that unbound pwqs never die without
1771636b927eSTejun Heo 	 * another pwq replacing it in cpu_pwq or while work items are executing
1772636b927eSTejun Heo 	 * on it, so the retrying is guaranteed to make forward-progress.
17739e8cd2f5STejun Heo 	 */
17749e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
17759e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
1776fe089f87STejun Heo 			raw_spin_unlock(&pool->lock);
17779e8cd2f5STejun Heo 			cpu_relax();
17789e8cd2f5STejun Heo 			goto retry;
17799e8cd2f5STejun Heo 		}
17809e8cd2f5STejun Heo 		/* oops */
17819e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
17829e8cd2f5STejun Heo 			  wq->name, cpu);
17839e8cd2f5STejun Heo 	}
17849e8cd2f5STejun Heo 
1785112202d9STejun Heo 	/* pwq determined, queue */
1786112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1787502ca9d8STejun Heo 
178824acfb71SThomas Gleixner 	if (WARN_ON(!list_empty(&work->entry)))
178924acfb71SThomas Gleixner 		goto out;
17901e19ffc6STejun Heo 
1791112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1792112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
17931e19ffc6STejun Heo 
1794d8354f26SGreg Kroah-Hartman 	if (likely(pwq->nr_active < pwq->max_active)) {
1795fe089f87STejun Heo 		if (list_empty(&pool->worklist))
1796fe089f87STejun Heo 			pool->watchdog_ts = jiffies;
1797fe089f87STejun Heo 
1798cdadf009STejun Heo 		trace_workqueue_activate_work(work);
17995debbff9SGreg Kroah-Hartman 		pwq->nr_active++;
1800fe089f87STejun Heo 		insert_work(pwq, work, &pool->worklist, work_flags);
18010219a352STejun Heo 		kick_pool(pool);
18028a2e8e5dSTejun Heo 	} else {
1803f97a4a1aSLai Jiangshan 		work_flags |= WORK_STRUCT_INACTIVE;
1804fe089f87STejun Heo 		insert_work(pwq, work, &pwq->inactive_works, work_flags);
18058a2e8e5dSTejun Heo 	}
18061e19ffc6STejun Heo 
180724acfb71SThomas Gleixner out:
1808fe089f87STejun Heo 	raw_spin_unlock(&pool->lock);
180924acfb71SThomas Gleixner 	rcu_read_unlock();
18101da177e4SLinus Torvalds }
18111da177e4SLinus Torvalds 
18120fcb78c2SRolf Eike Beer /**
1813c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1814c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1815c1a220e7SZhang Rui  * @wq: workqueue to use
1816c1a220e7SZhang Rui  * @work: work to queue
1817c1a220e7SZhang Rui  *
1818c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1819443378f0SPaul E. McKenney  * can't go away.  Callers that fail to ensure that the specified
1820443378f0SPaul E. McKenney  * CPU cannot go away will execute on a randomly chosen CPU.
1821854f5cc5SPaul E. McKenney  * But note well that callers specifying a CPU that never has been
1822854f5cc5SPaul E. McKenney  * online will get a splat.
1823d185af30SYacine Belkadi  *
1824d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
1825c1a220e7SZhang Rui  */
queue_work_on(int cpu,struct workqueue_struct * wq,struct work_struct * work)1826d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1827d4283e93STejun Heo 		   struct work_struct *work)
1828c1a220e7SZhang Rui {
1829d4283e93STejun Heo 	bool ret = false;
18308930cabaSTejun Heo 	unsigned long flags;
18318930cabaSTejun Heo 
18328930cabaSTejun Heo 	local_irq_save(flags);
1833c1a220e7SZhang Rui 
183422df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
18354690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1836d4283e93STejun Heo 		ret = true;
1837c1a220e7SZhang Rui 	}
18388930cabaSTejun Heo 
18398930cabaSTejun Heo 	local_irq_restore(flags);
1840c1a220e7SZhang Rui 	return ret;
1841c1a220e7SZhang Rui }
1842ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1843c1a220e7SZhang Rui 
18448204e0c1SAlexander Duyck /**
1845fef59c9cSTejun Heo  * select_numa_node_cpu - Select a CPU based on NUMA node
18468204e0c1SAlexander Duyck  * @node: NUMA node ID that we want to select a CPU from
18478204e0c1SAlexander Duyck  *
18488204e0c1SAlexander Duyck  * This function will attempt to find a "random" cpu available on a given
18498204e0c1SAlexander Duyck  * node. If there are no CPUs available on the given node it will return
18508204e0c1SAlexander Duyck  * WORK_CPU_UNBOUND indicating that we should just schedule to any
18518204e0c1SAlexander Duyck  * available CPU if we need to schedule this work.
18528204e0c1SAlexander Duyck  */
select_numa_node_cpu(int node)1853fef59c9cSTejun Heo static int select_numa_node_cpu(int node)
18548204e0c1SAlexander Duyck {
18558204e0c1SAlexander Duyck 	int cpu;
18568204e0c1SAlexander Duyck 
18578204e0c1SAlexander Duyck 	/* Delay binding to CPU if node is not valid or online */
18588204e0c1SAlexander Duyck 	if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
18598204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
18608204e0c1SAlexander Duyck 
18618204e0c1SAlexander Duyck 	/* Use local node/cpu if we are already there */
18628204e0c1SAlexander Duyck 	cpu = raw_smp_processor_id();
18638204e0c1SAlexander Duyck 	if (node == cpu_to_node(cpu))
18648204e0c1SAlexander Duyck 		return cpu;
18658204e0c1SAlexander Duyck 
18668204e0c1SAlexander Duyck 	/* Use "random" otherwise know as "first" online CPU of node */
18678204e0c1SAlexander Duyck 	cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
18688204e0c1SAlexander Duyck 
18698204e0c1SAlexander Duyck 	/* If CPU is valid return that, otherwise just defer */
18708204e0c1SAlexander Duyck 	return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
18718204e0c1SAlexander Duyck }
18728204e0c1SAlexander Duyck 
18738204e0c1SAlexander Duyck /**
18748204e0c1SAlexander Duyck  * queue_work_node - queue work on a "random" cpu for a given NUMA node
18758204e0c1SAlexander Duyck  * @node: NUMA node that we are targeting the work for
18768204e0c1SAlexander Duyck  * @wq: workqueue to use
18778204e0c1SAlexander Duyck  * @work: work to queue
18788204e0c1SAlexander Duyck  *
18798204e0c1SAlexander Duyck  * We queue the work to a "random" CPU within a given NUMA node. The basic
18808204e0c1SAlexander Duyck  * idea here is to provide a way to somehow associate work with a given
18818204e0c1SAlexander Duyck  * NUMA node.
18828204e0c1SAlexander Duyck  *
18838204e0c1SAlexander Duyck  * This function will only make a best effort attempt at getting this onto
18848204e0c1SAlexander Duyck  * the right NUMA node. If no node is requested or the requested node is
18858204e0c1SAlexander Duyck  * offline then we just fall back to standard queue_work behavior.
18868204e0c1SAlexander Duyck  *
18878204e0c1SAlexander Duyck  * Currently the "random" CPU ends up being the first available CPU in the
18888204e0c1SAlexander Duyck  * intersection of cpu_online_mask and the cpumask of the node, unless we
18898204e0c1SAlexander Duyck  * are running on the node. In that case we just use the current CPU.
18908204e0c1SAlexander Duyck  *
18918204e0c1SAlexander Duyck  * Return: %false if @work was already on a queue, %true otherwise.
18928204e0c1SAlexander Duyck  */
queue_work_node(int node,struct workqueue_struct * wq,struct work_struct * work)18938204e0c1SAlexander Duyck bool queue_work_node(int node, struct workqueue_struct *wq,
18948204e0c1SAlexander Duyck 		     struct work_struct *work)
18958204e0c1SAlexander Duyck {
18968204e0c1SAlexander Duyck 	unsigned long flags;
18978204e0c1SAlexander Duyck 	bool ret = false;
18988204e0c1SAlexander Duyck 
18998204e0c1SAlexander Duyck 	/*
19008204e0c1SAlexander Duyck 	 * This current implementation is specific to unbound workqueues.
19018204e0c1SAlexander Duyck 	 * Specifically we only return the first available CPU for a given
19028204e0c1SAlexander Duyck 	 * node instead of cycling through individual CPUs within the node.
19038204e0c1SAlexander Duyck 	 *
19048204e0c1SAlexander Duyck 	 * If this is used with a per-cpu workqueue then the logic in
19058204e0c1SAlexander Duyck 	 * workqueue_select_cpu_near would need to be updated to allow for
19068204e0c1SAlexander Duyck 	 * some round robin type logic.
19078204e0c1SAlexander Duyck 	 */
19088204e0c1SAlexander Duyck 	WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
19098204e0c1SAlexander Duyck 
19108204e0c1SAlexander Duyck 	local_irq_save(flags);
19118204e0c1SAlexander Duyck 
19128204e0c1SAlexander Duyck 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1913fef59c9cSTejun Heo 		int cpu = select_numa_node_cpu(node);
19148204e0c1SAlexander Duyck 
19158204e0c1SAlexander Duyck 		__queue_work(cpu, wq, work);
19168204e0c1SAlexander Duyck 		ret = true;
19178204e0c1SAlexander Duyck 	}
19188204e0c1SAlexander Duyck 
19198204e0c1SAlexander Duyck 	local_irq_restore(flags);
19208204e0c1SAlexander Duyck 	return ret;
19218204e0c1SAlexander Duyck }
19228204e0c1SAlexander Duyck EXPORT_SYMBOL_GPL(queue_work_node);
19238204e0c1SAlexander Duyck 
delayed_work_timer_fn(struct timer_list * t)19248c20feb6SKees Cook void delayed_work_timer_fn(struct timer_list *t)
19251da177e4SLinus Torvalds {
19268c20feb6SKees Cook 	struct delayed_work *dwork = from_timer(dwork, t, timer);
19271da177e4SLinus Torvalds 
1928e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
192960c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
19301da177e4SLinus Torvalds }
19311438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
19321da177e4SLinus Torvalds 
__queue_delayed_work(int cpu,struct workqueue_struct * wq,struct delayed_work * dwork,unsigned long delay)19337beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
193452bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
19351da177e4SLinus Torvalds {
19367beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
19377beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
19381da177e4SLinus Torvalds 
1939637fdbaeSTejun Heo 	WARN_ON_ONCE(!wq);
19404b243563SSami Tolvanen 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
1941fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1942fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
19437beb2edfSTejun Heo 
19448852aac2STejun Heo 	/*
19458852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
19468852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
19478852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
19488852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
19498852aac2STejun Heo 	 */
19508852aac2STejun Heo 	if (!delay) {
19518852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
19528852aac2STejun Heo 		return;
19538852aac2STejun Heo 	}
19548852aac2STejun Heo 
195560c057bcSLai Jiangshan 	dwork->wq = wq;
19561265057fSTejun Heo 	dwork->cpu = cpu;
19577beb2edfSTejun Heo 	timer->expires = jiffies + delay;
19587beb2edfSTejun Heo 
1959041bd12eSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
19607beb2edfSTejun Heo 		add_timer_on(timer, cpu);
1961041bd12eSTejun Heo 	else
1962041bd12eSTejun Heo 		add_timer(timer);
19637beb2edfSTejun Heo }
19641da177e4SLinus Torvalds 
19650fcb78c2SRolf Eike Beer /**
19660fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
19670fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
19680fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1969af9997e4SRandy Dunlap  * @dwork: work to queue
19700fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
19710fcb78c2SRolf Eike Beer  *
1972d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
1973715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1974715f1300STejun Heo  * execution.
19750fcb78c2SRolf Eike Beer  */
queue_delayed_work_on(int cpu,struct workqueue_struct * wq,struct delayed_work * dwork,unsigned long delay)1976d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
197752bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
19787a6bc1cdSVenkatesh Pallipadi {
197952bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1980d4283e93STejun Heo 	bool ret = false;
19818930cabaSTejun Heo 	unsigned long flags;
19828930cabaSTejun Heo 
19838930cabaSTejun Heo 	/* read the comment in __queue_work() */
19848930cabaSTejun Heo 	local_irq_save(flags);
19857a6bc1cdSVenkatesh Pallipadi 
198622df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
19877beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1988d4283e93STejun Heo 		ret = true;
19897a6bc1cdSVenkatesh Pallipadi 	}
19908930cabaSTejun Heo 
19918930cabaSTejun Heo 	local_irq_restore(flags);
19927a6bc1cdSVenkatesh Pallipadi 	return ret;
19937a6bc1cdSVenkatesh Pallipadi }
1994ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
19951da177e4SLinus Torvalds 
1996c8e55f36STejun Heo /**
19978376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
19988376fe22STejun Heo  * @cpu: CPU number to execute work on
19998376fe22STejun Heo  * @wq: workqueue to use
20008376fe22STejun Heo  * @dwork: work to queue
20018376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
20028376fe22STejun Heo  *
20038376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
20048376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
20058376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
20068376fe22STejun Heo  * current state.
20078376fe22STejun Heo  *
2008d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
20098376fe22STejun Heo  * pending and its timer was modified.
20108376fe22STejun Heo  *
2011e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
20128376fe22STejun Heo  * See try_to_grab_pending() for details.
20138376fe22STejun Heo  */
mod_delayed_work_on(int cpu,struct workqueue_struct * wq,struct delayed_work * dwork,unsigned long delay)20148376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
20158376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
20168376fe22STejun Heo {
20178376fe22STejun Heo 	unsigned long flags;
20188376fe22STejun Heo 	int ret;
20198376fe22STejun Heo 
20208376fe22STejun Heo 	do {
20218376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
20228376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
20238376fe22STejun Heo 
20248376fe22STejun Heo 	if (likely(ret >= 0)) {
20258376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
20268376fe22STejun Heo 		local_irq_restore(flags);
20278376fe22STejun Heo 	}
20288376fe22STejun Heo 
20298376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
20308376fe22STejun Heo 	return ret;
20318376fe22STejun Heo }
20328376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
20338376fe22STejun Heo 
rcu_work_rcufn(struct rcu_head * rcu)203405f0fe6bSTejun Heo static void rcu_work_rcufn(struct rcu_head *rcu)
203505f0fe6bSTejun Heo {
203605f0fe6bSTejun Heo 	struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
203705f0fe6bSTejun Heo 
203805f0fe6bSTejun Heo 	/* read the comment in __queue_work() */
203905f0fe6bSTejun Heo 	local_irq_disable();
204005f0fe6bSTejun Heo 	__queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
204105f0fe6bSTejun Heo 	local_irq_enable();
204205f0fe6bSTejun Heo }
204305f0fe6bSTejun Heo 
204405f0fe6bSTejun Heo /**
204505f0fe6bSTejun Heo  * queue_rcu_work - queue work after a RCU grace period
204605f0fe6bSTejun Heo  * @wq: workqueue to use
204705f0fe6bSTejun Heo  * @rwork: work to queue
204805f0fe6bSTejun Heo  *
204905f0fe6bSTejun Heo  * Return: %false if @rwork was already pending, %true otherwise.  Note
205005f0fe6bSTejun Heo  * that a full RCU grace period is guaranteed only after a %true return.
2051bf393fd4SBart Van Assche  * While @rwork is guaranteed to be executed after a %false return, the
205205f0fe6bSTejun Heo  * execution may happen before a full RCU grace period has passed.
205305f0fe6bSTejun Heo  */
queue_rcu_work(struct workqueue_struct * wq,struct rcu_work * rwork)205405f0fe6bSTejun Heo bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
205505f0fe6bSTejun Heo {
205605f0fe6bSTejun Heo 	struct work_struct *work = &rwork->work;
205705f0fe6bSTejun Heo 
205805f0fe6bSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
205905f0fe6bSTejun Heo 		rwork->wq = wq;
2060a7e30c0eSUladzislau Rezki 		call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
206105f0fe6bSTejun Heo 		return true;
206205f0fe6bSTejun Heo 	}
206305f0fe6bSTejun Heo 
206405f0fe6bSTejun Heo 	return false;
206505f0fe6bSTejun Heo }
206605f0fe6bSTejun Heo EXPORT_SYMBOL(queue_rcu_work);
206705f0fe6bSTejun Heo 
alloc_worker(int node)2068f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
2069c34056a3STejun Heo {
2070c34056a3STejun Heo 	struct worker *worker;
2071c34056a3STejun Heo 
2072f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
2073c8e55f36STejun Heo 	if (worker) {
2074c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
2075affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
2076da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
2077e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
2078e22bee78STejun Heo 		worker->flags = WORKER_PREP;
2079c8e55f36STejun Heo 	}
2080c34056a3STejun Heo 	return worker;
2081c34056a3STejun Heo }
2082c34056a3STejun Heo 
pool_allowed_cpus(struct worker_pool * pool)20839546b29eSTejun Heo static cpumask_t *pool_allowed_cpus(struct worker_pool *pool)
20849546b29eSTejun Heo {
20858639ecebSTejun Heo 	if (pool->cpu < 0 && pool->attrs->affn_strict)
20869546b29eSTejun Heo 		return pool->attrs->__pod_cpumask;
20878639ecebSTejun Heo 	else
20888639ecebSTejun Heo 		return pool->attrs->cpumask;
20899546b29eSTejun Heo }
20909546b29eSTejun Heo 
2091c34056a3STejun Heo /**
20924736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
20934736cbf7SLai Jiangshan  * @worker: worker to be attached
20944736cbf7SLai Jiangshan  * @pool: the target pool
20954736cbf7SLai Jiangshan  *
20964736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
20974736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
20984736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
20994736cbf7SLai Jiangshan  */
worker_attach_to_pool(struct worker * worker,struct worker_pool * pool)21004736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
21014736cbf7SLai Jiangshan 				   struct worker_pool *pool)
21024736cbf7SLai Jiangshan {
21031258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
21044736cbf7SLai Jiangshan 
21054736cbf7SLai Jiangshan 	/*
21061258fae7STejun Heo 	 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
21071258fae7STejun Heo 	 * stable across this function.  See the comments above the flag
21081258fae7STejun Heo 	 * definition for details.
21094736cbf7SLai Jiangshan 	 */
21104736cbf7SLai Jiangshan 	if (pool->flags & POOL_DISASSOCIATED)
21114736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
21125c25b5ffSPeter Zijlstra 	else
21135c25b5ffSPeter Zijlstra 		kthread_set_per_cpu(worker->task, pool->cpu);
21144736cbf7SLai Jiangshan 
2115640f17c8SPeter Zijlstra 	if (worker->rescue_wq)
21169546b29eSTejun Heo 		set_cpus_allowed_ptr(worker->task, pool_allowed_cpus(pool));
2117640f17c8SPeter Zijlstra 
21184736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
2119a2d812a2STejun Heo 	worker->pool = pool;
21204736cbf7SLai Jiangshan 
21211258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
21224736cbf7SLai Jiangshan }
21234736cbf7SLai Jiangshan 
21244736cbf7SLai Jiangshan /**
212560f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
212660f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
212760f5a4bcSLai Jiangshan  *
21284736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
21294736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
21304736cbf7SLai Jiangshan  * other reference to the pool.
213160f5a4bcSLai Jiangshan  */
worker_detach_from_pool(struct worker * worker)2132a2d812a2STejun Heo static void worker_detach_from_pool(struct worker *worker)
213360f5a4bcSLai Jiangshan {
2134a2d812a2STejun Heo 	struct worker_pool *pool = worker->pool;
213560f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
213660f5a4bcSLai Jiangshan 
21371258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2138a2d812a2STejun Heo 
21395c25b5ffSPeter Zijlstra 	kthread_set_per_cpu(worker->task, -1);
2140da028469SLai Jiangshan 	list_del(&worker->node);
2141a2d812a2STejun Heo 	worker->pool = NULL;
2142a2d812a2STejun Heo 
2143e02b9312SValentin Schneider 	if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
214460f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
21451258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
214660f5a4bcSLai Jiangshan 
2147b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
2148b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2149b62c0751SLai Jiangshan 
215060f5a4bcSLai Jiangshan 	if (detach_completion)
215160f5a4bcSLai Jiangshan 		complete(detach_completion);
215260f5a4bcSLai Jiangshan }
215360f5a4bcSLai Jiangshan 
215460f5a4bcSLai Jiangshan /**
2155c34056a3STejun Heo  * create_worker - create a new workqueue worker
215663d95a91STejun Heo  * @pool: pool the new worker will belong to
2157c34056a3STejun Heo  *
2158051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
2159c34056a3STejun Heo  *
2160c34056a3STejun Heo  * CONTEXT:
2161c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
2162c34056a3STejun Heo  *
2163d185af30SYacine Belkadi  * Return:
2164c34056a3STejun Heo  * Pointer to the newly created worker.
2165c34056a3STejun Heo  */
create_worker(struct worker_pool * pool)2166bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
2167c34056a3STejun Heo {
2168e441b56fSZhen Lei 	struct worker *worker;
2169e441b56fSZhen Lei 	int id;
21705d9c7a1eSLucy Mielke 	char id_buf[23];
2171c34056a3STejun Heo 
21727cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
2173e441b56fSZhen Lei 	id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
21743f0ea0b8SPetr Mladek 	if (id < 0) {
21753f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
21763f0ea0b8SPetr Mladek 			    ERR_PTR(id));
2177e441b56fSZhen Lei 		return NULL;
21783f0ea0b8SPetr Mladek 	}
2179c34056a3STejun Heo 
2180f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
21813f0ea0b8SPetr Mladek 	if (!worker) {
21823f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker\n");
2183c34056a3STejun Heo 		goto fail;
21843f0ea0b8SPetr Mladek 	}
2185c34056a3STejun Heo 
2186c34056a3STejun Heo 	worker->id = id;
2187c34056a3STejun Heo 
218829c91e99STejun Heo 	if (pool->cpu >= 0)
2189e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
2190e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
2191f3421797STejun Heo 	else
2192e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
2193e3c916a4STejun Heo 
2194f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
2195e3c916a4STejun Heo 					      "kworker/%s", id_buf);
21963f0ea0b8SPetr Mladek 	if (IS_ERR(worker->task)) {
219760f54038SPetr Mladek 		if (PTR_ERR(worker->task) == -EINTR) {
219860f54038SPetr Mladek 			pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n",
219960f54038SPetr Mladek 			       id_buf);
220060f54038SPetr Mladek 		} else {
22013f0ea0b8SPetr Mladek 			pr_err_once("workqueue: Failed to create a worker thread: %pe",
22023f0ea0b8SPetr Mladek 				    worker->task);
220360f54038SPetr Mladek 		}
2204c34056a3STejun Heo 		goto fail;
22053f0ea0b8SPetr Mladek 	}
2206c34056a3STejun Heo 
220791151228SOleg Nesterov 	set_user_nice(worker->task, pool->attrs->nice);
22089546b29eSTejun Heo 	kthread_bind_mask(worker->task, pool_allowed_cpus(pool));
220991151228SOleg Nesterov 
2210da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
22114736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
2212822d8405STejun Heo 
2213051e1850SLai Jiangshan 	/* start the newly created worker */
2214a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
22150219a352STejun Heo 
2216051e1850SLai Jiangshan 	worker->pool->nr_workers++;
2217051e1850SLai Jiangshan 	worker_enter_idle(worker);
22180219a352STejun Heo 	kick_pool(pool);
22190219a352STejun Heo 
22200219a352STejun Heo 	/*
22210219a352STejun Heo 	 * @worker is waiting on a completion in kthread() and will trigger hung
22220219a352STejun Heo 	 * check if not woken up soon. As kick_pool() might not have waken it
22230219a352STejun Heo 	 * up, wake it up explicitly once more.
22240219a352STejun Heo 	 */
2225051e1850SLai Jiangshan 	wake_up_process(worker->task);
22260219a352STejun Heo 
2227a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2228051e1850SLai Jiangshan 
2229c34056a3STejun Heo 	return worker;
2230822d8405STejun Heo 
2231c34056a3STejun Heo fail:
2232e441b56fSZhen Lei 	ida_free(&pool->worker_ida, id);
2233c34056a3STejun Heo 	kfree(worker);
2234c34056a3STejun Heo 	return NULL;
2235c34056a3STejun Heo }
2236c34056a3STejun Heo 
unbind_worker(struct worker * worker)2237793777bcSValentin Schneider static void unbind_worker(struct worker *worker)
2238793777bcSValentin Schneider {
2239793777bcSValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2240793777bcSValentin Schneider 
2241793777bcSValentin Schneider 	kthread_set_per_cpu(worker->task, -1);
2242793777bcSValentin Schneider 	if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2243793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2244793777bcSValentin Schneider 	else
2245793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2246793777bcSValentin Schneider }
2247793777bcSValentin Schneider 
wake_dying_workers(struct list_head * cull_list)2248e02b9312SValentin Schneider static void wake_dying_workers(struct list_head *cull_list)
2249e02b9312SValentin Schneider {
2250e02b9312SValentin Schneider 	struct worker *worker, *tmp;
2251e02b9312SValentin Schneider 
2252e02b9312SValentin Schneider 	list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2253e02b9312SValentin Schneider 		list_del_init(&worker->entry);
2254e02b9312SValentin Schneider 		unbind_worker(worker);
2255e02b9312SValentin Schneider 		/*
2256e02b9312SValentin Schneider 		 * If the worker was somehow already running, then it had to be
2257e02b9312SValentin Schneider 		 * in pool->idle_list when set_worker_dying() happened or we
2258e02b9312SValentin Schneider 		 * wouldn't have gotten here.
2259c34056a3STejun Heo 		 *
2260e02b9312SValentin Schneider 		 * Thus, the worker must either have observed the WORKER_DIE
2261e02b9312SValentin Schneider 		 * flag, or have set its state to TASK_IDLE. Either way, the
2262e02b9312SValentin Schneider 		 * below will be observed by the worker and is safe to do
2263e02b9312SValentin Schneider 		 * outside of pool->lock.
2264e02b9312SValentin Schneider 		 */
2265e02b9312SValentin Schneider 		wake_up_process(worker->task);
2266e02b9312SValentin Schneider 	}
2267e02b9312SValentin Schneider }
2268e02b9312SValentin Schneider 
2269e02b9312SValentin Schneider /**
2270e02b9312SValentin Schneider  * set_worker_dying - Tag a worker for destruction
2271e02b9312SValentin Schneider  * @worker: worker to be destroyed
2272e02b9312SValentin Schneider  * @list: transfer worker away from its pool->idle_list and into list
2273e02b9312SValentin Schneider  *
2274e02b9312SValentin Schneider  * Tag @worker for destruction and adjust @pool stats accordingly.  The worker
2275e02b9312SValentin Schneider  * should be idle.
2276c8e55f36STejun Heo  *
2277c8e55f36STejun Heo  * CONTEXT:
2278a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
2279c34056a3STejun Heo  */
set_worker_dying(struct worker * worker,struct list_head * list)2280e02b9312SValentin Schneider static void set_worker_dying(struct worker *worker, struct list_head *list)
2281c34056a3STejun Heo {
2282bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2283c34056a3STejun Heo 
2284cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
2285e02b9312SValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2286cd549687STejun Heo 
2287c34056a3STejun Heo 	/* sanity check frenzy */
22886183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
228973eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
229073eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
22916183c009STejun Heo 		return;
2292c34056a3STejun Heo 
2293bd7bdd43STejun Heo 	pool->nr_workers--;
2294bd7bdd43STejun Heo 	pool->nr_idle--;
2295c8e55f36STejun Heo 
2296cb444766STejun Heo 	worker->flags |= WORKER_DIE;
2297e02b9312SValentin Schneider 
2298e02b9312SValentin Schneider 	list_move(&worker->entry, list);
2299e02b9312SValentin Schneider 	list_move(&worker->node, &pool->dying_workers);
2300c34056a3STejun Heo }
2301c34056a3STejun Heo 
23023f959aa3SValentin Schneider /**
23033f959aa3SValentin Schneider  * idle_worker_timeout - check if some idle workers can now be deleted.
23043f959aa3SValentin Schneider  * @t: The pool's idle_timer that just expired
23053f959aa3SValentin Schneider  *
23063f959aa3SValentin Schneider  * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
23073f959aa3SValentin Schneider  * worker_leave_idle(), as a worker flicking between idle and active while its
23083f959aa3SValentin Schneider  * pool is at the too_many_workers() tipping point would cause too much timer
23093f959aa3SValentin Schneider  * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
23103f959aa3SValentin Schneider  * it expire and re-evaluate things from there.
23113f959aa3SValentin Schneider  */
idle_worker_timeout(struct timer_list * t)231232a6c723SKees Cook static void idle_worker_timeout(struct timer_list *t)
2313e22bee78STejun Heo {
231432a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, idle_timer);
23153f959aa3SValentin Schneider 	bool do_cull = false;
23163f959aa3SValentin Schneider 
23173f959aa3SValentin Schneider 	if (work_pending(&pool->idle_cull_work))
23183f959aa3SValentin Schneider 		return;
23193f959aa3SValentin Schneider 
23203f959aa3SValentin Schneider 	raw_spin_lock_irq(&pool->lock);
23213f959aa3SValentin Schneider 
23223f959aa3SValentin Schneider 	if (too_many_workers(pool)) {
23233f959aa3SValentin Schneider 		struct worker *worker;
23243f959aa3SValentin Schneider 		unsigned long expires;
23253f959aa3SValentin Schneider 
23263f959aa3SValentin Schneider 		/* idle_list is kept in LIFO order, check the last one */
23273f959aa3SValentin Schneider 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
23283f959aa3SValentin Schneider 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
23293f959aa3SValentin Schneider 		do_cull = !time_before(jiffies, expires);
23303f959aa3SValentin Schneider 
23313f959aa3SValentin Schneider 		if (!do_cull)
23323f959aa3SValentin Schneider 			mod_timer(&pool->idle_timer, expires);
23333f959aa3SValentin Schneider 	}
23343f959aa3SValentin Schneider 	raw_spin_unlock_irq(&pool->lock);
23353f959aa3SValentin Schneider 
23363f959aa3SValentin Schneider 	if (do_cull)
23373f959aa3SValentin Schneider 		queue_work(system_unbound_wq, &pool->idle_cull_work);
23383f959aa3SValentin Schneider }
23393f959aa3SValentin Schneider 
23403f959aa3SValentin Schneider /**
23413f959aa3SValentin Schneider  * idle_cull_fn - cull workers that have been idle for too long.
23423f959aa3SValentin Schneider  * @work: the pool's work for handling these idle workers
23433f959aa3SValentin Schneider  *
23443f959aa3SValentin Schneider  * This goes through a pool's idle workers and gets rid of those that have been
23453f959aa3SValentin Schneider  * idle for at least IDLE_WORKER_TIMEOUT seconds.
2346e02b9312SValentin Schneider  *
2347e02b9312SValentin Schneider  * We don't want to disturb isolated CPUs because of a pcpu kworker being
2348e02b9312SValentin Schneider  * culled, so this also resets worker affinity. This requires a sleepable
2349e02b9312SValentin Schneider  * context, hence the split between timer callback and work item.
23503f959aa3SValentin Schneider  */
idle_cull_fn(struct work_struct * work)23513f959aa3SValentin Schneider static void idle_cull_fn(struct work_struct *work)
23523f959aa3SValentin Schneider {
23533f959aa3SValentin Schneider 	struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
23549680540cSYang Yingliang 	LIST_HEAD(cull_list);
2355e22bee78STejun Heo 
2356e02b9312SValentin Schneider 	/*
2357e02b9312SValentin Schneider 	 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2358e02b9312SValentin Schneider 	 * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2359e02b9312SValentin Schneider 	 * path. This is required as a previously-preempted worker could run after
2360e02b9312SValentin Schneider 	 * set_worker_dying() has happened but before wake_dying_workers() did.
2361e02b9312SValentin Schneider 	 */
2362e02b9312SValentin Schneider 	mutex_lock(&wq_pool_attach_mutex);
2363a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2364e22bee78STejun Heo 
23653347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
2366e22bee78STejun Heo 		struct worker *worker;
2367e22bee78STejun Heo 		unsigned long expires;
2368e22bee78STejun Heo 
236963d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
2370e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2371e22bee78STejun Heo 
23723347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
237363d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
23743347fc9fSLai Jiangshan 			break;
2375e22bee78STejun Heo 		}
23763347fc9fSLai Jiangshan 
2377e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
2378e22bee78STejun Heo 	}
2379e22bee78STejun Heo 
2380a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2381e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
2382e02b9312SValentin Schneider 	mutex_unlock(&wq_pool_attach_mutex);
2383e22bee78STejun Heo }
2384e22bee78STejun Heo 
send_mayday(struct work_struct * work)2385493a1724STejun Heo static void send_mayday(struct work_struct *work)
2386e22bee78STejun Heo {
2387112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2388112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
2389493a1724STejun Heo 
23902e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
2391e22bee78STejun Heo 
2392493008a8STejun Heo 	if (!wq->rescuer)
2393493a1724STejun Heo 		return;
2394e22bee78STejun Heo 
2395e22bee78STejun Heo 	/* mayday mayday mayday */
2396493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
239777668c8bSLai Jiangshan 		/*
239877668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
239977668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
240077668c8bSLai Jiangshan 		 * rescuer is done with it.
240177668c8bSLai Jiangshan 		 */
240277668c8bSLai Jiangshan 		get_pwq(pwq);
2403493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
2404e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
2405725e8ec5STejun Heo 		pwq->stats[PWQ_STAT_MAYDAY]++;
2406493a1724STejun Heo 	}
2407e22bee78STejun Heo }
2408e22bee78STejun Heo 
pool_mayday_timeout(struct timer_list * t)240932a6c723SKees Cook static void pool_mayday_timeout(struct timer_list *t)
2410e22bee78STejun Heo {
241132a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2412e22bee78STejun Heo 	struct work_struct *work;
2413e22bee78STejun Heo 
2414a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2415a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&wq_mayday_lock);		/* for wq->maydays */
2416e22bee78STejun Heo 
241763d95a91STejun Heo 	if (need_to_create_worker(pool)) {
2418e22bee78STejun Heo 		/*
2419e22bee78STejun Heo 		 * We've been trying to create a new worker but
2420e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
2421e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
2422e22bee78STejun Heo 		 * rescuers.
2423e22bee78STejun Heo 		 */
242463d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
2425e22bee78STejun Heo 			send_mayday(work);
2426e22bee78STejun Heo 	}
2427e22bee78STejun Heo 
2428a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&wq_mayday_lock);
2429a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2430e22bee78STejun Heo 
243163d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2432e22bee78STejun Heo }
2433e22bee78STejun Heo 
2434e22bee78STejun Heo /**
2435e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
243663d95a91STejun Heo  * @pool: pool to create a new worker for
2437e22bee78STejun Heo  *
243863d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
2439e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
2440e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
244163d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
2442e22bee78STejun Heo  * possible allocation deadlock.
2443e22bee78STejun Heo  *
2444c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
2445c5aa87bbSTejun Heo  * may_start_working() %true.
2446e22bee78STejun Heo  *
2447e22bee78STejun Heo  * LOCKING:
2448a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2449e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
2450e22bee78STejun Heo  * manager.
2451e22bee78STejun Heo  */
maybe_create_worker(struct worker_pool * pool)245229187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
2453d565ed63STejun Heo __releases(&pool->lock)
2454d565ed63STejun Heo __acquires(&pool->lock)
2455e22bee78STejun Heo {
2456e22bee78STejun Heo restart:
2457a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
24589f9c2364STejun Heo 
2459e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
246063d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2461e22bee78STejun Heo 
2462e22bee78STejun Heo 	while (true) {
2463051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
2464e22bee78STejun Heo 			break;
2465e22bee78STejun Heo 
2466e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
24679f9c2364STejun Heo 
246863d95a91STejun Heo 		if (!need_to_create_worker(pool))
2469e22bee78STejun Heo 			break;
2470e22bee78STejun Heo 	}
2471e22bee78STejun Heo 
247263d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
2473a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2474051e1850SLai Jiangshan 	/*
2475051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
2476051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
2477051e1850SLai Jiangshan 	 * already become busy.
2478051e1850SLai Jiangshan 	 */
247963d95a91STejun Heo 	if (need_to_create_worker(pool))
2480e22bee78STejun Heo 		goto restart;
2481e22bee78STejun Heo }
2482e22bee78STejun Heo 
2483e22bee78STejun Heo /**
2484e22bee78STejun Heo  * manage_workers - manage worker pool
2485e22bee78STejun Heo  * @worker: self
2486e22bee78STejun Heo  *
2487706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
2488e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2489706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2490e22bee78STejun Heo  *
2491e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2492e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2493e22bee78STejun Heo  * and may_start_working() is true.
2494e22bee78STejun Heo  *
2495e22bee78STejun Heo  * CONTEXT:
2496a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2497e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2498e22bee78STejun Heo  *
2499d185af30SYacine Belkadi  * Return:
250029187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
250129187a9eSTejun Heo  * start processing works, %true if management function was performed and
250229187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
250329187a9eSTejun Heo  * no longer be true.
2504e22bee78STejun Heo  */
manage_workers(struct worker * worker)2505e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2506e22bee78STejun Heo {
250763d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2508e22bee78STejun Heo 
2509692b4825STejun Heo 	if (pool->flags & POOL_MANAGER_ACTIVE)
251029187a9eSTejun Heo 		return false;
2511692b4825STejun Heo 
2512692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
25132607d7a6STejun Heo 	pool->manager = worker;
2514e22bee78STejun Heo 
251529187a9eSTejun Heo 	maybe_create_worker(pool);
2516e22bee78STejun Heo 
25172607d7a6STejun Heo 	pool->manager = NULL;
2518692b4825STejun Heo 	pool->flags &= ~POOL_MANAGER_ACTIVE;
2519d8bb65abSSebastian Andrzej Siewior 	rcuwait_wake_up(&manager_wait);
252029187a9eSTejun Heo 	return true;
2521e22bee78STejun Heo }
2522e22bee78STejun Heo 
2523a62428c0STejun Heo /**
2524a62428c0STejun Heo  * process_one_work - process single work
2525c34056a3STejun Heo  * @worker: self
2526a62428c0STejun Heo  * @work: work to process
2527a62428c0STejun Heo  *
2528a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2529a62428c0STejun Heo  * process a single work including synchronization against and
2530a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2531a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2532a62428c0STejun Heo  * call this function to process a work.
2533a62428c0STejun Heo  *
2534a62428c0STejun Heo  * CONTEXT:
2535a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
2536a62428c0STejun Heo  */
process_one_work(struct worker * worker,struct work_struct * work)2537c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2538d565ed63STejun Heo __releases(&pool->lock)
2539d565ed63STejun Heo __acquires(&pool->lock)
25401da177e4SLinus Torvalds {
2541112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2542bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2543c4560c2cSLai Jiangshan 	unsigned long work_data;
25446dc67674STejun Heo 	int lockdep_start_depth, rcu_start_depth;
25454e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
25464e6045f1SJohannes Berg 	/*
2547a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2548a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2549a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2550a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2551a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
25524e6045f1SJohannes Berg 	 */
25534d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
25544d82a1deSPeter Zijlstra 
25554d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
25564e6045f1SJohannes Berg #endif
2557807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
255885327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2559ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
256025511a47STejun Heo 
25618930cabaSTejun Heo 	/* claim and dequeue */
2562dc186ad7SThomas Gleixner 	debug_work_deactivate(work);
2563c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2564c34056a3STejun Heo 	worker->current_work = work;
2565a2c1c57bSTejun Heo 	worker->current_func = work->func;
2566112202d9STejun Heo 	worker->current_pwq = pwq;
2567616db877STejun Heo 	worker->current_at = worker->task->se.sum_exec_runtime;
2568c4560c2cSLai Jiangshan 	work_data = *work_data_bits(work);
2569d812796eSLai Jiangshan 	worker->current_color = get_work_color(work_data);
25707a22ad75STejun Heo 
25718bf89593STejun Heo 	/*
25728bf89593STejun Heo 	 * Record wq name for cmdline and debug reporting, may get
25738bf89593STejun Heo 	 * overridden through set_worker_desc().
25748bf89593STejun Heo 	 */
25758bf89593STejun Heo 	strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
25768bf89593STejun Heo 
2577a62428c0STejun Heo 	list_del_init(&work->entry);
2578a62428c0STejun Heo 
2579649027d7STejun Heo 	/*
2580228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
2581228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
2582228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
2583228f1d00SLai Jiangshan 	 * execution of the pending work items.
2584fb0e7bebSTejun Heo 	 */
2585616db877STejun Heo 	if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
2586228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2587fb0e7bebSTejun Heo 
2588974271c4STejun Heo 	/*
25890219a352STejun Heo 	 * Kick @pool if necessary. It's always noop for per-cpu worker pools
25900219a352STejun Heo 	 * since nr_running would always be >= 1 at this point. This is used to
25910219a352STejun Heo 	 * chain execution of the pending work items for WORKER_NOT_RUNNING
25920219a352STejun Heo 	 * workers such as the UNBOUND and CPU_INTENSIVE ones.
2593974271c4STejun Heo 	 */
25940219a352STejun Heo 	kick_pool(pool);
2595974271c4STejun Heo 
25968930cabaSTejun Heo 	/*
25977c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2598d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
259923657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
260023657bb1STejun Heo 	 * disabled.
26018930cabaSTejun Heo 	 */
26027c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
26031da177e4SLinus Torvalds 
2604fe48ba7dSMirsad Goran Todorovac 	pwq->stats[PWQ_STAT_STARTED]++;
2605a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2606365970a1SDavid Howells 
26076dc67674STejun Heo 	rcu_start_depth = rcu_preempt_depth();
26086dc67674STejun Heo 	lockdep_start_depth = lockdep_depth(current);
2609a1d14934SPeter Zijlstra 	lock_map_acquire(&pwq->wq->lockdep_map);
26103295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2611e6f3faa7SPeter Zijlstra 	/*
2612f52be570SPeter Zijlstra 	 * Strictly speaking we should mark the invariant state without holding
2613f52be570SPeter Zijlstra 	 * any locks, that is, before these two lock_map_acquire()'s.
2614e6f3faa7SPeter Zijlstra 	 *
2615e6f3faa7SPeter Zijlstra 	 * However, that would result in:
2616e6f3faa7SPeter Zijlstra 	 *
2617e6f3faa7SPeter Zijlstra 	 *   A(W1)
2618e6f3faa7SPeter Zijlstra 	 *   WFC(C)
2619e6f3faa7SPeter Zijlstra 	 *		A(W1)
2620e6f3faa7SPeter Zijlstra 	 *		C(C)
2621e6f3faa7SPeter Zijlstra 	 *
2622e6f3faa7SPeter Zijlstra 	 * Which would create W1->C->W1 dependencies, even though there is no
2623e6f3faa7SPeter Zijlstra 	 * actual deadlock possible. There are two solutions, using a
2624e6f3faa7SPeter Zijlstra 	 * read-recursive acquire on the work(queue) 'locks', but this will then
2625f52be570SPeter Zijlstra 	 * hit the lockdep limitation on recursive locks, or simply discard
2626e6f3faa7SPeter Zijlstra 	 * these locks.
2627e6f3faa7SPeter Zijlstra 	 *
2628e6f3faa7SPeter Zijlstra 	 * AFAICT there is no possible deadlock scenario between the
2629e6f3faa7SPeter Zijlstra 	 * flush_work() and complete() primitives (except for single-threaded
2630e6f3faa7SPeter Zijlstra 	 * workqueues), so hiding them isn't a problem.
2631e6f3faa7SPeter Zijlstra 	 */
2632f52be570SPeter Zijlstra 	lockdep_invariant_state(true);
2633e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2634a2c1c57bSTejun Heo 	worker->current_func(work);
2635e36c886aSArjan van de Ven 	/*
2636e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2637e36c886aSArjan van de Ven 	 * point will only record its address.
2638e36c886aSArjan van de Ven 	 */
26391c5da0ecSDaniel Jordan 	trace_workqueue_execute_end(work, worker->current_func);
2640725e8ec5STejun Heo 	pwq->stats[PWQ_STAT_COMPLETED]++;
26413295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2642112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
26431da177e4SLinus Torvalds 
26446dc67674STejun Heo 	if (unlikely((worker->task && in_atomic()) ||
26456dc67674STejun Heo 		     lockdep_depth(current) != lockdep_start_depth ||
26466dc67674STejun Heo 		     rcu_preempt_depth() != rcu_start_depth)) {
26476dc67674STejun Heo 		pr_err("BUG: workqueue leaked atomic, lock or RCU: %s[%d]\n"
26486dc67674STejun Heo 		       "     preempt=0x%08x lock=%d->%d RCU=%d->%d workfn=%ps\n",
26496dc67674STejun Heo 		       current->comm, task_pid_nr(current), preempt_count(),
26506dc67674STejun Heo 		       lockdep_start_depth, lockdep_depth(current),
26516dc67674STejun Heo 		       rcu_start_depth, rcu_preempt_depth(),
26526dc67674STejun Heo 		       worker->current_func);
2653d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2654d5abe669SPeter Zijlstra 		dump_stack();
2655d5abe669SPeter Zijlstra 	}
2656d5abe669SPeter Zijlstra 
2657b22ce278STejun Heo 	/*
2658025f50f3SSebastian Andrzej Siewior 	 * The following prevents a kworker from hogging CPU on !PREEMPTION
2659b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
2660b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
2661b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
2662789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
2663789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
2664b22ce278STejun Heo 	 */
2665a7e6425eSPaul E. McKenney 	cond_resched();
2666b22ce278STejun Heo 
2667a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2668a62428c0STejun Heo 
2669616db877STejun Heo 	/*
2670616db877STejun Heo 	 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
2671616db877STejun Heo 	 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
2672616db877STejun Heo 	 * wq_cpu_intensive_thresh_us. Clear it.
2673616db877STejun Heo 	 */
2674fb0e7bebSTejun Heo 	worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2675fb0e7bebSTejun Heo 
26761b69ac6bSJohannes Weiner 	/* tag the worker for identification in schedule() */
26771b69ac6bSJohannes Weiner 	worker->last_func = worker->current_func;
26781b69ac6bSJohannes Weiner 
2679a62428c0STejun Heo 	/* we're done with it, release */
268042f8570fSSasha Levin 	hash_del(&worker->hentry);
2681c34056a3STejun Heo 	worker->current_work = NULL;
2682a2c1c57bSTejun Heo 	worker->current_func = NULL;
2683112202d9STejun Heo 	worker->current_pwq = NULL;
2684d812796eSLai Jiangshan 	worker->current_color = INT_MAX;
2685c4560c2cSLai Jiangshan 	pwq_dec_nr_in_flight(pwq, work_data);
26861da177e4SLinus Torvalds }
26871da177e4SLinus Torvalds 
2688affee4b2STejun Heo /**
2689affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2690affee4b2STejun Heo  * @worker: self
2691affee4b2STejun Heo  *
2692affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2693affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2694affee4b2STejun Heo  * fetches a work from the top and executes it.
2695affee4b2STejun Heo  *
2696affee4b2STejun Heo  * CONTEXT:
2697a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2698affee4b2STejun Heo  * multiple times.
2699affee4b2STejun Heo  */
process_scheduled_works(struct worker * worker)2700affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
27011da177e4SLinus Torvalds {
2702c0ab017dSTejun Heo 	struct work_struct *work;
2703c0ab017dSTejun Heo 	bool first = true;
2704c0ab017dSTejun Heo 
2705c0ab017dSTejun Heo 	while ((work = list_first_entry_or_null(&worker->scheduled,
2706c0ab017dSTejun Heo 						struct work_struct, entry))) {
2707c0ab017dSTejun Heo 		if (first) {
2708c0ab017dSTejun Heo 			worker->pool->watchdog_ts = jiffies;
2709c0ab017dSTejun Heo 			first = false;
2710c0ab017dSTejun Heo 		}
2711c34056a3STejun Heo 		process_one_work(worker, work);
2712a62428c0STejun Heo 	}
27131da177e4SLinus Torvalds }
27141da177e4SLinus Torvalds 
set_pf_worker(bool val)2715197f6accSTejun Heo static void set_pf_worker(bool val)
2716197f6accSTejun Heo {
2717197f6accSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2718197f6accSTejun Heo 	if (val)
2719197f6accSTejun Heo 		current->flags |= PF_WQ_WORKER;
2720197f6accSTejun Heo 	else
2721197f6accSTejun Heo 		current->flags &= ~PF_WQ_WORKER;
2722197f6accSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
2723197f6accSTejun Heo }
2724197f6accSTejun Heo 
27254690c4abSTejun Heo /**
27264690c4abSTejun Heo  * worker_thread - the worker thread function
2727c34056a3STejun Heo  * @__worker: self
27284690c4abSTejun Heo  *
2729c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2730c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2731c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2732c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2733c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
2734d185af30SYacine Belkadi  *
2735d185af30SYacine Belkadi  * Return: 0
27364690c4abSTejun Heo  */
worker_thread(void * __worker)2737c34056a3STejun Heo static int worker_thread(void *__worker)
27381da177e4SLinus Torvalds {
2739c34056a3STejun Heo 	struct worker *worker = __worker;
2740bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
27411da177e4SLinus Torvalds 
2742e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2743197f6accSTejun Heo 	set_pf_worker(true);
2744c8e55f36STejun Heo woke_up:
2745a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2746affee4b2STejun Heo 
2747a9ab775bSTejun Heo 	/* am I supposed to die? */
2748a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2749a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
2750197f6accSTejun Heo 		set_pf_worker(false);
275160f5a4bcSLai Jiangshan 
275260f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
2753e441b56fSZhen Lei 		ida_free(&pool->worker_ida, worker->id);
2754a2d812a2STejun Heo 		worker_detach_from_pool(worker);
2755e02b9312SValentin Schneider 		WARN_ON_ONCE(!list_empty(&worker->entry));
275660f5a4bcSLai Jiangshan 		kfree(worker);
2757c8e55f36STejun Heo 		return 0;
2758c8e55f36STejun Heo 	}
2759c8e55f36STejun Heo 
2760c8e55f36STejun Heo 	worker_leave_idle(worker);
2761db7bccf4STejun Heo recheck:
2762e22bee78STejun Heo 	/* no more worker necessary? */
276363d95a91STejun Heo 	if (!need_more_worker(pool))
2764e22bee78STejun Heo 		goto sleep;
2765e22bee78STejun Heo 
2766e22bee78STejun Heo 	/* do we need to manage? */
276763d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2768e22bee78STejun Heo 		goto recheck;
2769e22bee78STejun Heo 
2770c8e55f36STejun Heo 	/*
2771c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2772c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2773c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2774c8e55f36STejun Heo 	 */
27756183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2776c8e55f36STejun Heo 
2777e22bee78STejun Heo 	/*
2778a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2779a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2780a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2781a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2782a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2783e22bee78STejun Heo 	 */
2784a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2785e22bee78STejun Heo 
2786e22bee78STejun Heo 	do {
2787affee4b2STejun Heo 		struct work_struct *work =
2788bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2789affee4b2STejun Heo 					 struct work_struct, entry);
2790affee4b2STejun Heo 
2791873eaca6STejun Heo 		if (assign_work(work, worker, NULL))
2792affee4b2STejun Heo 			process_scheduled_works(worker);
279363d95a91STejun Heo 	} while (keep_working(pool));
2794affee4b2STejun Heo 
2795228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
2796d313dd85STejun Heo sleep:
2797c8e55f36STejun Heo 	/*
2798d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2799d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2800d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2801d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2802d565ed63STejun Heo 	 * event.
2803c8e55f36STejun Heo 	 */
2804c8e55f36STejun Heo 	worker_enter_idle(worker);
2805c5a94a61SPeter Zijlstra 	__set_current_state(TASK_IDLE);
2806a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
28071da177e4SLinus Torvalds 	schedule();
2808c8e55f36STejun Heo 	goto woke_up;
28091da177e4SLinus Torvalds }
28101da177e4SLinus Torvalds 
2811e22bee78STejun Heo /**
2812e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2813111c225aSTejun Heo  * @__rescuer: self
2814e22bee78STejun Heo  *
2815e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2816493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2817e22bee78STejun Heo  *
2818706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2819e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2820e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2821e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2822e22bee78STejun Heo  * the problem rescuer solves.
2823e22bee78STejun Heo  *
2824706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2825706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2826e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2827e22bee78STejun Heo  *
2828e22bee78STejun Heo  * This should happen rarely.
2829d185af30SYacine Belkadi  *
2830d185af30SYacine Belkadi  * Return: 0
2831e22bee78STejun Heo  */
rescuer_thread(void * __rescuer)2832111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2833e22bee78STejun Heo {
2834111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2835111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
28364d595b86SLai Jiangshan 	bool should_stop;
2837e22bee78STejun Heo 
2838e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2839111c225aSTejun Heo 
2840111c225aSTejun Heo 	/*
2841111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2842111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2843111c225aSTejun Heo 	 */
2844197f6accSTejun Heo 	set_pf_worker(true);
2845e22bee78STejun Heo repeat:
2846c5a94a61SPeter Zijlstra 	set_current_state(TASK_IDLE);
28471da177e4SLinus Torvalds 
28484d595b86SLai Jiangshan 	/*
28494d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
28504d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
28514d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
28524d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
28534d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
28544d595b86SLai Jiangshan 	 * list is always empty on exit.
28554d595b86SLai Jiangshan 	 */
28564d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
28571da177e4SLinus Torvalds 
2858493a1724STejun Heo 	/* see whether any pwq is asking for help */
2859a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq_mayday_lock);
2860493a1724STejun Heo 
2861493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2862493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2863493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2864112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2865e22bee78STejun Heo 		struct work_struct *work, *n;
2866e22bee78STejun Heo 
2867e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2868493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2869493a1724STejun Heo 
2870a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
2871e22bee78STejun Heo 
287251697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
287351697d39SLai Jiangshan 
2874a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
2875e22bee78STejun Heo 
2876e22bee78STejun Heo 		/*
2877e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2878e22bee78STejun Heo 		 * process'em.
2879e22bee78STejun Heo 		 */
2880873eaca6STejun Heo 		WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
288182607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
2882873eaca6STejun Heo 			if (get_work_pwq(work) == pwq &&
2883873eaca6STejun Heo 			    assign_work(work, rescuer, &n))
2884725e8ec5STejun Heo 				pwq->stats[PWQ_STAT_RESCUED]++;
288582607adcSTejun Heo 		}
2886e22bee78STejun Heo 
2887873eaca6STejun Heo 		if (!list_empty(&rescuer->scheduled)) {
2888e22bee78STejun Heo 			process_scheduled_works(rescuer);
28897576958aSTejun Heo 
28907576958aSTejun Heo 			/*
2891008847f6SNeilBrown 			 * The above execution of rescued work items could
2892008847f6SNeilBrown 			 * have created more to rescue through
2893f97a4a1aSLai Jiangshan 			 * pwq_activate_first_inactive() or chained
2894008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
2895008847f6SNeilBrown 			 * that such back-to-back work items, which may be
2896008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
2897008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
2898008847f6SNeilBrown 			 */
28994f3f4cf3SLai Jiangshan 			if (pwq->nr_active && need_to_create_worker(pool)) {
2900a9b8a985SSebastian Andrzej Siewior 				raw_spin_lock(&wq_mayday_lock);
2901e66b39afSTejun Heo 				/*
2902e66b39afSTejun Heo 				 * Queue iff we aren't racing destruction
2903e66b39afSTejun Heo 				 * and somebody else hasn't queued it already.
2904e66b39afSTejun Heo 				 */
2905e66b39afSTejun Heo 				if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2906008847f6SNeilBrown 					get_pwq(pwq);
2907e66b39afSTejun Heo 					list_add_tail(&pwq->mayday_node, &wq->maydays);
2908e66b39afSTejun Heo 				}
2909a9b8a985SSebastian Andrzej Siewior 				raw_spin_unlock(&wq_mayday_lock);
2910008847f6SNeilBrown 			}
2911008847f6SNeilBrown 		}
2912008847f6SNeilBrown 
2913008847f6SNeilBrown 		/*
291477668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
291513b1d625SLai Jiangshan 		 * go away while we're still attached to it.
291677668c8bSLai Jiangshan 		 */
291777668c8bSLai Jiangshan 		put_pwq(pwq);
291877668c8bSLai Jiangshan 
291977668c8bSLai Jiangshan 		/*
29200219a352STejun Heo 		 * Leave this pool. Notify regular workers; otherwise, we end up
29210219a352STejun Heo 		 * with 0 concurrency and stalling the execution.
29227576958aSTejun Heo 		 */
29230219a352STejun Heo 		kick_pool(pool);
29247576958aSTejun Heo 
2925a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
292613b1d625SLai Jiangshan 
2927a2d812a2STejun Heo 		worker_detach_from_pool(rescuer);
292813b1d625SLai Jiangshan 
2929a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
29301da177e4SLinus Torvalds 	}
29311da177e4SLinus Torvalds 
2932a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq_mayday_lock);
2933493a1724STejun Heo 
29344d595b86SLai Jiangshan 	if (should_stop) {
29354d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
2936197f6accSTejun Heo 		set_pf_worker(false);
29374d595b86SLai Jiangshan 		return 0;
29384d595b86SLai Jiangshan 	}
29394d595b86SLai Jiangshan 
2940111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2941111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2942e22bee78STejun Heo 	schedule();
2943e22bee78STejun Heo 	goto repeat;
29441da177e4SLinus Torvalds }
29451da177e4SLinus Torvalds 
2946fca839c0STejun Heo /**
2947fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
2948fca839c0STejun Heo  * @target_wq: workqueue being flushed
2949fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
2950*1fd2a57dSTvrtko Ursulin  * @from_cancel: are we called from the work cancel path
2951fca839c0STejun Heo  *
2952fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
2953*1fd2a57dSTvrtko Ursulin  * If this is not the cancel path (which implies work being flushed is either
2954*1fd2a57dSTvrtko Ursulin  * already running, or will not be at all), check if @target_wq doesn't have
2955*1fd2a57dSTvrtko Ursulin  * %WQ_MEM_RECLAIM and verify that %current is not reclaiming memory or running
2956*1fd2a57dSTvrtko Ursulin  * on a workqueue which doesn't have %WQ_MEM_RECLAIM as that can break forward-
2957*1fd2a57dSTvrtko Ursulin  * progress guarantee leading to a deadlock.
2958fca839c0STejun Heo  */
check_flush_dependency(struct workqueue_struct * target_wq,struct work_struct * target_work,bool from_cancel)2959fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
2960*1fd2a57dSTvrtko Ursulin 				   struct work_struct *target_work,
2961*1fd2a57dSTvrtko Ursulin 				   bool from_cancel)
2962fca839c0STejun Heo {
2963*1fd2a57dSTvrtko Ursulin 	work_func_t target_func;
2964fca839c0STejun Heo 	struct worker *worker;
2965fca839c0STejun Heo 
2966*1fd2a57dSTvrtko Ursulin 	if (from_cancel || target_wq->flags & WQ_MEM_RECLAIM)
2967fca839c0STejun Heo 		return;
2968fca839c0STejun Heo 
2969fca839c0STejun Heo 	worker = current_wq_worker();
2970*1fd2a57dSTvrtko Ursulin 	target_func = target_work ? target_work->func : NULL;
2971fca839c0STejun Heo 
2972fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
2973d75f773cSSakari Ailus 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
2974fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
297523d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
297623d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2977d75f773cSSakari Ailus 		  "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
2978fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
2979fca839c0STejun Heo 		  target_wq->name, target_func);
2980fca839c0STejun Heo }
2981fca839c0STejun Heo 
2982fc2e4d70SOleg Nesterov struct wq_barrier {
2983fc2e4d70SOleg Nesterov 	struct work_struct	work;
2984fc2e4d70SOleg Nesterov 	struct completion	done;
29852607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
2986fc2e4d70SOleg Nesterov };
2987fc2e4d70SOleg Nesterov 
wq_barrier_func(struct work_struct * work)2988fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2989fc2e4d70SOleg Nesterov {
2990fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2991fc2e4d70SOleg Nesterov 	complete(&barr->done);
2992fc2e4d70SOleg Nesterov }
2993fc2e4d70SOleg Nesterov 
29944690c4abSTejun Heo /**
29954690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2996112202d9STejun Heo  * @pwq: pwq to insert barrier into
29974690c4abSTejun Heo  * @barr: wq_barrier to insert
2998affee4b2STejun Heo  * @target: target work to attach @barr to
2999affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
30004690c4abSTejun Heo  *
3001affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
3002affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
3003affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
3004affee4b2STejun Heo  * cpu.
3005affee4b2STejun Heo  *
3006affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
3007affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
3008affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
3009affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
3010affee4b2STejun Heo  * after a work with LINKED flag set.
3011affee4b2STejun Heo  *
3012affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
3013112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
30144690c4abSTejun Heo  *
30154690c4abSTejun Heo  * CONTEXT:
3016a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
30174690c4abSTejun Heo  */
insert_wq_barrier(struct pool_workqueue * pwq,struct wq_barrier * barr,struct work_struct * target,struct worker * worker)3018112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
3019affee4b2STejun Heo 			      struct wq_barrier *barr,
3020affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
3021fc2e4d70SOleg Nesterov {
3022d812796eSLai Jiangshan 	unsigned int work_flags = 0;
3023d812796eSLai Jiangshan 	unsigned int work_color;
3024affee4b2STejun Heo 	struct list_head *head;
3025affee4b2STejun Heo 
3026dc186ad7SThomas Gleixner 	/*
3027d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
3028dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
3029dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
3030dc186ad7SThomas Gleixner 	 * might deadlock.
3031dc186ad7SThomas Gleixner 	 */
3032ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
303322df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
303452fa5bc5SBoqun Feng 
3035fd1a5b04SByungchul Park 	init_completion_map(&barr->done, &target->lockdep_map);
3036fd1a5b04SByungchul Park 
30372607d7a6STejun Heo 	barr->task = current;
303883c22520SOleg Nesterov 
30396741dd3fSGreg Kroah-Hartman 	/* The barrier work item does not participate in pwq->nr_active. */
3040018f3a13SLai Jiangshan 	work_flags |= WORK_STRUCT_INACTIVE;
3041018f3a13SLai Jiangshan 
3042affee4b2STejun Heo 	/*
3043affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
3044affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
3045affee4b2STejun Heo 	 */
3046d812796eSLai Jiangshan 	if (worker) {
3047affee4b2STejun Heo 		head = worker->scheduled.next;
3048d812796eSLai Jiangshan 		work_color = worker->current_color;
3049d812796eSLai Jiangshan 	} else {
3050affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
3051affee4b2STejun Heo 
3052affee4b2STejun Heo 		head = target->entry.next;
3053affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
3054d21cece0SLai Jiangshan 		work_flags |= *bits & WORK_STRUCT_LINKED;
3055d812796eSLai Jiangshan 		work_color = get_work_color(*bits);
3056affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
3057affee4b2STejun Heo 	}
3058affee4b2STejun Heo 
3059d812796eSLai Jiangshan 	pwq->nr_in_flight[work_color]++;
3060d812796eSLai Jiangshan 	work_flags |= work_color_to_flags(work_color);
3061d812796eSLai Jiangshan 
3062d21cece0SLai Jiangshan 	insert_work(pwq, &barr->work, head, work_flags);
3063fc2e4d70SOleg Nesterov }
3064fc2e4d70SOleg Nesterov 
306573f53c4aSTejun Heo /**
3066112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
306773f53c4aSTejun Heo  * @wq: workqueue being flushed
306873f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
306973f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
307073f53c4aSTejun Heo  *
3071112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
307273f53c4aSTejun Heo  *
3073112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
3074112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
3075112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
3076112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
3077112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
307873f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
307973f53c4aSTejun Heo  *
308073f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
308173f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
308273f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
308373f53c4aSTejun Heo  * is returned.
308473f53c4aSTejun Heo  *
3085112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
308673f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
308773f53c4aSTejun Heo  * advanced to @work_color.
308873f53c4aSTejun Heo  *
308973f53c4aSTejun Heo  * CONTEXT:
30903c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
309173f53c4aSTejun Heo  *
3092d185af30SYacine Belkadi  * Return:
309373f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
309473f53c4aSTejun Heo  * otherwise.
309573f53c4aSTejun Heo  */
flush_workqueue_prep_pwqs(struct workqueue_struct * wq,int flush_color,int work_color)3096112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
309773f53c4aSTejun Heo 				      int flush_color, int work_color)
30981da177e4SLinus Torvalds {
309973f53c4aSTejun Heo 	bool wait = false;
310049e3cf44STejun Heo 	struct pool_workqueue *pwq;
31011da177e4SLinus Torvalds 
310273f53c4aSTejun Heo 	if (flush_color >= 0) {
31036183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
3104112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
3105dc186ad7SThomas Gleixner 	}
310614441960SOleg Nesterov 
310749e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3108112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
31091da177e4SLinus Torvalds 
3110a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
311173f53c4aSTejun Heo 
311273f53c4aSTejun Heo 		if (flush_color >= 0) {
31136183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
311473f53c4aSTejun Heo 
3115112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
3116112202d9STejun Heo 				pwq->flush_color = flush_color;
3117112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
311873f53c4aSTejun Heo 				wait = true;
31191da177e4SLinus Torvalds 			}
312073f53c4aSTejun Heo 		}
312173f53c4aSTejun Heo 
312273f53c4aSTejun Heo 		if (work_color >= 0) {
31236183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
3124112202d9STejun Heo 			pwq->work_color = work_color;
312573f53c4aSTejun Heo 		}
312673f53c4aSTejun Heo 
3127a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
31281da177e4SLinus Torvalds 	}
31291da177e4SLinus Torvalds 
3130112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
313173f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
313273f53c4aSTejun Heo 
313373f53c4aSTejun Heo 	return wait;
313483c22520SOleg Nesterov }
31351da177e4SLinus Torvalds 
touch_wq_lockdep_map(struct workqueue_struct * wq)31366dc67674STejun Heo static void touch_wq_lockdep_map(struct workqueue_struct *wq)
31376dc67674STejun Heo {
31386dc67674STejun Heo 	lock_map_acquire(&wq->lockdep_map);
31396dc67674STejun Heo 	lock_map_release(&wq->lockdep_map);
31406dc67674STejun Heo }
31416dc67674STejun Heo 
touch_work_lockdep_map(struct work_struct * work,struct workqueue_struct * wq)31426dc67674STejun Heo static void touch_work_lockdep_map(struct work_struct *work,
31436dc67674STejun Heo 				   struct workqueue_struct *wq)
31446dc67674STejun Heo {
31456dc67674STejun Heo 	lock_map_acquire(&work->lockdep_map);
31466dc67674STejun Heo 	lock_map_release(&work->lockdep_map);
31476dc67674STejun Heo }
31486dc67674STejun Heo 
31490fcb78c2SRolf Eike Beer /**
3150c4f135d6STetsuo Handa  * __flush_workqueue - ensure that any scheduled work has run to completion.
31510fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
31521da177e4SLinus Torvalds  *
3153c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
3154c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
31551da177e4SLinus Torvalds  */
__flush_workqueue(struct workqueue_struct * wq)3156c4f135d6STetsuo Handa void __flush_workqueue(struct workqueue_struct *wq)
31571da177e4SLinus Torvalds {
315873f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
315973f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
316073f53c4aSTejun Heo 		.flush_color = -1,
3161fd1a5b04SByungchul Park 		.done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
316273f53c4aSTejun Heo 	};
316373f53c4aSTejun Heo 	int next_color;
3164b1f4ec17SOleg Nesterov 
31653347fa09STejun Heo 	if (WARN_ON(!wq_online))
31663347fa09STejun Heo 		return;
31673347fa09STejun Heo 
31686dc67674STejun Heo 	touch_wq_lockdep_map(wq);
316987915adcSJohannes Berg 
31703c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
317173f53c4aSTejun Heo 
317273f53c4aSTejun Heo 	/*
317373f53c4aSTejun Heo 	 * Start-to-wait phase
317473f53c4aSTejun Heo 	 */
317573f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
317673f53c4aSTejun Heo 
317773f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
317873f53c4aSTejun Heo 		/*
317973f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
318073f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
318173f53c4aSTejun Heo 		 * by one.
318273f53c4aSTejun Heo 		 */
31836183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
318473f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
318573f53c4aSTejun Heo 		wq->work_color = next_color;
318673f53c4aSTejun Heo 
318773f53c4aSTejun Heo 		if (!wq->first_flusher) {
318873f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
31896183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
319073f53c4aSTejun Heo 
319173f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
319273f53c4aSTejun Heo 
3193112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
319473f53c4aSTejun Heo 						       wq->work_color)) {
319573f53c4aSTejun Heo 				/* nothing to flush, done */
319673f53c4aSTejun Heo 				wq->flush_color = next_color;
319773f53c4aSTejun Heo 				wq->first_flusher = NULL;
319873f53c4aSTejun Heo 				goto out_unlock;
319973f53c4aSTejun Heo 			}
320073f53c4aSTejun Heo 		} else {
320173f53c4aSTejun Heo 			/* wait in queue */
32026183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
320373f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
3204112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
320573f53c4aSTejun Heo 		}
320673f53c4aSTejun Heo 	} else {
320773f53c4aSTejun Heo 		/*
320873f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
320973f53c4aSTejun Heo 		 * The next flush completion will assign us
321073f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
321173f53c4aSTejun Heo 		 */
321273f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
321373f53c4aSTejun Heo 	}
321473f53c4aSTejun Heo 
3215*1fd2a57dSTvrtko Ursulin 	check_flush_dependency(wq, NULL, false);
3216fca839c0STejun Heo 
32173c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
321873f53c4aSTejun Heo 
321973f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
322073f53c4aSTejun Heo 
322173f53c4aSTejun Heo 	/*
322273f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
322373f53c4aSTejun Heo 	 *
322473f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
322573f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
322673f53c4aSTejun Heo 	 */
322700d5d15bSChris Wilson 	if (READ_ONCE(wq->first_flusher) != &this_flusher)
322873f53c4aSTejun Heo 		return;
322973f53c4aSTejun Heo 
32303c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
323173f53c4aSTejun Heo 
32324ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
32334ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
32344ce48b37STejun Heo 		goto out_unlock;
32354ce48b37STejun Heo 
323600d5d15bSChris Wilson 	WRITE_ONCE(wq->first_flusher, NULL);
323773f53c4aSTejun Heo 
32386183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
32396183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
324073f53c4aSTejun Heo 
324173f53c4aSTejun Heo 	while (true) {
324273f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
324373f53c4aSTejun Heo 
324473f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
324573f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
324673f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
324773f53c4aSTejun Heo 				break;
324873f53c4aSTejun Heo 			list_del_init(&next->list);
324973f53c4aSTejun Heo 			complete(&next->done);
325073f53c4aSTejun Heo 		}
325173f53c4aSTejun Heo 
32526183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
325373f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
325473f53c4aSTejun Heo 
325573f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
325673f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
325773f53c4aSTejun Heo 
325873f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
325973f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
326073f53c4aSTejun Heo 			/*
326173f53c4aSTejun Heo 			 * Assign the same color to all overflowed
326273f53c4aSTejun Heo 			 * flushers, advance work_color and append to
326373f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
326473f53c4aSTejun Heo 			 * phase for these overflowed flushers.
326573f53c4aSTejun Heo 			 */
326673f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
326773f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
326873f53c4aSTejun Heo 
326973f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
327073f53c4aSTejun Heo 
327173f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
327273f53c4aSTejun Heo 					      &wq->flusher_queue);
3273112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
327473f53c4aSTejun Heo 		}
327573f53c4aSTejun Heo 
327673f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
32776183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
327873f53c4aSTejun Heo 			break;
327973f53c4aSTejun Heo 		}
328073f53c4aSTejun Heo 
328173f53c4aSTejun Heo 		/*
328273f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
3283112202d9STejun Heo 		 * the new first flusher and arm pwqs.
328473f53c4aSTejun Heo 		 */
32856183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
32866183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
328773f53c4aSTejun Heo 
328873f53c4aSTejun Heo 		list_del_init(&next->list);
328973f53c4aSTejun Heo 		wq->first_flusher = next;
329073f53c4aSTejun Heo 
3291112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
329273f53c4aSTejun Heo 			break;
329373f53c4aSTejun Heo 
329473f53c4aSTejun Heo 		/*
329573f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
329673f53c4aSTejun Heo 		 * flusher and repeat cascading.
329773f53c4aSTejun Heo 		 */
329873f53c4aSTejun Heo 		wq->first_flusher = NULL;
329973f53c4aSTejun Heo 	}
330073f53c4aSTejun Heo 
330173f53c4aSTejun Heo out_unlock:
33023c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
33031da177e4SLinus Torvalds }
3304c4f135d6STetsuo Handa EXPORT_SYMBOL(__flush_workqueue);
33051da177e4SLinus Torvalds 
33069c5a2ba7STejun Heo /**
33079c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
33089c5a2ba7STejun Heo  * @wq: workqueue to drain
33099c5a2ba7STejun Heo  *
33109c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
33119c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
33129c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
3313b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
33149c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
33159c5a2ba7STejun Heo  * takes too long.
33169c5a2ba7STejun Heo  */
drain_workqueue(struct workqueue_struct * wq)33179c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
33189c5a2ba7STejun Heo {
33199c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
332049e3cf44STejun Heo 	struct pool_workqueue *pwq;
33219c5a2ba7STejun Heo 
33229c5a2ba7STejun Heo 	/*
33239c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
33249c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
3325618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
33269c5a2ba7STejun Heo 	 */
332787fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
33289c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
3329618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
333087fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
33319c5a2ba7STejun Heo reflush:
3332c4f135d6STetsuo Handa 	__flush_workqueue(wq);
33339c5a2ba7STejun Heo 
3334b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
333576af4d93STejun Heo 
333649e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3337fa2563e4SThomas Tuttle 		bool drained;
33389c5a2ba7STejun Heo 
3339a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
334035bf38ddSGreg Kroah-Hartman 		drained = !pwq->nr_active && list_empty(&pwq->inactive_works);
3341a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
3342fa2563e4SThomas Tuttle 
3343fa2563e4SThomas Tuttle 		if (drained)
33449c5a2ba7STejun Heo 			continue;
33459c5a2ba7STejun Heo 
33469c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
33479c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
3348e9ad2eb3SStephen Zhang 			pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3349e9ad2eb3SStephen Zhang 				wq->name, __func__, flush_cnt);
335076af4d93STejun Heo 
3351b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
33529c5a2ba7STejun Heo 		goto reflush;
33539c5a2ba7STejun Heo 	}
33549c5a2ba7STejun Heo 
33559c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
3356618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
335787fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
33589c5a2ba7STejun Heo }
33599c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
33609c5a2ba7STejun Heo 
start_flush_work(struct work_struct * work,struct wq_barrier * barr,bool from_cancel)3361d6e89786SJohannes Berg static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3362d6e89786SJohannes Berg 			     bool from_cancel)
3363baf59022STejun Heo {
3364baf59022STejun Heo 	struct worker *worker = NULL;
3365c9e7cf27STejun Heo 	struct worker_pool *pool;
3366112202d9STejun Heo 	struct pool_workqueue *pwq;
33676dc67674STejun Heo 	struct workqueue_struct *wq;
3368baf59022STejun Heo 
3369baf59022STejun Heo 	might_sleep();
3370baf59022STejun Heo 
337124acfb71SThomas Gleixner 	rcu_read_lock();
3372fa1b54e6STejun Heo 	pool = get_work_pool(work);
3373fa1b54e6STejun Heo 	if (!pool) {
337424acfb71SThomas Gleixner 		rcu_read_unlock();
3375fa1b54e6STejun Heo 		return false;
3376fa1b54e6STejun Heo 	}
3377fa1b54e6STejun Heo 
3378a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
33790b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
3380112202d9STejun Heo 	pwq = get_work_pwq(work);
3381112202d9STejun Heo 	if (pwq) {
3382112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
3383baf59022STejun Heo 			goto already_gone;
3384606a5020STejun Heo 	} else {
3385c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
3386baf59022STejun Heo 		if (!worker)
3387baf59022STejun Heo 			goto already_gone;
3388112202d9STejun Heo 		pwq = worker->current_pwq;
3389606a5020STejun Heo 	}
3390baf59022STejun Heo 
33916dc67674STejun Heo 	wq = pwq->wq;
3392*1fd2a57dSTvrtko Ursulin 	check_flush_dependency(wq, work, from_cancel);
3393fca839c0STejun Heo 
3394112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
3395a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
3396baf59022STejun Heo 
33976dc67674STejun Heo 	touch_work_lockdep_map(work, wq);
33986dc67674STejun Heo 
3399e159489bSTejun Heo 	/*
3400a1d14934SPeter Zijlstra 	 * Force a lock recursion deadlock when using flush_work() inside a
3401a1d14934SPeter Zijlstra 	 * single-threaded or rescuer equipped workqueue.
3402a1d14934SPeter Zijlstra 	 *
3403a1d14934SPeter Zijlstra 	 * For single threaded workqueues the deadlock happens when the work
3404a1d14934SPeter Zijlstra 	 * is after the work issuing the flush_work(). For rescuer equipped
3405a1d14934SPeter Zijlstra 	 * workqueues the deadlock happens when the rescuer stalls, blocking
3406a1d14934SPeter Zijlstra 	 * forward progress.
3407e159489bSTejun Heo 	 */
34086dc67674STejun Heo 	if (!from_cancel && (wq->saved_max_active == 1 || wq->rescuer))
34096dc67674STejun Heo 		touch_wq_lockdep_map(wq);
34106dc67674STejun Heo 
341124acfb71SThomas Gleixner 	rcu_read_unlock();
3412baf59022STejun Heo 	return true;
3413baf59022STejun Heo already_gone:
3414a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
341524acfb71SThomas Gleixner 	rcu_read_unlock();
3416baf59022STejun Heo 	return false;
3417baf59022STejun Heo }
3418baf59022STejun Heo 
__flush_work(struct work_struct * work,bool from_cancel)3419d6e89786SJohannes Berg static bool __flush_work(struct work_struct *work, bool from_cancel)
3420d6e89786SJohannes Berg {
3421d6e89786SJohannes Berg 	struct wq_barrier barr;
3422d6e89786SJohannes Berg 
3423d6e89786SJohannes Berg 	if (WARN_ON(!wq_online))
3424d6e89786SJohannes Berg 		return false;
3425d6e89786SJohannes Berg 
34264d43d395STetsuo Handa 	if (WARN_ON(!work->func))
34274d43d395STetsuo Handa 		return false;
34284d43d395STetsuo Handa 
3429d6e89786SJohannes Berg 	if (start_flush_work(work, &barr, from_cancel)) {
3430d6e89786SJohannes Berg 		wait_for_completion(&barr.done);
3431d6e89786SJohannes Berg 		destroy_work_on_stack(&barr.work);
3432d6e89786SJohannes Berg 		return true;
3433d6e89786SJohannes Berg 	} else {
3434d6e89786SJohannes Berg 		return false;
3435d6e89786SJohannes Berg 	}
3436d6e89786SJohannes Berg }
3437d6e89786SJohannes Berg 
3438db700897SOleg Nesterov /**
3439401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
3440401a8d04STejun Heo  * @work: the work to flush
3441db700897SOleg Nesterov  *
3442606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
3443606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
3444401a8d04STejun Heo  *
3445d185af30SYacine Belkadi  * Return:
3446401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3447401a8d04STejun Heo  * %false if it was already idle.
3448db700897SOleg Nesterov  */
flush_work(struct work_struct * work)3449401a8d04STejun Heo bool flush_work(struct work_struct *work)
3450db700897SOleg Nesterov {
3451d6e89786SJohannes Berg 	return __flush_work(work, false);
3452606a5020STejun Heo }
3453db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
3454db700897SOleg Nesterov 
34558603e1b3STejun Heo struct cwt_wait {
3456ac6424b9SIngo Molnar 	wait_queue_entry_t		wait;
34578603e1b3STejun Heo 	struct work_struct	*work;
34588603e1b3STejun Heo };
34598603e1b3STejun Heo 
cwt_wakefn(wait_queue_entry_t * wait,unsigned mode,int sync,void * key)3460ac6424b9SIngo Molnar static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
34618603e1b3STejun Heo {
34628603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
34638603e1b3STejun Heo 
34648603e1b3STejun Heo 	if (cwait->work != key)
34658603e1b3STejun Heo 		return 0;
34668603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
34678603e1b3STejun Heo }
34688603e1b3STejun Heo 
__cancel_work_timer(struct work_struct * work,bool is_dwork)346936e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3470401a8d04STejun Heo {
34718603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3472bbb68dfaSTejun Heo 	unsigned long flags;
34731f1f642eSOleg Nesterov 	int ret;
34741f1f642eSOleg Nesterov 
34751f1f642eSOleg Nesterov 	do {
3476bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
3477bbb68dfaSTejun Heo 		/*
34788603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
34798603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
34808603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
34818603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
34828603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
34838603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
34848603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
34858603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
34868603e1b3STejun Heo 		 * we're hogging the CPU.
34878603e1b3STejun Heo 		 *
34888603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
34898603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
34908603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
34918603e1b3STejun Heo 		 * wait and wakeup.
3492bbb68dfaSTejun Heo 		 */
34938603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
34948603e1b3STejun Heo 			struct cwt_wait cwait;
34958603e1b3STejun Heo 
34968603e1b3STejun Heo 			init_wait(&cwait.wait);
34978603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
34988603e1b3STejun Heo 			cwait.work = work;
34998603e1b3STejun Heo 
35008603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
35018603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
35028603e1b3STejun Heo 			if (work_is_canceling(work))
35038603e1b3STejun Heo 				schedule();
35048603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
35058603e1b3STejun Heo 		}
35061f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
35071f1f642eSOleg Nesterov 
3508bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
3509bbb68dfaSTejun Heo 	mark_work_canceling(work);
3510bbb68dfaSTejun Heo 	local_irq_restore(flags);
3511bbb68dfaSTejun Heo 
35123347fa09STejun Heo 	/*
35133347fa09STejun Heo 	 * This allows canceling during early boot.  We know that @work
35143347fa09STejun Heo 	 * isn't executing.
35153347fa09STejun Heo 	 */
35163347fa09STejun Heo 	if (wq_online)
3517d6e89786SJohannes Berg 		__flush_work(work, true);
35183347fa09STejun Heo 
35197a22ad75STejun Heo 	clear_work_data(work);
35208603e1b3STejun Heo 
35218603e1b3STejun Heo 	/*
35228603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
35238603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
35248603e1b3STejun Heo 	 * visible there.
35258603e1b3STejun Heo 	 */
35268603e1b3STejun Heo 	smp_mb();
35278603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
35288603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
35298603e1b3STejun Heo 
35301f1f642eSOleg Nesterov 	return ret;
35311f1f642eSOleg Nesterov }
35321f1f642eSOleg Nesterov 
35336e84d644SOleg Nesterov /**
3534401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
3535401a8d04STejun Heo  * @work: the work to cancel
35366e84d644SOleg Nesterov  *
3537401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
3538401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
3539401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
3540401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
35411f1f642eSOleg Nesterov  *
3542401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
3543401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
35446e84d644SOleg Nesterov  *
3545401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
35466e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
3547401a8d04STejun Heo  *
3548d185af30SYacine Belkadi  * Return:
3549401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
35506e84d644SOleg Nesterov  */
cancel_work_sync(struct work_struct * work)3551401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
35526e84d644SOleg Nesterov {
355336e227d2STejun Heo 	return __cancel_work_timer(work, false);
3554b89deed3SOleg Nesterov }
355528e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
3556b89deed3SOleg Nesterov 
35576e84d644SOleg Nesterov /**
3558401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
3559401a8d04STejun Heo  * @dwork: the delayed work to flush
35606e84d644SOleg Nesterov  *
3561401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
3562401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
3563401a8d04STejun Heo  * considers the last queueing instance of @dwork.
35641f1f642eSOleg Nesterov  *
3565d185af30SYacine Belkadi  * Return:
3566401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3567401a8d04STejun Heo  * %false if it was already idle.
35686e84d644SOleg Nesterov  */
flush_delayed_work(struct delayed_work * dwork)3569401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
3570401a8d04STejun Heo {
35718930cabaSTejun Heo 	local_irq_disable();
3572401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
357360c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
35748930cabaSTejun Heo 	local_irq_enable();
3575401a8d04STejun Heo 	return flush_work(&dwork->work);
3576401a8d04STejun Heo }
3577401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3578401a8d04STejun Heo 
357905f0fe6bSTejun Heo /**
358005f0fe6bSTejun Heo  * flush_rcu_work - wait for a rwork to finish executing the last queueing
358105f0fe6bSTejun Heo  * @rwork: the rcu work to flush
358205f0fe6bSTejun Heo  *
358305f0fe6bSTejun Heo  * Return:
358405f0fe6bSTejun Heo  * %true if flush_rcu_work() waited for the work to finish execution,
358505f0fe6bSTejun Heo  * %false if it was already idle.
358605f0fe6bSTejun Heo  */
flush_rcu_work(struct rcu_work * rwork)358705f0fe6bSTejun Heo bool flush_rcu_work(struct rcu_work *rwork)
358805f0fe6bSTejun Heo {
358905f0fe6bSTejun Heo 	if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
359005f0fe6bSTejun Heo 		rcu_barrier();
359105f0fe6bSTejun Heo 		flush_work(&rwork->work);
359205f0fe6bSTejun Heo 		return true;
359305f0fe6bSTejun Heo 	} else {
359405f0fe6bSTejun Heo 		return flush_work(&rwork->work);
359505f0fe6bSTejun Heo 	}
359605f0fe6bSTejun Heo }
359705f0fe6bSTejun Heo EXPORT_SYMBOL(flush_rcu_work);
359805f0fe6bSTejun Heo 
__cancel_work(struct work_struct * work,bool is_dwork)3599f72b8792SJens Axboe static bool __cancel_work(struct work_struct *work, bool is_dwork)
3600f72b8792SJens Axboe {
3601f72b8792SJens Axboe 	unsigned long flags;
3602f72b8792SJens Axboe 	int ret;
3603f72b8792SJens Axboe 
3604f72b8792SJens Axboe 	do {
3605f72b8792SJens Axboe 		ret = try_to_grab_pending(work, is_dwork, &flags);
3606f72b8792SJens Axboe 	} while (unlikely(ret == -EAGAIN));
3607f72b8792SJens Axboe 
3608f72b8792SJens Axboe 	if (unlikely(ret < 0))
3609f72b8792SJens Axboe 		return false;
3610f72b8792SJens Axboe 
3611f72b8792SJens Axboe 	set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3612f72b8792SJens Axboe 	local_irq_restore(flags);
3613f72b8792SJens Axboe 	return ret;
3614f72b8792SJens Axboe }
3615f72b8792SJens Axboe 
361673b4b532SAndrey Grodzovsky /*
361773b4b532SAndrey Grodzovsky  * See cancel_delayed_work()
361873b4b532SAndrey Grodzovsky  */
cancel_work(struct work_struct * work)361973b4b532SAndrey Grodzovsky bool cancel_work(struct work_struct *work)
362073b4b532SAndrey Grodzovsky {
362173b4b532SAndrey Grodzovsky 	return __cancel_work(work, false);
362273b4b532SAndrey Grodzovsky }
362373b4b532SAndrey Grodzovsky EXPORT_SYMBOL(cancel_work);
362473b4b532SAndrey Grodzovsky 
3625401a8d04STejun Heo /**
362657b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
362757b30ae7STejun Heo  * @dwork: delayed_work to cancel
362809383498STejun Heo  *
3629d185af30SYacine Belkadi  * Kill off a pending delayed_work.
3630d185af30SYacine Belkadi  *
3631d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
3632d185af30SYacine Belkadi  * pending.
3633d185af30SYacine Belkadi  *
3634d185af30SYacine Belkadi  * Note:
3635d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
3636d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
3637d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
363809383498STejun Heo  *
363957b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
364009383498STejun Heo  */
cancel_delayed_work(struct delayed_work * dwork)364157b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
364209383498STejun Heo {
3643f72b8792SJens Axboe 	return __cancel_work(&dwork->work, true);
364409383498STejun Heo }
364557b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
364609383498STejun Heo 
364709383498STejun Heo /**
3648401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3649401a8d04STejun Heo  * @dwork: the delayed work cancel
3650401a8d04STejun Heo  *
3651401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
3652401a8d04STejun Heo  *
3653d185af30SYacine Belkadi  * Return:
3654401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
3655401a8d04STejun Heo  */
cancel_delayed_work_sync(struct delayed_work * dwork)3656401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
36576e84d644SOleg Nesterov {
365836e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
36596e84d644SOleg Nesterov }
3660f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
36611da177e4SLinus Torvalds 
36620fcb78c2SRolf Eike Beer /**
366331ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3664b6136773SAndrew Morton  * @func: the function to call
3665b6136773SAndrew Morton  *
366631ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
366731ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3668b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
366931ddd871STejun Heo  *
3670d185af30SYacine Belkadi  * Return:
367131ddd871STejun Heo  * 0 on success, -errno on failure.
3672b6136773SAndrew Morton  */
schedule_on_each_cpu(work_func_t func)367365f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
367415316ba8SChristoph Lameter {
367515316ba8SChristoph Lameter 	int cpu;
367638f51568SNamhyung Kim 	struct work_struct __percpu *works;
367715316ba8SChristoph Lameter 
3678b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3679b6136773SAndrew Morton 	if (!works)
368015316ba8SChristoph Lameter 		return -ENOMEM;
3681b6136773SAndrew Morton 
3682ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
368393981800STejun Heo 
368415316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
36859bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
36869bfb1839SIngo Molnar 
36879bfb1839SIngo Molnar 		INIT_WORK(work, func);
36888de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
368915316ba8SChristoph Lameter 	}
369093981800STejun Heo 
369193981800STejun Heo 	for_each_online_cpu(cpu)
36928616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
369393981800STejun Heo 
3694ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
3695b6136773SAndrew Morton 	free_percpu(works);
369615316ba8SChristoph Lameter 	return 0;
369715316ba8SChristoph Lameter }
369815316ba8SChristoph Lameter 
3699eef6a7d5SAlan Stern /**
37001fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
37011fa44ecaSJames Bottomley  * @fn:		the function to execute
37021fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
37031fa44ecaSJames Bottomley  *		be available when the work executes)
37041fa44ecaSJames Bottomley  *
37051fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
37061fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
37071fa44ecaSJames Bottomley  *
3708d185af30SYacine Belkadi  * Return:	0 - function was executed
37091fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
37101fa44ecaSJames Bottomley  */
execute_in_process_context(work_func_t fn,struct execute_work * ew)371165f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
37121fa44ecaSJames Bottomley {
37131fa44ecaSJames Bottomley 	if (!in_interrupt()) {
371465f27f38SDavid Howells 		fn(&ew->work);
37151fa44ecaSJames Bottomley 		return 0;
37161fa44ecaSJames Bottomley 	}
37171fa44ecaSJames Bottomley 
371865f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
37191fa44ecaSJames Bottomley 	schedule_work(&ew->work);
37201fa44ecaSJames Bottomley 
37211fa44ecaSJames Bottomley 	return 1;
37221fa44ecaSJames Bottomley }
37231fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
37241fa44ecaSJames Bottomley 
37257a4e344cSTejun Heo /**
37267a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
37277a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
37287a4e344cSTejun Heo  *
37297a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
37307a4e344cSTejun Heo  */
free_workqueue_attrs(struct workqueue_attrs * attrs)3731513c98d0SDaniel Jordan void free_workqueue_attrs(struct workqueue_attrs *attrs)
37327a4e344cSTejun Heo {
37337a4e344cSTejun Heo 	if (attrs) {
37347a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
37359546b29eSTejun Heo 		free_cpumask_var(attrs->__pod_cpumask);
37367a4e344cSTejun Heo 		kfree(attrs);
37377a4e344cSTejun Heo 	}
37387a4e344cSTejun Heo }
37397a4e344cSTejun Heo 
37407a4e344cSTejun Heo /**
37417a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
37427a4e344cSTejun Heo  *
37437a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3744d185af30SYacine Belkadi  * return it.
3745d185af30SYacine Belkadi  *
3746d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
37477a4e344cSTejun Heo  */
alloc_workqueue_attrs(void)3748513c98d0SDaniel Jordan struct workqueue_attrs *alloc_workqueue_attrs(void)
37497a4e344cSTejun Heo {
37507a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
37517a4e344cSTejun Heo 
3752be69d00dSThomas Gleixner 	attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
37537a4e344cSTejun Heo 	if (!attrs)
37547a4e344cSTejun Heo 		goto fail;
3755be69d00dSThomas Gleixner 	if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
37567a4e344cSTejun Heo 		goto fail;
37579546b29eSTejun Heo 	if (!alloc_cpumask_var(&attrs->__pod_cpumask, GFP_KERNEL))
37589546b29eSTejun Heo 		goto fail;
37597a4e344cSTejun Heo 
376013e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
3761523a301eSTejun Heo 	attrs->affn_scope = WQ_AFFN_DFL;
37627a4e344cSTejun Heo 	return attrs;
37637a4e344cSTejun Heo fail:
37647a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
37657a4e344cSTejun Heo 	return NULL;
37667a4e344cSTejun Heo }
37677a4e344cSTejun Heo 
copy_workqueue_attrs(struct workqueue_attrs * to,const struct workqueue_attrs * from)376829c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
376929c91e99STejun Heo 				 const struct workqueue_attrs *from)
377029c91e99STejun Heo {
377129c91e99STejun Heo 	to->nice = from->nice;
377229c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
37739546b29eSTejun Heo 	cpumask_copy(to->__pod_cpumask, from->__pod_cpumask);
37748639ecebSTejun Heo 	to->affn_strict = from->affn_strict;
377584193c07STejun Heo 
37762865a8fbSShaohua Li 	/*
377784193c07STejun Heo 	 * Unlike hash and equality test, copying shouldn't ignore wq-only
377884193c07STejun Heo 	 * fields as copying is used for both pool and wq attrs. Instead,
377984193c07STejun Heo 	 * get_unbound_pool() explicitly clears the fields.
37802865a8fbSShaohua Li 	 */
378184193c07STejun Heo 	to->affn_scope = from->affn_scope;
3782af73f5c9STejun Heo 	to->ordered = from->ordered;
378329c91e99STejun Heo }
378429c91e99STejun Heo 
37855de7a03cSTejun Heo /*
37865de7a03cSTejun Heo  * Some attrs fields are workqueue-only. Clear them for worker_pool's. See the
37875de7a03cSTejun Heo  * comments in 'struct workqueue_attrs' definition.
37885de7a03cSTejun Heo  */
wqattrs_clear_for_pool(struct workqueue_attrs * attrs)37895de7a03cSTejun Heo static void wqattrs_clear_for_pool(struct workqueue_attrs *attrs)
37905de7a03cSTejun Heo {
379184193c07STejun Heo 	attrs->affn_scope = WQ_AFFN_NR_TYPES;
37925de7a03cSTejun Heo 	attrs->ordered = false;
37935de7a03cSTejun Heo }
37945de7a03cSTejun Heo 
379529c91e99STejun Heo /* hash value of the content of @attr */
wqattrs_hash(const struct workqueue_attrs * attrs)379629c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
379729c91e99STejun Heo {
379829c91e99STejun Heo 	u32 hash = 0;
379929c91e99STejun Heo 
380029c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
380113e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
380213e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
38039546b29eSTejun Heo 	hash = jhash(cpumask_bits(attrs->__pod_cpumask),
38049546b29eSTejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
38058639ecebSTejun Heo 	hash = jhash_1word(attrs->affn_strict, hash);
380629c91e99STejun Heo 	return hash;
380729c91e99STejun Heo }
380829c91e99STejun Heo 
380929c91e99STejun Heo /* content equality test */
wqattrs_equal(const struct workqueue_attrs * a,const struct workqueue_attrs * b)381029c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
381129c91e99STejun Heo 			  const struct workqueue_attrs *b)
381229c91e99STejun Heo {
381329c91e99STejun Heo 	if (a->nice != b->nice)
381429c91e99STejun Heo 		return false;
381529c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
381629c91e99STejun Heo 		return false;
38179546b29eSTejun Heo 	if (!cpumask_equal(a->__pod_cpumask, b->__pod_cpumask))
38189546b29eSTejun Heo 		return false;
38198639ecebSTejun Heo 	if (a->affn_strict != b->affn_strict)
38208639ecebSTejun Heo 		return false;
382129c91e99STejun Heo 	return true;
382229c91e99STejun Heo }
382329c91e99STejun Heo 
38240f36ee24STejun Heo /* Update @attrs with actually available CPUs */
wqattrs_actualize_cpumask(struct workqueue_attrs * attrs,const cpumask_t * unbound_cpumask)38250f36ee24STejun Heo static void wqattrs_actualize_cpumask(struct workqueue_attrs *attrs,
38260f36ee24STejun Heo 				      const cpumask_t *unbound_cpumask)
38270f36ee24STejun Heo {
38280f36ee24STejun Heo 	/*
38290f36ee24STejun Heo 	 * Calculate the effective CPU mask of @attrs given @unbound_cpumask. If
38300f36ee24STejun Heo 	 * @attrs->cpumask doesn't overlap with @unbound_cpumask, we fallback to
38310f36ee24STejun Heo 	 * @unbound_cpumask.
38320f36ee24STejun Heo 	 */
38330f36ee24STejun Heo 	cpumask_and(attrs->cpumask, attrs->cpumask, unbound_cpumask);
38340f36ee24STejun Heo 	if (unlikely(cpumask_empty(attrs->cpumask)))
38350f36ee24STejun Heo 		cpumask_copy(attrs->cpumask, unbound_cpumask);
38360f36ee24STejun Heo }
38370f36ee24STejun Heo 
383884193c07STejun Heo /* find wq_pod_type to use for @attrs */
383984193c07STejun Heo static const struct wq_pod_type *
wqattrs_pod_type(const struct workqueue_attrs * attrs)384084193c07STejun Heo wqattrs_pod_type(const struct workqueue_attrs *attrs)
384184193c07STejun Heo {
3842523a301eSTejun Heo 	enum wq_affn_scope scope;
3843523a301eSTejun Heo 	struct wq_pod_type *pt;
3844523a301eSTejun Heo 
3845523a301eSTejun Heo 	/* to synchronize access to wq_affn_dfl */
3846523a301eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3847523a301eSTejun Heo 
3848523a301eSTejun Heo 	if (attrs->affn_scope == WQ_AFFN_DFL)
3849523a301eSTejun Heo 		scope = wq_affn_dfl;
3850523a301eSTejun Heo 	else
3851523a301eSTejun Heo 		scope = attrs->affn_scope;
3852523a301eSTejun Heo 
3853523a301eSTejun Heo 	pt = &wq_pod_types[scope];
385484193c07STejun Heo 
385584193c07STejun Heo 	if (!WARN_ON_ONCE(attrs->affn_scope == WQ_AFFN_NR_TYPES) &&
385684193c07STejun Heo 	    likely(pt->nr_pods))
385784193c07STejun Heo 		return pt;
385884193c07STejun Heo 
385984193c07STejun Heo 	/*
386084193c07STejun Heo 	 * Before workqueue_init_topology(), only SYSTEM is available which is
386184193c07STejun Heo 	 * initialized in workqueue_init_early().
386284193c07STejun Heo 	 */
386384193c07STejun Heo 	pt = &wq_pod_types[WQ_AFFN_SYSTEM];
386484193c07STejun Heo 	BUG_ON(!pt->nr_pods);
386584193c07STejun Heo 	return pt;
386684193c07STejun Heo }
386784193c07STejun Heo 
38687a4e344cSTejun Heo /**
38697a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
38707a4e344cSTejun Heo  * @pool: worker_pool to initialize
38717a4e344cSTejun Heo  *
3872402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3873d185af30SYacine Belkadi  *
3874d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
387529c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
387629c91e99STejun Heo  * on @pool safely to release it.
38777a4e344cSTejun Heo  */
init_worker_pool(struct worker_pool * pool)38787a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
38794e1a1f9aSTejun Heo {
3880a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_init(&pool->lock);
388129c91e99STejun Heo 	pool->id = -1;
388229c91e99STejun Heo 	pool->cpu = -1;
3883f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
38844e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
388582607adcSTejun Heo 	pool->watchdog_ts = jiffies;
38864e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
38874e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
38884e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
38894e1a1f9aSTejun Heo 
389032a6c723SKees Cook 	timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
38913f959aa3SValentin Schneider 	INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
38924e1a1f9aSTejun Heo 
389332a6c723SKees Cook 	timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
38944e1a1f9aSTejun Heo 
3895da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
3896e02b9312SValentin Schneider 	INIT_LIST_HEAD(&pool->dying_workers);
38977a4e344cSTejun Heo 
38987cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
389929c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
390029c91e99STejun Heo 	pool->refcnt = 1;
390129c91e99STejun Heo 
390229c91e99STejun Heo 	/* shouldn't fail above this point */
3903be69d00dSThomas Gleixner 	pool->attrs = alloc_workqueue_attrs();
39047a4e344cSTejun Heo 	if (!pool->attrs)
39057a4e344cSTejun Heo 		return -ENOMEM;
39065de7a03cSTejun Heo 
39075de7a03cSTejun Heo 	wqattrs_clear_for_pool(pool->attrs);
39085de7a03cSTejun Heo 
39097a4e344cSTejun Heo 	return 0;
39104e1a1f9aSTejun Heo }
39114e1a1f9aSTejun Heo 
3912669de8bdSBart Van Assche #ifdef CONFIG_LOCKDEP
wq_init_lockdep(struct workqueue_struct * wq)3913669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3914669de8bdSBart Van Assche {
3915669de8bdSBart Van Assche 	char *lock_name;
3916669de8bdSBart Van Assche 
3917669de8bdSBart Van Assche 	lockdep_register_key(&wq->key);
3918669de8bdSBart Van Assche 	lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3919669de8bdSBart Van Assche 	if (!lock_name)
3920669de8bdSBart Van Assche 		lock_name = wq->name;
392169a106c0SQian Cai 
392269a106c0SQian Cai 	wq->lock_name = lock_name;
3923669de8bdSBart Van Assche 	lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3924669de8bdSBart Van Assche }
3925669de8bdSBart Van Assche 
wq_unregister_lockdep(struct workqueue_struct * wq)3926669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3927669de8bdSBart Van Assche {
3928669de8bdSBart Van Assche 	lockdep_unregister_key(&wq->key);
3929669de8bdSBart Van Assche }
3930669de8bdSBart Van Assche 
wq_free_lockdep(struct workqueue_struct * wq)3931669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3932669de8bdSBart Van Assche {
3933669de8bdSBart Van Assche 	if (wq->lock_name != wq->name)
3934669de8bdSBart Van Assche 		kfree(wq->lock_name);
3935669de8bdSBart Van Assche }
3936669de8bdSBart Van Assche #else
wq_init_lockdep(struct workqueue_struct * wq)3937669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3938669de8bdSBart Van Assche {
3939669de8bdSBart Van Assche }
3940669de8bdSBart Van Assche 
wq_unregister_lockdep(struct workqueue_struct * wq)3941669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3942669de8bdSBart Van Assche {
3943669de8bdSBart Van Assche }
3944669de8bdSBart Van Assche 
wq_free_lockdep(struct workqueue_struct * wq)3945669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3946669de8bdSBart Van Assche {
3947669de8bdSBart Van Assche }
3948669de8bdSBart Van Assche #endif
3949669de8bdSBart Van Assche 
rcu_free_wq(struct rcu_head * rcu)3950e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
3951e2dca7adSTejun Heo {
3952e2dca7adSTejun Heo 	struct workqueue_struct *wq =
3953e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
3954e2dca7adSTejun Heo 
3955669de8bdSBart Van Assche 	wq_free_lockdep(wq);
3956ee1ceef7STejun Heo 	free_percpu(wq->cpu_pwq);
3957e2dca7adSTejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
3958e2dca7adSTejun Heo 	kfree(wq);
3959e2dca7adSTejun Heo }
3960e2dca7adSTejun Heo 
rcu_free_pool(struct rcu_head * rcu)396129c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
396229c91e99STejun Heo {
396329c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
396429c91e99STejun Heo 
39657cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
396629c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
396729c91e99STejun Heo 	kfree(pool);
396829c91e99STejun Heo }
396929c91e99STejun Heo 
397029c91e99STejun Heo /**
397129c91e99STejun Heo  * put_unbound_pool - put a worker_pool
397229c91e99STejun Heo  * @pool: worker_pool to put
397329c91e99STejun Heo  *
397424acfb71SThomas Gleixner  * Put @pool.  If its refcnt reaches zero, it gets destroyed in RCU
3975c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3976c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3977c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
3978a892caccSTejun Heo  *
3979a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
398029c91e99STejun Heo  */
put_unbound_pool(struct worker_pool * pool)398129c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
398229c91e99STejun Heo {
398360f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
398429c91e99STejun Heo 	struct worker *worker;
39859680540cSYang Yingliang 	LIST_HEAD(cull_list);
3986e02b9312SValentin Schneider 
3987a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3988a892caccSTejun Heo 
3989a892caccSTejun Heo 	if (--pool->refcnt)
399029c91e99STejun Heo 		return;
399129c91e99STejun Heo 
399229c91e99STejun Heo 	/* sanity checks */
399361d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
3994a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
399529c91e99STejun Heo 		return;
399629c91e99STejun Heo 
399729c91e99STejun Heo 	/* release id and unhash */
399829c91e99STejun Heo 	if (pool->id >= 0)
399929c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
400029c91e99STejun Heo 	hash_del(&pool->hash_node);
400129c91e99STejun Heo 
4002c5aa87bbSTejun Heo 	/*
4003692b4825STejun Heo 	 * Become the manager and destroy all workers.  This prevents
4004692b4825STejun Heo 	 * @pool's workers from blocking on attach_mutex.  We're the last
4005692b4825STejun Heo 	 * manager and @pool gets freed with the flag set.
40069ab03be4SValentin Schneider 	 *
40079ab03be4SValentin Schneider 	 * Having a concurrent manager is quite unlikely to happen as we can
40089ab03be4SValentin Schneider 	 * only get here with
40099ab03be4SValentin Schneider 	 *   pwq->refcnt == pool->refcnt == 0
40109ab03be4SValentin Schneider 	 * which implies no work queued to the pool, which implies no worker can
40119ab03be4SValentin Schneider 	 * become the manager. However a worker could have taken the role of
40129ab03be4SValentin Schneider 	 * manager before the refcnts dropped to 0, since maybe_create_worker()
40139ab03be4SValentin Schneider 	 * drops pool->lock
4014c5aa87bbSTejun Heo 	 */
40159ab03be4SValentin Schneider 	while (true) {
40169ab03be4SValentin Schneider 		rcuwait_wait_event(&manager_wait,
40179ab03be4SValentin Schneider 				   !(pool->flags & POOL_MANAGER_ACTIVE),
4018d8bb65abSSebastian Andrzej Siewior 				   TASK_UNINTERRUPTIBLE);
4019e02b9312SValentin Schneider 
4020e02b9312SValentin Schneider 		mutex_lock(&wq_pool_attach_mutex);
40219ab03be4SValentin Schneider 		raw_spin_lock_irq(&pool->lock);
40229ab03be4SValentin Schneider 		if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
4023692b4825STejun Heo 			pool->flags |= POOL_MANAGER_ACTIVE;
40249ab03be4SValentin Schneider 			break;
40259ab03be4SValentin Schneider 		}
40269ab03be4SValentin Schneider 		raw_spin_unlock_irq(&pool->lock);
4027e02b9312SValentin Schneider 		mutex_unlock(&wq_pool_attach_mutex);
40289ab03be4SValentin Schneider 	}
4029692b4825STejun Heo 
40301037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
4031e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
403229c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
4033a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
403460f5a4bcSLai Jiangshan 
4035e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
4036e02b9312SValentin Schneider 
4037e02b9312SValentin Schneider 	if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
403860f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
40391258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
404060f5a4bcSLai Jiangshan 
404160f5a4bcSLai Jiangshan 	if (pool->detach_completion)
404260f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
404360f5a4bcSLai Jiangshan 
404429c91e99STejun Heo 	/* shut down the timers */
404529c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
40463f959aa3SValentin Schneider 	cancel_work_sync(&pool->idle_cull_work);
404729c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
404829c91e99STejun Heo 
404924acfb71SThomas Gleixner 	/* RCU protected to allow dereferences from get_work_pool() */
405025b00775SPaul E. McKenney 	call_rcu(&pool->rcu, rcu_free_pool);
405129c91e99STejun Heo }
405229c91e99STejun Heo 
405329c91e99STejun Heo /**
405429c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
405529c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
405629c91e99STejun Heo  *
405729c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
405829c91e99STejun Heo  * reference count and return it.  If there already is a matching
405929c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
4060d185af30SYacine Belkadi  * create a new one.
4061a892caccSTejun Heo  *
4062a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
4063d185af30SYacine Belkadi  *
4064d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
4065d185af30SYacine Belkadi  * On failure, %NULL.
406629c91e99STejun Heo  */
get_unbound_pool(const struct workqueue_attrs * attrs)406729c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
406829c91e99STejun Heo {
406984193c07STejun Heo 	struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_NUMA];
407029c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
407129c91e99STejun Heo 	struct worker_pool *pool;
407284193c07STejun Heo 	int pod, node = NUMA_NO_NODE;
407329c91e99STejun Heo 
4074a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
407529c91e99STejun Heo 
407629c91e99STejun Heo 	/* do we already have a matching pool? */
407729c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
407829c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
407929c91e99STejun Heo 			pool->refcnt++;
40803fb1823cSLai Jiangshan 			return pool;
408129c91e99STejun Heo 		}
408229c91e99STejun Heo 	}
408329c91e99STejun Heo 
40849546b29eSTejun Heo 	/* If __pod_cpumask is contained inside a NUMA pod, that's our node */
408584193c07STejun Heo 	for (pod = 0; pod < pt->nr_pods; pod++) {
40869546b29eSTejun Heo 		if (cpumask_subset(attrs->__pod_cpumask, pt->pod_cpus[pod])) {
408784193c07STejun Heo 			node = pt->pod_node[pod];
4088e2273584SXunlei Pang 			break;
4089e2273584SXunlei Pang 		}
4090e2273584SXunlei Pang 	}
4091e2273584SXunlei Pang 
409229c91e99STejun Heo 	/* nope, create a new one */
409384193c07STejun Heo 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, node);
409429c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
409529c91e99STejun Heo 		goto fail;
409629c91e99STejun Heo 
409784193c07STejun Heo 	pool->node = node;
40985de7a03cSTejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
40995de7a03cSTejun Heo 	wqattrs_clear_for_pool(pool->attrs);
41002865a8fbSShaohua Li 
410129c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
410229c91e99STejun Heo 		goto fail;
410329c91e99STejun Heo 
410429c91e99STejun Heo 	/* create and start the initial worker */
41053347fa09STejun Heo 	if (wq_online && !create_worker(pool))
410629c91e99STejun Heo 		goto fail;
410729c91e99STejun Heo 
410829c91e99STejun Heo 	/* install */
410929c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
41103fb1823cSLai Jiangshan 
411129c91e99STejun Heo 	return pool;
411229c91e99STejun Heo fail:
411329c91e99STejun Heo 	if (pool)
411429c91e99STejun Heo 		put_unbound_pool(pool);
411529c91e99STejun Heo 	return NULL;
411629c91e99STejun Heo }
411729c91e99STejun Heo 
rcu_free_pwq(struct rcu_head * rcu)41188864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
41198864b4e5STejun Heo {
41208864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
41218864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
41228864b4e5STejun Heo }
41238864b4e5STejun Heo 
41248864b4e5STejun Heo /*
4125967b494eSTejun Heo  * Scheduled on pwq_release_worker by put_pwq() when an unbound pwq hits zero
4126967b494eSTejun Heo  * refcnt and needs to be destroyed.
41278864b4e5STejun Heo  */
pwq_release_workfn(struct kthread_work * work)4128687a9aa5STejun Heo static void pwq_release_workfn(struct kthread_work *work)
41298864b4e5STejun Heo {
41308864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
4131687a9aa5STejun Heo 						  release_work);
41328864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
41338864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
4134b42b0bddSYang Yingliang 	bool is_last = false;
41358864b4e5STejun Heo 
4136b42b0bddSYang Yingliang 	/*
4137687a9aa5STejun Heo 	 * When @pwq is not linked, it doesn't hold any reference to the
4138b42b0bddSYang Yingliang 	 * @wq, and @wq is invalid to access.
4139b42b0bddSYang Yingliang 	 */
4140b42b0bddSYang Yingliang 	if (!list_empty(&pwq->pwqs_node)) {
41413c25a55dSLai Jiangshan 		mutex_lock(&wq->mutex);
41428864b4e5STejun Heo 		list_del_rcu(&pwq->pwqs_node);
4143bc0caf09STejun Heo 		is_last = list_empty(&wq->pwqs);
41443c25a55dSLai Jiangshan 		mutex_unlock(&wq->mutex);
4145b42b0bddSYang Yingliang 	}
41468864b4e5STejun Heo 
4147687a9aa5STejun Heo 	if (wq->flags & WQ_UNBOUND) {
4148a892caccSTejun Heo 		mutex_lock(&wq_pool_mutex);
41498864b4e5STejun Heo 		put_unbound_pool(pool);
4150a892caccSTejun Heo 		mutex_unlock(&wq_pool_mutex);
4151687a9aa5STejun Heo 	}
4152a892caccSTejun Heo 
415325b00775SPaul E. McKenney 	call_rcu(&pwq->rcu, rcu_free_pwq);
41548864b4e5STejun Heo 
41558864b4e5STejun Heo 	/*
41568864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
4157e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
41588864b4e5STejun Heo 	 */
4159669de8bdSBart Van Assche 	if (is_last) {
4160669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
416125b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
41626029a918STejun Heo 	}
4163669de8bdSBart Van Assche }
41648864b4e5STejun Heo 
4165d8354f26SGreg Kroah-Hartman /**
4166d8354f26SGreg Kroah-Hartman  * pwq_adjust_max_active - update a pwq's max_active to the current setting
4167d8354f26SGreg Kroah-Hartman  * @pwq: target pool_workqueue
4168d8354f26SGreg Kroah-Hartman  *
4169d8354f26SGreg Kroah-Hartman  * If @pwq isn't freezing, set @pwq->max_active to the associated
4170d8354f26SGreg Kroah-Hartman  * workqueue's saved_max_active and activate inactive work items
4171d8354f26SGreg Kroah-Hartman  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
4172d8354f26SGreg Kroah-Hartman  */
pwq_adjust_max_active(struct pool_workqueue * pwq)4173d8354f26SGreg Kroah-Hartman static void pwq_adjust_max_active(struct pool_workqueue *pwq)
4174d8354f26SGreg Kroah-Hartman {
4175d8354f26SGreg Kroah-Hartman 	struct workqueue_struct *wq = pwq->wq;
4176d8354f26SGreg Kroah-Hartman 	bool freezable = wq->flags & WQ_FREEZABLE;
4177d8354f26SGreg Kroah-Hartman 	unsigned long flags;
4178d8354f26SGreg Kroah-Hartman 
4179d8354f26SGreg Kroah-Hartman 	/* for @wq->saved_max_active */
4180d8354f26SGreg Kroah-Hartman 	lockdep_assert_held(&wq->mutex);
4181d8354f26SGreg Kroah-Hartman 
4182d8354f26SGreg Kroah-Hartman 	/* fast exit for non-freezable wqs */
4183d8354f26SGreg Kroah-Hartman 	if (!freezable && pwq->max_active == wq->saved_max_active)
4184d8354f26SGreg Kroah-Hartman 		return;
4185d8354f26SGreg Kroah-Hartman 
4186d8354f26SGreg Kroah-Hartman 	/* this function can be called during early boot w/ irq disabled */
4187d8354f26SGreg Kroah-Hartman 	raw_spin_lock_irqsave(&pwq->pool->lock, flags);
4188d8354f26SGreg Kroah-Hartman 
4189d8354f26SGreg Kroah-Hartman 	/*
4190d8354f26SGreg Kroah-Hartman 	 * During [un]freezing, the caller is responsible for ensuring that
4191d8354f26SGreg Kroah-Hartman 	 * this function is called at least once after @workqueue_freezing
4192d8354f26SGreg Kroah-Hartman 	 * is updated and visible.
4193d8354f26SGreg Kroah-Hartman 	 */
4194d8354f26SGreg Kroah-Hartman 	if (!freezable || !workqueue_freezing) {
4195d8354f26SGreg Kroah-Hartman 		pwq->max_active = wq->saved_max_active;
4196d8354f26SGreg Kroah-Hartman 
4197d8354f26SGreg Kroah-Hartman 		while (!list_empty(&pwq->inactive_works) &&
4198d8354f26SGreg Kroah-Hartman 		       pwq->nr_active < pwq->max_active)
4199d8354f26SGreg Kroah-Hartman 			pwq_activate_first_inactive(pwq);
4200d8354f26SGreg Kroah-Hartman 
4201d8354f26SGreg Kroah-Hartman 		kick_pool(pwq->pool);
4202d8354f26SGreg Kroah-Hartman 	} else {
4203d8354f26SGreg Kroah-Hartman 		pwq->max_active = 0;
4204d8354f26SGreg Kroah-Hartman 	}
4205d8354f26SGreg Kroah-Hartman 
4206d8354f26SGreg Kroah-Hartman 	raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
4207d8354f26SGreg Kroah-Hartman }
4208d8354f26SGreg Kroah-Hartman 
420967dc8325SCai Huoqing /* initialize newly allocated @pwq which is associated with @wq and @pool */
init_pwq(struct pool_workqueue * pwq,struct workqueue_struct * wq,struct worker_pool * pool)4210f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
4211f147f29eSTejun Heo 		     struct worker_pool *pool)
4212d2c1d404STejun Heo {
4213d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
4214d2c1d404STejun Heo 
4215e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
4216e50aba9aSTejun Heo 
4217d2c1d404STejun Heo 	pwq->pool = pool;
4218d2c1d404STejun Heo 	pwq->wq = wq;
4219d2c1d404STejun Heo 	pwq->flush_color = -1;
42208864b4e5STejun Heo 	pwq->refcnt = 1;
4221f97a4a1aSLai Jiangshan 	INIT_LIST_HEAD(&pwq->inactive_works);
42221befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
4223d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
4224687a9aa5STejun Heo 	kthread_init_work(&pwq->release_work, pwq_release_workfn);
4225f147f29eSTejun Heo }
4226d2c1d404STejun Heo 
4227f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
link_pwq(struct pool_workqueue * pwq)42281befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
4229f147f29eSTejun Heo {
4230f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
4231f147f29eSTejun Heo 
4232f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
423375ccf595STejun Heo 
42341befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
42351befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
42361befcf30STejun Heo 		return;
42371befcf30STejun Heo 
423829b1cb41SLai Jiangshan 	/* set the matching work_color */
423975ccf595STejun Heo 	pwq->work_color = wq->work_color;
4240983ca25eSTejun Heo 
4241d8354f26SGreg Kroah-Hartman 	/* sync max_active to the current setting */
4242d8354f26SGreg Kroah-Hartman 	pwq_adjust_max_active(pwq);
4243d8354f26SGreg Kroah-Hartman 
4244983ca25eSTejun Heo 	/* link in @pwq */
42459e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
4246df2d5ae4STejun Heo }
42476029a918STejun Heo 
4248f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
alloc_unbound_pwq(struct workqueue_struct * wq,const struct workqueue_attrs * attrs)4249f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
4250f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
4251f147f29eSTejun Heo {
4252f147f29eSTejun Heo 	struct worker_pool *pool;
4253f147f29eSTejun Heo 	struct pool_workqueue *pwq;
4254f147f29eSTejun Heo 
4255f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
4256f147f29eSTejun Heo 
4257f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
4258f147f29eSTejun Heo 	if (!pool)
4259f147f29eSTejun Heo 		return NULL;
4260f147f29eSTejun Heo 
4261e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
4262f147f29eSTejun Heo 	if (!pwq) {
4263f147f29eSTejun Heo 		put_unbound_pool(pool);
4264f147f29eSTejun Heo 		return NULL;
4265f147f29eSTejun Heo 	}
4266f147f29eSTejun Heo 
4267f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
4268f147f29eSTejun Heo 	return pwq;
4269d2c1d404STejun Heo }
4270d2c1d404STejun Heo 
42714c16bd32STejun Heo /**
4272fef59c9cSTejun Heo  * wq_calc_pod_cpumask - calculate a wq_attrs' cpumask for a pod
4273042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
427484193c07STejun Heo  * @cpu: the target CPU
42754c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
42764c16bd32STejun Heo  *
4277fef59c9cSTejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @pod. If
4278fef59c9cSTejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during calculation.
42799546b29eSTejun Heo  * The result is stored in @attrs->__pod_cpumask.
42804c16bd32STejun Heo  *
4281fef59c9cSTejun Heo  * If pod affinity is not enabled, @attrs->cpumask is always used. If enabled
4282fef59c9cSTejun Heo  * and @pod has online CPUs requested by @attrs, the returned cpumask is the
4283fef59c9cSTejun Heo  * intersection of the possible CPUs of @pod and @attrs->cpumask.
42844c16bd32STejun Heo  *
4285fef59c9cSTejun Heo  * The caller is responsible for ensuring that the cpumask of @pod stays stable.
42864c16bd32STejun Heo  */
wq_calc_pod_cpumask(struct workqueue_attrs * attrs,int cpu,int cpu_going_down)42879546b29eSTejun Heo static void wq_calc_pod_cpumask(struct workqueue_attrs *attrs, int cpu,
42889546b29eSTejun Heo 				int cpu_going_down)
42894c16bd32STejun Heo {
429084193c07STejun Heo 	const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
429184193c07STejun Heo 	int pod = pt->cpu_pod[cpu];
42924c16bd32STejun Heo 
4293fef59c9cSTejun Heo 	/* does @pod have any online CPUs @attrs wants? */
42949546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, pt->pod_cpus[pod], attrs->cpumask);
42959546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, attrs->__pod_cpumask, cpu_online_mask);
42964c16bd32STejun Heo 	if (cpu_going_down >= 0)
42979546b29eSTejun Heo 		cpumask_clear_cpu(cpu_going_down, attrs->__pod_cpumask);
42984c16bd32STejun Heo 
42999546b29eSTejun Heo 	if (cpumask_empty(attrs->__pod_cpumask)) {
43009546b29eSTejun Heo 		cpumask_copy(attrs->__pod_cpumask, attrs->cpumask);
430184193c07STejun Heo 		return;
430284193c07STejun Heo 	}
43034c16bd32STejun Heo 
4304fef59c9cSTejun Heo 	/* yeap, return possible CPUs in @pod that @attrs wants */
43059546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, attrs->cpumask, pt->pod_cpus[pod]);
43061ad0f0a7SMichael Bringmann 
43079546b29eSTejun Heo 	if (cpumask_empty(attrs->__pod_cpumask))
43081ad0f0a7SMichael Bringmann 		pr_warn_once("WARNING: workqueue cpumask: online intersect > "
43091ad0f0a7SMichael Bringmann 				"possible intersect\n");
43104c16bd32STejun Heo }
43114c16bd32STejun Heo 
4312f3c11cb2SGreg Kroah-Hartman /* install @pwq into @wq's cpu_pwq and return the old pwq */
install_unbound_pwq(struct workqueue_struct * wq,int cpu,struct pool_workqueue * pwq)4313636b927eSTejun Heo static struct pool_workqueue *install_unbound_pwq(struct workqueue_struct *wq,
4314636b927eSTejun Heo 					int cpu, struct pool_workqueue *pwq)
43151befcf30STejun Heo {
43161befcf30STejun Heo 	struct pool_workqueue *old_pwq;
43171befcf30STejun Heo 
43185b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
43191befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
43201befcf30STejun Heo 
43211befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
43221befcf30STejun Heo 	link_pwq(pwq);
43231befcf30STejun Heo 
4324f3c11cb2SGreg Kroah-Hartman 	old_pwq = rcu_access_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu));
4325f3c11cb2SGreg Kroah-Hartman 	rcu_assign_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu), pwq);
43261befcf30STejun Heo 	return old_pwq;
43271befcf30STejun Heo }
43281befcf30STejun Heo 
43292d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
43302d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
43312d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
43322d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
4333042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
43342d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
43352d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
43362d5f0764SLai Jiangshan };
43372d5f0764SLai Jiangshan 
43382d5f0764SLai Jiangshan /* free the resources after success or abort */
apply_wqattrs_cleanup(struct apply_wqattrs_ctx * ctx)43392d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
43402d5f0764SLai Jiangshan {
43412d5f0764SLai Jiangshan 	if (ctx) {
4342636b927eSTejun Heo 		int cpu;
43432d5f0764SLai Jiangshan 
4344636b927eSTejun Heo 		for_each_possible_cpu(cpu)
4345636b927eSTejun Heo 			put_pwq_unlocked(ctx->pwq_tbl[cpu]);
43462d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
43472d5f0764SLai Jiangshan 
43482d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
43492d5f0764SLai Jiangshan 
43502d5f0764SLai Jiangshan 		kfree(ctx);
43512d5f0764SLai Jiangshan 	}
43522d5f0764SLai Jiangshan }
43532d5f0764SLai Jiangshan 
43542d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
43552d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
apply_wqattrs_prepare(struct workqueue_struct * wq,const struct workqueue_attrs * attrs,const cpumask_var_t unbound_cpumask)43562d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
435799c621efSLai Jiangshan 		      const struct workqueue_attrs *attrs,
435899c621efSLai Jiangshan 		      const cpumask_var_t unbound_cpumask)
43592d5f0764SLai Jiangshan {
43602d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
43619546b29eSTejun Heo 	struct workqueue_attrs *new_attrs;
4362636b927eSTejun Heo 	int cpu;
43632d5f0764SLai Jiangshan 
43642d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
43652d5f0764SLai Jiangshan 
436684193c07STejun Heo 	if (WARN_ON(attrs->affn_scope < 0 ||
436784193c07STejun Heo 		    attrs->affn_scope >= WQ_AFFN_NR_TYPES))
436884193c07STejun Heo 		return ERR_PTR(-EINVAL);
436984193c07STejun Heo 
4370636b927eSTejun Heo 	ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_cpu_ids), GFP_KERNEL);
43712d5f0764SLai Jiangshan 
4372be69d00dSThomas Gleixner 	new_attrs = alloc_workqueue_attrs();
43739546b29eSTejun Heo 	if (!ctx || !new_attrs)
43742d5f0764SLai Jiangshan 		goto out_free;
43752d5f0764SLai Jiangshan 
4376042f7df1SLai Jiangshan 	/*
43772d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
43782d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
43792d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
43802d5f0764SLai Jiangshan 	 */
43810f36ee24STejun Heo 	copy_workqueue_attrs(new_attrs, attrs);
43820f36ee24STejun Heo 	wqattrs_actualize_cpumask(new_attrs, unbound_cpumask);
43839546b29eSTejun Heo 	cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
43842d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
43852d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
43862d5f0764SLai Jiangshan 		goto out_free;
43872d5f0764SLai Jiangshan 
4388636b927eSTejun Heo 	for_each_possible_cpu(cpu) {
4389af73f5c9STejun Heo 		if (new_attrs->ordered) {
43902d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
4391636b927eSTejun Heo 			ctx->pwq_tbl[cpu] = ctx->dfl_pwq;
4392636b927eSTejun Heo 		} else {
43939546b29eSTejun Heo 			wq_calc_pod_cpumask(new_attrs, cpu, -1);
43949546b29eSTejun Heo 			ctx->pwq_tbl[cpu] = alloc_unbound_pwq(wq, new_attrs);
4395636b927eSTejun Heo 			if (!ctx->pwq_tbl[cpu])
4396636b927eSTejun Heo 				goto out_free;
43972d5f0764SLai Jiangshan 		}
43982d5f0764SLai Jiangshan 	}
43992d5f0764SLai Jiangshan 
4400042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
4401042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
4402042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
44039546b29eSTejun Heo 	cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
44042d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
4405042f7df1SLai Jiangshan 
44062d5f0764SLai Jiangshan 	ctx->wq = wq;
44072d5f0764SLai Jiangshan 	return ctx;
44082d5f0764SLai Jiangshan 
44092d5f0764SLai Jiangshan out_free:
44102d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
44112d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
441284193c07STejun Heo 	return ERR_PTR(-ENOMEM);
44132d5f0764SLai Jiangshan }
44142d5f0764SLai Jiangshan 
44152d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
apply_wqattrs_commit(struct apply_wqattrs_ctx * ctx)44162d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
44172d5f0764SLai Jiangshan {
4418636b927eSTejun Heo 	int cpu;
44192d5f0764SLai Jiangshan 
44202d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
44212d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
44222d5f0764SLai Jiangshan 
44232d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
44242d5f0764SLai Jiangshan 
4425f3c11cb2SGreg Kroah-Hartman 	/* save the previous pwq and install the new one */
4426636b927eSTejun Heo 	for_each_possible_cpu(cpu)
4427636b927eSTejun Heo 		ctx->pwq_tbl[cpu] = install_unbound_pwq(ctx->wq, cpu,
4428636b927eSTejun Heo 							ctx->pwq_tbl[cpu]);
4429f3c11cb2SGreg Kroah-Hartman 
4430f3c11cb2SGreg Kroah-Hartman 	/* @dfl_pwq might not have been used, ensure it's linked */
4431f3c11cb2SGreg Kroah-Hartman 	link_pwq(ctx->dfl_pwq);
4432f3c11cb2SGreg Kroah-Hartman 	swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
44332d5f0764SLai Jiangshan 
44342d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
44352d5f0764SLai Jiangshan }
44362d5f0764SLai Jiangshan 
apply_wqattrs_lock(void)4437a0111cf6SLai Jiangshan static void apply_wqattrs_lock(void)
4438a0111cf6SLai Jiangshan {
4439a0111cf6SLai Jiangshan 	/* CPUs should stay stable across pwq creations and installations */
4440ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4441a0111cf6SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4442a0111cf6SLai Jiangshan }
4443a0111cf6SLai Jiangshan 
apply_wqattrs_unlock(void)4444a0111cf6SLai Jiangshan static void apply_wqattrs_unlock(void)
4445a0111cf6SLai Jiangshan {
4446a0111cf6SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4447ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4448a0111cf6SLai Jiangshan }
4449a0111cf6SLai Jiangshan 
apply_workqueue_attrs_locked(struct workqueue_struct * wq,const struct workqueue_attrs * attrs)4450a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4451a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
4452a0111cf6SLai Jiangshan {
4453a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
4454a0111cf6SLai Jiangshan 
4455a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
4456a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4457a0111cf6SLai Jiangshan 		return -EINVAL;
4458a0111cf6SLai Jiangshan 
4459a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
44600a94efb5STejun Heo 	if (!list_empty(&wq->pwqs)) {
44610a94efb5STejun Heo 		if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4462a0111cf6SLai Jiangshan 			return -EINVAL;
4463a0111cf6SLai Jiangshan 
44640a94efb5STejun Heo 		wq->flags &= ~__WQ_ORDERED;
44650a94efb5STejun Heo 	}
44660a94efb5STejun Heo 
446799c621efSLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
446884193c07STejun Heo 	if (IS_ERR(ctx))
446984193c07STejun Heo 		return PTR_ERR(ctx);
4470a0111cf6SLai Jiangshan 
4471a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
4472a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
4473a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
4474a0111cf6SLai Jiangshan 
44756201171eSwanghaibin 	return 0;
4476a0111cf6SLai Jiangshan }
4477a0111cf6SLai Jiangshan 
44789e8cd2f5STejun Heo /**
44799e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
44809e8cd2f5STejun Heo  * @wq: the target workqueue
44819e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
44829e8cd2f5STejun Heo  *
4483fef59c9cSTejun Heo  * Apply @attrs to an unbound workqueue @wq. Unless disabled, this function maps
4484fef59c9cSTejun Heo  * a separate pwq to each CPU pod with possibles CPUs in @attrs->cpumask so that
4485fef59c9cSTejun Heo  * work items are affine to the pod it was issued on. Older pwqs are released as
4486fef59c9cSTejun Heo  * in-flight work items finish. Note that a work item which repeatedly requeues
4487fef59c9cSTejun Heo  * itself back-to-back will stay on its current pwq.
44889e8cd2f5STejun Heo  *
4489d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
4490d185af30SYacine Belkadi  *
4491ffd8bea8SSebastian Andrzej Siewior  * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
4492509b3204SDaniel Jordan  *
4493d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
44949e8cd2f5STejun Heo  */
apply_workqueue_attrs(struct workqueue_struct * wq,const struct workqueue_attrs * attrs)4495513c98d0SDaniel Jordan int apply_workqueue_attrs(struct workqueue_struct *wq,
44969e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
44979e8cd2f5STejun Heo {
4498a0111cf6SLai Jiangshan 	int ret;
44999e8cd2f5STejun Heo 
4500509b3204SDaniel Jordan 	lockdep_assert_cpus_held();
4501509b3204SDaniel Jordan 
4502509b3204SDaniel Jordan 	mutex_lock(&wq_pool_mutex);
4503a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
4504509b3204SDaniel Jordan 	mutex_unlock(&wq_pool_mutex);
45052d5f0764SLai Jiangshan 
45062d5f0764SLai Jiangshan 	return ret;
45079e8cd2f5STejun Heo }
45089e8cd2f5STejun Heo 
45094c16bd32STejun Heo /**
4510fef59c9cSTejun Heo  * wq_update_pod - update pod affinity of a wq for CPU hot[un]plug
45114c16bd32STejun Heo  * @wq: the target workqueue
45124cbfd3deSTejun Heo  * @cpu: the CPU to update pool association for
45134cbfd3deSTejun Heo  * @hotplug_cpu: the CPU coming up or going down
45144c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
45154c16bd32STejun Heo  *
45164c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
4517fef59c9cSTejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update pod affinity of
45184c16bd32STejun Heo  * @wq accordingly.
45194c16bd32STejun Heo  *
45204c16bd32STejun Heo  *
4521fef59c9cSTejun Heo  * If pod affinity can't be adjusted due to memory allocation failure, it falls
4522fef59c9cSTejun Heo  * back to @wq->dfl_pwq which may not be optimal but is always correct.
4523fef59c9cSTejun Heo  *
4524fef59c9cSTejun Heo  * Note that when the last allowed CPU of a pod goes offline for a workqueue
4525fef59c9cSTejun Heo  * with a cpumask spanning multiple pods, the workers which were already
4526fef59c9cSTejun Heo  * executing the work items for the workqueue will lose their CPU affinity and
4527fef59c9cSTejun Heo  * may execute on any CPU. This is similar to how per-cpu workqueues behave on
4528fef59c9cSTejun Heo  * CPU_DOWN. If a workqueue user wants strict affinity, it's the user's
4529fef59c9cSTejun Heo  * responsibility to flush the work item from CPU_DOWN_PREPARE.
45304c16bd32STejun Heo  */
wq_update_pod(struct workqueue_struct * wq,int cpu,int hotplug_cpu,bool online)4531fef59c9cSTejun Heo static void wq_update_pod(struct workqueue_struct *wq, int cpu,
45324cbfd3deSTejun Heo 			  int hotplug_cpu, bool online)
45334c16bd32STejun Heo {
45344cbfd3deSTejun Heo 	int off_cpu = online ? -1 : hotplug_cpu;
45354c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
45364c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
45374c16bd32STejun Heo 
45384c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
45394c16bd32STejun Heo 
454084193c07STejun Heo 	if (!(wq->flags & WQ_UNBOUND) || wq->unbound_attrs->ordered)
45414c16bd32STejun Heo 		return;
45424c16bd32STejun Heo 
45434c16bd32STejun Heo 	/*
45444c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
45454c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
45464c16bd32STejun Heo 	 * CPU hotplug exclusion.
45474c16bd32STejun Heo 	 */
4548fef59c9cSTejun Heo 	target_attrs = wq_update_pod_attrs_buf;
45494c16bd32STejun Heo 
45504c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
45510f36ee24STejun Heo 	wqattrs_actualize_cpumask(target_attrs, wq_unbound_cpumask);
45524c16bd32STejun Heo 
4553636b927eSTejun Heo 	/* nothing to do if the target cpumask matches the current pwq */
45549546b29eSTejun Heo 	wq_calc_pod_cpumask(target_attrs, cpu, off_cpu);
4555f3c11cb2SGreg Kroah-Hartman 	pwq = rcu_dereference_protected(*per_cpu_ptr(wq->cpu_pwq, cpu),
4556f3c11cb2SGreg Kroah-Hartman 					lockdep_is_held(&wq_pool_mutex));
4557f3c11cb2SGreg Kroah-Hartman 	if (wqattrs_equal(target_attrs, pwq->pool->attrs))
4558f7142ed4SLai Jiangshan 		return;
45594c16bd32STejun Heo 
45604c16bd32STejun Heo 	/* create a new pwq */
45614c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
45624c16bd32STejun Heo 	if (!pwq) {
4563fef59c9cSTejun Heo 		pr_warn("workqueue: allocation failed while updating CPU pod affinity of \"%s\"\n",
45644c16bd32STejun Heo 			wq->name);
456577f300b1SDaeseok Youn 		goto use_dfl_pwq;
45664c16bd32STejun Heo 	}
45674c16bd32STejun Heo 
4568f7142ed4SLai Jiangshan 	/* Install the new pwq. */
45694c16bd32STejun Heo 	mutex_lock(&wq->mutex);
4570636b927eSTejun Heo 	old_pwq = install_unbound_pwq(wq, cpu, pwq);
45714c16bd32STejun Heo 	goto out_unlock;
45724c16bd32STejun Heo 
45734c16bd32STejun Heo use_dfl_pwq:
4574f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
4575f3c11cb2SGreg Kroah-Hartman 	raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
4576f3c11cb2SGreg Kroah-Hartman 	get_pwq(wq->dfl_pwq);
4577f3c11cb2SGreg Kroah-Hartman 	raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
4578f3c11cb2SGreg Kroah-Hartman 	old_pwq = install_unbound_pwq(wq, cpu, wq->dfl_pwq);
45794c16bd32STejun Heo out_unlock:
45804c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
45814c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
45824c16bd32STejun Heo }
45834c16bd32STejun Heo 
alloc_and_link_pwqs(struct workqueue_struct * wq)458430cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
45851da177e4SLinus Torvalds {
458649e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
45878a2b7538STejun Heo 	int cpu, ret;
4588e1d8aa9fSFrederic Weisbecker 
4589687a9aa5STejun Heo 	wq->cpu_pwq = alloc_percpu(struct pool_workqueue *);
4590ee1ceef7STejun Heo 	if (!wq->cpu_pwq)
4591687a9aa5STejun Heo 		goto enomem;
459230cdf249STejun Heo 
4593636b927eSTejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
459430cdf249STejun Heo 		for_each_possible_cpu(cpu) {
4595687a9aa5STejun Heo 			struct pool_workqueue **pwq_p =
4596ee1ceef7STejun Heo 				per_cpu_ptr(wq->cpu_pwq, cpu);
4597687a9aa5STejun Heo 			struct worker_pool *pool =
4598687a9aa5STejun Heo 				&(per_cpu_ptr(cpu_worker_pools, cpu)[highpri]);
459930cdf249STejun Heo 
4600687a9aa5STejun Heo 			*pwq_p = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL,
4601687a9aa5STejun Heo 						       pool->node);
4602687a9aa5STejun Heo 			if (!*pwq_p)
4603687a9aa5STejun Heo 				goto enomem;
4604687a9aa5STejun Heo 
4605687a9aa5STejun Heo 			init_pwq(*pwq_p, wq, pool);
4606f147f29eSTejun Heo 
4607f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
4608687a9aa5STejun Heo 			link_pwq(*pwq_p);
4609f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
461030cdf249STejun Heo 		}
461130cdf249STejun Heo 		return 0;
4612509b3204SDaniel Jordan 	}
4613509b3204SDaniel Jordan 
4614ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
4615509b3204SDaniel Jordan 	if (wq->flags & __WQ_ORDERED) {
46168a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
46178a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
4618f3c11cb2SGreg Kroah-Hartman 		WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
4619f3c11cb2SGreg Kroah-Hartman 			      wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
46208a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
46219e8cd2f5STejun Heo 	} else {
4622509b3204SDaniel Jordan 		ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
46239e8cd2f5STejun Heo 	}
4624ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4625509b3204SDaniel Jordan 
462664344553SZqiang 	/* for unbound pwq, flush the pwq_release_worker ensures that the
462764344553SZqiang 	 * pwq_release_workfn() completes before calling kfree(wq).
462864344553SZqiang 	 */
462964344553SZqiang 	if (ret)
463064344553SZqiang 		kthread_flush_worker(pwq_release_worker);
463164344553SZqiang 
4632509b3204SDaniel Jordan 	return ret;
4633687a9aa5STejun Heo 
4634687a9aa5STejun Heo enomem:
4635687a9aa5STejun Heo 	if (wq->cpu_pwq) {
46367b42f401SZqiang 		for_each_possible_cpu(cpu) {
46377b42f401SZqiang 			struct pool_workqueue *pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
46387b42f401SZqiang 
46397b42f401SZqiang 			if (pwq)
46407b42f401SZqiang 				kmem_cache_free(pwq_cache, pwq);
46417b42f401SZqiang 		}
4642687a9aa5STejun Heo 		free_percpu(wq->cpu_pwq);
4643687a9aa5STejun Heo 		wq->cpu_pwq = NULL;
4644687a9aa5STejun Heo 	}
4645687a9aa5STejun Heo 	return -ENOMEM;
46460f900049STejun Heo }
46470f900049STejun Heo 
wq_clamp_max_active(int max_active,unsigned int flags,const char * name)4648f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
4649f3421797STejun Heo 			       const char *name)
4650b71ab8c2STejun Heo {
4651636b927eSTejun Heo 	if (max_active < 1 || max_active > WQ_MAX_ACTIVE)
4652044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4653636b927eSTejun Heo 			max_active, name, 1, WQ_MAX_ACTIVE);
4654b71ab8c2STejun Heo 
4655636b927eSTejun Heo 	return clamp_val(max_active, 1, WQ_MAX_ACTIVE);
4656b71ab8c2STejun Heo }
4657b71ab8c2STejun Heo 
4658983c7515STejun Heo /*
4659983c7515STejun Heo  * Workqueues which may be used during memory reclaim should have a rescuer
4660983c7515STejun Heo  * to guarantee forward progress.
4661983c7515STejun Heo  */
init_rescuer(struct workqueue_struct * wq)4662983c7515STejun Heo static int init_rescuer(struct workqueue_struct *wq)
4663983c7515STejun Heo {
4664983c7515STejun Heo 	struct worker *rescuer;
4665b92b36eaSDan Carpenter 	int ret;
4666983c7515STejun Heo 
4667983c7515STejun Heo 	if (!(wq->flags & WQ_MEM_RECLAIM))
4668983c7515STejun Heo 		return 0;
4669983c7515STejun Heo 
4670983c7515STejun Heo 	rescuer = alloc_worker(NUMA_NO_NODE);
46714c0736a7SPetr Mladek 	if (!rescuer) {
46724c0736a7SPetr Mladek 		pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
46734c0736a7SPetr Mladek 		       wq->name);
4674983c7515STejun Heo 		return -ENOMEM;
46754c0736a7SPetr Mladek 	}
4676983c7515STejun Heo 
4677983c7515STejun Heo 	rescuer->rescue_wq = wq;
4678b6a46f72SAaron Tomlin 	rescuer->task = kthread_create(rescuer_thread, rescuer, "kworker/R-%s", wq->name);
4679f187b697SSean Fu 	if (IS_ERR(rescuer->task)) {
4680b92b36eaSDan Carpenter 		ret = PTR_ERR(rescuer->task);
46814c0736a7SPetr Mladek 		pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
46824c0736a7SPetr Mladek 		       wq->name, ERR_PTR(ret));
4683983c7515STejun Heo 		kfree(rescuer);
4684b92b36eaSDan Carpenter 		return ret;
4685983c7515STejun Heo 	}
4686983c7515STejun Heo 
4687983c7515STejun Heo 	wq->rescuer = rescuer;
4688983c7515STejun Heo 	kthread_bind_mask(rescuer->task, cpu_possible_mask);
4689983c7515STejun Heo 	wake_up_process(rescuer->task);
4690983c7515STejun Heo 
4691983c7515STejun Heo 	return 0;
4692983c7515STejun Heo }
4693983c7515STejun Heo 
4694a2775bbcSMathieu Malaterre __printf(1, 4)
alloc_workqueue(const char * fmt,unsigned int flags,int max_active,...)4695669de8bdSBart Van Assche struct workqueue_struct *alloc_workqueue(const char *fmt,
469697e37d7bSTejun Heo 					 unsigned int flags,
4697669de8bdSBart Van Assche 					 int max_active, ...)
46983af24433SOleg Nesterov {
4699ecf6881fSTejun Heo 	va_list args;
47003af24433SOleg Nesterov 	struct workqueue_struct *wq;
4701d8354f26SGreg Kroah-Hartman 	struct pool_workqueue *pwq;
4702b196be89STejun Heo 
47035c0338c6STejun Heo 	/*
4704fef59c9cSTejun Heo 	 * Unbound && max_active == 1 used to imply ordered, which is no longer
4705fef59c9cSTejun Heo 	 * the case on many machines due to per-pod pools. While
47065c0338c6STejun Heo 	 * alloc_ordered_workqueue() is the right way to create an ordered
4707fef59c9cSTejun Heo 	 * workqueue, keep the previous behavior to avoid subtle breakages.
47085c0338c6STejun Heo 	 */
47095c0338c6STejun Heo 	if ((flags & WQ_UNBOUND) && max_active == 1)
47105c0338c6STejun Heo 		flags |= __WQ_ORDERED;
47115c0338c6STejun Heo 
4712cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
4713cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4714cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
4715cee22a15SViresh Kumar 
4716ecf6881fSTejun Heo 	/* allocate wq and format name */
4717bfb429f3SGreg Kroah-Hartman 	wq = kzalloc(sizeof(*wq), GFP_KERNEL);
4718b196be89STejun Heo 	if (!wq)
4719d2c1d404STejun Heo 		return NULL;
4720b196be89STejun Heo 
47216029a918STejun Heo 	if (flags & WQ_UNBOUND) {
4722be69d00dSThomas Gleixner 		wq->unbound_attrs = alloc_workqueue_attrs();
47236029a918STejun Heo 		if (!wq->unbound_attrs)
47246029a918STejun Heo 			goto err_free_wq;
47256029a918STejun Heo 	}
47266029a918STejun Heo 
4727669de8bdSBart Van Assche 	va_start(args, max_active);
4728a99d7274SGreg Kroah-Hartman 	vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4729b196be89STejun Heo 	va_end(args);
47303af24433SOleg Nesterov 
4731d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
4732b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
47333af24433SOleg Nesterov 
4734b196be89STejun Heo 	/* init wq */
473597e37d7bSTejun Heo 	wq->flags = flags;
47366741dd3fSGreg Kroah-Hartman 	wq->saved_max_active = max_active;
47373c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
4738112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
473930cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
474073f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
474173f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
4742493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
47433af24433SOleg Nesterov 
4744669de8bdSBart Van Assche 	wq_init_lockdep(wq);
4745cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
47463af24433SOleg Nesterov 
4747b522229aSTejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
4748bfb429f3SGreg Kroah-Hartman 		goto err_unreg_lockdep;
47491537663fSTejun Heo 
475040c17f75STejun Heo 	if (wq_online && init_rescuer(wq) < 0)
4751d2c1d404STejun Heo 		goto err_destroy;
4752e22bee78STejun Heo 
4753226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4754226223abSTejun Heo 		goto err_destroy;
4755226223abSTejun Heo 
47566af8bf3dSOleg Nesterov 	/*
475768e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
475868e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
475968e13a67SLai Jiangshan 	 * list.
47606af8bf3dSOleg Nesterov 	 */
476168e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4762a0a1a5fdSTejun Heo 
4763a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4764d8354f26SGreg Kroah-Hartman 	for_each_pwq(pwq, wq)
4765d8354f26SGreg Kroah-Hartman 		pwq_adjust_max_active(pwq);
4766a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4767a0a1a5fdSTejun Heo 
4768e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
4769a0a1a5fdSTejun Heo 
477068e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
47713af24433SOleg Nesterov 
47723af24433SOleg Nesterov 	return wq;
4773d2c1d404STejun Heo 
477482efcab3SBart Van Assche err_unreg_lockdep:
4775009bb421SBart Van Assche 	wq_unregister_lockdep(wq);
4776009bb421SBart Van Assche 	wq_free_lockdep(wq);
477782efcab3SBart Van Assche err_free_wq:
47786029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
47794690c4abSTejun Heo 	kfree(wq);
4780d2c1d404STejun Heo 	return NULL;
4781d2c1d404STejun Heo err_destroy:
4782d2c1d404STejun Heo 	destroy_workqueue(wq);
47834690c4abSTejun Heo 	return NULL;
47841da177e4SLinus Torvalds }
4785669de8bdSBart Van Assche EXPORT_SYMBOL_GPL(alloc_workqueue);
47861da177e4SLinus Torvalds 
pwq_busy(struct pool_workqueue * pwq)4787c29eb853STejun Heo static bool pwq_busy(struct pool_workqueue *pwq)
4788c29eb853STejun Heo {
4789c29eb853STejun Heo 	int i;
4790c29eb853STejun Heo 
4791c29eb853STejun Heo 	for (i = 0; i < WORK_NR_COLORS; i++)
4792c29eb853STejun Heo 		if (pwq->nr_in_flight[i])
4793c29eb853STejun Heo 			return true;
4794c29eb853STejun Heo 
4795f3c11cb2SGreg Kroah-Hartman 	if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4796c29eb853STejun Heo 		return true;
479735bf38ddSGreg Kroah-Hartman 	if (pwq->nr_active || !list_empty(&pwq->inactive_works))
4798c29eb853STejun Heo 		return true;
4799c29eb853STejun Heo 
4800c29eb853STejun Heo 	return false;
4801c29eb853STejun Heo }
4802c29eb853STejun Heo 
48033af24433SOleg Nesterov /**
48043af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
48053af24433SOleg Nesterov  * @wq: target workqueue
48063af24433SOleg Nesterov  *
48073af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
48083af24433SOleg Nesterov  */
destroy_workqueue(struct workqueue_struct * wq)48093af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
48103af24433SOleg Nesterov {
481149e3cf44STejun Heo 	struct pool_workqueue *pwq;
4812636b927eSTejun Heo 	int cpu;
48133af24433SOleg Nesterov 
4814def98c84STejun Heo 	/*
4815def98c84STejun Heo 	 * Remove it from sysfs first so that sanity check failure doesn't
4816def98c84STejun Heo 	 * lead to sysfs name conflicts.
4817def98c84STejun Heo 	 */
4818def98c84STejun Heo 	workqueue_sysfs_unregister(wq);
4819def98c84STejun Heo 
482033e3f0a3SRichard Clark 	/* mark the workqueue destruction is in progress */
482133e3f0a3SRichard Clark 	mutex_lock(&wq->mutex);
482233e3f0a3SRichard Clark 	wq->flags |= __WQ_DESTROYING;
482333e3f0a3SRichard Clark 	mutex_unlock(&wq->mutex);
482433e3f0a3SRichard Clark 
48259c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
48269c5a2ba7STejun Heo 	drain_workqueue(wq);
4827c8efcc25STejun Heo 
4828def98c84STejun Heo 	/* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4829def98c84STejun Heo 	if (wq->rescuer) {
4830def98c84STejun Heo 		struct worker *rescuer = wq->rescuer;
4831def98c84STejun Heo 
4832def98c84STejun Heo 		/* this prevents new queueing */
4833a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
4834def98c84STejun Heo 		wq->rescuer = NULL;
4835a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
4836def98c84STejun Heo 
4837def98c84STejun Heo 		/* rescuer will empty maydays list before exiting */
4838def98c84STejun Heo 		kthread_stop(rescuer->task);
48398efe1223STejun Heo 		kfree(rescuer);
4840def98c84STejun Heo 	}
4841def98c84STejun Heo 
4842c29eb853STejun Heo 	/*
4843c29eb853STejun Heo 	 * Sanity checks - grab all the locks so that we wait for all
4844c29eb853STejun Heo 	 * in-flight operations which may do put_pwq().
4845c29eb853STejun Heo 	 */
4846c29eb853STejun Heo 	mutex_lock(&wq_pool_mutex);
4847b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
484849e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
4849a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
4850c29eb853STejun Heo 		if (WARN_ON(pwq_busy(pwq))) {
48511d9a6159SKefeng Wang 			pr_warn("%s: %s has the following busy pwq\n",
4852e66b39afSTejun Heo 				__func__, wq->name);
4853c29eb853STejun Heo 			show_pwq(pwq);
4854a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pwq->pool->lock);
4855b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
4856c29eb853STejun Heo 			mutex_unlock(&wq_pool_mutex);
485755df0933SImran Khan 			show_one_workqueue(wq);
48586183c009STejun Heo 			return;
485976af4d93STejun Heo 		}
4860a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
486176af4d93STejun Heo 	}
4862b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
48636183c009STejun Heo 
4864a0a1a5fdSTejun Heo 	/*
4865a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
4866a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
4867a0a1a5fdSTejun Heo 	 */
4868e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
486968e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
48703af24433SOleg Nesterov 
48718864b4e5STejun Heo 	/*
4872636b927eSTejun Heo 	 * We're the sole accessor of @wq. Directly access cpu_pwq and dfl_pwq
4873636b927eSTejun Heo 	 * to put the base refs. @wq will be auto-destroyed from the last
4874636b927eSTejun Heo 	 * pwq_put. RCU read lock prevents @wq from going away from under us.
48758864b4e5STejun Heo 	 */
4876636b927eSTejun Heo 	rcu_read_lock();
4877636b927eSTejun Heo 
4878636b927eSTejun Heo 	for_each_possible_cpu(cpu) {
4879f3c11cb2SGreg Kroah-Hartman 		pwq = rcu_access_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu));
4880f3c11cb2SGreg Kroah-Hartman 		RCU_INIT_POINTER(*per_cpu_ptr(wq->cpu_pwq, cpu), NULL);
4881f3c11cb2SGreg Kroah-Hartman 		put_pwq_unlocked(pwq);
48824c16bd32STejun Heo 	}
48834c16bd32STejun Heo 
4884f3c11cb2SGreg Kroah-Hartman 	put_pwq_unlocked(wq->dfl_pwq);
4885f3c11cb2SGreg Kroah-Hartman 	wq->dfl_pwq = NULL;
4886636b927eSTejun Heo 
4887636b927eSTejun Heo 	rcu_read_unlock();
48883af24433SOleg Nesterov }
48893af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
48903af24433SOleg Nesterov 
4891dcd989cbSTejun Heo /**
4892dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
4893dcd989cbSTejun Heo  * @wq: target workqueue
4894dcd989cbSTejun Heo  * @max_active: new max_active value.
4895dcd989cbSTejun Heo  *
48966741dd3fSGreg Kroah-Hartman  * Set max_active of @wq to @max_active.
4897dcd989cbSTejun Heo  *
4898dcd989cbSTejun Heo  * CONTEXT:
4899dcd989cbSTejun Heo  * Don't call from IRQ context.
4900dcd989cbSTejun Heo  */
workqueue_set_max_active(struct workqueue_struct * wq,int max_active)4901dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4902dcd989cbSTejun Heo {
4903d8354f26SGreg Kroah-Hartman 	struct pool_workqueue *pwq;
4904d8354f26SGreg Kroah-Hartman 
49058719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
49060a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
49078719dceaSTejun Heo 		return;
49088719dceaSTejun Heo 
4909f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4910dcd989cbSTejun Heo 
4911a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4912dcd989cbSTejun Heo 
49130a94efb5STejun Heo 	wq->flags &= ~__WQ_ORDERED;
4914dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4915d8354f26SGreg Kroah-Hartman 
4916d8354f26SGreg Kroah-Hartman 	for_each_pwq(pwq, wq)
4917d8354f26SGreg Kroah-Hartman 		pwq_adjust_max_active(pwq);
4918dcd989cbSTejun Heo 
4919a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4920dcd989cbSTejun Heo }
4921dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4922dcd989cbSTejun Heo 
4923dcd989cbSTejun Heo /**
492427d4ee03SLukas Wunner  * current_work - retrieve %current task's work struct
492527d4ee03SLukas Wunner  *
492627d4ee03SLukas Wunner  * Determine if %current task is a workqueue worker and what it's working on.
492727d4ee03SLukas Wunner  * Useful to find out the context that the %current task is running in.
492827d4ee03SLukas Wunner  *
492927d4ee03SLukas Wunner  * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
493027d4ee03SLukas Wunner  */
current_work(void)493127d4ee03SLukas Wunner struct work_struct *current_work(void)
493227d4ee03SLukas Wunner {
493327d4ee03SLukas Wunner 	struct worker *worker = current_wq_worker();
493427d4ee03SLukas Wunner 
493527d4ee03SLukas Wunner 	return worker ? worker->current_work : NULL;
493627d4ee03SLukas Wunner }
493727d4ee03SLukas Wunner EXPORT_SYMBOL(current_work);
493827d4ee03SLukas Wunner 
493927d4ee03SLukas Wunner /**
4940e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4941e6267616STejun Heo  *
4942e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4943e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4944d185af30SYacine Belkadi  *
4945d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
4946e6267616STejun Heo  */
current_is_workqueue_rescuer(void)4947e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4948e6267616STejun Heo {
4949e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4950e6267616STejun Heo 
49516a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
4952e6267616STejun Heo }
4953e6267616STejun Heo 
4954e6267616STejun Heo /**
4955dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4956dcd989cbSTejun Heo  * @cpu: CPU in question
4957dcd989cbSTejun Heo  * @wq: target workqueue
4958dcd989cbSTejun Heo  *
4959dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4960dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4961dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4962dcd989cbSTejun Heo  *
4963d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4964636b927eSTejun Heo  *
4965636b927eSTejun Heo  * With the exception of ordered workqueues, all workqueues have per-cpu
4966636b927eSTejun Heo  * pool_workqueues, each with its own congested state. A workqueue being
4967636b927eSTejun Heo  * congested on one CPU doesn't mean that the workqueue is contested on any
4968636b927eSTejun Heo  * other CPUs.
4969d3251859STejun Heo  *
4970d185af30SYacine Belkadi  * Return:
4971dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4972dcd989cbSTejun Heo  */
workqueue_congested(int cpu,struct workqueue_struct * wq)4973d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4974dcd989cbSTejun Heo {
49757fb98ea7STejun Heo 	struct pool_workqueue *pwq;
497676af4d93STejun Heo 	bool ret;
497776af4d93STejun Heo 
497824acfb71SThomas Gleixner 	rcu_read_lock();
497924acfb71SThomas Gleixner 	preempt_disable();
49807fb98ea7STejun Heo 
4981d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
4982d3251859STejun Heo 		cpu = smp_processor_id();
4983d3251859STejun Heo 
4984687a9aa5STejun Heo 	pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
4985f97a4a1aSLai Jiangshan 	ret = !list_empty(&pwq->inactive_works);
4986636b927eSTejun Heo 
498724acfb71SThomas Gleixner 	preempt_enable();
498824acfb71SThomas Gleixner 	rcu_read_unlock();
498976af4d93STejun Heo 
499076af4d93STejun Heo 	return ret;
4991dcd989cbSTejun Heo }
4992dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4993dcd989cbSTejun Heo 
4994dcd989cbSTejun Heo /**
4995dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4996dcd989cbSTejun Heo  * @work: the work to be tested
4997dcd989cbSTejun Heo  *
4998dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4999dcd989cbSTejun Heo  * synchronization around this function and the test result is
5000dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
5001dcd989cbSTejun Heo  *
5002d185af30SYacine Belkadi  * Return:
5003dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
5004dcd989cbSTejun Heo  */
work_busy(struct work_struct * work)5005dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
5006dcd989cbSTejun Heo {
5007fa1b54e6STejun Heo 	struct worker_pool *pool;
5008dcd989cbSTejun Heo 	unsigned long flags;
5009dcd989cbSTejun Heo 	unsigned int ret = 0;
5010dcd989cbSTejun Heo 
5011dcd989cbSTejun Heo 	if (work_pending(work))
5012dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
5013038366c5SLai Jiangshan 
501424acfb71SThomas Gleixner 	rcu_read_lock();
5015fa1b54e6STejun Heo 	pool = get_work_pool(work);
5016038366c5SLai Jiangshan 	if (pool) {
5017a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pool->lock, flags);
5018c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
5019dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
5020a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pool->lock, flags);
5021038366c5SLai Jiangshan 	}
502224acfb71SThomas Gleixner 	rcu_read_unlock();
5023dcd989cbSTejun Heo 
5024dcd989cbSTejun Heo 	return ret;
5025dcd989cbSTejun Heo }
5026dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
5027dcd989cbSTejun Heo 
50283d1cb205STejun Heo /**
50293d1cb205STejun Heo  * set_worker_desc - set description for the current work item
50303d1cb205STejun Heo  * @fmt: printf-style format string
50313d1cb205STejun Heo  * @...: arguments for the format string
50323d1cb205STejun Heo  *
50333d1cb205STejun Heo  * This function can be called by a running work function to describe what
50343d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
50353d1cb205STejun Heo  * information will be printed out together to help debugging.  The
50363d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
50373d1cb205STejun Heo  */
set_worker_desc(const char * fmt,...)50383d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
50393d1cb205STejun Heo {
50403d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
50413d1cb205STejun Heo 	va_list args;
50423d1cb205STejun Heo 
50433d1cb205STejun Heo 	if (worker) {
50443d1cb205STejun Heo 		va_start(args, fmt);
50453d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
50463d1cb205STejun Heo 		va_end(args);
50473d1cb205STejun Heo 	}
50483d1cb205STejun Heo }
50495c750d58SSteffen Maier EXPORT_SYMBOL_GPL(set_worker_desc);
50503d1cb205STejun Heo 
50513d1cb205STejun Heo /**
50523d1cb205STejun Heo  * print_worker_info - print out worker information and description
50533d1cb205STejun Heo  * @log_lvl: the log level to use when printing
50543d1cb205STejun Heo  * @task: target task
50553d1cb205STejun Heo  *
50563d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
50573d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
50583d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
50593d1cb205STejun Heo  *
50603d1cb205STejun Heo  * This function can be safely called on any task as long as the
50613d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
50623d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
50633d1cb205STejun Heo  */
print_worker_info(const char * log_lvl,struct task_struct * task)50643d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
50653d1cb205STejun Heo {
50663d1cb205STejun Heo 	work_func_t *fn = NULL;
50673d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
50683d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
50693d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
50703d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
50713d1cb205STejun Heo 	struct worker *worker;
50723d1cb205STejun Heo 
50733d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
50743d1cb205STejun Heo 		return;
50753d1cb205STejun Heo 
50763d1cb205STejun Heo 	/*
50773d1cb205STejun Heo 	 * This function is called without any synchronization and @task
50783d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
50793d1cb205STejun Heo 	 */
5080e700591aSPetr Mladek 	worker = kthread_probe_data(task);
50813d1cb205STejun Heo 
50823d1cb205STejun Heo 	/*
50838bf89593STejun Heo 	 * Carefully copy the associated workqueue's workfn, name and desc.
50848bf89593STejun Heo 	 * Keep the original last '\0' in case the original is garbage.
50853d1cb205STejun Heo 	 */
5086fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
5087fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
5088fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
5089fe557319SChristoph Hellwig 	copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
5090fe557319SChristoph Hellwig 	copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
50913d1cb205STejun Heo 
50923d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
5093d75f773cSSakari Ailus 		printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
50948bf89593STejun Heo 		if (strcmp(name, desc))
50953d1cb205STejun Heo 			pr_cont(" (%s)", desc);
50963d1cb205STejun Heo 		pr_cont("\n");
50973d1cb205STejun Heo 	}
50983d1cb205STejun Heo }
50993d1cb205STejun Heo 
pr_cont_pool_info(struct worker_pool * pool)51003494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
51013494fc30STejun Heo {
51023494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
51033494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
51043494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
51053494fc30STejun Heo 	pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
51063494fc30STejun Heo }
51073494fc30STejun Heo 
5108c76feb0dSPaul E. McKenney struct pr_cont_work_struct {
5109c76feb0dSPaul E. McKenney 	bool comma;
5110c76feb0dSPaul E. McKenney 	work_func_t func;
5111c76feb0dSPaul E. McKenney 	long ctr;
5112c76feb0dSPaul E. McKenney };
5113c76feb0dSPaul E. McKenney 
pr_cont_work_flush(bool comma,work_func_t func,struct pr_cont_work_struct * pcwsp)5114c76feb0dSPaul E. McKenney static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
5115c76feb0dSPaul E. McKenney {
5116c76feb0dSPaul E. McKenney 	if (!pcwsp->ctr)
5117c76feb0dSPaul E. McKenney 		goto out_record;
5118c76feb0dSPaul E. McKenney 	if (func == pcwsp->func) {
5119c76feb0dSPaul E. McKenney 		pcwsp->ctr++;
5120c76feb0dSPaul E. McKenney 		return;
5121c76feb0dSPaul E. McKenney 	}
5122c76feb0dSPaul E. McKenney 	if (pcwsp->ctr == 1)
5123c76feb0dSPaul E. McKenney 		pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
5124c76feb0dSPaul E. McKenney 	else
5125c76feb0dSPaul E. McKenney 		pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
5126c76feb0dSPaul E. McKenney 	pcwsp->ctr = 0;
5127c76feb0dSPaul E. McKenney out_record:
5128c76feb0dSPaul E. McKenney 	if ((long)func == -1L)
5129c76feb0dSPaul E. McKenney 		return;
5130c76feb0dSPaul E. McKenney 	pcwsp->comma = comma;
5131c76feb0dSPaul E. McKenney 	pcwsp->func = func;
5132c76feb0dSPaul E. McKenney 	pcwsp->ctr = 1;
5133c76feb0dSPaul E. McKenney }
5134c76feb0dSPaul E. McKenney 
pr_cont_work(bool comma,struct work_struct * work,struct pr_cont_work_struct * pcwsp)5135c76feb0dSPaul E. McKenney static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
51363494fc30STejun Heo {
51373494fc30STejun Heo 	if (work->func == wq_barrier_func) {
51383494fc30STejun Heo 		struct wq_barrier *barr;
51393494fc30STejun Heo 
51403494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
51413494fc30STejun Heo 
5142c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
51433494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
51443494fc30STejun Heo 			task_pid_nr(barr->task));
51453494fc30STejun Heo 	} else {
5146c76feb0dSPaul E. McKenney 		if (!comma)
5147c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5148c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, work->func, pcwsp);
51493494fc30STejun Heo 	}
51503494fc30STejun Heo }
51513494fc30STejun Heo 
show_pwq(struct pool_workqueue * pwq)51523494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
51533494fc30STejun Heo {
5154c76feb0dSPaul E. McKenney 	struct pr_cont_work_struct pcws = { .ctr = 0, };
51553494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
51563494fc30STejun Heo 	struct work_struct *work;
51573494fc30STejun Heo 	struct worker *worker;
51583494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
51593494fc30STejun Heo 	int bkt;
51603494fc30STejun Heo 
51613494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
51623494fc30STejun Heo 	pr_cont_pool_info(pool);
51633494fc30STejun Heo 
5164d8354f26SGreg Kroah-Hartman 	pr_cont(" active=%d/%d refcnt=%d%s\n",
5165d8354f26SGreg Kroah-Hartman 		pwq->nr_active, pwq->max_active, pwq->refcnt,
51663494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
51673494fc30STejun Heo 
51683494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
51693494fc30STejun Heo 		if (worker->current_pwq == pwq) {
51703494fc30STejun Heo 			has_in_flight = true;
51713494fc30STejun Heo 			break;
51723494fc30STejun Heo 		}
51733494fc30STejun Heo 	}
51743494fc30STejun Heo 	if (has_in_flight) {
51753494fc30STejun Heo 		bool comma = false;
51763494fc30STejun Heo 
51773494fc30STejun Heo 		pr_info("    in-flight:");
51783494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
51793494fc30STejun Heo 			if (worker->current_pwq != pwq)
51803494fc30STejun Heo 				continue;
51813494fc30STejun Heo 
5182d75f773cSSakari Ailus 			pr_cont("%s %d%s:%ps", comma ? "," : "",
51833494fc30STejun Heo 				task_pid_nr(worker->task),
518430ae2fc0STejun Heo 				worker->rescue_wq ? "(RESCUER)" : "",
51853494fc30STejun Heo 				worker->current_func);
51863494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
5187c76feb0dSPaul E. McKenney 				pr_cont_work(false, work, &pcws);
5188c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
51893494fc30STejun Heo 			comma = true;
51903494fc30STejun Heo 		}
51913494fc30STejun Heo 		pr_cont("\n");
51923494fc30STejun Heo 	}
51933494fc30STejun Heo 
51943494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
51953494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
51963494fc30STejun Heo 			has_pending = true;
51973494fc30STejun Heo 			break;
51983494fc30STejun Heo 		}
51993494fc30STejun Heo 	}
52003494fc30STejun Heo 	if (has_pending) {
52013494fc30STejun Heo 		bool comma = false;
52023494fc30STejun Heo 
52033494fc30STejun Heo 		pr_info("    pending:");
52043494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
52053494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
52063494fc30STejun Heo 				continue;
52073494fc30STejun Heo 
5208c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
52093494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
52103494fc30STejun Heo 		}
5211c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
52123494fc30STejun Heo 		pr_cont("\n");
52133494fc30STejun Heo 	}
52143494fc30STejun Heo 
5215f97a4a1aSLai Jiangshan 	if (!list_empty(&pwq->inactive_works)) {
52163494fc30STejun Heo 		bool comma = false;
52173494fc30STejun Heo 
5218f97a4a1aSLai Jiangshan 		pr_info("    inactive:");
5219f97a4a1aSLai Jiangshan 		list_for_each_entry(work, &pwq->inactive_works, entry) {
5220c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
52213494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
52223494fc30STejun Heo 		}
5223c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
52243494fc30STejun Heo 		pr_cont("\n");
52253494fc30STejun Heo 	}
52263494fc30STejun Heo }
52273494fc30STejun Heo 
52283494fc30STejun Heo /**
522955df0933SImran Khan  * show_one_workqueue - dump state of specified workqueue
523055df0933SImran Khan  * @wq: workqueue whose state will be printed
52313494fc30STejun Heo  */
show_one_workqueue(struct workqueue_struct * wq)523255df0933SImran Khan void show_one_workqueue(struct workqueue_struct *wq)
52333494fc30STejun Heo {
52343494fc30STejun Heo 	struct pool_workqueue *pwq;
52353494fc30STejun Heo 	bool idle = true;
523655df0933SImran Khan 	unsigned long flags;
52373494fc30STejun Heo 
52383494fc30STejun Heo 	for_each_pwq(pwq, wq) {
523935bf38ddSGreg Kroah-Hartman 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
52403494fc30STejun Heo 			idle = false;
52413494fc30STejun Heo 			break;
52423494fc30STejun Heo 		}
52433494fc30STejun Heo 	}
524455df0933SImran Khan 	if (idle) /* Nothing to print for idle workqueue */
524555df0933SImran Khan 		return;
52463494fc30STejun Heo 
52473494fc30STejun Heo 	pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
52483494fc30STejun Heo 
52493494fc30STejun Heo 	for_each_pwq(pwq, wq) {
5250a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pwq->pool->lock, flags);
525135bf38ddSGreg Kroah-Hartman 		if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
525257116ce1SJohan Hovold 			/*
525357116ce1SJohan Hovold 			 * Defer printing to avoid deadlocks in console
525457116ce1SJohan Hovold 			 * drivers that queue work while holding locks
525557116ce1SJohan Hovold 			 * also taken in their write paths.
525657116ce1SJohan Hovold 			 */
525757116ce1SJohan Hovold 			printk_deferred_enter();
52583494fc30STejun Heo 			show_pwq(pwq);
525957116ce1SJohan Hovold 			printk_deferred_exit();
526057116ce1SJohan Hovold 		}
5261a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
526262635ea8SSergey Senozhatsky 		/*
526362635ea8SSergey Senozhatsky 		 * We could be printing a lot from atomic context, e.g.
526455df0933SImran Khan 		 * sysrq-t -> show_all_workqueues(). Avoid triggering
526562635ea8SSergey Senozhatsky 		 * hard lockup.
526662635ea8SSergey Senozhatsky 		 */
526762635ea8SSergey Senozhatsky 		touch_nmi_watchdog();
52683494fc30STejun Heo 	}
526955df0933SImran Khan 
52703494fc30STejun Heo }
52713494fc30STejun Heo 
527255df0933SImran Khan /**
527355df0933SImran Khan  * show_one_worker_pool - dump state of specified worker pool
527455df0933SImran Khan  * @pool: worker pool whose state will be printed
527555df0933SImran Khan  */
show_one_worker_pool(struct worker_pool * pool)527655df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool)
527755df0933SImran Khan {
52783494fc30STejun Heo 	struct worker *worker;
52793494fc30STejun Heo 	bool first = true;
528055df0933SImran Khan 	unsigned long flags;
5281335a42ebSPetr Mladek 	unsigned long hung = 0;
52823494fc30STejun Heo 
5283a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pool->lock, flags);
52843494fc30STejun Heo 	if (pool->nr_workers == pool->nr_idle)
52853494fc30STejun Heo 		goto next_pool;
5286335a42ebSPetr Mladek 
5287335a42ebSPetr Mladek 	/* How long the first pending work is waiting for a worker. */
5288335a42ebSPetr Mladek 	if (!list_empty(&pool->worklist))
5289335a42ebSPetr Mladek 		hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
5290335a42ebSPetr Mladek 
529157116ce1SJohan Hovold 	/*
529257116ce1SJohan Hovold 	 * Defer printing to avoid deadlocks in console drivers that
529357116ce1SJohan Hovold 	 * queue work while holding locks also taken in their write
529457116ce1SJohan Hovold 	 * paths.
529557116ce1SJohan Hovold 	 */
529657116ce1SJohan Hovold 	printk_deferred_enter();
52973494fc30STejun Heo 	pr_info("pool %d:", pool->id);
52983494fc30STejun Heo 	pr_cont_pool_info(pool);
5299335a42ebSPetr Mladek 	pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
53003494fc30STejun Heo 	if (pool->manager)
53013494fc30STejun Heo 		pr_cont(" manager: %d",
53023494fc30STejun Heo 			task_pid_nr(pool->manager->task));
53033494fc30STejun Heo 	list_for_each_entry(worker, &pool->idle_list, entry) {
53043494fc30STejun Heo 		pr_cont(" %s%d", first ? "idle: " : "",
53053494fc30STejun Heo 			task_pid_nr(worker->task));
53063494fc30STejun Heo 		first = false;
53073494fc30STejun Heo 	}
53083494fc30STejun Heo 	pr_cont("\n");
530957116ce1SJohan Hovold 	printk_deferred_exit();
53103494fc30STejun Heo next_pool:
5311a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pool->lock, flags);
531262635ea8SSergey Senozhatsky 	/*
531362635ea8SSergey Senozhatsky 	 * We could be printing a lot from atomic context, e.g.
531455df0933SImran Khan 	 * sysrq-t -> show_all_workqueues(). Avoid triggering
531562635ea8SSergey Senozhatsky 	 * hard lockup.
531662635ea8SSergey Senozhatsky 	 */
531762635ea8SSergey Senozhatsky 	touch_nmi_watchdog();
531855df0933SImran Khan 
53193494fc30STejun Heo }
53203494fc30STejun Heo 
532155df0933SImran Khan /**
532255df0933SImran Khan  * show_all_workqueues - dump workqueue state
532355df0933SImran Khan  *
5324704bc669SJungseung Lee  * Called from a sysrq handler and prints out all busy workqueues and pools.
532555df0933SImran Khan  */
show_all_workqueues(void)532655df0933SImran Khan void show_all_workqueues(void)
532755df0933SImran Khan {
532855df0933SImran Khan 	struct workqueue_struct *wq;
532955df0933SImran Khan 	struct worker_pool *pool;
533055df0933SImran Khan 	int pi;
533155df0933SImran Khan 
533255df0933SImran Khan 	rcu_read_lock();
533355df0933SImran Khan 
533455df0933SImran Khan 	pr_info("Showing busy workqueues and worker pools:\n");
533555df0933SImran Khan 
533655df0933SImran Khan 	list_for_each_entry_rcu(wq, &workqueues, list)
533755df0933SImran Khan 		show_one_workqueue(wq);
533855df0933SImran Khan 
533955df0933SImran Khan 	for_each_pool(pool, pi)
534055df0933SImran Khan 		show_one_worker_pool(pool);
534155df0933SImran Khan 
534224acfb71SThomas Gleixner 	rcu_read_unlock();
53433494fc30STejun Heo }
53443494fc30STejun Heo 
5345704bc669SJungseung Lee /**
5346704bc669SJungseung Lee  * show_freezable_workqueues - dump freezable workqueue state
5347704bc669SJungseung Lee  *
5348704bc669SJungseung Lee  * Called from try_to_freeze_tasks() and prints out all freezable workqueues
5349704bc669SJungseung Lee  * still busy.
5350704bc669SJungseung Lee  */
show_freezable_workqueues(void)5351704bc669SJungseung Lee void show_freezable_workqueues(void)
5352704bc669SJungseung Lee {
5353704bc669SJungseung Lee 	struct workqueue_struct *wq;
5354704bc669SJungseung Lee 
5355704bc669SJungseung Lee 	rcu_read_lock();
5356704bc669SJungseung Lee 
5357704bc669SJungseung Lee 	pr_info("Showing freezable workqueues that are still busy:\n");
5358704bc669SJungseung Lee 
5359704bc669SJungseung Lee 	list_for_each_entry_rcu(wq, &workqueues, list) {
5360704bc669SJungseung Lee 		if (!(wq->flags & WQ_FREEZABLE))
5361704bc669SJungseung Lee 			continue;
5362704bc669SJungseung Lee 		show_one_workqueue(wq);
5363704bc669SJungseung Lee 	}
5364704bc669SJungseung Lee 
5365704bc669SJungseung Lee 	rcu_read_unlock();
5366704bc669SJungseung Lee }
5367704bc669SJungseung Lee 
53686b59808bSTejun Heo /* used to show worker information through /proc/PID/{comm,stat,status} */
wq_worker_comm(char * buf,size_t size,struct task_struct * task)53696b59808bSTejun Heo void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
53706b59808bSTejun Heo {
53716b59808bSTejun Heo 	int off;
53726b59808bSTejun Heo 
53736b59808bSTejun Heo 	/* always show the actual comm */
53746b59808bSTejun Heo 	off = strscpy(buf, task->comm, size);
53756b59808bSTejun Heo 	if (off < 0)
53766b59808bSTejun Heo 		return;
53776b59808bSTejun Heo 
5378197f6accSTejun Heo 	/* stabilize PF_WQ_WORKER and worker pool association */
53796b59808bSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
53806b59808bSTejun Heo 
5381197f6accSTejun Heo 	if (task->flags & PF_WQ_WORKER) {
5382197f6accSTejun Heo 		struct worker *worker = kthread_data(task);
5383197f6accSTejun Heo 		struct worker_pool *pool = worker->pool;
53846b59808bSTejun Heo 
53856b59808bSTejun Heo 		if (pool) {
5386a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock_irq(&pool->lock);
53876b59808bSTejun Heo 			/*
5388197f6accSTejun Heo 			 * ->desc tracks information (wq name or
5389197f6accSTejun Heo 			 * set_worker_desc()) for the latest execution.  If
5390197f6accSTejun Heo 			 * current, prepend '+', otherwise '-'.
53916b59808bSTejun Heo 			 */
53926b59808bSTejun Heo 			if (worker->desc[0] != '\0') {
53936b59808bSTejun Heo 				if (worker->current_work)
53946b59808bSTejun Heo 					scnprintf(buf + off, size - off, "+%s",
53956b59808bSTejun Heo 						  worker->desc);
53966b59808bSTejun Heo 				else
53976b59808bSTejun Heo 					scnprintf(buf + off, size - off, "-%s",
53986b59808bSTejun Heo 						  worker->desc);
53996b59808bSTejun Heo 			}
5400a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pool->lock);
54016b59808bSTejun Heo 		}
5402197f6accSTejun Heo 	}
54036b59808bSTejun Heo 
54046b59808bSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
54056b59808bSTejun Heo }
54066b59808bSTejun Heo 
540766448bc2SMathieu Malaterre #ifdef CONFIG_SMP
540866448bc2SMathieu Malaterre 
5409db7bccf4STejun Heo /*
5410db7bccf4STejun Heo  * CPU hotplug.
5411db7bccf4STejun Heo  *
5412e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
5413112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
5414706026c2STejun Heo  * pool which make migrating pending and scheduled works very
5415e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
541694cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
5417e22bee78STejun Heo  * blocked draining impractical.
5418e22bee78STejun Heo  *
541924647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
5420628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
5421628c78e7STejun Heo  * cpu comes back online.
5422db7bccf4STejun Heo  */
5423db7bccf4STejun Heo 
unbind_workers(int cpu)5424e8b3f8dbSLai Jiangshan static void unbind_workers(int cpu)
5425db7bccf4STejun Heo {
54264ce62e9eSTejun Heo 	struct worker_pool *pool;
5427db7bccf4STejun Heo 	struct worker *worker;
5428db7bccf4STejun Heo 
5429f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
54301258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
5431a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
5432e22bee78STejun Heo 
5433f2d5a0eeSTejun Heo 		/*
543492f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
543594cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
543611b45b0bSLai Jiangshan 		 * must be on the cpu.  After this, they may become diasporas.
5437b4ac9384SLai Jiangshan 		 * And the preemption disabled section in their sched callbacks
5438b4ac9384SLai Jiangshan 		 * are guaranteed to see WORKER_UNBOUND since the code here
5439b4ac9384SLai Jiangshan 		 * is on the same cpu.
5440f2d5a0eeSTejun Heo 		 */
5441da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
5442403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
5443db7bccf4STejun Heo 
544424647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
5445f2d5a0eeSTejun Heo 
5446e22bee78STejun Heo 		/*
5447989442d7SLai Jiangshan 		 * The handling of nr_running in sched callbacks are disabled
5448989442d7SLai Jiangshan 		 * now.  Zap nr_running.  After this, nr_running stays zero and
5449989442d7SLai Jiangshan 		 * need_more_worker() and keep_working() are always true as
5450989442d7SLai Jiangshan 		 * long as the worklist is not empty.  This pool now behaves as
5451989442d7SLai Jiangshan 		 * an unbound (in terms of concurrency management) pool which
5452eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
5453e22bee78STejun Heo 		 */
5454bc35f7efSLai Jiangshan 		pool->nr_running = 0;
5455eb283428SLai Jiangshan 
5456eb283428SLai Jiangshan 		/*
5457eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
5458eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
5459eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
5460eb283428SLai Jiangshan 		 */
54610219a352STejun Heo 		kick_pool(pool);
5462989442d7SLai Jiangshan 
5463a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
5464989442d7SLai Jiangshan 
5465793777bcSValentin Schneider 		for_each_pool_worker(worker, pool)
5466793777bcSValentin Schneider 			unbind_worker(worker);
5467989442d7SLai Jiangshan 
5468989442d7SLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
5469eb283428SLai Jiangshan 	}
5470db7bccf4STejun Heo }
5471db7bccf4STejun Heo 
5472bd7c089eSTejun Heo /**
5473bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
5474bd7c089eSTejun Heo  * @pool: pool of interest
5475bd7c089eSTejun Heo  *
5476a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
5477bd7c089eSTejun Heo  */
rebind_workers(struct worker_pool * pool)5478bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
5479bd7c089eSTejun Heo {
5480a9ab775bSTejun Heo 	struct worker *worker;
5481bd7c089eSTejun Heo 
54821258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
5483bd7c089eSTejun Heo 
5484bd7c089eSTejun Heo 	/*
5485a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
5486a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
5487402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
5488a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
5489a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
5490bd7c089eSTejun Heo 	 */
5491c63a2e52SValentin Schneider 	for_each_pool_worker(worker, pool) {
5492c63a2e52SValentin Schneider 		kthread_set_per_cpu(worker->task, pool->cpu);
5493c63a2e52SValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
54949546b29eSTejun Heo 						  pool_allowed_cpus(pool)) < 0);
5495c63a2e52SValentin Schneider 	}
5496a9ab775bSTejun Heo 
5497a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
5498f7c17d26SWanpeng Li 
54993de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
5500a9ab775bSTejun Heo 
5501da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
5502a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
5503a9ab775bSTejun Heo 
5504a9ab775bSTejun Heo 		/*
5505a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
5506a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
5507a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5508a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
5509a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
5510a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
5511a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
5512a9ab775bSTejun Heo 		 *
5513c95491edSMark Rutland 		 * WRITE_ONCE() is necessary because @worker->flags may be
5514a9ab775bSTejun Heo 		 * tested without holding any lock in
55156d25be57SThomas Gleixner 		 * wq_worker_running().  Without it, NOT_RUNNING test may
5516a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
5517a9ab775bSTejun Heo 		 * management operations.
5518bd7c089eSTejun Heo 		 */
5519a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5520a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
5521a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
5522c95491edSMark Rutland 		WRITE_ONCE(worker->flags, worker_flags);
5523bd7c089eSTejun Heo 	}
5524a9ab775bSTejun Heo 
5525a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
5526bd7c089eSTejun Heo }
5527bd7c089eSTejun Heo 
55287dbc725eSTejun Heo /**
55297dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
55307dbc725eSTejun Heo  * @pool: unbound pool of interest
55317dbc725eSTejun Heo  * @cpu: the CPU which is coming up
55327dbc725eSTejun Heo  *
55337dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
55347dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
55357dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
55367dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
55377dbc725eSTejun Heo  */
restore_unbound_workers_cpumask(struct worker_pool * pool,int cpu)55387dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
55397dbc725eSTejun Heo {
55407dbc725eSTejun Heo 	static cpumask_t cpumask;
55417dbc725eSTejun Heo 	struct worker *worker;
55427dbc725eSTejun Heo 
55431258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
55447dbc725eSTejun Heo 
55457dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
55467dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
55477dbc725eSTejun Heo 		return;
55487dbc725eSTejun Heo 
55497dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
55507dbc725eSTejun Heo 
55517dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
5552da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
5553d945b5e9SPeter Zijlstra 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
55547dbc725eSTejun Heo }
55557dbc725eSTejun Heo 
workqueue_prepare_cpu(unsigned int cpu)55567ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
55571da177e4SLinus Torvalds {
55584ce62e9eSTejun Heo 	struct worker_pool *pool;
55591da177e4SLinus Torvalds 
5560f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
55613ce63377STejun Heo 		if (pool->nr_workers)
55623ce63377STejun Heo 			continue;
5563051e1850SLai Jiangshan 		if (!create_worker(pool))
55647ee681b2SThomas Gleixner 			return -ENOMEM;
55653af24433SOleg Nesterov 	}
55667ee681b2SThomas Gleixner 	return 0;
55677ee681b2SThomas Gleixner }
55681da177e4SLinus Torvalds 
workqueue_online_cpu(unsigned int cpu)55697ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
55707ee681b2SThomas Gleixner {
55717ee681b2SThomas Gleixner 	struct worker_pool *pool;
55727ee681b2SThomas Gleixner 	struct workqueue_struct *wq;
55737ee681b2SThomas Gleixner 	int pi;
55747ee681b2SThomas Gleixner 
557568e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
55767dbc725eSTejun Heo 
55777dbc725eSTejun Heo 	for_each_pool(pool, pi) {
55781258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
557994cf58bbSTejun Heo 
5580f05b558dSLai Jiangshan 		if (pool->cpu == cpu)
558194cf58bbSTejun Heo 			rebind_workers(pool);
5582f05b558dSLai Jiangshan 		else if (pool->cpu < 0)
55837dbc725eSTejun Heo 			restore_unbound_workers_cpumask(pool, cpu);
558494cf58bbSTejun Heo 
55851258fae7STejun Heo 		mutex_unlock(&wq_pool_attach_mutex);
558694cf58bbSTejun Heo 	}
55877dbc725eSTejun Heo 
5588fef59c9cSTejun Heo 	/* update pod affinity of unbound workqueues */
55894cbfd3deSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
559084193c07STejun Heo 		struct workqueue_attrs *attrs = wq->unbound_attrs;
559184193c07STejun Heo 
559284193c07STejun Heo 		if (attrs) {
559384193c07STejun Heo 			const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
55944cbfd3deSTejun Heo 			int tcpu;
55954cbfd3deSTejun Heo 
559684193c07STejun Heo 			for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
5597fef59c9cSTejun Heo 				wq_update_pod(wq, tcpu, cpu, true);
55984cbfd3deSTejun Heo 		}
55994cbfd3deSTejun Heo 	}
56004c16bd32STejun Heo 
560168e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
56027ee681b2SThomas Gleixner 	return 0;
560365758202STejun Heo }
560465758202STejun Heo 
workqueue_offline_cpu(unsigned int cpu)56057ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
560665758202STejun Heo {
56074c16bd32STejun Heo 	struct workqueue_struct *wq;
56088db25e78STejun Heo 
56094c16bd32STejun Heo 	/* unbinding per-cpu workers should happen on the local CPU */
5610e8b3f8dbSLai Jiangshan 	if (WARN_ON(cpu != smp_processor_id()))
5611e8b3f8dbSLai Jiangshan 		return -1;
5612e8b3f8dbSLai Jiangshan 
5613e8b3f8dbSLai Jiangshan 	unbind_workers(cpu);
56144c16bd32STejun Heo 
5615fef59c9cSTejun Heo 	/* update pod affinity of unbound workqueues */
56164c16bd32STejun Heo 	mutex_lock(&wq_pool_mutex);
56174cbfd3deSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
561884193c07STejun Heo 		struct workqueue_attrs *attrs = wq->unbound_attrs;
561984193c07STejun Heo 
562084193c07STejun Heo 		if (attrs) {
562184193c07STejun Heo 			const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
56224cbfd3deSTejun Heo 			int tcpu;
56234cbfd3deSTejun Heo 
562484193c07STejun Heo 			for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
5625fef59c9cSTejun Heo 				wq_update_pod(wq, tcpu, cpu, false);
56264cbfd3deSTejun Heo 		}
56274cbfd3deSTejun Heo 	}
56284c16bd32STejun Heo 	mutex_unlock(&wq_pool_mutex);
56294c16bd32STejun Heo 
56307ee681b2SThomas Gleixner 	return 0;
563165758202STejun Heo }
563265758202STejun Heo 
56332d3854a3SRusty Russell struct work_for_cpu {
5634ed48ece2STejun Heo 	struct work_struct work;
56352d3854a3SRusty Russell 	long (*fn)(void *);
56362d3854a3SRusty Russell 	void *arg;
56372d3854a3SRusty Russell 	long ret;
56382d3854a3SRusty Russell };
56392d3854a3SRusty Russell 
work_for_cpu_fn(struct work_struct * work)5640ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
56412d3854a3SRusty Russell {
5642ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5643ed48ece2STejun Heo 
56442d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
56452d3854a3SRusty Russell }
56462d3854a3SRusty Russell 
56472d3854a3SRusty Russell /**
5648be2355b7SFrederic Weisbecker  * work_on_cpu_key - run a function in thread context on a particular cpu
56492d3854a3SRusty Russell  * @cpu: the cpu to run on
56502d3854a3SRusty Russell  * @fn: the function to run
56512d3854a3SRusty Russell  * @arg: the function arg
5652be2355b7SFrederic Weisbecker  * @key: The lock class key for lock debugging purposes
56532d3854a3SRusty Russell  *
565431ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
56556b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
5656d185af30SYacine Belkadi  *
5657d185af30SYacine Belkadi  * Return: The value @fn returns.
56582d3854a3SRusty Russell  */
work_on_cpu_key(int cpu,long (* fn)(void *),void * arg,struct lock_class_key * key)5659be2355b7SFrederic Weisbecker long work_on_cpu_key(int cpu, long (*fn)(void *),
5660be2355b7SFrederic Weisbecker 		     void *arg, struct lock_class_key *key)
56612d3854a3SRusty Russell {
5662ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
56632d3854a3SRusty Russell 
5664be2355b7SFrederic Weisbecker 	INIT_WORK_ONSTACK_KEY(&wfc.work, work_for_cpu_fn, key);
5665ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
566612997d1aSBjorn Helgaas 	flush_work(&wfc.work);
5667440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
56682d3854a3SRusty Russell 	return wfc.ret;
56692d3854a3SRusty Russell }
5670be2355b7SFrederic Weisbecker EXPORT_SYMBOL_GPL(work_on_cpu_key);
56710e8d6a93SThomas Gleixner 
56720e8d6a93SThomas Gleixner /**
5673be2355b7SFrederic Weisbecker  * work_on_cpu_safe_key - run a function in thread context on a particular cpu
56740e8d6a93SThomas Gleixner  * @cpu: the cpu to run on
56750e8d6a93SThomas Gleixner  * @fn:  the function to run
56760e8d6a93SThomas Gleixner  * @arg: the function argument
5677be2355b7SFrederic Weisbecker  * @key: The lock class key for lock debugging purposes
56780e8d6a93SThomas Gleixner  *
56790e8d6a93SThomas Gleixner  * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
56800e8d6a93SThomas Gleixner  * any locks which would prevent @fn from completing.
56810e8d6a93SThomas Gleixner  *
56820e8d6a93SThomas Gleixner  * Return: The value @fn returns.
56830e8d6a93SThomas Gleixner  */
work_on_cpu_safe_key(int cpu,long (* fn)(void *),void * arg,struct lock_class_key * key)5684be2355b7SFrederic Weisbecker long work_on_cpu_safe_key(int cpu, long (*fn)(void *),
5685be2355b7SFrederic Weisbecker 			  void *arg, struct lock_class_key *key)
56860e8d6a93SThomas Gleixner {
56870e8d6a93SThomas Gleixner 	long ret = -ENODEV;
56880e8d6a93SThomas Gleixner 
5689ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
56900e8d6a93SThomas Gleixner 	if (cpu_online(cpu))
5691be2355b7SFrederic Weisbecker 		ret = work_on_cpu_key(cpu, fn, arg, key);
5692ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
56930e8d6a93SThomas Gleixner 	return ret;
56940e8d6a93SThomas Gleixner }
5695be2355b7SFrederic Weisbecker EXPORT_SYMBOL_GPL(work_on_cpu_safe_key);
56962d3854a3SRusty Russell #endif /* CONFIG_SMP */
56972d3854a3SRusty Russell 
5698a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
5699e7577c50SRusty Russell 
5700a0a1a5fdSTejun Heo /**
5701a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
5702a0a1a5fdSTejun Heo  *
570358a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
5704f97a4a1aSLai Jiangshan  * workqueues will queue new works to their inactive_works list instead of
5705706026c2STejun Heo  * pool->worklist.
5706a0a1a5fdSTejun Heo  *
5707a0a1a5fdSTejun Heo  * CONTEXT:
5708a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5709a0a1a5fdSTejun Heo  */
freeze_workqueues_begin(void)5710a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
5711a0a1a5fdSTejun Heo {
571224b8a847STejun Heo 	struct workqueue_struct *wq;
5713d8354f26SGreg Kroah-Hartman 	struct pool_workqueue *pwq;
5714a0a1a5fdSTejun Heo 
571568e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5716a0a1a5fdSTejun Heo 
57176183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
5718a0a1a5fdSTejun Heo 	workqueue_freezing = true;
5719a0a1a5fdSTejun Heo 
572024b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5721a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5722d8354f26SGreg Kroah-Hartman 		for_each_pwq(pwq, wq)
5723d8354f26SGreg Kroah-Hartman 			pwq_adjust_max_active(pwq);
5724a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
5725a1056305STejun Heo 	}
57265bcab335STejun Heo 
572768e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5728a0a1a5fdSTejun Heo }
5729a0a1a5fdSTejun Heo 
5730a0a1a5fdSTejun Heo /**
573158a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
5732a0a1a5fdSTejun Heo  *
5733a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
5734a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
5735a0a1a5fdSTejun Heo  *
5736a0a1a5fdSTejun Heo  * CONTEXT:
573768e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
5738a0a1a5fdSTejun Heo  *
5739d185af30SYacine Belkadi  * Return:
574058a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
574158a69cb4STejun Heo  * is complete.
5742a0a1a5fdSTejun Heo  */
freeze_workqueues_busy(void)5743a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
5744a0a1a5fdSTejun Heo {
5745a0a1a5fdSTejun Heo 	bool busy = false;
574624b8a847STejun Heo 	struct workqueue_struct *wq;
574724b8a847STejun Heo 	struct pool_workqueue *pwq;
5748a0a1a5fdSTejun Heo 
574968e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5750a0a1a5fdSTejun Heo 
57516183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
5752a0a1a5fdSTejun Heo 
575324b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
575424b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
575524b8a847STejun Heo 			continue;
5756a0a1a5fdSTejun Heo 		/*
5757a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
5758a0a1a5fdSTejun Heo 		 * to peek without lock.
5759a0a1a5fdSTejun Heo 		 */
576024acfb71SThomas Gleixner 		rcu_read_lock();
576124b8a847STejun Heo 		for_each_pwq(pwq, wq) {
57626183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
5763112202d9STejun Heo 			if (pwq->nr_active) {
5764a0a1a5fdSTejun Heo 				busy = true;
576524acfb71SThomas Gleixner 				rcu_read_unlock();
5766a0a1a5fdSTejun Heo 				goto out_unlock;
5767a0a1a5fdSTejun Heo 			}
5768a0a1a5fdSTejun Heo 		}
576924acfb71SThomas Gleixner 		rcu_read_unlock();
5770a0a1a5fdSTejun Heo 	}
5771a0a1a5fdSTejun Heo out_unlock:
577268e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5773a0a1a5fdSTejun Heo 	return busy;
5774a0a1a5fdSTejun Heo }
5775a0a1a5fdSTejun Heo 
5776a0a1a5fdSTejun Heo /**
5777a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
5778a0a1a5fdSTejun Heo  *
5779a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
5780706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
5781a0a1a5fdSTejun Heo  *
5782a0a1a5fdSTejun Heo  * CONTEXT:
5783a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5784a0a1a5fdSTejun Heo  */
thaw_workqueues(void)5785a0a1a5fdSTejun Heo void thaw_workqueues(void)
5786a0a1a5fdSTejun Heo {
578724b8a847STejun Heo 	struct workqueue_struct *wq;
5788d8354f26SGreg Kroah-Hartman 	struct pool_workqueue *pwq;
5789a0a1a5fdSTejun Heo 
579068e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5791a0a1a5fdSTejun Heo 
5792a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
5793a0a1a5fdSTejun Heo 		goto out_unlock;
5794a0a1a5fdSTejun Heo 
579574b414eaSLai Jiangshan 	workqueue_freezing = false;
579624b8a847STejun Heo 
579724b8a847STejun Heo 	/* restore max_active and repopulate worklist */
579824b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5799a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5800d8354f26SGreg Kroah-Hartman 		for_each_pwq(pwq, wq)
5801d8354f26SGreg Kroah-Hartman 			pwq_adjust_max_active(pwq);
5802a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
580324b8a847STejun Heo 	}
580424b8a847STejun Heo 
5805a0a1a5fdSTejun Heo out_unlock:
580668e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5807a0a1a5fdSTejun Heo }
5808a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
5809a0a1a5fdSTejun Heo 
workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)581099c621efSLai Jiangshan static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
5811042f7df1SLai Jiangshan {
5812042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
5813042f7df1SLai Jiangshan 	int ret = 0;
5814042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
5815042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
5816042f7df1SLai Jiangshan 
5817042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5818042f7df1SLai Jiangshan 
5819042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
5820042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
5821042f7df1SLai Jiangshan 			continue;
5822042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
58235ad73e10STejun Heo 		if (wq->flags & __WQ_ORDERED)
5824042f7df1SLai Jiangshan 			continue;
5825042f7df1SLai Jiangshan 
582699c621efSLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
582784193c07STejun Heo 		if (IS_ERR(ctx)) {
582884193c07STejun Heo 			ret = PTR_ERR(ctx);
5829042f7df1SLai Jiangshan 			break;
5830042f7df1SLai Jiangshan 		}
5831042f7df1SLai Jiangshan 
5832042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
5833042f7df1SLai Jiangshan 	}
5834042f7df1SLai Jiangshan 
5835042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
5836042f7df1SLai Jiangshan 		if (!ret)
5837042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
5838042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
5839042f7df1SLai Jiangshan 	}
5840042f7df1SLai Jiangshan 
584199c621efSLai Jiangshan 	if (!ret) {
584299c621efSLai Jiangshan 		mutex_lock(&wq_pool_attach_mutex);
584399c621efSLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
584499c621efSLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
584599c621efSLai Jiangshan 	}
5846042f7df1SLai Jiangshan 	return ret;
5847042f7df1SLai Jiangshan }
5848042f7df1SLai Jiangshan 
5849042f7df1SLai Jiangshan /**
5850042f7df1SLai Jiangshan  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5851042f7df1SLai Jiangshan  *  @cpumask: the cpumask to set
5852042f7df1SLai Jiangshan  *
5853042f7df1SLai Jiangshan  *  The low-level workqueues cpumask is a global cpumask that limits
5854042f7df1SLai Jiangshan  *  the affinity of all unbound workqueues.  This function check the @cpumask
5855042f7df1SLai Jiangshan  *  and apply it to all unbound workqueues and updates all pwqs of them.
5856042f7df1SLai Jiangshan  *
585767dc8325SCai Huoqing  *  Return:	0	- Success
5858042f7df1SLai Jiangshan  *  		-EINVAL	- Invalid @cpumask
5859042f7df1SLai Jiangshan  *  		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
5860042f7df1SLai Jiangshan  */
workqueue_set_unbound_cpumask(cpumask_var_t cpumask)5861042f7df1SLai Jiangshan int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5862042f7df1SLai Jiangshan {
5863042f7df1SLai Jiangshan 	int ret = -EINVAL;
5864042f7df1SLai Jiangshan 
5865c98a9805STal Shorer 	/*
5866c98a9805STal Shorer 	 * Not excluding isolated cpus on purpose.
5867c98a9805STal Shorer 	 * If the user wishes to include them, we allow that.
5868c98a9805STal Shorer 	 */
5869042f7df1SLai Jiangshan 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
5870042f7df1SLai Jiangshan 	if (!cpumask_empty(cpumask)) {
5871a0111cf6SLai Jiangshan 		apply_wqattrs_lock();
5872d25302e4SMenglong Dong 		if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
5873d25302e4SMenglong Dong 			ret = 0;
5874d25302e4SMenglong Dong 			goto out_unlock;
5875d25302e4SMenglong Dong 		}
5876d25302e4SMenglong Dong 
587799c621efSLai Jiangshan 		ret = workqueue_apply_unbound_cpumask(cpumask);
5878042f7df1SLai Jiangshan 
5879d25302e4SMenglong Dong out_unlock:
5880a0111cf6SLai Jiangshan 		apply_wqattrs_unlock();
5881042f7df1SLai Jiangshan 	}
5882042f7df1SLai Jiangshan 
5883042f7df1SLai Jiangshan 	return ret;
5884042f7df1SLai Jiangshan }
5885042f7df1SLai Jiangshan 
parse_affn_scope(const char * val)588663c5484eSTejun Heo static int parse_affn_scope(const char *val)
588763c5484eSTejun Heo {
588863c5484eSTejun Heo 	int i;
588963c5484eSTejun Heo 
589063c5484eSTejun Heo 	for (i = 0; i < ARRAY_SIZE(wq_affn_names); i++) {
589163c5484eSTejun Heo 		if (!strncasecmp(val, wq_affn_names[i], strlen(wq_affn_names[i])))
589263c5484eSTejun Heo 			return i;
589363c5484eSTejun Heo 	}
589463c5484eSTejun Heo 	return -EINVAL;
589563c5484eSTejun Heo }
589663c5484eSTejun Heo 
wq_affn_dfl_set(const char * val,const struct kernel_param * kp)589763c5484eSTejun Heo static int wq_affn_dfl_set(const char *val, const struct kernel_param *kp)
589863c5484eSTejun Heo {
5899523a301eSTejun Heo 	struct workqueue_struct *wq;
5900523a301eSTejun Heo 	int affn, cpu;
590163c5484eSTejun Heo 
590263c5484eSTejun Heo 	affn = parse_affn_scope(val);
590363c5484eSTejun Heo 	if (affn < 0)
590463c5484eSTejun Heo 		return affn;
5905523a301eSTejun Heo 	if (affn == WQ_AFFN_DFL)
5906523a301eSTejun Heo 		return -EINVAL;
5907523a301eSTejun Heo 
5908523a301eSTejun Heo 	cpus_read_lock();
5909523a301eSTejun Heo 	mutex_lock(&wq_pool_mutex);
591063c5484eSTejun Heo 
591163c5484eSTejun Heo 	wq_affn_dfl = affn;
5912523a301eSTejun Heo 
5913523a301eSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5914523a301eSTejun Heo 		for_each_online_cpu(cpu) {
5915523a301eSTejun Heo 			wq_update_pod(wq, cpu, cpu, true);
5916523a301eSTejun Heo 		}
5917523a301eSTejun Heo 	}
5918523a301eSTejun Heo 
5919523a301eSTejun Heo 	mutex_unlock(&wq_pool_mutex);
5920523a301eSTejun Heo 	cpus_read_unlock();
5921523a301eSTejun Heo 
592263c5484eSTejun Heo 	return 0;
592363c5484eSTejun Heo }
592463c5484eSTejun Heo 
wq_affn_dfl_get(char * buffer,const struct kernel_param * kp)592563c5484eSTejun Heo static int wq_affn_dfl_get(char *buffer, const struct kernel_param *kp)
592663c5484eSTejun Heo {
592763c5484eSTejun Heo 	return scnprintf(buffer, PAGE_SIZE, "%s\n", wq_affn_names[wq_affn_dfl]);
592863c5484eSTejun Heo }
592963c5484eSTejun Heo 
593063c5484eSTejun Heo static const struct kernel_param_ops wq_affn_dfl_ops = {
593163c5484eSTejun Heo 	.set	= wq_affn_dfl_set,
593263c5484eSTejun Heo 	.get	= wq_affn_dfl_get,
593363c5484eSTejun Heo };
593463c5484eSTejun Heo 
593563c5484eSTejun Heo module_param_cb(default_affinity_scope, &wq_affn_dfl_ops, NULL, 0644);
593663c5484eSTejun Heo 
59376ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
59386ba94429SFrederic Weisbecker /*
59396ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
59406ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
59416ba94429SFrederic Weisbecker  * following attributes.
59426ba94429SFrederic Weisbecker  *
59436ba94429SFrederic Weisbecker  *  per_cpu		RO bool	: whether the workqueue is per-cpu or unbound
59446ba94429SFrederic Weisbecker  *  max_active		RW int	: maximum number of in-flight work items
59456ba94429SFrederic Weisbecker  *
59466ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
59476ba94429SFrederic Weisbecker  *
59486ba94429SFrederic Weisbecker  *  nice		RW int	: nice value of the workers
59496ba94429SFrederic Weisbecker  *  cpumask		RW mask	: bitmask of allowed CPUs for the workers
595063c5484eSTejun Heo  *  affinity_scope	RW str  : worker CPU affinity scope (cache, numa, none)
59518639ecebSTejun Heo  *  affinity_strict	RW bool : worker CPU affinity is strict
59526ba94429SFrederic Weisbecker  */
59536ba94429SFrederic Weisbecker struct wq_device {
59546ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
59556ba94429SFrederic Weisbecker 	struct device			dev;
59566ba94429SFrederic Weisbecker };
59576ba94429SFrederic Weisbecker 
dev_to_wq(struct device * dev)59586ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
59596ba94429SFrederic Weisbecker {
59606ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
59616ba94429SFrederic Weisbecker 
59626ba94429SFrederic Weisbecker 	return wq_dev->wq;
59636ba94429SFrederic Weisbecker }
59646ba94429SFrederic Weisbecker 
per_cpu_show(struct device * dev,struct device_attribute * attr,char * buf)59656ba94429SFrederic Weisbecker static ssize_t per_cpu_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 
59706ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
59716ba94429SFrederic Weisbecker }
59726ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
59736ba94429SFrederic Weisbecker 
max_active_show(struct device * dev,struct device_attribute * attr,char * buf)59746ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
59756ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
59766ba94429SFrederic Weisbecker {
59776ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
59786ba94429SFrederic Weisbecker 
59796ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
59806ba94429SFrederic Weisbecker }
59816ba94429SFrederic Weisbecker 
max_active_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)59826ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
59836ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
59846ba94429SFrederic Weisbecker 				size_t count)
59856ba94429SFrederic Weisbecker {
59866ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
59876ba94429SFrederic Weisbecker 	int val;
59886ba94429SFrederic Weisbecker 
59896ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
59906ba94429SFrederic Weisbecker 		return -EINVAL;
59916ba94429SFrederic Weisbecker 
59926ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
59936ba94429SFrederic Weisbecker 	return count;
59946ba94429SFrederic Weisbecker }
59956ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
59966ba94429SFrederic Weisbecker 
59976ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
59986ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
59996ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
60006ba94429SFrederic Weisbecker 	NULL,
60016ba94429SFrederic Weisbecker };
60026ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
60036ba94429SFrederic Weisbecker 
wq_nice_show(struct device * dev,struct device_attribute * attr,char * buf)60046ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
60056ba94429SFrederic Weisbecker 			    char *buf)
60066ba94429SFrederic Weisbecker {
60076ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
60086ba94429SFrederic Weisbecker 	int written;
60096ba94429SFrederic Weisbecker 
60106ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
60116ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
60126ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
60136ba94429SFrederic Weisbecker 
60146ba94429SFrederic Weisbecker 	return written;
60156ba94429SFrederic Weisbecker }
60166ba94429SFrederic Weisbecker 
60176ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
wq_sysfs_prep_attrs(struct workqueue_struct * wq)60186ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
60196ba94429SFrederic Weisbecker {
60206ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
60216ba94429SFrederic Weisbecker 
6022899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
6023899a94feSLai Jiangshan 
6024be69d00dSThomas Gleixner 	attrs = alloc_workqueue_attrs();
60256ba94429SFrederic Weisbecker 	if (!attrs)
60266ba94429SFrederic Weisbecker 		return NULL;
60276ba94429SFrederic Weisbecker 
60286ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
60296ba94429SFrederic Weisbecker 	return attrs;
60306ba94429SFrederic Weisbecker }
60316ba94429SFrederic Weisbecker 
wq_nice_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)60326ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
60336ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
60346ba94429SFrederic Weisbecker {
60356ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
60366ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
6037d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
6038d4d3e257SLai Jiangshan 
6039d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
60406ba94429SFrederic Weisbecker 
60416ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
60426ba94429SFrederic Weisbecker 	if (!attrs)
6043d4d3e257SLai Jiangshan 		goto out_unlock;
60446ba94429SFrederic Weisbecker 
60456ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
60466ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
6047d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
60486ba94429SFrederic Weisbecker 	else
60496ba94429SFrederic Weisbecker 		ret = -EINVAL;
60506ba94429SFrederic Weisbecker 
6051d4d3e257SLai Jiangshan out_unlock:
6052d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
60536ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
60546ba94429SFrederic Weisbecker 	return ret ?: count;
60556ba94429SFrederic Weisbecker }
60566ba94429SFrederic Weisbecker 
wq_cpumask_show(struct device * dev,struct device_attribute * attr,char * buf)60576ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
60586ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
60596ba94429SFrederic Weisbecker {
60606ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
60616ba94429SFrederic Weisbecker 	int written;
60626ba94429SFrederic Weisbecker 
60636ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
60646ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
60656ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
60666ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
60676ba94429SFrederic Weisbecker 	return written;
60686ba94429SFrederic Weisbecker }
60696ba94429SFrederic Weisbecker 
wq_cpumask_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)60706ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
60716ba94429SFrederic Weisbecker 				struct device_attribute *attr,
60726ba94429SFrederic Weisbecker 				const char *buf, size_t count)
60736ba94429SFrederic Weisbecker {
60746ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
60756ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
6076d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
6077d4d3e257SLai Jiangshan 
6078d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
60796ba94429SFrederic Weisbecker 
60806ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
60816ba94429SFrederic Weisbecker 	if (!attrs)
6082d4d3e257SLai Jiangshan 		goto out_unlock;
60836ba94429SFrederic Weisbecker 
60846ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
60856ba94429SFrederic Weisbecker 	if (!ret)
6086d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
60876ba94429SFrederic Weisbecker 
6088d4d3e257SLai Jiangshan out_unlock:
6089d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
60906ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
60916ba94429SFrederic Weisbecker 	return ret ?: count;
60926ba94429SFrederic Weisbecker }
60936ba94429SFrederic Weisbecker 
wq_affn_scope_show(struct device * dev,struct device_attribute * attr,char * buf)609463c5484eSTejun Heo static ssize_t wq_affn_scope_show(struct device *dev,
609563c5484eSTejun Heo 				  struct device_attribute *attr, char *buf)
609663c5484eSTejun Heo {
609763c5484eSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
609863c5484eSTejun Heo 	int written;
609963c5484eSTejun Heo 
610063c5484eSTejun Heo 	mutex_lock(&wq->mutex);
6101523a301eSTejun Heo 	if (wq->unbound_attrs->affn_scope == WQ_AFFN_DFL)
6102523a301eSTejun Heo 		written = scnprintf(buf, PAGE_SIZE, "%s (%s)\n",
6103523a301eSTejun Heo 				    wq_affn_names[WQ_AFFN_DFL],
6104523a301eSTejun Heo 				    wq_affn_names[wq_affn_dfl]);
6105523a301eSTejun Heo 	else
610663c5484eSTejun Heo 		written = scnprintf(buf, PAGE_SIZE, "%s\n",
610763c5484eSTejun Heo 				    wq_affn_names[wq->unbound_attrs->affn_scope]);
610863c5484eSTejun Heo 	mutex_unlock(&wq->mutex);
610963c5484eSTejun Heo 
611063c5484eSTejun Heo 	return written;
611163c5484eSTejun Heo }
611263c5484eSTejun Heo 
wq_affn_scope_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)611363c5484eSTejun Heo static ssize_t wq_affn_scope_store(struct device *dev,
611463c5484eSTejun Heo 				   struct device_attribute *attr,
611563c5484eSTejun Heo 				   const char *buf, size_t count)
611663c5484eSTejun Heo {
611763c5484eSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
611863c5484eSTejun Heo 	struct workqueue_attrs *attrs;
611963c5484eSTejun Heo 	int affn, ret = -ENOMEM;
612063c5484eSTejun Heo 
612163c5484eSTejun Heo 	affn = parse_affn_scope(buf);
612263c5484eSTejun Heo 	if (affn < 0)
612363c5484eSTejun Heo 		return affn;
612463c5484eSTejun Heo 
612563c5484eSTejun Heo 	apply_wqattrs_lock();
612663c5484eSTejun Heo 	attrs = wq_sysfs_prep_attrs(wq);
612763c5484eSTejun Heo 	if (attrs) {
612863c5484eSTejun Heo 		attrs->affn_scope = affn;
612963c5484eSTejun Heo 		ret = apply_workqueue_attrs_locked(wq, attrs);
613063c5484eSTejun Heo 	}
613163c5484eSTejun Heo 	apply_wqattrs_unlock();
613263c5484eSTejun Heo 	free_workqueue_attrs(attrs);
613363c5484eSTejun Heo 	return ret ?: count;
613463c5484eSTejun Heo }
613563c5484eSTejun Heo 
wq_affinity_strict_show(struct device * dev,struct device_attribute * attr,char * buf)61368639ecebSTejun Heo static ssize_t wq_affinity_strict_show(struct device *dev,
61378639ecebSTejun Heo 				       struct device_attribute *attr, char *buf)
61388639ecebSTejun Heo {
61398639ecebSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
61408639ecebSTejun Heo 
61418639ecebSTejun Heo 	return scnprintf(buf, PAGE_SIZE, "%d\n",
61428639ecebSTejun Heo 			 wq->unbound_attrs->affn_strict);
61438639ecebSTejun Heo }
61448639ecebSTejun Heo 
wq_affinity_strict_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)61458639ecebSTejun Heo static ssize_t wq_affinity_strict_store(struct device *dev,
61468639ecebSTejun Heo 					struct device_attribute *attr,
61478639ecebSTejun Heo 					const char *buf, size_t count)
61488639ecebSTejun Heo {
61498639ecebSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
61508639ecebSTejun Heo 	struct workqueue_attrs *attrs;
61518639ecebSTejun Heo 	int v, ret = -ENOMEM;
61528639ecebSTejun Heo 
61538639ecebSTejun Heo 	if (sscanf(buf, "%d", &v) != 1)
61548639ecebSTejun Heo 		return -EINVAL;
61558639ecebSTejun Heo 
61568639ecebSTejun Heo 	apply_wqattrs_lock();
61578639ecebSTejun Heo 	attrs = wq_sysfs_prep_attrs(wq);
61588639ecebSTejun Heo 	if (attrs) {
61598639ecebSTejun Heo 		attrs->affn_strict = (bool)v;
61608639ecebSTejun Heo 		ret = apply_workqueue_attrs_locked(wq, attrs);
61618639ecebSTejun Heo 	}
61628639ecebSTejun Heo 	apply_wqattrs_unlock();
61638639ecebSTejun Heo 	free_workqueue_attrs(attrs);
61648639ecebSTejun Heo 	return ret ?: count;
61658639ecebSTejun Heo }
61668639ecebSTejun Heo 
61676ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
61686ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
61696ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
617063c5484eSTejun Heo 	__ATTR(affinity_scope, 0644, wq_affn_scope_show, wq_affn_scope_store),
61718639ecebSTejun Heo 	__ATTR(affinity_strict, 0644, wq_affinity_strict_show, wq_affinity_strict_store),
61726ba94429SFrederic Weisbecker 	__ATTR_NULL,
61736ba94429SFrederic Weisbecker };
61746ba94429SFrederic Weisbecker 
61756ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
61766ba94429SFrederic Weisbecker 	.name				= "workqueue",
61776ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
61786ba94429SFrederic Weisbecker };
61796ba94429SFrederic Weisbecker 
wq_unbound_cpumask_show(struct device * dev,struct device_attribute * attr,char * buf)6180b05a7928SFrederic Weisbecker static ssize_t wq_unbound_cpumask_show(struct device *dev,
6181b05a7928SFrederic Weisbecker 		struct device_attribute *attr, char *buf)
6182b05a7928SFrederic Weisbecker {
6183b05a7928SFrederic Weisbecker 	int written;
6184b05a7928SFrederic Weisbecker 
6185042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
6186b05a7928SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
6187b05a7928SFrederic Weisbecker 			    cpumask_pr_args(wq_unbound_cpumask));
6188042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
6189b05a7928SFrederic Weisbecker 
6190b05a7928SFrederic Weisbecker 	return written;
6191b05a7928SFrederic Weisbecker }
6192b05a7928SFrederic Weisbecker 
wq_unbound_cpumask_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)6193042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
6194042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
6195042f7df1SLai Jiangshan {
6196042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
6197042f7df1SLai Jiangshan 	int ret;
6198042f7df1SLai Jiangshan 
6199042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
6200042f7df1SLai Jiangshan 		return -ENOMEM;
6201042f7df1SLai Jiangshan 
6202042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
6203042f7df1SLai Jiangshan 	if (!ret)
6204042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
6205042f7df1SLai Jiangshan 
6206042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
6207042f7df1SLai Jiangshan 	return ret ? ret : count;
6208042f7df1SLai Jiangshan }
6209042f7df1SLai Jiangshan 
6210b05a7928SFrederic Weisbecker static struct device_attribute wq_sysfs_cpumask_attr =
6211042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
6212042f7df1SLai Jiangshan 	       wq_unbound_cpumask_store);
6213b05a7928SFrederic Weisbecker 
wq_sysfs_init(void)62146ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
62156ba94429SFrederic Weisbecker {
6216686f6697SGreg Kroah-Hartman 	struct device *dev_root;
6217b05a7928SFrederic Weisbecker 	int err;
6218b05a7928SFrederic Weisbecker 
6219b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
6220b05a7928SFrederic Weisbecker 	if (err)
6221b05a7928SFrederic Weisbecker 		return err;
6222b05a7928SFrederic Weisbecker 
6223686f6697SGreg Kroah-Hartman 	dev_root = bus_get_dev_root(&wq_subsys);
6224686f6697SGreg Kroah-Hartman 	if (dev_root) {
6225686f6697SGreg Kroah-Hartman 		err = device_create_file(dev_root, &wq_sysfs_cpumask_attr);
6226686f6697SGreg Kroah-Hartman 		put_device(dev_root);
6227686f6697SGreg Kroah-Hartman 	}
6228686f6697SGreg Kroah-Hartman 	return err;
62296ba94429SFrederic Weisbecker }
62306ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
62316ba94429SFrederic Weisbecker 
wq_device_release(struct device * dev)62326ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
62336ba94429SFrederic Weisbecker {
62346ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
62356ba94429SFrederic Weisbecker 
62366ba94429SFrederic Weisbecker 	kfree(wq_dev);
62376ba94429SFrederic Weisbecker }
62386ba94429SFrederic Weisbecker 
62396ba94429SFrederic Weisbecker /**
62406ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
62416ba94429SFrederic Weisbecker  * @wq: the workqueue to register
62426ba94429SFrederic Weisbecker  *
62436ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
62446ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
62456ba94429SFrederic Weisbecker  * which is the preferred method.
62466ba94429SFrederic Weisbecker  *
62476ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
62486ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
62496ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
62506ba94429SFrederic Weisbecker  * attributes.
62516ba94429SFrederic Weisbecker  *
62526ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
62536ba94429SFrederic Weisbecker  */
workqueue_sysfs_register(struct workqueue_struct * wq)62546ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
62556ba94429SFrederic Weisbecker {
62566ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
62576ba94429SFrederic Weisbecker 	int ret;
62586ba94429SFrederic Weisbecker 
62596ba94429SFrederic Weisbecker 	/*
6260402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
62616ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
62626ba94429SFrederic Weisbecker 	 * workqueues.
62636ba94429SFrederic Weisbecker 	 */
62640a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
62656ba94429SFrederic Weisbecker 		return -EINVAL;
62666ba94429SFrederic Weisbecker 
62676ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
62686ba94429SFrederic Weisbecker 	if (!wq_dev)
62696ba94429SFrederic Weisbecker 		return -ENOMEM;
62706ba94429SFrederic Weisbecker 
62716ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
62726ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
62736ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
627423217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
62756ba94429SFrederic Weisbecker 
62766ba94429SFrederic Weisbecker 	/*
62776ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
62786ba94429SFrederic Weisbecker 	 * everything is ready.
62796ba94429SFrederic Weisbecker 	 */
62806ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
62816ba94429SFrederic Weisbecker 
62826ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
62836ba94429SFrederic Weisbecker 	if (ret) {
6284537f4146SArvind Yadav 		put_device(&wq_dev->dev);
62856ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
62866ba94429SFrederic Weisbecker 		return ret;
62876ba94429SFrederic Weisbecker 	}
62886ba94429SFrederic Weisbecker 
62896ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
62906ba94429SFrederic Weisbecker 		struct device_attribute *attr;
62916ba94429SFrederic Weisbecker 
62926ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
62936ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
62946ba94429SFrederic Weisbecker 			if (ret) {
62956ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
62966ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
62976ba94429SFrederic Weisbecker 				return ret;
62986ba94429SFrederic Weisbecker 			}
62996ba94429SFrederic Weisbecker 		}
63006ba94429SFrederic Weisbecker 	}
63016ba94429SFrederic Weisbecker 
63026ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
63036ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
63046ba94429SFrederic Weisbecker 	return 0;
63056ba94429SFrederic Weisbecker }
63066ba94429SFrederic Weisbecker 
63076ba94429SFrederic Weisbecker /**
63086ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
63096ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
63106ba94429SFrederic Weisbecker  *
63116ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
63126ba94429SFrederic Weisbecker  */
workqueue_sysfs_unregister(struct workqueue_struct * wq)63136ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
63146ba94429SFrederic Weisbecker {
63156ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
63166ba94429SFrederic Weisbecker 
63176ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
63186ba94429SFrederic Weisbecker 		return;
63196ba94429SFrederic Weisbecker 
63206ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
63216ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
63226ba94429SFrederic Weisbecker }
63236ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
workqueue_sysfs_unregister(struct workqueue_struct * wq)63246ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
63256ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
63266ba94429SFrederic Weisbecker 
632782607adcSTejun Heo /*
632882607adcSTejun Heo  * Workqueue watchdog.
632982607adcSTejun Heo  *
633082607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
633182607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
633282607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
633382607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
633482607adcSTejun Heo  * largely opaque.
633582607adcSTejun Heo  *
633682607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
633782607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
633882607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
633982607adcSTejun Heo  *
634082607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
634182607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
634282607adcSTejun Heo  * corresponding sysfs parameter file.
634382607adcSTejun Heo  */
634482607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
634582607adcSTejun Heo 
634682607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
63475cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
634882607adcSTejun Heo 
634982607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
635082607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
635182607adcSTejun Heo 
6352cd2440d6SPetr Mladek /*
6353cd2440d6SPetr Mladek  * Show workers that might prevent the processing of pending work items.
6354cd2440d6SPetr Mladek  * The only candidates are CPU-bound workers in the running state.
6355cd2440d6SPetr Mladek  * Pending work items should be handled by another idle worker
6356cd2440d6SPetr Mladek  * in all other situations.
6357cd2440d6SPetr Mladek  */
show_cpu_pool_hog(struct worker_pool * pool)6358cd2440d6SPetr Mladek static void show_cpu_pool_hog(struct worker_pool *pool)
6359cd2440d6SPetr Mladek {
6360cd2440d6SPetr Mladek 	struct worker *worker;
6361cd2440d6SPetr Mladek 	unsigned long flags;
6362cd2440d6SPetr Mladek 	int bkt;
6363cd2440d6SPetr Mladek 
6364cd2440d6SPetr Mladek 	raw_spin_lock_irqsave(&pool->lock, flags);
6365cd2440d6SPetr Mladek 
6366cd2440d6SPetr Mladek 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
6367cd2440d6SPetr Mladek 		if (task_is_running(worker->task)) {
6368cd2440d6SPetr Mladek 			/*
6369cd2440d6SPetr Mladek 			 * Defer printing to avoid deadlocks in console
6370cd2440d6SPetr Mladek 			 * drivers that queue work while holding locks
6371cd2440d6SPetr Mladek 			 * also taken in their write paths.
6372cd2440d6SPetr Mladek 			 */
6373cd2440d6SPetr Mladek 			printk_deferred_enter();
6374cd2440d6SPetr Mladek 
6375cd2440d6SPetr Mladek 			pr_info("pool %d:\n", pool->id);
6376cd2440d6SPetr Mladek 			sched_show_task(worker->task);
6377cd2440d6SPetr Mladek 
6378cd2440d6SPetr Mladek 			printk_deferred_exit();
6379cd2440d6SPetr Mladek 		}
6380cd2440d6SPetr Mladek 	}
6381cd2440d6SPetr Mladek 
6382cd2440d6SPetr Mladek 	raw_spin_unlock_irqrestore(&pool->lock, flags);
6383cd2440d6SPetr Mladek }
6384cd2440d6SPetr Mladek 
show_cpu_pools_hogs(void)6385cd2440d6SPetr Mladek static void show_cpu_pools_hogs(void)
6386cd2440d6SPetr Mladek {
6387cd2440d6SPetr Mladek 	struct worker_pool *pool;
6388cd2440d6SPetr Mladek 	int pi;
6389cd2440d6SPetr Mladek 
6390cd2440d6SPetr Mladek 	pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
6391cd2440d6SPetr Mladek 
6392cd2440d6SPetr Mladek 	rcu_read_lock();
6393cd2440d6SPetr Mladek 
6394cd2440d6SPetr Mladek 	for_each_pool(pool, pi) {
6395cd2440d6SPetr Mladek 		if (pool->cpu_stall)
6396cd2440d6SPetr Mladek 			show_cpu_pool_hog(pool);
6397cd2440d6SPetr Mladek 
6398cd2440d6SPetr Mladek 	}
6399cd2440d6SPetr Mladek 
6400cd2440d6SPetr Mladek 	rcu_read_unlock();
6401cd2440d6SPetr Mladek }
6402cd2440d6SPetr Mladek 
wq_watchdog_reset_touched(void)640382607adcSTejun Heo static void wq_watchdog_reset_touched(void)
640482607adcSTejun Heo {
640582607adcSTejun Heo 	int cpu;
640682607adcSTejun Heo 
640782607adcSTejun Heo 	wq_watchdog_touched = jiffies;
640882607adcSTejun Heo 	for_each_possible_cpu(cpu)
640982607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
641082607adcSTejun Heo }
641182607adcSTejun Heo 
wq_watchdog_timer_fn(struct timer_list * unused)64125cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
641382607adcSTejun Heo {
641482607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
641582607adcSTejun Heo 	bool lockup_detected = false;
6416cd2440d6SPetr Mladek 	bool cpu_pool_stall = false;
6417940d71c6SSergey Senozhatsky 	unsigned long now = jiffies;
641882607adcSTejun Heo 	struct worker_pool *pool;
641982607adcSTejun Heo 	int pi;
642082607adcSTejun Heo 
642182607adcSTejun Heo 	if (!thresh)
642282607adcSTejun Heo 		return;
642382607adcSTejun Heo 
642482607adcSTejun Heo 	rcu_read_lock();
642582607adcSTejun Heo 
642682607adcSTejun Heo 	for_each_pool(pool, pi) {
642782607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
642882607adcSTejun Heo 
6429cd2440d6SPetr Mladek 		pool->cpu_stall = false;
643082607adcSTejun Heo 		if (list_empty(&pool->worklist))
643182607adcSTejun Heo 			continue;
643282607adcSTejun Heo 
6433940d71c6SSergey Senozhatsky 		/*
6434940d71c6SSergey Senozhatsky 		 * If a virtual machine is stopped by the host it can look to
6435940d71c6SSergey Senozhatsky 		 * the watchdog like a stall.
6436940d71c6SSergey Senozhatsky 		 */
6437940d71c6SSergey Senozhatsky 		kvm_check_and_clear_guest_paused();
6438940d71c6SSergey Senozhatsky 
643982607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
644089e28ce6SWang Qing 		if (pool->cpu >= 0)
644189e28ce6SWang Qing 			touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
644289e28ce6SWang Qing 		else
644382607adcSTejun Heo 			touched = READ_ONCE(wq_watchdog_touched);
644489e28ce6SWang Qing 		pool_ts = READ_ONCE(pool->watchdog_ts);
644582607adcSTejun Heo 
644682607adcSTejun Heo 		if (time_after(pool_ts, touched))
644782607adcSTejun Heo 			ts = pool_ts;
644882607adcSTejun Heo 		else
644982607adcSTejun Heo 			ts = touched;
645082607adcSTejun Heo 
645182607adcSTejun Heo 		/* did we stall? */
6452940d71c6SSergey Senozhatsky 		if (time_after(now, ts + thresh)) {
645382607adcSTejun Heo 			lockup_detected = true;
6454cd2440d6SPetr Mladek 			if (pool->cpu >= 0) {
6455cd2440d6SPetr Mladek 				pool->cpu_stall = true;
6456cd2440d6SPetr Mladek 				cpu_pool_stall = true;
6457cd2440d6SPetr Mladek 			}
645882607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
645982607adcSTejun Heo 			pr_cont_pool_info(pool);
646082607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
6461940d71c6SSergey Senozhatsky 				jiffies_to_msecs(now - pool_ts) / 1000);
646282607adcSTejun Heo 		}
6463cd2440d6SPetr Mladek 
6464cd2440d6SPetr Mladek 
646582607adcSTejun Heo 	}
646682607adcSTejun Heo 
646782607adcSTejun Heo 	rcu_read_unlock();
646882607adcSTejun Heo 
646982607adcSTejun Heo 	if (lockup_detected)
647055df0933SImran Khan 		show_all_workqueues();
647182607adcSTejun Heo 
6472cd2440d6SPetr Mladek 	if (cpu_pool_stall)
6473cd2440d6SPetr Mladek 		show_cpu_pools_hogs();
6474cd2440d6SPetr Mladek 
647582607adcSTejun Heo 	wq_watchdog_reset_touched();
647682607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
647782607adcSTejun Heo }
647882607adcSTejun Heo 
wq_watchdog_touch(int cpu)6479cb9d7fd5SVincent Whitchurch notrace void wq_watchdog_touch(int cpu)
648082607adcSTejun Heo {
6481241bce1cSNicholas Piggin 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
6482241bce1cSNicholas Piggin 	unsigned long touch_ts = READ_ONCE(wq_watchdog_touched);
6483241bce1cSNicholas Piggin 	unsigned long now = jiffies;
6484241bce1cSNicholas Piggin 
648582607adcSTejun Heo 	if (cpu >= 0)
6486241bce1cSNicholas Piggin 		per_cpu(wq_watchdog_touched_cpu, cpu) = now;
64875ff0a441SNicholas Piggin 	else
64885ff0a441SNicholas Piggin 		WARN_ONCE(1, "%s should be called with valid CPU", __func__);
648989e28ce6SWang Qing 
6490241bce1cSNicholas Piggin 	/* Don't unnecessarily store to global cacheline */
6491241bce1cSNicholas Piggin 	if (time_after(now, touch_ts + thresh / 4))
6492241bce1cSNicholas Piggin 		WRITE_ONCE(wq_watchdog_touched, jiffies);
649382607adcSTejun Heo }
649482607adcSTejun Heo 
wq_watchdog_set_thresh(unsigned long thresh)649582607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
649682607adcSTejun Heo {
649782607adcSTejun Heo 	wq_watchdog_thresh = 0;
649882607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
649982607adcSTejun Heo 
650082607adcSTejun Heo 	if (thresh) {
650182607adcSTejun Heo 		wq_watchdog_thresh = thresh;
650282607adcSTejun Heo 		wq_watchdog_reset_touched();
650382607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
650482607adcSTejun Heo 	}
650582607adcSTejun Heo }
650682607adcSTejun Heo 
wq_watchdog_param_set_thresh(const char * val,const struct kernel_param * kp)650782607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
650882607adcSTejun Heo 					const struct kernel_param *kp)
650982607adcSTejun Heo {
651082607adcSTejun Heo 	unsigned long thresh;
651182607adcSTejun Heo 	int ret;
651282607adcSTejun Heo 
651382607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
651482607adcSTejun Heo 	if (ret)
651582607adcSTejun Heo 		return ret;
651682607adcSTejun Heo 
651782607adcSTejun Heo 	if (system_wq)
651882607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
651982607adcSTejun Heo 	else
652082607adcSTejun Heo 		wq_watchdog_thresh = thresh;
652182607adcSTejun Heo 
652282607adcSTejun Heo 	return 0;
652382607adcSTejun Heo }
652482607adcSTejun Heo 
652582607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
652682607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
652782607adcSTejun Heo 	.get	= param_get_ulong,
652882607adcSTejun Heo };
652982607adcSTejun Heo 
653082607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
653182607adcSTejun Heo 		0644);
653282607adcSTejun Heo 
wq_watchdog_init(void)653382607adcSTejun Heo static void wq_watchdog_init(void)
653482607adcSTejun Heo {
65355cd79d6aSKees Cook 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
653682607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
653782607adcSTejun Heo }
653882607adcSTejun Heo 
653982607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
654082607adcSTejun Heo 
wq_watchdog_init(void)654182607adcSTejun Heo static inline void wq_watchdog_init(void) { }
654282607adcSTejun Heo 
654382607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
654482607adcSTejun Heo 
restrict_unbound_cpumask(const char * name,const struct cpumask * mask)6545b2c562a7STejun Heo static void __init restrict_unbound_cpumask(const char *name, const struct cpumask *mask)
6546b2c562a7STejun Heo {
6547b2c562a7STejun Heo 	if (!cpumask_intersects(wq_unbound_cpumask, mask)) {
6548b2c562a7STejun Heo 		pr_warn("workqueue: Restricting unbound_cpumask (%*pb) with %s (%*pb) leaves no CPU, ignoring\n",
6549b2c562a7STejun Heo 			cpumask_pr_args(wq_unbound_cpumask), name, cpumask_pr_args(mask));
6550b2c562a7STejun Heo 		return;
6551b2c562a7STejun Heo 	}
6552b2c562a7STejun Heo 
6553b2c562a7STejun Heo 	cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, mask);
6554b2c562a7STejun Heo }
6555b2c562a7STejun Heo 
65563347fa09STejun Heo /**
65573347fa09STejun Heo  * workqueue_init_early - early init for workqueue subsystem
65583347fa09STejun Heo  *
65592930155bSTejun Heo  * This is the first step of three-staged workqueue subsystem initialization and
65602930155bSTejun Heo  * invoked as soon as the bare basics - memory allocation, cpumasks and idr are
65612930155bSTejun Heo  * up. It sets up all the data structures and system workqueues and allows early
65622930155bSTejun Heo  * boot code to create workqueues and queue/cancel work items. Actual work item
65632930155bSTejun Heo  * execution starts only after kthreads can be created and scheduled right
65642930155bSTejun Heo  * before early initcalls.
65653347fa09STejun Heo  */
workqueue_init_early(void)65662333e829SYu Chen void __init workqueue_init_early(void)
65671da177e4SLinus Torvalds {
656884193c07STejun Heo 	struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_SYSTEM];
65697a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
65707a4e344cSTejun Heo 	int i, cpu;
6571c34056a3STejun Heo 
657210cdb157SLai Jiangshan 	BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
6573e904e6c2STejun Heo 
6574b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
6575b2c562a7STejun Heo 	cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
6576b2c562a7STejun Heo 	restrict_unbound_cpumask("HK_TYPE_WQ", housekeeping_cpumask(HK_TYPE_WQ));
6577b2c562a7STejun Heo 	restrict_unbound_cpumask("HK_TYPE_DOMAIN", housekeeping_cpumask(HK_TYPE_DOMAIN));
6578ace3c549Stiozhang 	if (!cpumask_empty(&wq_cmdline_cpumask))
6579b2c562a7STejun Heo 		restrict_unbound_cpumask("workqueue.unbound_cpus", &wq_cmdline_cpumask);
6580ace3c549Stiozhang 
6581e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6582e904e6c2STejun Heo 
65832930155bSTejun Heo 	wq_update_pod_attrs_buf = alloc_workqueue_attrs();
65842930155bSTejun Heo 	BUG_ON(!wq_update_pod_attrs_buf);
65852930155bSTejun Heo 
658684193c07STejun Heo 	/* initialize WQ_AFFN_SYSTEM pods */
658784193c07STejun Heo 	pt->pod_cpus = kcalloc(1, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
658884193c07STejun Heo 	pt->pod_node = kcalloc(1, sizeof(pt->pod_node[0]), GFP_KERNEL);
658984193c07STejun Heo 	pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
659084193c07STejun Heo 	BUG_ON(!pt->pod_cpus || !pt->pod_node || !pt->cpu_pod);
659184193c07STejun Heo 
659284193c07STejun Heo 	BUG_ON(!zalloc_cpumask_var_node(&pt->pod_cpus[0], GFP_KERNEL, NUMA_NO_NODE));
659384193c07STejun Heo 
659484193c07STejun Heo 	pt->nr_pods = 1;
659584193c07STejun Heo 	cpumask_copy(pt->pod_cpus[0], cpu_possible_mask);
659684193c07STejun Heo 	pt->pod_node[0] = NUMA_NO_NODE;
659784193c07STejun Heo 	pt->cpu_pod[0] = 0;
659884193c07STejun Heo 
6599706026c2STejun Heo 	/* initialize CPU pools */
660029c91e99STejun Heo 	for_each_possible_cpu(cpu) {
66014ce62e9eSTejun Heo 		struct worker_pool *pool;
66028b03ae3cSTejun Heo 
66037a4e344cSTejun Heo 		i = 0;
6604f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
66057a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
6606ec22ca5eSTejun Heo 			pool->cpu = cpu;
66077a4e344cSTejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
66089546b29eSTejun Heo 			cpumask_copy(pool->attrs->__pod_cpumask, cpumask_of(cpu));
66097a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
66108639ecebSTejun Heo 			pool->attrs->affn_strict = true;
6611f3f90ad4STejun Heo 			pool->node = cpu_to_node(cpu);
66127a4e344cSTejun Heo 
66139daf9e67STejun Heo 			/* alloc pool ID */
661468e13a67SLai Jiangshan 			mutex_lock(&wq_pool_mutex);
66159daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
661668e13a67SLai Jiangshan 			mutex_unlock(&wq_pool_mutex);
66174ce62e9eSTejun Heo 		}
66188b03ae3cSTejun Heo 	}
66198b03ae3cSTejun Heo 
66208a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
662129c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
662229c91e99STejun Heo 		struct workqueue_attrs *attrs;
662329c91e99STejun Heo 
6624be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
662529c91e99STejun Heo 		attrs->nice = std_nice[i];
662629c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
66278a2b7538STejun Heo 
66288a2b7538STejun Heo 		/*
66298a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
66308a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
66318a2b7538STejun Heo 		 */
6632be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
66338a2b7538STejun Heo 		attrs->nice = std_nice[i];
6634af73f5c9STejun Heo 		attrs->ordered = true;
66358a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
663629c91e99STejun Heo 	}
663729c91e99STejun Heo 
6638d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
66391aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
6640d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
6641f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
6642636b927eSTejun Heo 					    WQ_MAX_ACTIVE);
664324d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
664424d51addSTejun Heo 					      WQ_FREEZABLE, 0);
66450668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
66460668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
66477bff1820SGreg Kroah-Hartman 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
66480668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
66490668106cSViresh Kumar 					      0);
66501aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
66510668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
66520668106cSViresh Kumar 	       !system_power_efficient_wq ||
66530668106cSViresh Kumar 	       !system_freezable_power_efficient_wq);
66543347fa09STejun Heo }
66553347fa09STejun Heo 
wq_cpu_intensive_thresh_init(void)6656aa6fde93STejun Heo static void __init wq_cpu_intensive_thresh_init(void)
6657aa6fde93STejun Heo {
6658aa6fde93STejun Heo 	unsigned long thresh;
6659aa6fde93STejun Heo 	unsigned long bogo;
6660aa6fde93STejun Heo 
6661dd64c873SZqiang 	pwq_release_worker = kthread_create_worker(0, "pool_workqueue_release");
6662dd64c873SZqiang 	BUG_ON(IS_ERR(pwq_release_worker));
6663dd64c873SZqiang 
6664aa6fde93STejun Heo 	/* if the user set it to a specific value, keep it */
6665aa6fde93STejun Heo 	if (wq_cpu_intensive_thresh_us != ULONG_MAX)
6666aa6fde93STejun Heo 		return;
6667aa6fde93STejun Heo 
6668aa6fde93STejun Heo 	/*
6669aa6fde93STejun Heo 	 * The default of 10ms is derived from the fact that most modern (as of
6670aa6fde93STejun Heo 	 * 2023) processors can do a lot in 10ms and that it's just below what
6671aa6fde93STejun Heo 	 * most consider human-perceivable. However, the kernel also runs on a
6672aa6fde93STejun Heo 	 * lot slower CPUs including microcontrollers where the threshold is way
6673aa6fde93STejun Heo 	 * too low.
6674aa6fde93STejun Heo 	 *
6675aa6fde93STejun Heo 	 * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
6676aa6fde93STejun Heo 	 * This is by no means accurate but it doesn't have to be. The mechanism
6677aa6fde93STejun Heo 	 * is still useful even when the threshold is fully scaled up. Also, as
6678aa6fde93STejun Heo 	 * the reports would usually be applicable to everyone, some machines
6679aa6fde93STejun Heo 	 * operating on longer thresholds won't significantly diminish their
6680aa6fde93STejun Heo 	 * usefulness.
6681aa6fde93STejun Heo 	 */
6682aa6fde93STejun Heo 	thresh = 10 * USEC_PER_MSEC;
6683aa6fde93STejun Heo 
6684aa6fde93STejun Heo 	/* see init/calibrate.c for lpj -> BogoMIPS calculation */
6685aa6fde93STejun Heo 	bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
6686aa6fde93STejun Heo 	if (bogo < 4000)
6687aa6fde93STejun Heo 		thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
6688aa6fde93STejun Heo 
6689aa6fde93STejun Heo 	pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
6690aa6fde93STejun Heo 		 loops_per_jiffy, bogo, thresh);
6691aa6fde93STejun Heo 
6692aa6fde93STejun Heo 	wq_cpu_intensive_thresh_us = thresh;
6693aa6fde93STejun Heo }
6694aa6fde93STejun Heo 
66953347fa09STejun Heo /**
66963347fa09STejun Heo  * workqueue_init - bring workqueue subsystem fully online
66973347fa09STejun Heo  *
66982930155bSTejun Heo  * This is the second step of three-staged workqueue subsystem initialization
66992930155bSTejun Heo  * and invoked as soon as kthreads can be created and scheduled. Workqueues have
67002930155bSTejun Heo  * been created and work items queued on them, but there are no kworkers
67012930155bSTejun Heo  * executing the work items yet. Populate the worker pools with the initial
67022930155bSTejun Heo  * workers and enable future kworker creations.
67033347fa09STejun Heo  */
workqueue_init(void)67042333e829SYu Chen void __init workqueue_init(void)
67053347fa09STejun Heo {
67062186d9f9STejun Heo 	struct workqueue_struct *wq;
67073347fa09STejun Heo 	struct worker_pool *pool;
67083347fa09STejun Heo 	int cpu, bkt;
67093347fa09STejun Heo 
6710aa6fde93STejun Heo 	wq_cpu_intensive_thresh_init();
6711aa6fde93STejun Heo 
67122186d9f9STejun Heo 	mutex_lock(&wq_pool_mutex);
67132186d9f9STejun Heo 
67142930155bSTejun Heo 	/*
67152930155bSTejun Heo 	 * Per-cpu pools created earlier could be missing node hint. Fix them
67162930155bSTejun Heo 	 * up. Also, create a rescuer for workqueues that requested it.
67172930155bSTejun Heo 	 */
67182186d9f9STejun Heo 	for_each_possible_cpu(cpu) {
67192186d9f9STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
67202186d9f9STejun Heo 			pool->node = cpu_to_node(cpu);
67212186d9f9STejun Heo 		}
67222186d9f9STejun Heo 	}
67232186d9f9STejun Heo 
672440c17f75STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
672540c17f75STejun Heo 		WARN(init_rescuer(wq),
672640c17f75STejun Heo 		     "workqueue: failed to create early rescuer for %s",
672740c17f75STejun Heo 		     wq->name);
672840c17f75STejun Heo 	}
67292186d9f9STejun Heo 
67302186d9f9STejun Heo 	mutex_unlock(&wq_pool_mutex);
67312186d9f9STejun Heo 
67323347fa09STejun Heo 	/* create the initial workers */
67333347fa09STejun Heo 	for_each_online_cpu(cpu) {
67343347fa09STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
67353347fa09STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
67363347fa09STejun Heo 			BUG_ON(!create_worker(pool));
67373347fa09STejun Heo 		}
67383347fa09STejun Heo 	}
67393347fa09STejun Heo 
67403347fa09STejun Heo 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
67413347fa09STejun Heo 		BUG_ON(!create_worker(pool));
67423347fa09STejun Heo 
67433347fa09STejun Heo 	wq_online = true;
674482607adcSTejun Heo 	wq_watchdog_init();
67451da177e4SLinus Torvalds }
6746c4f135d6STetsuo Handa 
6747025e1684STejun Heo /*
6748025e1684STejun Heo  * Initialize @pt by first initializing @pt->cpu_pod[] with pod IDs according to
6749025e1684STejun Heo  * @cpu_shares_pod(). Each subset of CPUs that share a pod is assigned a unique
6750025e1684STejun Heo  * and consecutive pod ID. The rest of @pt is initialized accordingly.
6751025e1684STejun Heo  */
init_pod_type(struct wq_pod_type * pt,bool (* cpus_share_pod)(int,int))6752025e1684STejun Heo static void __init init_pod_type(struct wq_pod_type *pt,
6753025e1684STejun Heo 				 bool (*cpus_share_pod)(int, int))
6754025e1684STejun Heo {
6755025e1684STejun Heo 	int cur, pre, cpu, pod;
6756025e1684STejun Heo 
6757025e1684STejun Heo 	pt->nr_pods = 0;
6758025e1684STejun Heo 
6759025e1684STejun Heo 	/* init @pt->cpu_pod[] according to @cpus_share_pod() */
6760025e1684STejun Heo 	pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
6761025e1684STejun Heo 	BUG_ON(!pt->cpu_pod);
6762025e1684STejun Heo 
6763025e1684STejun Heo 	for_each_possible_cpu(cur) {
6764025e1684STejun Heo 		for_each_possible_cpu(pre) {
6765025e1684STejun Heo 			if (pre >= cur) {
6766025e1684STejun Heo 				pt->cpu_pod[cur] = pt->nr_pods++;
6767025e1684STejun Heo 				break;
6768025e1684STejun Heo 			}
6769025e1684STejun Heo 			if (cpus_share_pod(cur, pre)) {
6770025e1684STejun Heo 				pt->cpu_pod[cur] = pt->cpu_pod[pre];
6771025e1684STejun Heo 				break;
6772025e1684STejun Heo 			}
6773025e1684STejun Heo 		}
6774025e1684STejun Heo 	}
6775025e1684STejun Heo 
6776025e1684STejun Heo 	/* init the rest to match @pt->cpu_pod[] */
6777025e1684STejun Heo 	pt->pod_cpus = kcalloc(pt->nr_pods, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
6778025e1684STejun Heo 	pt->pod_node = kcalloc(pt->nr_pods, sizeof(pt->pod_node[0]), GFP_KERNEL);
6779025e1684STejun Heo 	BUG_ON(!pt->pod_cpus || !pt->pod_node);
6780025e1684STejun Heo 
6781025e1684STejun Heo 	for (pod = 0; pod < pt->nr_pods; pod++)
6782025e1684STejun Heo 		BUG_ON(!zalloc_cpumask_var(&pt->pod_cpus[pod], GFP_KERNEL));
6783025e1684STejun Heo 
6784025e1684STejun Heo 	for_each_possible_cpu(cpu) {
6785025e1684STejun Heo 		cpumask_set_cpu(cpu, pt->pod_cpus[pt->cpu_pod[cpu]]);
6786025e1684STejun Heo 		pt->pod_node[pt->cpu_pod[cpu]] = cpu_to_node(cpu);
6787025e1684STejun Heo 	}
6788025e1684STejun Heo }
6789025e1684STejun Heo 
cpus_dont_share(int cpu0,int cpu1)679063c5484eSTejun Heo static bool __init cpus_dont_share(int cpu0, int cpu1)
679163c5484eSTejun Heo {
679263c5484eSTejun Heo 	return false;
679363c5484eSTejun Heo }
679463c5484eSTejun Heo 
cpus_share_smt(int cpu0,int cpu1)679563c5484eSTejun Heo static bool __init cpus_share_smt(int cpu0, int cpu1)
679663c5484eSTejun Heo {
679763c5484eSTejun Heo #ifdef CONFIG_SCHED_SMT
679863c5484eSTejun Heo 	return cpumask_test_cpu(cpu0, cpu_smt_mask(cpu1));
679963c5484eSTejun Heo #else
680063c5484eSTejun Heo 	return false;
680163c5484eSTejun Heo #endif
680263c5484eSTejun Heo }
680363c5484eSTejun Heo 
cpus_share_numa(int cpu0,int cpu1)6804025e1684STejun Heo static bool __init cpus_share_numa(int cpu0, int cpu1)
6805025e1684STejun Heo {
6806025e1684STejun Heo 	return cpu_to_node(cpu0) == cpu_to_node(cpu1);
6807025e1684STejun Heo }
6808025e1684STejun Heo 
68092930155bSTejun Heo /**
68102930155bSTejun Heo  * workqueue_init_topology - initialize CPU pods for unbound workqueues
68112930155bSTejun Heo  *
68122930155bSTejun Heo  * This is the third step of there-staged workqueue subsystem initialization and
68132930155bSTejun Heo  * invoked after SMP and topology information are fully initialized. It
68142930155bSTejun Heo  * initializes the unbound CPU pods accordingly.
68152930155bSTejun Heo  */
workqueue_init_topology(void)68162930155bSTejun Heo void __init workqueue_init_topology(void)
6817a86feae6STejun Heo {
68182930155bSTejun Heo 	struct workqueue_struct *wq;
6819025e1684STejun Heo 	int cpu;
6820a86feae6STejun Heo 
682163c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_CPU], cpus_dont_share);
682263c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_SMT], cpus_share_smt);
682363c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_CACHE], cpus_share_cache);
6824025e1684STejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_NUMA], cpus_share_numa);
6825a86feae6STejun Heo 
68262930155bSTejun Heo 	mutex_lock(&wq_pool_mutex);
6827a86feae6STejun Heo 
6828a86feae6STejun Heo 	/*
68292930155bSTejun Heo 	 * Workqueues allocated earlier would have all CPUs sharing the default
68302930155bSTejun Heo 	 * worker pool. Explicitly call wq_update_pod() on all workqueue and CPU
68312930155bSTejun Heo 	 * combinations to apply per-pod sharing.
68322930155bSTejun Heo 	 */
68332930155bSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
68346741dd3fSGreg Kroah-Hartman 		for_each_online_cpu(cpu) {
68352930155bSTejun Heo 			wq_update_pod(wq, cpu, cpu, true);
68362930155bSTejun Heo 		}
68372930155bSTejun Heo 	}
68382930155bSTejun Heo 
68392930155bSTejun Heo 	mutex_unlock(&wq_pool_mutex);
6840a86feae6STejun Heo }
6841a86feae6STejun Heo 
__warn_flushing_systemwide_wq(void)684220bdedafSTetsuo Handa void __warn_flushing_systemwide_wq(void)
684320bdedafSTetsuo Handa {
684420bdedafSTetsuo Handa 	pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
684520bdedafSTetsuo Handa 	dump_stack();
684620bdedafSTetsuo Handa }
6847c4f135d6STetsuo Handa EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
6848ace3c549Stiozhang 
workqueue_unbound_cpus_setup(char * str)6849ace3c549Stiozhang static int __init workqueue_unbound_cpus_setup(char *str)
6850ace3c549Stiozhang {
6851ace3c549Stiozhang 	if (cpulist_parse(str, &wq_cmdline_cpumask) < 0) {
6852ace3c549Stiozhang 		cpumask_clear(&wq_cmdline_cpumask);
6853ace3c549Stiozhang 		pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
6854ace3c549Stiozhang 	}
6855ace3c549Stiozhang 
6856ace3c549Stiozhang 	return 1;
6857ace3c549Stiozhang }
6858ace3c549Stiozhang __setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup);
6859