xref: /linux-6.15/kernel/workqueue.c (revision 5cd79d6a)
11da177e4SLinus Torvalds /*
2c54fce6eSTejun Heo  * kernel/workqueue.c - generic async execution with shared worker pool
31da177e4SLinus Torvalds  *
4c54fce6eSTejun Heo  * Copyright (C) 2002		Ingo Molnar
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  *   Derived from the taskqueue/keventd code by:
71da177e4SLinus Torvalds  *     David Woodhouse <[email protected]>
8e1f8e874SFrancois Cami  *     Andrew Morton
91da177e4SLinus Torvalds  *     Kai Petzke <[email protected]>
101da177e4SLinus Torvalds  *     Theodore Ts'o <[email protected]>
1189ada679SChristoph Lameter  *
12cde53535SChristoph Lameter  * Made to use alloc_percpu by Christoph Lameter.
13c54fce6eSTejun Heo  *
14c54fce6eSTejun Heo  * Copyright (C) 2010		SUSE Linux Products GmbH
15c54fce6eSTejun Heo  * Copyright (C) 2010		Tejun Heo <[email protected]>
16c54fce6eSTejun Heo  *
17c54fce6eSTejun Heo  * This is the generic async execution mechanism.  Work items as are
18c54fce6eSTejun Heo  * executed in process context.  The worker pool is shared and
19b11895c4SLibin  * automatically managed.  There are two worker pools for each CPU (one for
20b11895c4SLibin  * normal work items and the other for high priority ones) and some extra
21b11895c4SLibin  * pools for workqueues which are not bound to any specific CPU - the
22b11895c4SLibin  * number of these backing pools is dynamic.
23c54fce6eSTejun Heo  *
249a261491SBenjamin Peterson  * Please read Documentation/core-api/workqueue.rst for details.
251da177e4SLinus Torvalds  */
261da177e4SLinus Torvalds 
279984de1aSPaul Gortmaker #include <linux/export.h>
281da177e4SLinus Torvalds #include <linux/kernel.h>
291da177e4SLinus Torvalds #include <linux/sched.h>
301da177e4SLinus Torvalds #include <linux/init.h>
311da177e4SLinus Torvalds #include <linux/signal.h>
321da177e4SLinus Torvalds #include <linux/completion.h>
331da177e4SLinus Torvalds #include <linux/workqueue.h>
341da177e4SLinus Torvalds #include <linux/slab.h>
351da177e4SLinus Torvalds #include <linux/cpu.h>
361da177e4SLinus Torvalds #include <linux/notifier.h>
371da177e4SLinus Torvalds #include <linux/kthread.h>
381fa44ecaSJames Bottomley #include <linux/hardirq.h>
3946934023SChristoph Lameter #include <linux/mempolicy.h>
40341a5958SRafael J. Wysocki #include <linux/freezer.h>
41d5abe669SPeter Zijlstra #include <linux/kallsyms.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>
51e22bee78STejun Heo 
52ea138446STejun Heo #include "workqueue_internal.h"
531da177e4SLinus Torvalds 
54c8e55f36STejun Heo enum {
55bc2ae0f5STejun Heo 	/*
5624647570STejun Heo 	 * worker_pool flags
57bc2ae0f5STejun Heo 	 *
5824647570STejun Heo 	 * A bound pool is either associated or disassociated with its CPU.
59bc2ae0f5STejun Heo 	 * While associated (!DISASSOCIATED), all workers are bound to the
60bc2ae0f5STejun Heo 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
61bc2ae0f5STejun Heo 	 * is in effect.
62bc2ae0f5STejun Heo 	 *
63bc2ae0f5STejun Heo 	 * While DISASSOCIATED, the cpu may be offline and all workers have
64bc2ae0f5STejun Heo 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
6524647570STejun Heo 	 * be executing on any CPU.  The pool behaves as an unbound one.
66bc2ae0f5STejun Heo 	 *
67bc3a1afcSTejun Heo 	 * Note that DISASSOCIATED should be flipped only while holding
6892f9c5c4SLai Jiangshan 	 * attach_mutex to avoid changing binding state while
694736cbf7SLai Jiangshan 	 * worker_attach_to_pool() is in progress.
70bc2ae0f5STejun Heo 	 */
7124647570STejun Heo 	POOL_DISASSOCIATED	= 1 << 2,	/* cpu can't serve workers */
72db7bccf4STejun Heo 
73c8e55f36STejun Heo 	/* worker flags */
74c8e55f36STejun Heo 	WORKER_DIE		= 1 << 1,	/* die die die */
75c8e55f36STejun Heo 	WORKER_IDLE		= 1 << 2,	/* is idle */
76e22bee78STejun Heo 	WORKER_PREP		= 1 << 3,	/* preparing to run works */
77fb0e7bebSTejun Heo 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
78f3421797STejun Heo 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
79a9ab775bSTejun Heo 	WORKER_REBOUND		= 1 << 8,	/* worker was rebound */
80e22bee78STejun Heo 
81a9ab775bSTejun Heo 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_CPU_INTENSIVE |
82a9ab775bSTejun Heo 				  WORKER_UNBOUND | WORKER_REBOUND,
83db7bccf4STejun Heo 
84e34cdddbSTejun Heo 	NR_STD_WORKER_POOLS	= 2,		/* # standard pools per cpu */
854ce62e9eSTejun Heo 
8629c91e99STejun Heo 	UNBOUND_POOL_HASH_ORDER	= 6,		/* hashed by pool->attrs */
87c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
88db7bccf4STejun Heo 
89e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
90e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
91e22bee78STejun Heo 
923233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
933233cdbdSTejun Heo 						/* call for help after 10ms
943233cdbdSTejun Heo 						   (min two ticks) */
95e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
96e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
971da177e4SLinus Torvalds 
981da177e4SLinus Torvalds 	/*
99e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
1008698a745SDongsheng Yang 	 * all cpus.  Give MIN_NICE.
101e22bee78STejun Heo 	 */
1028698a745SDongsheng Yang 	RESCUER_NICE_LEVEL	= MIN_NICE,
1038698a745SDongsheng Yang 	HIGHPRI_NICE_LEVEL	= MIN_NICE,
104ecf6881fSTejun Heo 
105ecf6881fSTejun Heo 	WQ_NAME_LEN		= 24,
106c8e55f36STejun Heo };
107c8e55f36STejun Heo 
1081da177e4SLinus Torvalds /*
1094690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1104690c4abSTejun Heo  *
111e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
112e41e704bSTejun Heo  *    everyone else.
1134690c4abSTejun Heo  *
114e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
115e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
116e22bee78STejun Heo  *
117d565ed63STejun Heo  * L: pool->lock protected.  Access with pool->lock held.
1184690c4abSTejun Heo  *
119d565ed63STejun Heo  * X: During normal operation, modification requires pool->lock and should
120d565ed63STejun Heo  *    be done only from local cpu.  Either disabling preemption on local
121d565ed63STejun Heo  *    cpu or grabbing pool->lock is enough for read access.  If
122d565ed63STejun Heo  *    POOL_DISASSOCIATED is set, it's identical to L.
123e22bee78STejun Heo  *
12492f9c5c4SLai Jiangshan  * A: pool->attach_mutex protected.
125822d8405STejun Heo  *
12668e13a67SLai Jiangshan  * PL: wq_pool_mutex protected.
12776af4d93STejun Heo  *
12868e13a67SLai Jiangshan  * PR: wq_pool_mutex protected for writes.  Sched-RCU protected for reads.
1295bcab335STejun Heo  *
1305b95e1afSLai Jiangshan  * PW: wq_pool_mutex and wq->mutex protected for writes.  Either for reads.
1315b95e1afSLai Jiangshan  *
1325b95e1afSLai Jiangshan  * PWR: wq_pool_mutex and wq->mutex protected for writes.  Either or
1335b95e1afSLai Jiangshan  *      sched-RCU for reads.
1345b95e1afSLai Jiangshan  *
1353c25a55dSLai Jiangshan  * WQ: wq->mutex protected.
1363c25a55dSLai Jiangshan  *
137b5927605SLai Jiangshan  * WR: wq->mutex protected for writes.  Sched-RCU protected for reads.
1382e109a28STejun Heo  *
1392e109a28STejun Heo  * MD: wq_mayday_lock protected.
1404690c4abSTejun Heo  */
1414690c4abSTejun Heo 
1422eaebdb3STejun Heo /* struct worker is defined in workqueue_internal.h */
143c34056a3STejun Heo 
144bd7bdd43STejun Heo struct worker_pool {
145d565ed63STejun Heo 	spinlock_t		lock;		/* the pool lock */
146d84ff051STejun Heo 	int			cpu;		/* I: the associated cpu */
147f3f90ad4STejun Heo 	int			node;		/* I: the associated node ID */
1489daf9e67STejun Heo 	int			id;		/* I: pool ID */
14911ebea50STejun Heo 	unsigned int		flags;		/* X: flags */
150bd7bdd43STejun Heo 
15182607adcSTejun Heo 	unsigned long		watchdog_ts;	/* L: watchdog timestamp */
15282607adcSTejun Heo 
153bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
154bd7bdd43STejun Heo 	int			nr_workers;	/* L: total number of workers */
155ea1abd61SLai Jiangshan 
156ea1abd61SLai Jiangshan 	/* nr_idle includes the ones off idle_list for rebinding */
157bd7bdd43STejun Heo 	int			nr_idle;	/* L: currently idle ones */
158bd7bdd43STejun Heo 
159bd7bdd43STejun Heo 	struct list_head	idle_list;	/* X: list of idle workers */
160bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
161bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	/* L: SOS timer for workers */
162bd7bdd43STejun Heo 
163c5aa87bbSTejun Heo 	/* a workers is either on busy_hash or idle_list, or the manager */
164c9e7cf27STejun Heo 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
165c9e7cf27STejun Heo 						/* L: hash of busy workers */
166c9e7cf27STejun Heo 
167bc3a1afcSTejun Heo 	/* see manage_workers() for details on the two manager mutexes */
16834a06bd6STejun Heo 	struct mutex		manager_arb;	/* manager arbitration */
1692607d7a6STejun Heo 	struct worker		*manager;	/* L: purely informational */
17092f9c5c4SLai Jiangshan 	struct mutex		attach_mutex;	/* attach/detach exclusion */
17192f9c5c4SLai Jiangshan 	struct list_head	workers;	/* A: attached workers */
17260f5a4bcSLai Jiangshan 	struct completion	*detach_completion; /* all workers detached */
173e19e397aSTejun Heo 
1747cda9aaeSLai Jiangshan 	struct ida		worker_ida;	/* worker IDs for task name */
175e19e397aSTejun Heo 
1767a4e344cSTejun Heo 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
17768e13a67SLai Jiangshan 	struct hlist_node	hash_node;	/* PL: unbound_pool_hash node */
17868e13a67SLai Jiangshan 	int			refcnt;		/* PL: refcnt for unbound pools */
1797a4e344cSTejun Heo 
180e19e397aSTejun Heo 	/*
181e19e397aSTejun Heo 	 * The current concurrency level.  As it's likely to be accessed
182e19e397aSTejun Heo 	 * from other CPUs during try_to_wake_up(), put it in a separate
183e19e397aSTejun Heo 	 * cacheline.
184e19e397aSTejun Heo 	 */
185e19e397aSTejun Heo 	atomic_t		nr_running ____cacheline_aligned_in_smp;
18629c91e99STejun Heo 
18729c91e99STejun Heo 	/*
18829c91e99STejun Heo 	 * Destruction of pool is sched-RCU protected to allow dereferences
18929c91e99STejun Heo 	 * from get_work_pool().
19029c91e99STejun Heo 	 */
19129c91e99STejun Heo 	struct rcu_head		rcu;
1928b03ae3cSTejun Heo } ____cacheline_aligned_in_smp;
1938b03ae3cSTejun Heo 
1948b03ae3cSTejun Heo /*
195112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
196112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
197112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
198112202d9STejun Heo  * number of flag bits.
1991da177e4SLinus Torvalds  */
200112202d9STejun Heo struct pool_workqueue {
201bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
2024690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
20373f53c4aSTejun Heo 	int			work_color;	/* L: current color */
20473f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
2058864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
20673f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
20773f53c4aSTejun Heo 						/* L: nr of in_flight works */
2081e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
209a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
2101e19ffc6STejun Heo 	struct list_head	delayed_works;	/* L: delayed works */
2113c25a55dSLai Jiangshan 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
2122e109a28STejun Heo 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
2138864b4e5STejun Heo 
2148864b4e5STejun Heo 	/*
2158864b4e5STejun Heo 	 * Release of unbound pwq is punted to system_wq.  See put_pwq()
2168864b4e5STejun Heo 	 * and pwq_unbound_release_workfn() for details.  pool_workqueue
2178864b4e5STejun Heo 	 * itself is also sched-RCU protected so that the first pwq can be
218b09f4fd3SLai Jiangshan 	 * determined without grabbing wq->mutex.
2198864b4e5STejun Heo 	 */
2208864b4e5STejun Heo 	struct work_struct	unbound_release_work;
2218864b4e5STejun Heo 	struct rcu_head		rcu;
222e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2231da177e4SLinus Torvalds 
2241da177e4SLinus Torvalds /*
22573f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
22673f53c4aSTejun Heo  */
22773f53c4aSTejun Heo struct wq_flusher {
2283c25a55dSLai Jiangshan 	struct list_head	list;		/* WQ: list of flushers */
2293c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: flush color waiting for */
23073f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
23173f53c4aSTejun Heo };
2321da177e4SLinus Torvalds 
233226223abSTejun Heo struct wq_device;
234226223abSTejun Heo 
23573f53c4aSTejun Heo /*
236c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
237c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
2381da177e4SLinus Torvalds  */
2391da177e4SLinus Torvalds struct workqueue_struct {
2403c25a55dSLai Jiangshan 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
241e2dca7adSTejun Heo 	struct list_head	list;		/* PR: list of all workqueues */
24273f53c4aSTejun Heo 
2433c25a55dSLai Jiangshan 	struct mutex		mutex;		/* protects this wq */
2443c25a55dSLai Jiangshan 	int			work_color;	/* WQ: current work color */
2453c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: current flush color */
246112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
2473c25a55dSLai Jiangshan 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
2483c25a55dSLai Jiangshan 	struct list_head	flusher_queue;	/* WQ: flush waiters */
2493c25a55dSLai Jiangshan 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
25073f53c4aSTejun Heo 
2512e109a28STejun Heo 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
252e22bee78STejun Heo 	struct worker		*rescuer;	/* I: rescue worker */
253e22bee78STejun Heo 
25487fc741eSLai Jiangshan 	int			nr_drainers;	/* WQ: drain in progress */
255a357fc03SLai Jiangshan 	int			saved_max_active; /* WQ: saved pwq max_active */
256226223abSTejun Heo 
2575b95e1afSLai Jiangshan 	struct workqueue_attrs	*unbound_attrs;	/* PW: only for unbound wqs */
2585b95e1afSLai Jiangshan 	struct pool_workqueue	*dfl_pwq;	/* PW: only for unbound wqs */
2596029a918STejun Heo 
260226223abSTejun Heo #ifdef CONFIG_SYSFS
261226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
262226223abSTejun Heo #endif
2634e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
2644e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
2654e6045f1SJohannes Berg #endif
266ecf6881fSTejun Heo 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
2672728fd2fSTejun Heo 
268e2dca7adSTejun Heo 	/*
269e2dca7adSTejun Heo 	 * Destruction of workqueue_struct is sched-RCU protected to allow
270e2dca7adSTejun Heo 	 * walking the workqueues list without grabbing wq_pool_mutex.
271e2dca7adSTejun Heo 	 * This is used to dump all workqueues from sysrq.
272e2dca7adSTejun Heo 	 */
273e2dca7adSTejun Heo 	struct rcu_head		rcu;
274e2dca7adSTejun Heo 
2752728fd2fSTejun Heo 	/* hot fields used during command issue, aligned to cacheline */
2762728fd2fSTejun Heo 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
2772728fd2fSTejun Heo 	struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
2785b95e1afSLai Jiangshan 	struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
2791da177e4SLinus Torvalds };
2801da177e4SLinus Torvalds 
281e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
282e904e6c2STejun Heo 
283bce90380STejun Heo static cpumask_var_t *wq_numa_possible_cpumask;
284bce90380STejun Heo 					/* possible CPUs of each node */
285bce90380STejun Heo 
286d55262c4STejun Heo static bool wq_disable_numa;
287d55262c4STejun Heo module_param_named(disable_numa, wq_disable_numa, bool, 0444);
288d55262c4STejun Heo 
289cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
290552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
291cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
292cee22a15SViresh Kumar 
293863b710bSTejun Heo static bool wq_online;			/* can kworkers be created yet? */
2943347fa09STejun Heo 
295bce90380STejun Heo static bool wq_numa_enabled;		/* unbound NUMA affinity enabled */
296bce90380STejun Heo 
2974c16bd32STejun Heo /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
2984c16bd32STejun Heo static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
2994c16bd32STejun Heo 
30068e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
3012e109a28STejun Heo static DEFINE_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
3025bcab335STejun Heo 
303e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
30468e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
3057d19c5ceSTejun Heo 
306ef557180SMike Galbraith /* PL: allowable cpus for unbound wqs and work items */
307ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
308ef557180SMike Galbraith 
309ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
310ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
311b05a7928SFrederic Weisbecker 
312f303fccbSTejun Heo /*
313f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
314f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
315f303fccbSTejun Heo  * to uncover usages which depend on it.
316f303fccbSTejun Heo  */
317f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
318f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
319f303fccbSTejun Heo #else
320f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
321f303fccbSTejun Heo #endif
322f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
323f303fccbSTejun Heo 
3247d19c5ceSTejun Heo /* the per-cpu worker pools */
32525528213SPeter Zijlstra static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
3267d19c5ceSTejun Heo 
32768e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
3287d19c5ceSTejun Heo 
32968e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
33029c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
33129c91e99STejun Heo 
332c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
33329c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
33429c91e99STejun Heo 
3358a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
3368a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
3378a2b7538STejun Heo 
338d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
339ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
340044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
3411aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
342044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
343d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
344044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
345f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
346044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
34724d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
3480668106cSViresh Kumar struct workqueue_struct *system_power_efficient_wq __read_mostly;
3490668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
3500668106cSViresh Kumar struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
3510668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
352d320c038STejun Heo 
3537d19c5ceSTejun Heo static int worker_thread(void *__worker);
3546ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
3557d19c5ceSTejun Heo 
35697bd2347STejun Heo #define CREATE_TRACE_POINTS
35797bd2347STejun Heo #include <trace/events/workqueue.h>
35897bd2347STejun Heo 
35968e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
360f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
361f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
36268e13a67SLai Jiangshan 			 "sched RCU or wq_pool_mutex should be held")
3635bcab335STejun Heo 
364b09f4fd3SLai Jiangshan #define assert_rcu_or_wq_mutex(wq)					\
365f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
366f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex),			\
367b09f4fd3SLai Jiangshan 			 "sched RCU or wq->mutex should be held")
36876af4d93STejun Heo 
3695b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
370f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
371f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
372f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
3735b95e1afSLai Jiangshan 			 "sched RCU, wq->mutex or wq_pool_mutex should be held")
3745b95e1afSLai Jiangshan 
375f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
376f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
377f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
3787a62c2c8STejun Heo 	     (pool)++)
3794ce62e9eSTejun Heo 
38049e3cf44STejun Heo /**
38117116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
38217116969STejun Heo  * @pool: iteration cursor
383611c92a0STejun Heo  * @pi: integer used for iteration
384fa1b54e6STejun Heo  *
38568e13a67SLai Jiangshan  * This must be called either with wq_pool_mutex held or sched RCU read
38668e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
38768e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
388fa1b54e6STejun Heo  *
389fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
390fa1b54e6STejun Heo  * ignored.
39117116969STejun Heo  */
392611c92a0STejun Heo #define for_each_pool(pool, pi)						\
393611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
39468e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
395fa1b54e6STejun Heo 		else
39617116969STejun Heo 
39717116969STejun Heo /**
398822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
399822d8405STejun Heo  * @worker: iteration cursor
400822d8405STejun Heo  * @pool: worker_pool to iterate workers of
401822d8405STejun Heo  *
40292f9c5c4SLai Jiangshan  * This must be called with @pool->attach_mutex.
403822d8405STejun Heo  *
404822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
405822d8405STejun Heo  * ignored.
406822d8405STejun Heo  */
407da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
408da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
40992f9c5c4SLai Jiangshan 		if (({ lockdep_assert_held(&pool->attach_mutex); false; })) { } \
410822d8405STejun Heo 		else
411822d8405STejun Heo 
412822d8405STejun Heo /**
41349e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
41449e3cf44STejun Heo  * @pwq: iteration cursor
41549e3cf44STejun Heo  * @wq: the target workqueue
41676af4d93STejun Heo  *
417b09f4fd3SLai Jiangshan  * This must be called either with wq->mutex held or sched RCU read locked.
418794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
419794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
42076af4d93STejun Heo  *
42176af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
42276af4d93STejun Heo  * ignored.
42349e3cf44STejun Heo  */
42449e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
42576af4d93STejun Heo 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node)		\
426b09f4fd3SLai Jiangshan 		if (({ assert_rcu_or_wq_mutex(wq); false; })) { }	\
42776af4d93STejun Heo 		else
428f3421797STejun Heo 
429dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
430dc186ad7SThomas Gleixner 
431dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr;
432dc186ad7SThomas Gleixner 
43399777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
43499777288SStanislaw Gruszka {
43599777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
43699777288SStanislaw Gruszka }
43799777288SStanislaw Gruszka 
438b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
439b9fdac7fSDu, Changbin {
440b9fdac7fSDu, Changbin 	struct work_struct *work = addr;
441b9fdac7fSDu, Changbin 
442b9fdac7fSDu, Changbin 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
443b9fdac7fSDu, Changbin }
444b9fdac7fSDu, Changbin 
445dc186ad7SThomas Gleixner /*
446dc186ad7SThomas Gleixner  * fixup_init is called when:
447dc186ad7SThomas Gleixner  * - an active object is initialized
448dc186ad7SThomas Gleixner  */
44902a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
450dc186ad7SThomas Gleixner {
451dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
452dc186ad7SThomas Gleixner 
453dc186ad7SThomas Gleixner 	switch (state) {
454dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
455dc186ad7SThomas Gleixner 		cancel_work_sync(work);
456dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
45702a982a6SDu, Changbin 		return true;
458dc186ad7SThomas Gleixner 	default:
45902a982a6SDu, Changbin 		return false;
460dc186ad7SThomas Gleixner 	}
461dc186ad7SThomas Gleixner }
462dc186ad7SThomas Gleixner 
463dc186ad7SThomas Gleixner /*
464dc186ad7SThomas Gleixner  * fixup_free is called when:
465dc186ad7SThomas Gleixner  * - an active object is freed
466dc186ad7SThomas Gleixner  */
46702a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
468dc186ad7SThomas Gleixner {
469dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
470dc186ad7SThomas Gleixner 
471dc186ad7SThomas Gleixner 	switch (state) {
472dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
473dc186ad7SThomas Gleixner 		cancel_work_sync(work);
474dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
47502a982a6SDu, Changbin 		return true;
476dc186ad7SThomas Gleixner 	default:
47702a982a6SDu, Changbin 		return false;
478dc186ad7SThomas Gleixner 	}
479dc186ad7SThomas Gleixner }
480dc186ad7SThomas Gleixner 
481dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr = {
482dc186ad7SThomas Gleixner 	.name		= "work_struct",
48399777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
484b9fdac7fSDu, Changbin 	.is_static_object = work_is_static_object,
485dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
486dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
487dc186ad7SThomas Gleixner };
488dc186ad7SThomas Gleixner 
489dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
490dc186ad7SThomas Gleixner {
491dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
492dc186ad7SThomas Gleixner }
493dc186ad7SThomas Gleixner 
494dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
495dc186ad7SThomas Gleixner {
496dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
497dc186ad7SThomas Gleixner }
498dc186ad7SThomas Gleixner 
499dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
500dc186ad7SThomas Gleixner {
501dc186ad7SThomas Gleixner 	if (onstack)
502dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
503dc186ad7SThomas Gleixner 	else
504dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
505dc186ad7SThomas Gleixner }
506dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
507dc186ad7SThomas Gleixner 
508dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
509dc186ad7SThomas Gleixner {
510dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
511dc186ad7SThomas Gleixner }
512dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
513dc186ad7SThomas Gleixner 
514ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
515ea2e64f2SThomas Gleixner {
516ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
517ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
518ea2e64f2SThomas Gleixner }
519ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
520ea2e64f2SThomas Gleixner 
521dc186ad7SThomas Gleixner #else
522dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
523dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
524dc186ad7SThomas Gleixner #endif
525dc186ad7SThomas Gleixner 
5264e8b22bdSLi Bin /**
5274e8b22bdSLi Bin  * worker_pool_assign_id - allocate ID and assing it to @pool
5284e8b22bdSLi Bin  * @pool: the pool pointer of interest
5294e8b22bdSLi Bin  *
5304e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
5314e8b22bdSLi Bin  * successfully, -errno on failure.
5324e8b22bdSLi Bin  */
5339daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
5349daf9e67STejun Heo {
5359daf9e67STejun Heo 	int ret;
5369daf9e67STejun Heo 
53768e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5385bcab335STejun Heo 
5394e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
5404e8b22bdSLi Bin 			GFP_KERNEL);
541229641a6STejun Heo 	if (ret >= 0) {
542e68035fbSTejun Heo 		pool->id = ret;
543229641a6STejun Heo 		return 0;
544229641a6STejun Heo 	}
5459daf9e67STejun Heo 	return ret;
5469daf9e67STejun Heo }
5479daf9e67STejun Heo 
54876af4d93STejun Heo /**
549df2d5ae4STejun Heo  * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
550df2d5ae4STejun Heo  * @wq: the target workqueue
551df2d5ae4STejun Heo  * @node: the node ID
552df2d5ae4STejun Heo  *
5535b95e1afSLai Jiangshan  * This must be called with any of wq_pool_mutex, wq->mutex or sched RCU
5545b95e1afSLai Jiangshan  * read locked.
555df2d5ae4STejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
556df2d5ae4STejun Heo  * responsible for guaranteeing that the pwq stays online.
557d185af30SYacine Belkadi  *
558d185af30SYacine Belkadi  * Return: The unbound pool_workqueue for @node.
559df2d5ae4STejun Heo  */
560df2d5ae4STejun Heo static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
561df2d5ae4STejun Heo 						  int node)
562df2d5ae4STejun Heo {
5635b95e1afSLai Jiangshan 	assert_rcu_or_wq_mutex_or_pool_mutex(wq);
564d6e022f1STejun Heo 
565d6e022f1STejun Heo 	/*
566d6e022f1STejun Heo 	 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
567d6e022f1STejun Heo 	 * delayed item is pending.  The plan is to keep CPU -> NODE
568d6e022f1STejun Heo 	 * mapping valid and stable across CPU on/offlines.  Once that
569d6e022f1STejun Heo 	 * happens, this workaround can be removed.
570d6e022f1STejun Heo 	 */
571d6e022f1STejun Heo 	if (unlikely(node == NUMA_NO_NODE))
572d6e022f1STejun Heo 		return wq->dfl_pwq;
573d6e022f1STejun Heo 
574df2d5ae4STejun Heo 	return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
575df2d5ae4STejun Heo }
576df2d5ae4STejun Heo 
57773f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
57873f53c4aSTejun Heo {
57973f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
58073f53c4aSTejun Heo }
58173f53c4aSTejun Heo 
58273f53c4aSTejun Heo static int get_work_color(struct work_struct *work)
58373f53c4aSTejun Heo {
58473f53c4aSTejun Heo 	return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
58573f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
58673f53c4aSTejun Heo }
58773f53c4aSTejun Heo 
58873f53c4aSTejun Heo static int work_next_color(int color)
58973f53c4aSTejun Heo {
59073f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
591a848e3b6SOleg Nesterov }
592a848e3b6SOleg Nesterov 
5934594bf15SDavid Howells /*
594112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
595112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
5967c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
5977a22ad75STejun Heo  *
598112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
599112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
600bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
601bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
6027a22ad75STejun Heo  *
603112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6047c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
605112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
6067c3eed5cSTejun Heo  * available only while the work item is queued.
607bbb68dfaSTejun Heo  *
608bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
609bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
610bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
611bbb68dfaSTejun Heo  * try to steal the PENDING bit.
6124594bf15SDavid Howells  */
6137a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6147a22ad75STejun Heo 				 unsigned long flags)
6157a22ad75STejun Heo {
6166183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
6177a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
6187a22ad75STejun Heo }
6197a22ad75STejun Heo 
620112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6214690c4abSTejun Heo 			 unsigned long extra_flags)
622365970a1SDavid Howells {
623112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
624112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
625365970a1SDavid Howells }
626365970a1SDavid Howells 
6274468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6284468a00fSLai Jiangshan 					   int pool_id)
6294468a00fSLai Jiangshan {
6304468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6314468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6324468a00fSLai Jiangshan }
6334468a00fSLai Jiangshan 
6347c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6357c3eed5cSTejun Heo 					    int pool_id)
6364d707b9fSOleg Nesterov {
63723657bb1STejun Heo 	/*
63823657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
63923657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
64023657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
64123657bb1STejun Heo 	 * owner.
64223657bb1STejun Heo 	 */
64323657bb1STejun Heo 	smp_wmb();
6447c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
645346c09f8SRoman Pen 	/*
646346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
647346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
648346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
649346c09f8SRoman Pen 	 * reordering can lead to a missed execution on attempt to qeueue
650346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
651346c09f8SRoman Pen 	 *
652346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
653346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
654346c09f8SRoman Pen 	 *
655346c09f8SRoman Pen 	 * 1  STORE event_indicated
656346c09f8SRoman Pen 	 * 2  queue_work_on() {
657346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
658346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
659346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
660346c09f8SRoman Pen 	 * 6                                 smp_mb()
661346c09f8SRoman Pen 	 * 7                               work->current_func() {
662346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
663346c09f8SRoman Pen 	 *				   }
664346c09f8SRoman Pen 	 *
665346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
666346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
667346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
668346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
669346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
670346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
671346c09f8SRoman Pen 	 * before actual STORE.
672346c09f8SRoman Pen 	 */
673346c09f8SRoman Pen 	smp_mb();
6744d707b9fSOleg Nesterov }
6754d707b9fSOleg Nesterov 
6767a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
677365970a1SDavid Howells {
6787c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
6797c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
6807a22ad75STejun Heo }
6817a22ad75STejun Heo 
682112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
6837a22ad75STejun Heo {
684e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
6857a22ad75STejun Heo 
686112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
687e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
688e120153dSTejun Heo 	else
689e120153dSTejun Heo 		return NULL;
6907a22ad75STejun Heo }
6917a22ad75STejun Heo 
6927c3eed5cSTejun Heo /**
6937c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
6947c3eed5cSTejun Heo  * @work: the work item of interest
6957c3eed5cSTejun Heo  *
69668e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
69768e13a67SLai Jiangshan  * access under sched-RCU read lock.  As such, this function should be
69868e13a67SLai Jiangshan  * called under wq_pool_mutex or with preemption disabled.
699fa1b54e6STejun Heo  *
700fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
701fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
702fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
703fa1b54e6STejun Heo  * returned pool is and stays online.
704d185af30SYacine Belkadi  *
705d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
7067c3eed5cSTejun Heo  */
7077c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
7087a22ad75STejun Heo {
709e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7107c3eed5cSTejun Heo 	int pool_id;
7117a22ad75STejun Heo 
71268e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
713fa1b54e6STejun Heo 
714112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
715112202d9STejun Heo 		return ((struct pool_workqueue *)
7167c3eed5cSTejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool;
7177a22ad75STejun Heo 
7187c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
7197c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
7207a22ad75STejun Heo 		return NULL;
7217a22ad75STejun Heo 
722fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
7237c3eed5cSTejun Heo }
7247c3eed5cSTejun Heo 
7257c3eed5cSTejun Heo /**
7267c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
7277c3eed5cSTejun Heo  * @work: the work item of interest
7287c3eed5cSTejun Heo  *
729d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
7307c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
7317c3eed5cSTejun Heo  */
7327c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
7337c3eed5cSTejun Heo {
73454d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
7357c3eed5cSTejun Heo 
736112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
737112202d9STejun Heo 		return ((struct pool_workqueue *)
73854d5b7d0SLai Jiangshan 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
73954d5b7d0SLai Jiangshan 
74054d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
7417c3eed5cSTejun Heo }
7427c3eed5cSTejun Heo 
743bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
744bbb68dfaSTejun Heo {
7457c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
746bbb68dfaSTejun Heo 
7477c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
7487c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
749bbb68dfaSTejun Heo }
750bbb68dfaSTejun Heo 
751bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
752bbb68dfaSTejun Heo {
753bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
754bbb68dfaSTejun Heo 
755112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
756bbb68dfaSTejun Heo }
757bbb68dfaSTejun Heo 
758e22bee78STejun Heo /*
7593270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
7603270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
761d565ed63STejun Heo  * they're being called with pool->lock held.
762e22bee78STejun Heo  */
763e22bee78STejun Heo 
76463d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
765649027d7STejun Heo {
766e19e397aSTejun Heo 	return !atomic_read(&pool->nr_running);
767649027d7STejun Heo }
768649027d7STejun Heo 
769e22bee78STejun Heo /*
770e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
771e22bee78STejun Heo  * running workers.
772974271c4STejun Heo  *
773974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
774706026c2STejun Heo  * function will always return %true for unbound pools as long as the
775974271c4STejun Heo  * worklist isn't empty.
776e22bee78STejun Heo  */
77763d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
778e22bee78STejun Heo {
77963d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
780e22bee78STejun Heo }
781e22bee78STejun Heo 
782e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
78363d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
784e22bee78STejun Heo {
78563d95a91STejun Heo 	return pool->nr_idle;
786e22bee78STejun Heo }
787e22bee78STejun Heo 
788e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
78963d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
790e22bee78STejun Heo {
791e19e397aSTejun Heo 	return !list_empty(&pool->worklist) &&
792e19e397aSTejun Heo 		atomic_read(&pool->nr_running) <= 1;
793e22bee78STejun Heo }
794e22bee78STejun Heo 
795e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
79663d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
797e22bee78STejun Heo {
79863d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
799e22bee78STejun Heo }
800e22bee78STejun Heo 
801e22bee78STejun Heo /* Do we have too many workers and should some go away? */
80263d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
803e22bee78STejun Heo {
80434a06bd6STejun Heo 	bool managing = mutex_is_locked(&pool->manager_arb);
80563d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
80663d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
807e22bee78STejun Heo 
808e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
809e22bee78STejun Heo }
810e22bee78STejun Heo 
811e22bee78STejun Heo /*
812e22bee78STejun Heo  * Wake up functions.
813e22bee78STejun Heo  */
814e22bee78STejun Heo 
8151037de36SLai Jiangshan /* Return the first idle worker.  Safe with preemption disabled */
8161037de36SLai Jiangshan static struct worker *first_idle_worker(struct worker_pool *pool)
8177e11629dSTejun Heo {
81863d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
8197e11629dSTejun Heo 		return NULL;
8207e11629dSTejun Heo 
82163d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
8227e11629dSTejun Heo }
8237e11629dSTejun Heo 
8247e11629dSTejun Heo /**
8257e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
82663d95a91STejun Heo  * @pool: worker pool to wake worker from
8277e11629dSTejun Heo  *
82863d95a91STejun Heo  * Wake up the first idle worker of @pool.
8297e11629dSTejun Heo  *
8307e11629dSTejun Heo  * CONTEXT:
831d565ed63STejun Heo  * spin_lock_irq(pool->lock).
8327e11629dSTejun Heo  */
83363d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
8347e11629dSTejun Heo {
8351037de36SLai Jiangshan 	struct worker *worker = first_idle_worker(pool);
8367e11629dSTejun Heo 
8377e11629dSTejun Heo 	if (likely(worker))
8387e11629dSTejun Heo 		wake_up_process(worker->task);
8397e11629dSTejun Heo }
8407e11629dSTejun Heo 
8414690c4abSTejun Heo /**
842e22bee78STejun Heo  * wq_worker_waking_up - a worker is waking up
843e22bee78STejun Heo  * @task: task waking up
844e22bee78STejun Heo  * @cpu: CPU @task is waking up to
845e22bee78STejun Heo  *
846e22bee78STejun Heo  * This function is called during try_to_wake_up() when a worker is
847e22bee78STejun Heo  * being awoken.
848e22bee78STejun Heo  *
849e22bee78STejun Heo  * CONTEXT:
850e22bee78STejun Heo  * spin_lock_irq(rq->lock)
851e22bee78STejun Heo  */
852d84ff051STejun Heo void wq_worker_waking_up(struct task_struct *task, int cpu)
853e22bee78STejun Heo {
854e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
855e22bee78STejun Heo 
85636576000SJoonsoo Kim 	if (!(worker->flags & WORKER_NOT_RUNNING)) {
857ec22ca5eSTejun Heo 		WARN_ON_ONCE(worker->pool->cpu != cpu);
858e19e397aSTejun Heo 		atomic_inc(&worker->pool->nr_running);
859e22bee78STejun Heo 	}
86036576000SJoonsoo Kim }
861e22bee78STejun Heo 
862e22bee78STejun Heo /**
863e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
864e22bee78STejun Heo  * @task: task going to sleep
865e22bee78STejun Heo  *
866e22bee78STejun Heo  * This function is called during schedule() when a busy worker is
867e22bee78STejun Heo  * going to sleep.  Worker on the same cpu can be woken up by
868e22bee78STejun Heo  * returning pointer to its task.
869e22bee78STejun Heo  *
870e22bee78STejun Heo  * CONTEXT:
871e22bee78STejun Heo  * spin_lock_irq(rq->lock)
872e22bee78STejun Heo  *
873d185af30SYacine Belkadi  * Return:
874e22bee78STejun Heo  * Worker task on @cpu to wake up, %NULL if none.
875e22bee78STejun Heo  */
8769b7f6597SAlexander Gordeev struct task_struct *wq_worker_sleeping(struct task_struct *task)
877e22bee78STejun Heo {
878e22bee78STejun Heo 	struct worker *worker = kthread_data(task), *to_wakeup = NULL;
879111c225aSTejun Heo 	struct worker_pool *pool;
880e22bee78STejun Heo 
881111c225aSTejun Heo 	/*
882111c225aSTejun Heo 	 * Rescuers, which may not have all the fields set up like normal
883111c225aSTejun Heo 	 * workers, also reach here, let's not access anything before
884111c225aSTejun Heo 	 * checking NOT_RUNNING.
885111c225aSTejun Heo 	 */
8862d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
887e22bee78STejun Heo 		return NULL;
888e22bee78STejun Heo 
889111c225aSTejun Heo 	pool = worker->pool;
890111c225aSTejun Heo 
891e22bee78STejun Heo 	/* this can only happen on the local cpu */
8929b7f6597SAlexander Gordeev 	if (WARN_ON_ONCE(pool->cpu != raw_smp_processor_id()))
8936183c009STejun Heo 		return NULL;
894e22bee78STejun Heo 
895e22bee78STejun Heo 	/*
896e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
897e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
898e22bee78STejun Heo 	 * Please read comment there.
899e22bee78STejun Heo 	 *
900628c78e7STejun Heo 	 * NOT_RUNNING is clear.  This means that we're bound to and
901628c78e7STejun Heo 	 * running on the local cpu w/ rq lock held and preemption
902628c78e7STejun Heo 	 * disabled, which in turn means that none else could be
903d565ed63STejun Heo 	 * manipulating idle_list, so dereferencing idle_list without pool
904628c78e7STejun Heo 	 * lock is safe.
905e22bee78STejun Heo 	 */
906e19e397aSTejun Heo 	if (atomic_dec_and_test(&pool->nr_running) &&
907e19e397aSTejun Heo 	    !list_empty(&pool->worklist))
9081037de36SLai Jiangshan 		to_wakeup = first_idle_worker(pool);
909e22bee78STejun Heo 	return to_wakeup ? to_wakeup->task : NULL;
910e22bee78STejun Heo }
911e22bee78STejun Heo 
912e22bee78STejun Heo /**
913e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
914cb444766STejun Heo  * @worker: self
915d302f017STejun Heo  * @flags: flags to set
916d302f017STejun Heo  *
917228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
918d302f017STejun Heo  *
919cb444766STejun Heo  * CONTEXT:
920d565ed63STejun Heo  * spin_lock_irq(pool->lock)
921d302f017STejun Heo  */
922228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
923d302f017STejun Heo {
924bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
925e22bee78STejun Heo 
926cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
927cb444766STejun Heo 
928228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
929e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
930e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
931e19e397aSTejun Heo 		atomic_dec(&pool->nr_running);
932e22bee78STejun Heo 	}
933e22bee78STejun Heo 
934d302f017STejun Heo 	worker->flags |= flags;
935d302f017STejun Heo }
936d302f017STejun Heo 
937d302f017STejun Heo /**
938e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
939cb444766STejun Heo  * @worker: self
940d302f017STejun Heo  * @flags: flags to clear
941d302f017STejun Heo  *
942e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
943d302f017STejun Heo  *
944cb444766STejun Heo  * CONTEXT:
945d565ed63STejun Heo  * spin_lock_irq(pool->lock)
946d302f017STejun Heo  */
947d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
948d302f017STejun Heo {
94963d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
950e22bee78STejun Heo 	unsigned int oflags = worker->flags;
951e22bee78STejun Heo 
952cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
953cb444766STejun Heo 
954d302f017STejun Heo 	worker->flags &= ~flags;
955e22bee78STejun Heo 
95642c025f3STejun Heo 	/*
95742c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
95842c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
95942c025f3STejun Heo 	 * of multiple flags, not a single flag.
96042c025f3STejun Heo 	 */
961e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
962e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
963e19e397aSTejun Heo 			atomic_inc(&pool->nr_running);
964d302f017STejun Heo }
965d302f017STejun Heo 
966d302f017STejun Heo /**
9678cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
968c9e7cf27STejun Heo  * @pool: pool of interest
9698cca0eeaSTejun Heo  * @work: work to find worker for
9708cca0eeaSTejun Heo  *
971c9e7cf27STejun Heo  * Find a worker which is executing @work on @pool by searching
972c9e7cf27STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
973a2c1c57bSTejun Heo  * to match, its current execution should match the address of @work and
974a2c1c57bSTejun Heo  * its work function.  This is to avoid unwanted dependency between
975a2c1c57bSTejun Heo  * unrelated work executions through a work item being recycled while still
976a2c1c57bSTejun Heo  * being executed.
977a2c1c57bSTejun Heo  *
978a2c1c57bSTejun Heo  * This is a bit tricky.  A work item may be freed once its execution
979a2c1c57bSTejun Heo  * starts and nothing prevents the freed area from being recycled for
980a2c1c57bSTejun Heo  * another work item.  If the same work item address ends up being reused
981a2c1c57bSTejun Heo  * before the original execution finishes, workqueue will identify the
982a2c1c57bSTejun Heo  * recycled work item as currently executing and make it wait until the
983a2c1c57bSTejun Heo  * current execution finishes, introducing an unwanted dependency.
984a2c1c57bSTejun Heo  *
985c5aa87bbSTejun Heo  * This function checks the work item address and work function to avoid
986c5aa87bbSTejun Heo  * false positives.  Note that this isn't complete as one may construct a
987c5aa87bbSTejun Heo  * work function which can introduce dependency onto itself through a
988c5aa87bbSTejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
989c5aa87bbSTejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
990c5aa87bbSTejun Heo  * actually occurs, it should be easy to locate the culprit work function.
9918cca0eeaSTejun Heo  *
9928cca0eeaSTejun Heo  * CONTEXT:
993d565ed63STejun Heo  * spin_lock_irq(pool->lock).
9948cca0eeaSTejun Heo  *
995d185af30SYacine Belkadi  * Return:
996d185af30SYacine Belkadi  * Pointer to worker which is executing @work if found, %NULL
9978cca0eeaSTejun Heo  * otherwise.
9988cca0eeaSTejun Heo  */
999c9e7cf27STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
10008cca0eeaSTejun Heo 						 struct work_struct *work)
10018cca0eeaSTejun Heo {
100242f8570fSSasha Levin 	struct worker *worker;
100342f8570fSSasha Levin 
1004b67bfe0dSSasha Levin 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1005a2c1c57bSTejun Heo 			       (unsigned long)work)
1006a2c1c57bSTejun Heo 		if (worker->current_work == work &&
1007a2c1c57bSTejun Heo 		    worker->current_func == work->func)
100842f8570fSSasha Levin 			return worker;
100942f8570fSSasha Levin 
101042f8570fSSasha Levin 	return NULL;
10118cca0eeaSTejun Heo }
10128cca0eeaSTejun Heo 
10138cca0eeaSTejun Heo /**
1014bf4ede01STejun Heo  * move_linked_works - move linked works to a list
1015bf4ede01STejun Heo  * @work: start of series of works to be scheduled
1016bf4ede01STejun Heo  * @head: target list to append @work to
1017402dd89dSShailendra Verma  * @nextp: out parameter for nested worklist walking
1018bf4ede01STejun Heo  *
1019bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
1020bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
1021bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
1022bf4ede01STejun Heo  *
1023bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
1024bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
1025bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
1026bf4ede01STejun Heo  *
1027bf4ede01STejun Heo  * CONTEXT:
1028d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1029bf4ede01STejun Heo  */
1030bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1031bf4ede01STejun Heo 			      struct work_struct **nextp)
1032bf4ede01STejun Heo {
1033bf4ede01STejun Heo 	struct work_struct *n;
1034bf4ede01STejun Heo 
1035bf4ede01STejun Heo 	/*
1036bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
1037bf4ede01STejun Heo 	 * use NULL for list head.
1038bf4ede01STejun Heo 	 */
1039bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1040bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
1041bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1042bf4ede01STejun Heo 			break;
1043bf4ede01STejun Heo 	}
1044bf4ede01STejun Heo 
1045bf4ede01STejun Heo 	/*
1046bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
1047bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
1048bf4ede01STejun Heo 	 * needs to be updated.
1049bf4ede01STejun Heo 	 */
1050bf4ede01STejun Heo 	if (nextp)
1051bf4ede01STejun Heo 		*nextp = n;
1052bf4ede01STejun Heo }
1053bf4ede01STejun Heo 
10548864b4e5STejun Heo /**
10558864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
10568864b4e5STejun Heo  * @pwq: pool_workqueue to get
10578864b4e5STejun Heo  *
10588864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
10598864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
10608864b4e5STejun Heo  */
10618864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
10628864b4e5STejun Heo {
10638864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
10648864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
10658864b4e5STejun Heo 	pwq->refcnt++;
10668864b4e5STejun Heo }
10678864b4e5STejun Heo 
10688864b4e5STejun Heo /**
10698864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
10708864b4e5STejun Heo  * @pwq: pool_workqueue to put
10718864b4e5STejun Heo  *
10728864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
10738864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
10748864b4e5STejun Heo  */
10758864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
10768864b4e5STejun Heo {
10778864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
10788864b4e5STejun Heo 	if (likely(--pwq->refcnt))
10798864b4e5STejun Heo 		return;
10808864b4e5STejun Heo 	if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
10818864b4e5STejun Heo 		return;
10828864b4e5STejun Heo 	/*
10838864b4e5STejun Heo 	 * @pwq can't be released under pool->lock, bounce to
10848864b4e5STejun Heo 	 * pwq_unbound_release_workfn().  This never recurses on the same
10858864b4e5STejun Heo 	 * pool->lock as this path is taken only for unbound workqueues and
10868864b4e5STejun Heo 	 * the release work item is scheduled on a per-cpu workqueue.  To
10878864b4e5STejun Heo 	 * avoid lockdep warning, unbound pool->locks are given lockdep
10888864b4e5STejun Heo 	 * subclass of 1 in get_unbound_pool().
10898864b4e5STejun Heo 	 */
10908864b4e5STejun Heo 	schedule_work(&pwq->unbound_release_work);
10918864b4e5STejun Heo }
10928864b4e5STejun Heo 
1093dce90d47STejun Heo /**
1094dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1095dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1096dce90d47STejun Heo  *
1097dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1098dce90d47STejun Heo  */
1099dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1100dce90d47STejun Heo {
1101dce90d47STejun Heo 	if (pwq) {
1102dce90d47STejun Heo 		/*
1103dce90d47STejun Heo 		 * As both pwqs and pools are sched-RCU protected, the
1104dce90d47STejun Heo 		 * following lock operations are safe.
1105dce90d47STejun Heo 		 */
1106dce90d47STejun Heo 		spin_lock_irq(&pwq->pool->lock);
1107dce90d47STejun Heo 		put_pwq(pwq);
1108dce90d47STejun Heo 		spin_unlock_irq(&pwq->pool->lock);
1109dce90d47STejun Heo 	}
1110dce90d47STejun Heo }
1111dce90d47STejun Heo 
1112112202d9STejun Heo static void pwq_activate_delayed_work(struct work_struct *work)
1113bf4ede01STejun Heo {
1114112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1115bf4ede01STejun Heo 
1116bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
111782607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
111882607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1119112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
1120bf4ede01STejun Heo 	__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1121112202d9STejun Heo 	pwq->nr_active++;
1122bf4ede01STejun Heo }
1123bf4ede01STejun Heo 
1124112202d9STejun Heo static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
11253aa62497SLai Jiangshan {
1126112202d9STejun Heo 	struct work_struct *work = list_first_entry(&pwq->delayed_works,
11273aa62497SLai Jiangshan 						    struct work_struct, entry);
11283aa62497SLai Jiangshan 
1129112202d9STejun Heo 	pwq_activate_delayed_work(work);
11303aa62497SLai Jiangshan }
11313aa62497SLai Jiangshan 
1132bf4ede01STejun Heo /**
1133112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1134112202d9STejun Heo  * @pwq: pwq of interest
1135bf4ede01STejun Heo  * @color: color of work which left the queue
1136bf4ede01STejun Heo  *
1137bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1138112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1139bf4ede01STejun Heo  *
1140bf4ede01STejun Heo  * CONTEXT:
1141d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1142bf4ede01STejun Heo  */
1143112202d9STejun Heo static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1144bf4ede01STejun Heo {
11458864b4e5STejun Heo 	/* uncolored work items don't participate in flushing or nr_active */
1146bf4ede01STejun Heo 	if (color == WORK_NO_COLOR)
11478864b4e5STejun Heo 		goto out_put;
1148bf4ede01STejun Heo 
1149112202d9STejun Heo 	pwq->nr_in_flight[color]--;
1150bf4ede01STejun Heo 
1151112202d9STejun Heo 	pwq->nr_active--;
1152112202d9STejun Heo 	if (!list_empty(&pwq->delayed_works)) {
1153bf4ede01STejun Heo 		/* one down, submit a delayed one */
1154112202d9STejun Heo 		if (pwq->nr_active < pwq->max_active)
1155112202d9STejun Heo 			pwq_activate_first_delayed(pwq);
1156bf4ede01STejun Heo 	}
1157bf4ede01STejun Heo 
1158bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1159112202d9STejun Heo 	if (likely(pwq->flush_color != color))
11608864b4e5STejun Heo 		goto out_put;
1161bf4ede01STejun Heo 
1162bf4ede01STejun Heo 	/* are there still in-flight works? */
1163112202d9STejun Heo 	if (pwq->nr_in_flight[color])
11648864b4e5STejun Heo 		goto out_put;
1165bf4ede01STejun Heo 
1166112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1167112202d9STejun Heo 	pwq->flush_color = -1;
1168bf4ede01STejun Heo 
1169bf4ede01STejun Heo 	/*
1170112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1171bf4ede01STejun Heo 	 * will handle the rest.
1172bf4ede01STejun Heo 	 */
1173112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1174112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
11758864b4e5STejun Heo out_put:
11768864b4e5STejun Heo 	put_pwq(pwq);
1177bf4ede01STejun Heo }
1178bf4ede01STejun Heo 
117936e227d2STejun Heo /**
1180bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
118136e227d2STejun Heo  * @work: work item to steal
118236e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1183bbb68dfaSTejun Heo  * @flags: place to store irq state
118436e227d2STejun Heo  *
118536e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1186d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
118736e227d2STejun Heo  *
1188d185af30SYacine Belkadi  * Return:
118936e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
119036e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
119136e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1192bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1193bbb68dfaSTejun Heo  *		for arbitrarily long
119436e227d2STejun Heo  *
1195d185af30SYacine Belkadi  * Note:
1196bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1197e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1198e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1199e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1200bbb68dfaSTejun Heo  *
1201bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1202bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1203bbb68dfaSTejun Heo  *
1204e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1205bf4ede01STejun Heo  */
1206bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1207bbb68dfaSTejun Heo 			       unsigned long *flags)
1208bf4ede01STejun Heo {
1209d565ed63STejun Heo 	struct worker_pool *pool;
1210112202d9STejun Heo 	struct pool_workqueue *pwq;
1211bf4ede01STejun Heo 
1212bbb68dfaSTejun Heo 	local_irq_save(*flags);
1213bbb68dfaSTejun Heo 
121436e227d2STejun Heo 	/* try to steal the timer if it exists */
121536e227d2STejun Heo 	if (is_dwork) {
121636e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
121736e227d2STejun Heo 
1218e0aecdd8STejun Heo 		/*
1219e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1220e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1221e0aecdd8STejun Heo 		 * running on the local CPU.
1222e0aecdd8STejun Heo 		 */
122336e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
122436e227d2STejun Heo 			return 1;
122536e227d2STejun Heo 	}
122636e227d2STejun Heo 
122736e227d2STejun Heo 	/* try to claim PENDING the normal way */
1228bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1229bf4ede01STejun Heo 		return 0;
1230bf4ede01STejun Heo 
1231bf4ede01STejun Heo 	/*
1232bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1233bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1234bf4ede01STejun Heo 	 */
1235d565ed63STejun Heo 	pool = get_work_pool(work);
1236d565ed63STejun Heo 	if (!pool)
1237bbb68dfaSTejun Heo 		goto fail;
1238bf4ede01STejun Heo 
1239d565ed63STejun Heo 	spin_lock(&pool->lock);
1240bf4ede01STejun Heo 	/*
1241112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1242112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1243112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1244112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1245112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
12460b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1247bf4ede01STejun Heo 	 */
1248112202d9STejun Heo 	pwq = get_work_pwq(work);
1249112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1250bf4ede01STejun Heo 		debug_work_deactivate(work);
12513aa62497SLai Jiangshan 
12523aa62497SLai Jiangshan 		/*
125316062836STejun Heo 		 * A delayed work item cannot be grabbed directly because
125416062836STejun Heo 		 * it might have linked NO_COLOR work items which, if left
1255112202d9STejun Heo 		 * on the delayed_list, will confuse pwq->nr_active
125616062836STejun Heo 		 * management later on and cause stall.  Make sure the work
125716062836STejun Heo 		 * item is activated before grabbing.
12583aa62497SLai Jiangshan 		 */
12593aa62497SLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1260112202d9STejun Heo 			pwq_activate_delayed_work(work);
12613aa62497SLai Jiangshan 
1262bf4ede01STejun Heo 		list_del_init(&work->entry);
12639c34a704SLai Jiangshan 		pwq_dec_nr_in_flight(pwq, get_work_color(work));
126436e227d2STejun Heo 
1265112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
12664468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
12674468a00fSLai Jiangshan 
1268d565ed63STejun Heo 		spin_unlock(&pool->lock);
126936e227d2STejun Heo 		return 1;
1270bf4ede01STejun Heo 	}
1271d565ed63STejun Heo 	spin_unlock(&pool->lock);
1272bbb68dfaSTejun Heo fail:
1273bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1274bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1275bbb68dfaSTejun Heo 		return -ENOENT;
1276bbb68dfaSTejun Heo 	cpu_relax();
127736e227d2STejun Heo 	return -EAGAIN;
1278bf4ede01STejun Heo }
1279bf4ede01STejun Heo 
1280bf4ede01STejun Heo /**
1281706026c2STejun Heo  * insert_work - insert a work into a pool
1282112202d9STejun Heo  * @pwq: pwq @work belongs to
12834690c4abSTejun Heo  * @work: work to insert
12844690c4abSTejun Heo  * @head: insertion point
12854690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
12864690c4abSTejun Heo  *
1287112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1288706026c2STejun Heo  * work_struct flags.
12894690c4abSTejun Heo  *
12904690c4abSTejun Heo  * CONTEXT:
1291d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1292365970a1SDavid Howells  */
1293112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1294112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1295b89deed3SOleg Nesterov {
1296112202d9STejun Heo 	struct worker_pool *pool = pwq->pool;
1297e1d8aa9fSFrederic Weisbecker 
12984690c4abSTejun Heo 	/* we own @work, set data and link */
1299112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
13001a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
13018864b4e5STejun Heo 	get_pwq(pwq);
1302e22bee78STejun Heo 
1303e22bee78STejun Heo 	/*
1304c5aa87bbSTejun Heo 	 * Ensure either wq_worker_sleeping() sees the above
1305c5aa87bbSTejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers lying
1306c5aa87bbSTejun Heo 	 * around lazily while there are works to be processed.
1307e22bee78STejun Heo 	 */
1308e22bee78STejun Heo 	smp_mb();
1309e22bee78STejun Heo 
131063d95a91STejun Heo 	if (__need_more_worker(pool))
131163d95a91STejun Heo 		wake_up_worker(pool);
1312b89deed3SOleg Nesterov }
1313b89deed3SOleg Nesterov 
1314c8efcc25STejun Heo /*
1315c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
13168d03ecfeSTejun Heo  * same workqueue.
1317c8efcc25STejun Heo  */
1318c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1319c8efcc25STejun Heo {
1320c8efcc25STejun Heo 	struct worker *worker;
1321c8efcc25STejun Heo 
13228d03ecfeSTejun Heo 	worker = current_wq_worker();
1323c8efcc25STejun Heo 	/*
13248d03ecfeSTejun Heo 	 * Return %true iff I'm a worker execuing a work item on @wq.  If
13258d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1326c8efcc25STejun Heo 	 */
1327112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1328c8efcc25STejun Heo }
1329c8efcc25STejun Heo 
1330ef557180SMike Galbraith /*
1331ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
1332ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
1333ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
1334ef557180SMike Galbraith  */
1335ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1336ef557180SMike Galbraith {
1337f303fccbSTejun Heo 	static bool printed_dbg_warning;
1338ef557180SMike Galbraith 	int new_cpu;
1339ef557180SMike Galbraith 
1340f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
1341ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1342ef557180SMike Galbraith 			return cpu;
1343f303fccbSTejun Heo 	} else if (!printed_dbg_warning) {
1344f303fccbSTejun Heo 		pr_warn("workqueue: round-robin CPU selection forced, expect performance impact\n");
1345f303fccbSTejun Heo 		printed_dbg_warning = true;
1346f303fccbSTejun Heo 	}
1347f303fccbSTejun Heo 
1348ef557180SMike Galbraith 	if (cpumask_empty(wq_unbound_cpumask))
1349ef557180SMike Galbraith 		return cpu;
1350ef557180SMike Galbraith 
1351ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
1352ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1353ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
1354ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1355ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
1356ef557180SMike Galbraith 			return cpu;
1357ef557180SMike Galbraith 	}
1358ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
1359ef557180SMike Galbraith 
1360ef557180SMike Galbraith 	return new_cpu;
1361ef557180SMike Galbraith }
1362ef557180SMike Galbraith 
1363d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
13641da177e4SLinus Torvalds 			 struct work_struct *work)
13651da177e4SLinus Torvalds {
1366112202d9STejun Heo 	struct pool_workqueue *pwq;
1367c9178087STejun Heo 	struct worker_pool *last_pool;
13681e19ffc6STejun Heo 	struct list_head *worklist;
13698a2e8e5dSTejun Heo 	unsigned int work_flags;
1370b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
13718930cabaSTejun Heo 
13728930cabaSTejun Heo 	/*
13738930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
13748930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
13758930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
13768930cabaSTejun Heo 	 * happen with IRQ disabled.
13778930cabaSTejun Heo 	 */
13788930cabaSTejun Heo 	WARN_ON_ONCE(!irqs_disabled());
13791da177e4SLinus Torvalds 
1380dc186ad7SThomas Gleixner 	debug_work_activate(work);
13811e19ffc6STejun Heo 
13829ef28a73SLi Bin 	/* if draining, only works from the same workqueue are allowed */
1383618b01ebSTejun Heo 	if (unlikely(wq->flags & __WQ_DRAINING) &&
1384c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
1385e41e704bSTejun Heo 		return;
13869e8cd2f5STejun Heo retry:
1387df2d5ae4STejun Heo 	if (req_cpu == WORK_CPU_UNBOUND)
1388ef557180SMike Galbraith 		cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1389df2d5ae4STejun Heo 
1390df2d5ae4STejun Heo 	/* pwq which will be used unless @work is executing elsewhere */
1391df2d5ae4STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
1392c9178087STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1393df2d5ae4STejun Heo 	else
1394df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1395f3421797STejun Heo 
139618aa9effSTejun Heo 	/*
1397c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1398c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1399c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
140018aa9effSTejun Heo 	 */
1401c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1402112202d9STejun Heo 	if (last_pool && last_pool != pwq->pool) {
140318aa9effSTejun Heo 		struct worker *worker;
140418aa9effSTejun Heo 
1405d565ed63STejun Heo 		spin_lock(&last_pool->lock);
140618aa9effSTejun Heo 
1407c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
140818aa9effSTejun Heo 
1409112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1410c9178087STejun Heo 			pwq = worker->current_pwq;
14118594fadeSLai Jiangshan 		} else {
141218aa9effSTejun Heo 			/* meh... not running there, queue here */
1413d565ed63STejun Heo 			spin_unlock(&last_pool->lock);
1414112202d9STejun Heo 			spin_lock(&pwq->pool->lock);
141518aa9effSTejun Heo 		}
14168930cabaSTejun Heo 	} else {
1417112202d9STejun Heo 		spin_lock(&pwq->pool->lock);
14188930cabaSTejun Heo 	}
1419502ca9d8STejun Heo 
14209e8cd2f5STejun Heo 	/*
14219e8cd2f5STejun Heo 	 * pwq is determined and locked.  For unbound pools, we could have
14229e8cd2f5STejun Heo 	 * raced with pwq release and it could already be dead.  If its
14239e8cd2f5STejun Heo 	 * refcnt is zero, repeat pwq selection.  Note that pwqs never die
1424df2d5ae4STejun Heo 	 * without another pwq replacing it in the numa_pwq_tbl or while
1425df2d5ae4STejun Heo 	 * work items are executing on it, so the retrying is guaranteed to
14269e8cd2f5STejun Heo 	 * make forward-progress.
14279e8cd2f5STejun Heo 	 */
14289e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
14299e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
14309e8cd2f5STejun Heo 			spin_unlock(&pwq->pool->lock);
14319e8cd2f5STejun Heo 			cpu_relax();
14329e8cd2f5STejun Heo 			goto retry;
14339e8cd2f5STejun Heo 		}
14349e8cd2f5STejun Heo 		/* oops */
14359e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
14369e8cd2f5STejun Heo 			  wq->name, cpu);
14379e8cd2f5STejun Heo 	}
14389e8cd2f5STejun Heo 
1439112202d9STejun Heo 	/* pwq determined, queue */
1440112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1441502ca9d8STejun Heo 
1442f5b2552bSDan Carpenter 	if (WARN_ON(!list_empty(&work->entry))) {
1443112202d9STejun Heo 		spin_unlock(&pwq->pool->lock);
1444f5b2552bSDan Carpenter 		return;
1445f5b2552bSDan Carpenter 	}
14461e19ffc6STejun Heo 
1447112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1448112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
14491e19ffc6STejun Heo 
1450112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1451cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1452112202d9STejun Heo 		pwq->nr_active++;
1453112202d9STejun Heo 		worklist = &pwq->pool->worklist;
145482607adcSTejun Heo 		if (list_empty(worklist))
145582607adcSTejun Heo 			pwq->pool->watchdog_ts = jiffies;
14568a2e8e5dSTejun Heo 	} else {
14578a2e8e5dSTejun Heo 		work_flags |= WORK_STRUCT_DELAYED;
1458112202d9STejun Heo 		worklist = &pwq->delayed_works;
14598a2e8e5dSTejun Heo 	}
14601e19ffc6STejun Heo 
1461112202d9STejun Heo 	insert_work(pwq, work, worklist, work_flags);
14621e19ffc6STejun Heo 
1463112202d9STejun Heo 	spin_unlock(&pwq->pool->lock);
14641da177e4SLinus Torvalds }
14651da177e4SLinus Torvalds 
14660fcb78c2SRolf Eike Beer /**
1467c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1468c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1469c1a220e7SZhang Rui  * @wq: workqueue to use
1470c1a220e7SZhang Rui  * @work: work to queue
1471c1a220e7SZhang Rui  *
1472c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1473c1a220e7SZhang Rui  * can't go away.
1474d185af30SYacine Belkadi  *
1475d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
1476c1a220e7SZhang Rui  */
1477d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1478d4283e93STejun Heo 		   struct work_struct *work)
1479c1a220e7SZhang Rui {
1480d4283e93STejun Heo 	bool ret = false;
14818930cabaSTejun Heo 	unsigned long flags;
14828930cabaSTejun Heo 
14838930cabaSTejun Heo 	local_irq_save(flags);
1484c1a220e7SZhang Rui 
148522df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
14864690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1487d4283e93STejun Heo 		ret = true;
1488c1a220e7SZhang Rui 	}
14898930cabaSTejun Heo 
14908930cabaSTejun Heo 	local_irq_restore(flags);
1491c1a220e7SZhang Rui 	return ret;
1492c1a220e7SZhang Rui }
1493ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1494c1a220e7SZhang Rui 
1495d8e794dfSTejun Heo void delayed_work_timer_fn(unsigned long __data)
14961da177e4SLinus Torvalds {
149752bad64dSDavid Howells 	struct delayed_work *dwork = (struct delayed_work *)__data;
14981da177e4SLinus Torvalds 
1499e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
150060c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
15011da177e4SLinus Torvalds }
15021438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
15031da177e4SLinus Torvalds 
15047beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
150552bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
15061da177e4SLinus Torvalds {
15077beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
15087beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
15091da177e4SLinus Torvalds 
1510637fdbaeSTejun Heo 	WARN_ON_ONCE(!wq);
15117beb2edfSTejun Heo 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
15127beb2edfSTejun Heo 		     timer->data != (unsigned long)dwork);
1513fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1514fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
15157beb2edfSTejun Heo 
15168852aac2STejun Heo 	/*
15178852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
15188852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
15198852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
15208852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
15218852aac2STejun Heo 	 */
15228852aac2STejun Heo 	if (!delay) {
15238852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
15248852aac2STejun Heo 		return;
15258852aac2STejun Heo 	}
15268852aac2STejun Heo 
152760c057bcSLai Jiangshan 	dwork->wq = wq;
15281265057fSTejun Heo 	dwork->cpu = cpu;
15297beb2edfSTejun Heo 	timer->expires = jiffies + delay;
15307beb2edfSTejun Heo 
1531041bd12eSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
15327beb2edfSTejun Heo 		add_timer_on(timer, cpu);
1533041bd12eSTejun Heo 	else
1534041bd12eSTejun Heo 		add_timer(timer);
15357beb2edfSTejun Heo }
15361da177e4SLinus Torvalds 
15370fcb78c2SRolf Eike Beer /**
15380fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
15390fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
15400fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1541af9997e4SRandy Dunlap  * @dwork: work to queue
15420fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
15430fcb78c2SRolf Eike Beer  *
1544d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
1545715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1546715f1300STejun Heo  * execution.
15470fcb78c2SRolf Eike Beer  */
1548d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
154952bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
15507a6bc1cdSVenkatesh Pallipadi {
155152bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1552d4283e93STejun Heo 	bool ret = false;
15538930cabaSTejun Heo 	unsigned long flags;
15548930cabaSTejun Heo 
15558930cabaSTejun Heo 	/* read the comment in __queue_work() */
15568930cabaSTejun Heo 	local_irq_save(flags);
15577a6bc1cdSVenkatesh Pallipadi 
155822df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
15597beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1560d4283e93STejun Heo 		ret = true;
15617a6bc1cdSVenkatesh Pallipadi 	}
15628930cabaSTejun Heo 
15638930cabaSTejun Heo 	local_irq_restore(flags);
15647a6bc1cdSVenkatesh Pallipadi 	return ret;
15657a6bc1cdSVenkatesh Pallipadi }
1566ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
15671da177e4SLinus Torvalds 
1568c8e55f36STejun Heo /**
15698376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
15708376fe22STejun Heo  * @cpu: CPU number to execute work on
15718376fe22STejun Heo  * @wq: workqueue to use
15728376fe22STejun Heo  * @dwork: work to queue
15738376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
15748376fe22STejun Heo  *
15758376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
15768376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
15778376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
15788376fe22STejun Heo  * current state.
15798376fe22STejun Heo  *
1580d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
15818376fe22STejun Heo  * pending and its timer was modified.
15828376fe22STejun Heo  *
1583e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
15848376fe22STejun Heo  * See try_to_grab_pending() for details.
15858376fe22STejun Heo  */
15868376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
15878376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
15888376fe22STejun Heo {
15898376fe22STejun Heo 	unsigned long flags;
15908376fe22STejun Heo 	int ret;
15918376fe22STejun Heo 
15928376fe22STejun Heo 	do {
15938376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
15948376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
15958376fe22STejun Heo 
15968376fe22STejun Heo 	if (likely(ret >= 0)) {
15978376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
15988376fe22STejun Heo 		local_irq_restore(flags);
15998376fe22STejun Heo 	}
16008376fe22STejun Heo 
16018376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
16028376fe22STejun Heo 	return ret;
16038376fe22STejun Heo }
16048376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
16058376fe22STejun Heo 
16068376fe22STejun Heo /**
1607c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1608c8e55f36STejun Heo  * @worker: worker which is entering idle state
1609c8e55f36STejun Heo  *
1610c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1611c8e55f36STejun Heo  * necessary.
1612c8e55f36STejun Heo  *
1613c8e55f36STejun Heo  * LOCKING:
1614d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1615c8e55f36STejun Heo  */
1616c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
16171da177e4SLinus Torvalds {
1618bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1619c8e55f36STejun Heo 
16206183c009STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
16216183c009STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
16226183c009STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
16236183c009STejun Heo 		return;
1624c8e55f36STejun Heo 
1625051e1850SLai Jiangshan 	/* can't use worker_set_flags(), also called from create_worker() */
1626cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1627bd7bdd43STejun Heo 	pool->nr_idle++;
1628e22bee78STejun Heo 	worker->last_active = jiffies;
1629c8e55f36STejun Heo 
1630c8e55f36STejun Heo 	/* idle_list is LIFO */
1631bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1632db7bccf4STejun Heo 
163363d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1634628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1635cb444766STejun Heo 
1636544ecf31STejun Heo 	/*
1637706026c2STejun Heo 	 * Sanity check nr_running.  Because wq_unbind_fn() releases
1638d565ed63STejun Heo 	 * pool->lock between setting %WORKER_UNBOUND and zapping
1639628c78e7STejun Heo 	 * nr_running, the warning may trigger spuriously.  Check iff
1640628c78e7STejun Heo 	 * unbind is not in progress.
1641544ecf31STejun Heo 	 */
164224647570STejun Heo 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1643bd7bdd43STejun Heo 		     pool->nr_workers == pool->nr_idle &&
1644e19e397aSTejun Heo 		     atomic_read(&pool->nr_running));
1645c8e55f36STejun Heo }
1646c8e55f36STejun Heo 
1647c8e55f36STejun Heo /**
1648c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1649c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1650c8e55f36STejun Heo  *
1651c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1652c8e55f36STejun Heo  *
1653c8e55f36STejun Heo  * LOCKING:
1654d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1655c8e55f36STejun Heo  */
1656c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1657c8e55f36STejun Heo {
1658bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1659c8e55f36STejun Heo 
16606183c009STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
16616183c009STejun Heo 		return;
1662d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1663bd7bdd43STejun Heo 	pool->nr_idle--;
1664c8e55f36STejun Heo 	list_del_init(&worker->entry);
1665c8e55f36STejun Heo }
1666c8e55f36STejun Heo 
1667f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
1668c34056a3STejun Heo {
1669c34056a3STejun Heo 	struct worker *worker;
1670c34056a3STejun Heo 
1671f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1672c8e55f36STejun Heo 	if (worker) {
1673c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1674affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
1675da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
1676e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1677e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1678c8e55f36STejun Heo 	}
1679c34056a3STejun Heo 	return worker;
1680c34056a3STejun Heo }
1681c34056a3STejun Heo 
1682c34056a3STejun Heo /**
16834736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
16844736cbf7SLai Jiangshan  * @worker: worker to be attached
16854736cbf7SLai Jiangshan  * @pool: the target pool
16864736cbf7SLai Jiangshan  *
16874736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
16884736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
16894736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
16904736cbf7SLai Jiangshan  */
16914736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
16924736cbf7SLai Jiangshan 				   struct worker_pool *pool)
16934736cbf7SLai Jiangshan {
16944736cbf7SLai Jiangshan 	mutex_lock(&pool->attach_mutex);
16954736cbf7SLai Jiangshan 
16964736cbf7SLai Jiangshan 	/*
16974736cbf7SLai Jiangshan 	 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
16984736cbf7SLai Jiangshan 	 * online CPUs.  It'll be re-applied when any of the CPUs come up.
16994736cbf7SLai Jiangshan 	 */
17004736cbf7SLai Jiangshan 	set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
17014736cbf7SLai Jiangshan 
17024736cbf7SLai Jiangshan 	/*
17034736cbf7SLai Jiangshan 	 * The pool->attach_mutex ensures %POOL_DISASSOCIATED remains
17044736cbf7SLai Jiangshan 	 * stable across this function.  See the comments above the
17054736cbf7SLai Jiangshan 	 * flag definition for details.
17064736cbf7SLai Jiangshan 	 */
17074736cbf7SLai Jiangshan 	if (pool->flags & POOL_DISASSOCIATED)
17084736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
17094736cbf7SLai Jiangshan 
17104736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
17114736cbf7SLai Jiangshan 
17124736cbf7SLai Jiangshan 	mutex_unlock(&pool->attach_mutex);
17134736cbf7SLai Jiangshan }
17144736cbf7SLai Jiangshan 
17154736cbf7SLai Jiangshan /**
171660f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
171760f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
171860f5a4bcSLai Jiangshan  * @pool: the pool @worker is attached to
171960f5a4bcSLai Jiangshan  *
17204736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
17214736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
17224736cbf7SLai Jiangshan  * other reference to the pool.
172360f5a4bcSLai Jiangshan  */
172460f5a4bcSLai Jiangshan static void worker_detach_from_pool(struct worker *worker,
172560f5a4bcSLai Jiangshan 				    struct worker_pool *pool)
172660f5a4bcSLai Jiangshan {
172760f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
172860f5a4bcSLai Jiangshan 
172992f9c5c4SLai Jiangshan 	mutex_lock(&pool->attach_mutex);
1730da028469SLai Jiangshan 	list_del(&worker->node);
1731da028469SLai Jiangshan 	if (list_empty(&pool->workers))
173260f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
173392f9c5c4SLai Jiangshan 	mutex_unlock(&pool->attach_mutex);
173460f5a4bcSLai Jiangshan 
1735b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
1736b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1737b62c0751SLai Jiangshan 
173860f5a4bcSLai Jiangshan 	if (detach_completion)
173960f5a4bcSLai Jiangshan 		complete(detach_completion);
174060f5a4bcSLai Jiangshan }
174160f5a4bcSLai Jiangshan 
174260f5a4bcSLai Jiangshan /**
1743c34056a3STejun Heo  * create_worker - create a new workqueue worker
174463d95a91STejun Heo  * @pool: pool the new worker will belong to
1745c34056a3STejun Heo  *
1746051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
1747c34056a3STejun Heo  *
1748c34056a3STejun Heo  * CONTEXT:
1749c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1750c34056a3STejun Heo  *
1751d185af30SYacine Belkadi  * Return:
1752c34056a3STejun Heo  * Pointer to the newly created worker.
1753c34056a3STejun Heo  */
1754bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1755c34056a3STejun Heo {
1756c34056a3STejun Heo 	struct worker *worker = NULL;
1757f3421797STejun Heo 	int id = -1;
1758e3c916a4STejun Heo 	char id_buf[16];
1759c34056a3STejun Heo 
17607cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
17617cda9aaeSLai Jiangshan 	id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL);
1762822d8405STejun Heo 	if (id < 0)
1763c34056a3STejun Heo 		goto fail;
1764c34056a3STejun Heo 
1765f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
1766c34056a3STejun Heo 	if (!worker)
1767c34056a3STejun Heo 		goto fail;
1768c34056a3STejun Heo 
1769bd7bdd43STejun Heo 	worker->pool = pool;
1770c34056a3STejun Heo 	worker->id = id;
1771c34056a3STejun Heo 
177229c91e99STejun Heo 	if (pool->cpu >= 0)
1773e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1774e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
1775f3421797STejun Heo 	else
1776e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1777e3c916a4STejun Heo 
1778f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1779e3c916a4STejun Heo 					      "kworker/%s", id_buf);
1780c34056a3STejun Heo 	if (IS_ERR(worker->task))
1781c34056a3STejun Heo 		goto fail;
1782c34056a3STejun Heo 
178391151228SOleg Nesterov 	set_user_nice(worker->task, pool->attrs->nice);
178425834c73SPeter Zijlstra 	kthread_bind_mask(worker->task, pool->attrs->cpumask);
178591151228SOleg Nesterov 
1786da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
17874736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
1788822d8405STejun Heo 
1789051e1850SLai Jiangshan 	/* start the newly created worker */
1790051e1850SLai Jiangshan 	spin_lock_irq(&pool->lock);
1791051e1850SLai Jiangshan 	worker->pool->nr_workers++;
1792051e1850SLai Jiangshan 	worker_enter_idle(worker);
1793051e1850SLai Jiangshan 	wake_up_process(worker->task);
1794051e1850SLai Jiangshan 	spin_unlock_irq(&pool->lock);
1795051e1850SLai Jiangshan 
1796c34056a3STejun Heo 	return worker;
1797822d8405STejun Heo 
1798c34056a3STejun Heo fail:
17999625ab17SLai Jiangshan 	if (id >= 0)
18007cda9aaeSLai Jiangshan 		ida_simple_remove(&pool->worker_ida, id);
1801c34056a3STejun Heo 	kfree(worker);
1802c34056a3STejun Heo 	return NULL;
1803c34056a3STejun Heo }
1804c34056a3STejun Heo 
1805c34056a3STejun Heo /**
1806c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1807c34056a3STejun Heo  * @worker: worker to be destroyed
1808c34056a3STejun Heo  *
180973eb7fe7SLai Jiangshan  * Destroy @worker and adjust @pool stats accordingly.  The worker should
181073eb7fe7SLai Jiangshan  * be idle.
1811c8e55f36STejun Heo  *
1812c8e55f36STejun Heo  * CONTEXT:
181360f5a4bcSLai Jiangshan  * spin_lock_irq(pool->lock).
1814c34056a3STejun Heo  */
1815c34056a3STejun Heo static void destroy_worker(struct worker *worker)
1816c34056a3STejun Heo {
1817bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1818c34056a3STejun Heo 
1819cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
1820cd549687STejun Heo 
1821c34056a3STejun Heo 	/* sanity check frenzy */
18226183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
182373eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
182473eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
18256183c009STejun Heo 		return;
1826c34056a3STejun Heo 
1827bd7bdd43STejun Heo 	pool->nr_workers--;
1828bd7bdd43STejun Heo 	pool->nr_idle--;
1829c8e55f36STejun Heo 
1830c8e55f36STejun Heo 	list_del_init(&worker->entry);
1831cb444766STejun Heo 	worker->flags |= WORKER_DIE;
183260f5a4bcSLai Jiangshan 	wake_up_process(worker->task);
1833c34056a3STejun Heo }
1834c34056a3STejun Heo 
183563d95a91STejun Heo static void idle_worker_timeout(unsigned long __pool)
1836e22bee78STejun Heo {
183763d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
1838e22bee78STejun Heo 
1839d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1840e22bee78STejun Heo 
18413347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
1842e22bee78STejun Heo 		struct worker *worker;
1843e22bee78STejun Heo 		unsigned long expires;
1844e22bee78STejun Heo 
1845e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
184663d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1847e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1848e22bee78STejun Heo 
18493347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
185063d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
18513347fc9fSLai Jiangshan 			break;
1852e22bee78STejun Heo 		}
18533347fc9fSLai Jiangshan 
18543347fc9fSLai Jiangshan 		destroy_worker(worker);
1855e22bee78STejun Heo 	}
1856e22bee78STejun Heo 
1857d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1858e22bee78STejun Heo }
1859e22bee78STejun Heo 
1860493a1724STejun Heo static void send_mayday(struct work_struct *work)
1861e22bee78STejun Heo {
1862112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1863112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
1864493a1724STejun Heo 
18652e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
1866e22bee78STejun Heo 
1867493008a8STejun Heo 	if (!wq->rescuer)
1868493a1724STejun Heo 		return;
1869e22bee78STejun Heo 
1870e22bee78STejun Heo 	/* mayday mayday mayday */
1871493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
187277668c8bSLai Jiangshan 		/*
187377668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
187477668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
187577668c8bSLai Jiangshan 		 * rescuer is done with it.
187677668c8bSLai Jiangshan 		 */
187777668c8bSLai Jiangshan 		get_pwq(pwq);
1878493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
1879e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
1880493a1724STejun Heo 	}
1881e22bee78STejun Heo }
1882e22bee78STejun Heo 
1883706026c2STejun Heo static void pool_mayday_timeout(unsigned long __pool)
1884e22bee78STejun Heo {
188563d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
1886e22bee78STejun Heo 	struct work_struct *work;
1887e22bee78STejun Heo 
1888b2d82909STejun Heo 	spin_lock_irq(&pool->lock);
1889b2d82909STejun Heo 	spin_lock(&wq_mayday_lock);		/* for wq->maydays */
1890e22bee78STejun Heo 
189163d95a91STejun Heo 	if (need_to_create_worker(pool)) {
1892e22bee78STejun Heo 		/*
1893e22bee78STejun Heo 		 * We've been trying to create a new worker but
1894e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
1895e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
1896e22bee78STejun Heo 		 * rescuers.
1897e22bee78STejun Heo 		 */
189863d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
1899e22bee78STejun Heo 			send_mayday(work);
1900e22bee78STejun Heo 	}
1901e22bee78STejun Heo 
1902b2d82909STejun Heo 	spin_unlock(&wq_mayday_lock);
1903b2d82909STejun Heo 	spin_unlock_irq(&pool->lock);
1904e22bee78STejun Heo 
190563d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1906e22bee78STejun Heo }
1907e22bee78STejun Heo 
1908e22bee78STejun Heo /**
1909e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
191063d95a91STejun Heo  * @pool: pool to create a new worker for
1911e22bee78STejun Heo  *
191263d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
1913e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
1914e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
191563d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
1916e22bee78STejun Heo  * possible allocation deadlock.
1917e22bee78STejun Heo  *
1918c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
1919c5aa87bbSTejun Heo  * may_start_working() %true.
1920e22bee78STejun Heo  *
1921e22bee78STejun Heo  * LOCKING:
1922d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
1923e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
1924e22bee78STejun Heo  * manager.
1925e22bee78STejun Heo  */
192629187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
1927d565ed63STejun Heo __releases(&pool->lock)
1928d565ed63STejun Heo __acquires(&pool->lock)
1929e22bee78STejun Heo {
1930e22bee78STejun Heo restart:
1931d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
19329f9c2364STejun Heo 
1933e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
193463d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1935e22bee78STejun Heo 
1936e22bee78STejun Heo 	while (true) {
1937051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
1938e22bee78STejun Heo 			break;
1939e22bee78STejun Heo 
1940e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
19419f9c2364STejun Heo 
194263d95a91STejun Heo 		if (!need_to_create_worker(pool))
1943e22bee78STejun Heo 			break;
1944e22bee78STejun Heo 	}
1945e22bee78STejun Heo 
194663d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
1947d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1948051e1850SLai Jiangshan 	/*
1949051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
1950051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
1951051e1850SLai Jiangshan 	 * already become busy.
1952051e1850SLai Jiangshan 	 */
195363d95a91STejun Heo 	if (need_to_create_worker(pool))
1954e22bee78STejun Heo 		goto restart;
1955e22bee78STejun Heo }
1956e22bee78STejun Heo 
1957e22bee78STejun Heo /**
1958e22bee78STejun Heo  * manage_workers - manage worker pool
1959e22bee78STejun Heo  * @worker: self
1960e22bee78STejun Heo  *
1961706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
1962e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
1963706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
1964e22bee78STejun Heo  *
1965e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
1966e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
1967e22bee78STejun Heo  * and may_start_working() is true.
1968e22bee78STejun Heo  *
1969e22bee78STejun Heo  * CONTEXT:
1970d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
1971e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
1972e22bee78STejun Heo  *
1973d185af30SYacine Belkadi  * Return:
197429187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
197529187a9eSTejun Heo  * start processing works, %true if management function was performed and
197629187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
197729187a9eSTejun Heo  * no longer be true.
1978e22bee78STejun Heo  */
1979e22bee78STejun Heo static bool manage_workers(struct worker *worker)
1980e22bee78STejun Heo {
198163d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
1982e22bee78STejun Heo 
1983bc3a1afcSTejun Heo 	/*
1984bc3a1afcSTejun Heo 	 * Anyone who successfully grabs manager_arb wins the arbitration
1985bc3a1afcSTejun Heo 	 * and becomes the manager.  mutex_trylock() on pool->manager_arb
1986bc3a1afcSTejun Heo 	 * failure while holding pool->lock reliably indicates that someone
1987bc3a1afcSTejun Heo 	 * else is managing the pool and the worker which failed trylock
1988bc3a1afcSTejun Heo 	 * can proceed to executing work items.  This means that anyone
1989bc3a1afcSTejun Heo 	 * grabbing manager_arb is responsible for actually performing
1990bc3a1afcSTejun Heo 	 * manager duties.  If manager_arb is grabbed and released without
1991bc3a1afcSTejun Heo 	 * actual management, the pool may stall indefinitely.
1992bc3a1afcSTejun Heo 	 */
199334a06bd6STejun Heo 	if (!mutex_trylock(&pool->manager_arb))
199429187a9eSTejun Heo 		return false;
19952607d7a6STejun Heo 	pool->manager = worker;
1996e22bee78STejun Heo 
199729187a9eSTejun Heo 	maybe_create_worker(pool);
1998e22bee78STejun Heo 
19992607d7a6STejun Heo 	pool->manager = NULL;
200034a06bd6STejun Heo 	mutex_unlock(&pool->manager_arb);
200129187a9eSTejun Heo 	return true;
2002e22bee78STejun Heo }
2003e22bee78STejun Heo 
2004a62428c0STejun Heo /**
2005a62428c0STejun Heo  * process_one_work - process single work
2006c34056a3STejun Heo  * @worker: self
2007a62428c0STejun Heo  * @work: work to process
2008a62428c0STejun Heo  *
2009a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2010a62428c0STejun Heo  * process a single work including synchronization against and
2011a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2012a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2013a62428c0STejun Heo  * call this function to process a work.
2014a62428c0STejun Heo  *
2015a62428c0STejun Heo  * CONTEXT:
2016d565ed63STejun Heo  * spin_lock_irq(pool->lock) which is released and regrabbed.
2017a62428c0STejun Heo  */
2018c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2019d565ed63STejun Heo __releases(&pool->lock)
2020d565ed63STejun Heo __acquires(&pool->lock)
20211da177e4SLinus Torvalds {
2022112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2023bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2024112202d9STejun Heo 	bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
202573f53c4aSTejun Heo 	int work_color;
20267e11629dSTejun Heo 	struct worker *collision;
20274e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
20284e6045f1SJohannes Berg 	/*
2029a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2030a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2031a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2032a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2033a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
20344e6045f1SJohannes Berg 	 */
20354d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
20364d82a1deSPeter Zijlstra 
20374d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
20384e6045f1SJohannes Berg #endif
2039807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
204085327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2041ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
204225511a47STejun Heo 
20437e11629dSTejun Heo 	/*
20447e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
20457e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
20467e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
20477e11629dSTejun Heo 	 * currently executing one.
20487e11629dSTejun Heo 	 */
2049c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
20507e11629dSTejun Heo 	if (unlikely(collision)) {
20517e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
20527e11629dSTejun Heo 		return;
20537e11629dSTejun Heo 	}
20541da177e4SLinus Torvalds 
20558930cabaSTejun Heo 	/* claim and dequeue */
20561da177e4SLinus Torvalds 	debug_work_deactivate(work);
2057c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2058c34056a3STejun Heo 	worker->current_work = work;
2059a2c1c57bSTejun Heo 	worker->current_func = work->func;
2060112202d9STejun Heo 	worker->current_pwq = pwq;
206173f53c4aSTejun Heo 	work_color = get_work_color(work);
20627a22ad75STejun Heo 
2063a62428c0STejun Heo 	list_del_init(&work->entry);
2064a62428c0STejun Heo 
2065649027d7STejun Heo 	/*
2066228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
2067228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
2068228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
2069228f1d00SLai Jiangshan 	 * execution of the pending work items.
2070fb0e7bebSTejun Heo 	 */
2071fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2072228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2073fb0e7bebSTejun Heo 
2074974271c4STejun Heo 	/*
2075a489a03eSLai Jiangshan 	 * Wake up another worker if necessary.  The condition is always
2076a489a03eSLai Jiangshan 	 * false for normal per-cpu workers since nr_running would always
2077a489a03eSLai Jiangshan 	 * be >= 1 at this point.  This is used to chain execution of the
2078a489a03eSLai Jiangshan 	 * pending work items for WORKER_NOT_RUNNING workers such as the
2079228f1d00SLai Jiangshan 	 * UNBOUND and CPU_INTENSIVE ones.
2080974271c4STejun Heo 	 */
2081a489a03eSLai Jiangshan 	if (need_more_worker(pool))
208263d95a91STejun Heo 		wake_up_worker(pool);
2083974271c4STejun Heo 
20848930cabaSTejun Heo 	/*
20857c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2086d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
208723657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
208823657bb1STejun Heo 	 * disabled.
20898930cabaSTejun Heo 	 */
20907c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
20911da177e4SLinus Torvalds 
2092d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2093365970a1SDavid Howells 
2094a1d14934SPeter Zijlstra 	lock_map_acquire(&pwq->wq->lockdep_map);
20953295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2096e6f3faa7SPeter Zijlstra 	/*
2097f52be570SPeter Zijlstra 	 * Strictly speaking we should mark the invariant state without holding
2098f52be570SPeter Zijlstra 	 * any locks, that is, before these two lock_map_acquire()'s.
2099e6f3faa7SPeter Zijlstra 	 *
2100e6f3faa7SPeter Zijlstra 	 * However, that would result in:
2101e6f3faa7SPeter Zijlstra 	 *
2102e6f3faa7SPeter Zijlstra 	 *   A(W1)
2103e6f3faa7SPeter Zijlstra 	 *   WFC(C)
2104e6f3faa7SPeter Zijlstra 	 *		A(W1)
2105e6f3faa7SPeter Zijlstra 	 *		C(C)
2106e6f3faa7SPeter Zijlstra 	 *
2107e6f3faa7SPeter Zijlstra 	 * Which would create W1->C->W1 dependencies, even though there is no
2108e6f3faa7SPeter Zijlstra 	 * actual deadlock possible. There are two solutions, using a
2109e6f3faa7SPeter Zijlstra 	 * read-recursive acquire on the work(queue) 'locks', but this will then
2110f52be570SPeter Zijlstra 	 * hit the lockdep limitation on recursive locks, or simply discard
2111e6f3faa7SPeter Zijlstra 	 * these locks.
2112e6f3faa7SPeter Zijlstra 	 *
2113e6f3faa7SPeter Zijlstra 	 * AFAICT there is no possible deadlock scenario between the
2114e6f3faa7SPeter Zijlstra 	 * flush_work() and complete() primitives (except for single-threaded
2115e6f3faa7SPeter Zijlstra 	 * workqueues), so hiding them isn't a problem.
2116e6f3faa7SPeter Zijlstra 	 */
2117f52be570SPeter Zijlstra 	lockdep_invariant_state(true);
2118e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2119a2c1c57bSTejun Heo 	worker->current_func(work);
2120e36c886aSArjan van de Ven 	/*
2121e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2122e36c886aSArjan van de Ven 	 * point will only record its address.
2123e36c886aSArjan van de Ven 	 */
2124e36c886aSArjan van de Ven 	trace_workqueue_execute_end(work);
21253295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2126112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
21271da177e4SLinus Torvalds 
2128d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2129044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2130044c782cSValentin Ilie 		       "     last function: %pf\n",
2131a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2132a2c1c57bSTejun Heo 		       worker->current_func);
2133d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2134d5abe669SPeter Zijlstra 		dump_stack();
2135d5abe669SPeter Zijlstra 	}
2136d5abe669SPeter Zijlstra 
2137b22ce278STejun Heo 	/*
2138b22ce278STejun Heo 	 * The following prevents a kworker from hogging CPU on !PREEMPT
2139b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
2140b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
2141b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
2142789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
2143789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
2144b22ce278STejun Heo 	 */
21453e28e377SJoe Lawrence 	cond_resched_rcu_qs();
2146b22ce278STejun Heo 
2147d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2148a62428c0STejun Heo 
2149fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2150fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2151fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2152fb0e7bebSTejun Heo 
2153a62428c0STejun Heo 	/* we're done with it, release */
215442f8570fSSasha Levin 	hash_del(&worker->hentry);
2155c34056a3STejun Heo 	worker->current_work = NULL;
2156a2c1c57bSTejun Heo 	worker->current_func = NULL;
2157112202d9STejun Heo 	worker->current_pwq = NULL;
21583d1cb205STejun Heo 	worker->desc_valid = false;
2159112202d9STejun Heo 	pwq_dec_nr_in_flight(pwq, work_color);
21601da177e4SLinus Torvalds }
21611da177e4SLinus Torvalds 
2162affee4b2STejun Heo /**
2163affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2164affee4b2STejun Heo  * @worker: self
2165affee4b2STejun Heo  *
2166affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2167affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2168affee4b2STejun Heo  * fetches a work from the top and executes it.
2169affee4b2STejun Heo  *
2170affee4b2STejun Heo  * CONTEXT:
2171d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2172affee4b2STejun Heo  * multiple times.
2173affee4b2STejun Heo  */
2174affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
21751da177e4SLinus Torvalds {
2176affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2177affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2178a62428c0STejun Heo 						struct work_struct, entry);
2179c34056a3STejun Heo 		process_one_work(worker, work);
2180a62428c0STejun Heo 	}
21811da177e4SLinus Torvalds }
21821da177e4SLinus Torvalds 
21834690c4abSTejun Heo /**
21844690c4abSTejun Heo  * worker_thread - the worker thread function
2185c34056a3STejun Heo  * @__worker: self
21864690c4abSTejun Heo  *
2187c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2188c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2189c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2190c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2191c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
2192d185af30SYacine Belkadi  *
2193d185af30SYacine Belkadi  * Return: 0
21944690c4abSTejun Heo  */
2195c34056a3STejun Heo static int worker_thread(void *__worker)
21961da177e4SLinus Torvalds {
2197c34056a3STejun Heo 	struct worker *worker = __worker;
2198bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
21991da177e4SLinus Torvalds 
2200e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2201e22bee78STejun Heo 	worker->task->flags |= PF_WQ_WORKER;
2202c8e55f36STejun Heo woke_up:
2203d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2204affee4b2STejun Heo 
2205a9ab775bSTejun Heo 	/* am I supposed to die? */
2206a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2207d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
2208a9ab775bSTejun Heo 		WARN_ON_ONCE(!list_empty(&worker->entry));
2209e22bee78STejun Heo 		worker->task->flags &= ~PF_WQ_WORKER;
221060f5a4bcSLai Jiangshan 
221160f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
22127cda9aaeSLai Jiangshan 		ida_simple_remove(&pool->worker_ida, worker->id);
221360f5a4bcSLai Jiangshan 		worker_detach_from_pool(worker, pool);
221460f5a4bcSLai Jiangshan 		kfree(worker);
2215c8e55f36STejun Heo 		return 0;
2216c8e55f36STejun Heo 	}
2217c8e55f36STejun Heo 
2218c8e55f36STejun Heo 	worker_leave_idle(worker);
2219db7bccf4STejun Heo recheck:
2220e22bee78STejun Heo 	/* no more worker necessary? */
222163d95a91STejun Heo 	if (!need_more_worker(pool))
2222e22bee78STejun Heo 		goto sleep;
2223e22bee78STejun Heo 
2224e22bee78STejun Heo 	/* do we need to manage? */
222563d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2226e22bee78STejun Heo 		goto recheck;
2227e22bee78STejun Heo 
2228c8e55f36STejun Heo 	/*
2229c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2230c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2231c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2232c8e55f36STejun Heo 	 */
22336183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2234c8e55f36STejun Heo 
2235e22bee78STejun Heo 	/*
2236a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2237a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2238a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2239a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2240a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2241e22bee78STejun Heo 	 */
2242a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2243e22bee78STejun Heo 
2244e22bee78STejun Heo 	do {
2245affee4b2STejun Heo 		struct work_struct *work =
2246bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2247affee4b2STejun Heo 					 struct work_struct, entry);
2248affee4b2STejun Heo 
224982607adcSTejun Heo 		pool->watchdog_ts = jiffies;
225082607adcSTejun Heo 
2251c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2252affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2253affee4b2STejun Heo 			process_one_work(worker, work);
2254affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2255affee4b2STejun Heo 				process_scheduled_works(worker);
2256affee4b2STejun Heo 		} else {
2257c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2258affee4b2STejun Heo 			process_scheduled_works(worker);
2259affee4b2STejun Heo 		}
226063d95a91STejun Heo 	} while (keep_working(pool));
2261affee4b2STejun Heo 
2262228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
2263d313dd85STejun Heo sleep:
2264c8e55f36STejun Heo 	/*
2265d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2266d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2267d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2268d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2269d565ed63STejun Heo 	 * event.
2270c8e55f36STejun Heo 	 */
2271c8e55f36STejun Heo 	worker_enter_idle(worker);
2272c5a94a61SPeter Zijlstra 	__set_current_state(TASK_IDLE);
2273d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
22741da177e4SLinus Torvalds 	schedule();
2275c8e55f36STejun Heo 	goto woke_up;
22761da177e4SLinus Torvalds }
22771da177e4SLinus Torvalds 
2278e22bee78STejun Heo /**
2279e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2280111c225aSTejun Heo  * @__rescuer: self
2281e22bee78STejun Heo  *
2282e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2283493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2284e22bee78STejun Heo  *
2285706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2286e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2287e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2288e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2289e22bee78STejun Heo  * the problem rescuer solves.
2290e22bee78STejun Heo  *
2291706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2292706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2293e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2294e22bee78STejun Heo  *
2295e22bee78STejun Heo  * This should happen rarely.
2296d185af30SYacine Belkadi  *
2297d185af30SYacine Belkadi  * Return: 0
2298e22bee78STejun Heo  */
2299111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2300e22bee78STejun Heo {
2301111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2302111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2303e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
23044d595b86SLai Jiangshan 	bool should_stop;
2305e22bee78STejun Heo 
2306e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2307111c225aSTejun Heo 
2308111c225aSTejun Heo 	/*
2309111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2310111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2311111c225aSTejun Heo 	 */
2312111c225aSTejun Heo 	rescuer->task->flags |= PF_WQ_WORKER;
2313e22bee78STejun Heo repeat:
2314c5a94a61SPeter Zijlstra 	set_current_state(TASK_IDLE);
23151da177e4SLinus Torvalds 
23164d595b86SLai Jiangshan 	/*
23174d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
23184d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
23194d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
23204d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
23214d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
23224d595b86SLai Jiangshan 	 * list is always empty on exit.
23234d595b86SLai Jiangshan 	 */
23244d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
23251da177e4SLinus Torvalds 
2326493a1724STejun Heo 	/* see whether any pwq is asking for help */
23272e109a28STejun Heo 	spin_lock_irq(&wq_mayday_lock);
2328493a1724STejun Heo 
2329493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2330493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2331493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2332112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2333e22bee78STejun Heo 		struct work_struct *work, *n;
233482607adcSTejun Heo 		bool first = true;
2335e22bee78STejun Heo 
2336e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2337493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2338493a1724STejun Heo 
23392e109a28STejun Heo 		spin_unlock_irq(&wq_mayday_lock);
2340e22bee78STejun Heo 
234151697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
234251697d39SLai Jiangshan 
234351697d39SLai Jiangshan 		spin_lock_irq(&pool->lock);
2344b3104104SLai Jiangshan 		rescuer->pool = pool;
2345e22bee78STejun Heo 
2346e22bee78STejun Heo 		/*
2347e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2348e22bee78STejun Heo 		 * process'em.
2349e22bee78STejun Heo 		 */
23500479c8c5STejun Heo 		WARN_ON_ONCE(!list_empty(scheduled));
235182607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
235282607adcSTejun Heo 			if (get_work_pwq(work) == pwq) {
235382607adcSTejun Heo 				if (first)
235482607adcSTejun Heo 					pool->watchdog_ts = jiffies;
2355e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
235682607adcSTejun Heo 			}
235782607adcSTejun Heo 			first = false;
235882607adcSTejun Heo 		}
2359e22bee78STejun Heo 
2360008847f6SNeilBrown 		if (!list_empty(scheduled)) {
2361e22bee78STejun Heo 			process_scheduled_works(rescuer);
23627576958aSTejun Heo 
23637576958aSTejun Heo 			/*
2364008847f6SNeilBrown 			 * The above execution of rescued work items could
2365008847f6SNeilBrown 			 * have created more to rescue through
2366008847f6SNeilBrown 			 * pwq_activate_first_delayed() or chained
2367008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
2368008847f6SNeilBrown 			 * that such back-to-back work items, which may be
2369008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
2370008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
2371008847f6SNeilBrown 			 */
2372008847f6SNeilBrown 			if (need_to_create_worker(pool)) {
2373008847f6SNeilBrown 				spin_lock(&wq_mayday_lock);
2374008847f6SNeilBrown 				get_pwq(pwq);
2375008847f6SNeilBrown 				list_move_tail(&pwq->mayday_node, &wq->maydays);
2376008847f6SNeilBrown 				spin_unlock(&wq_mayday_lock);
2377008847f6SNeilBrown 			}
2378008847f6SNeilBrown 		}
2379008847f6SNeilBrown 
2380008847f6SNeilBrown 		/*
238177668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
238213b1d625SLai Jiangshan 		 * go away while we're still attached to it.
238377668c8bSLai Jiangshan 		 */
238477668c8bSLai Jiangshan 		put_pwq(pwq);
238577668c8bSLai Jiangshan 
238677668c8bSLai Jiangshan 		/*
2387d8ca83e6SLai Jiangshan 		 * Leave this pool.  If need_more_worker() is %true, notify a
23887576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
23897576958aSTejun Heo 		 * and stalling the execution.
23907576958aSTejun Heo 		 */
2391d8ca83e6SLai Jiangshan 		if (need_more_worker(pool))
239263d95a91STejun Heo 			wake_up_worker(pool);
23937576958aSTejun Heo 
2394b3104104SLai Jiangshan 		rescuer->pool = NULL;
239513b1d625SLai Jiangshan 		spin_unlock_irq(&pool->lock);
239613b1d625SLai Jiangshan 
239713b1d625SLai Jiangshan 		worker_detach_from_pool(rescuer, pool);
239813b1d625SLai Jiangshan 
239913b1d625SLai Jiangshan 		spin_lock_irq(&wq_mayday_lock);
24001da177e4SLinus Torvalds 	}
24011da177e4SLinus Torvalds 
24022e109a28STejun Heo 	spin_unlock_irq(&wq_mayday_lock);
2403493a1724STejun Heo 
24044d595b86SLai Jiangshan 	if (should_stop) {
24054d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
24064d595b86SLai Jiangshan 		rescuer->task->flags &= ~PF_WQ_WORKER;
24074d595b86SLai Jiangshan 		return 0;
24084d595b86SLai Jiangshan 	}
24094d595b86SLai Jiangshan 
2410111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2411111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2412e22bee78STejun Heo 	schedule();
2413e22bee78STejun Heo 	goto repeat;
24141da177e4SLinus Torvalds }
24151da177e4SLinus Torvalds 
2416fca839c0STejun Heo /**
2417fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
2418fca839c0STejun Heo  * @target_wq: workqueue being flushed
2419fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
2420fca839c0STejun Heo  *
2421fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
2422fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2423fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
2424fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2425fca839c0STejun Heo  * a deadlock.
2426fca839c0STejun Heo  */
2427fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
2428fca839c0STejun Heo 				   struct work_struct *target_work)
2429fca839c0STejun Heo {
2430fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
2431fca839c0STejun Heo 	struct worker *worker;
2432fca839c0STejun Heo 
2433fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
2434fca839c0STejun Heo 		return;
2435fca839c0STejun Heo 
2436fca839c0STejun Heo 	worker = current_wq_worker();
2437fca839c0STejun Heo 
2438fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
2439fca839c0STejun Heo 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%pf",
2440fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
244123d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
244223d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2443fca839c0STejun Heo 		  "workqueue: WQ_MEM_RECLAIM %s:%pf is flushing !WQ_MEM_RECLAIM %s:%pf",
2444fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
2445fca839c0STejun Heo 		  target_wq->name, target_func);
2446fca839c0STejun Heo }
2447fca839c0STejun Heo 
2448fc2e4d70SOleg Nesterov struct wq_barrier {
2449fc2e4d70SOleg Nesterov 	struct work_struct	work;
2450fc2e4d70SOleg Nesterov 	struct completion	done;
24512607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
2452fc2e4d70SOleg Nesterov };
2453fc2e4d70SOleg Nesterov 
2454fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2455fc2e4d70SOleg Nesterov {
2456fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2457fc2e4d70SOleg Nesterov 	complete(&barr->done);
2458fc2e4d70SOleg Nesterov }
2459fc2e4d70SOleg Nesterov 
24604690c4abSTejun Heo /**
24614690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2462112202d9STejun Heo  * @pwq: pwq to insert barrier into
24634690c4abSTejun Heo  * @barr: wq_barrier to insert
2464affee4b2STejun Heo  * @target: target work to attach @barr to
2465affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
24664690c4abSTejun Heo  *
2467affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2468affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2469affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2470affee4b2STejun Heo  * cpu.
2471affee4b2STejun Heo  *
2472affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2473affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2474affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2475affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2476affee4b2STejun Heo  * after a work with LINKED flag set.
2477affee4b2STejun Heo  *
2478affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2479112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
24804690c4abSTejun Heo  *
24814690c4abSTejun Heo  * CONTEXT:
2482d565ed63STejun Heo  * spin_lock_irq(pool->lock).
24834690c4abSTejun Heo  */
2484112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2485affee4b2STejun Heo 			      struct wq_barrier *barr,
2486affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2487fc2e4d70SOleg Nesterov {
2488affee4b2STejun Heo 	struct list_head *head;
2489affee4b2STejun Heo 	unsigned int linked = 0;
2490affee4b2STejun Heo 
2491dc186ad7SThomas Gleixner 	/*
2492d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2493dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2494dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2495dc186ad7SThomas Gleixner 	 * might deadlock.
2496dc186ad7SThomas Gleixner 	 */
2497ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
249822df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
249952fa5bc5SBoqun Feng 
250052fa5bc5SBoqun Feng 	/*
250152fa5bc5SBoqun Feng 	 * Explicitly init the crosslock for wq_barrier::done, make its lock
250252fa5bc5SBoqun Feng 	 * key a subkey of the corresponding work. As a result we won't
250352fa5bc5SBoqun Feng 	 * build a dependency between wq_barrier::done and unrelated work.
250452fa5bc5SBoqun Feng 	 */
250552fa5bc5SBoqun Feng 	lockdep_init_map_crosslock((struct lockdep_map *)&barr->done.map,
250652fa5bc5SBoqun Feng 				   "(complete)wq_barr::done",
250752fa5bc5SBoqun Feng 				   target->lockdep_map.key, 1);
250852fa5bc5SBoqun Feng 	__init_completion(&barr->done);
25092607d7a6STejun Heo 	barr->task = current;
251083c22520SOleg Nesterov 
2511affee4b2STejun Heo 	/*
2512affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2513affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2514affee4b2STejun Heo 	 */
2515affee4b2STejun Heo 	if (worker)
2516affee4b2STejun Heo 		head = worker->scheduled.next;
2517affee4b2STejun Heo 	else {
2518affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2519affee4b2STejun Heo 
2520affee4b2STejun Heo 		head = target->entry.next;
2521affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2522affee4b2STejun Heo 		linked = *bits & WORK_STRUCT_LINKED;
2523affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2524affee4b2STejun Heo 	}
2525affee4b2STejun Heo 
2526dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2527112202d9STejun Heo 	insert_work(pwq, &barr->work, head,
2528affee4b2STejun Heo 		    work_color_to_flags(WORK_NO_COLOR) | linked);
2529fc2e4d70SOleg Nesterov }
2530fc2e4d70SOleg Nesterov 
253173f53c4aSTejun Heo /**
2532112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
253373f53c4aSTejun Heo  * @wq: workqueue being flushed
253473f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
253573f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
253673f53c4aSTejun Heo  *
2537112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
253873f53c4aSTejun Heo  *
2539112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
2540112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
2541112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
2542112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
2543112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
254473f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
254573f53c4aSTejun Heo  *
254673f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
254773f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
254873f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
254973f53c4aSTejun Heo  * is returned.
255073f53c4aSTejun Heo  *
2551112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
255273f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
255373f53c4aSTejun Heo  * advanced to @work_color.
255473f53c4aSTejun Heo  *
255573f53c4aSTejun Heo  * CONTEXT:
25563c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
255773f53c4aSTejun Heo  *
2558d185af30SYacine Belkadi  * Return:
255973f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
256073f53c4aSTejun Heo  * otherwise.
256173f53c4aSTejun Heo  */
2562112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
256373f53c4aSTejun Heo 				      int flush_color, int work_color)
25641da177e4SLinus Torvalds {
256573f53c4aSTejun Heo 	bool wait = false;
256649e3cf44STejun Heo 	struct pool_workqueue *pwq;
25671da177e4SLinus Torvalds 
256873f53c4aSTejun Heo 	if (flush_color >= 0) {
25696183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2570112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
2571dc186ad7SThomas Gleixner 	}
257214441960SOleg Nesterov 
257349e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2574112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
25751da177e4SLinus Torvalds 
2576b09f4fd3SLai Jiangshan 		spin_lock_irq(&pool->lock);
257773f53c4aSTejun Heo 
257873f53c4aSTejun Heo 		if (flush_color >= 0) {
25796183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
258073f53c4aSTejun Heo 
2581112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
2582112202d9STejun Heo 				pwq->flush_color = flush_color;
2583112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
258473f53c4aSTejun Heo 				wait = true;
25851da177e4SLinus Torvalds 			}
258673f53c4aSTejun Heo 		}
258773f53c4aSTejun Heo 
258873f53c4aSTejun Heo 		if (work_color >= 0) {
25896183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2590112202d9STejun Heo 			pwq->work_color = work_color;
259173f53c4aSTejun Heo 		}
259273f53c4aSTejun Heo 
2593b09f4fd3SLai Jiangshan 		spin_unlock_irq(&pool->lock);
25941da177e4SLinus Torvalds 	}
25951da177e4SLinus Torvalds 
2596112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
259773f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
259873f53c4aSTejun Heo 
259973f53c4aSTejun Heo 	return wait;
260083c22520SOleg Nesterov }
26011da177e4SLinus Torvalds 
26020fcb78c2SRolf Eike Beer /**
26031da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
26040fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
26051da177e4SLinus Torvalds  *
2606c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
2607c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
26081da177e4SLinus Torvalds  */
26097ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
26101da177e4SLinus Torvalds {
261173f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
261273f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
261373f53c4aSTejun Heo 		.flush_color = -1,
261473f53c4aSTejun Heo 		.done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
261573f53c4aSTejun Heo 	};
261673f53c4aSTejun Heo 	int next_color;
2617b1f4ec17SOleg Nesterov 
26183347fa09STejun Heo 	if (WARN_ON(!wq_online))
26193347fa09STejun Heo 		return;
26203347fa09STejun Heo 
26213295f0efSIngo Molnar 	lock_map_acquire(&wq->lockdep_map);
26223295f0efSIngo Molnar 	lock_map_release(&wq->lockdep_map);
262373f53c4aSTejun Heo 
26243c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
262573f53c4aSTejun Heo 
262673f53c4aSTejun Heo 	/*
262773f53c4aSTejun Heo 	 * Start-to-wait phase
262873f53c4aSTejun Heo 	 */
262973f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
263073f53c4aSTejun Heo 
263173f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
263273f53c4aSTejun Heo 		/*
263373f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
263473f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
263573f53c4aSTejun Heo 		 * by one.
263673f53c4aSTejun Heo 		 */
26376183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
263873f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
263973f53c4aSTejun Heo 		wq->work_color = next_color;
264073f53c4aSTejun Heo 
264173f53c4aSTejun Heo 		if (!wq->first_flusher) {
264273f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
26436183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
264473f53c4aSTejun Heo 
264573f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
264673f53c4aSTejun Heo 
2647112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
264873f53c4aSTejun Heo 						       wq->work_color)) {
264973f53c4aSTejun Heo 				/* nothing to flush, done */
265073f53c4aSTejun Heo 				wq->flush_color = next_color;
265173f53c4aSTejun Heo 				wq->first_flusher = NULL;
265273f53c4aSTejun Heo 				goto out_unlock;
265373f53c4aSTejun Heo 			}
265473f53c4aSTejun Heo 		} else {
265573f53c4aSTejun Heo 			/* wait in queue */
26566183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
265773f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
2658112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
265973f53c4aSTejun Heo 		}
266073f53c4aSTejun Heo 	} else {
266173f53c4aSTejun Heo 		/*
266273f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
266373f53c4aSTejun Heo 		 * The next flush completion will assign us
266473f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
266573f53c4aSTejun Heo 		 */
266673f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
266773f53c4aSTejun Heo 	}
266873f53c4aSTejun Heo 
2669fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
2670fca839c0STejun Heo 
26713c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
267273f53c4aSTejun Heo 
267373f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
267473f53c4aSTejun Heo 
267573f53c4aSTejun Heo 	/*
267673f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
267773f53c4aSTejun Heo 	 *
267873f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
267973f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
268073f53c4aSTejun Heo 	 */
268173f53c4aSTejun Heo 	if (wq->first_flusher != &this_flusher)
268273f53c4aSTejun Heo 		return;
268373f53c4aSTejun Heo 
26843c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
268573f53c4aSTejun Heo 
26864ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
26874ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
26884ce48b37STejun Heo 		goto out_unlock;
26894ce48b37STejun Heo 
269073f53c4aSTejun Heo 	wq->first_flusher = NULL;
269173f53c4aSTejun Heo 
26926183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
26936183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
269473f53c4aSTejun Heo 
269573f53c4aSTejun Heo 	while (true) {
269673f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
269773f53c4aSTejun Heo 
269873f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
269973f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
270073f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
270173f53c4aSTejun Heo 				break;
270273f53c4aSTejun Heo 			list_del_init(&next->list);
270373f53c4aSTejun Heo 			complete(&next->done);
270473f53c4aSTejun Heo 		}
270573f53c4aSTejun Heo 
27066183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
270773f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
270873f53c4aSTejun Heo 
270973f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
271073f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
271173f53c4aSTejun Heo 
271273f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
271373f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
271473f53c4aSTejun Heo 			/*
271573f53c4aSTejun Heo 			 * Assign the same color to all overflowed
271673f53c4aSTejun Heo 			 * flushers, advance work_color and append to
271773f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
271873f53c4aSTejun Heo 			 * phase for these overflowed flushers.
271973f53c4aSTejun Heo 			 */
272073f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
272173f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
272273f53c4aSTejun Heo 
272373f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
272473f53c4aSTejun Heo 
272573f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
272673f53c4aSTejun Heo 					      &wq->flusher_queue);
2727112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
272873f53c4aSTejun Heo 		}
272973f53c4aSTejun Heo 
273073f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
27316183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
273273f53c4aSTejun Heo 			break;
273373f53c4aSTejun Heo 		}
273473f53c4aSTejun Heo 
273573f53c4aSTejun Heo 		/*
273673f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
2737112202d9STejun Heo 		 * the new first flusher and arm pwqs.
273873f53c4aSTejun Heo 		 */
27396183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
27406183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
274173f53c4aSTejun Heo 
274273f53c4aSTejun Heo 		list_del_init(&next->list);
274373f53c4aSTejun Heo 		wq->first_flusher = next;
274473f53c4aSTejun Heo 
2745112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
274673f53c4aSTejun Heo 			break;
274773f53c4aSTejun Heo 
274873f53c4aSTejun Heo 		/*
274973f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
275073f53c4aSTejun Heo 		 * flusher and repeat cascading.
275173f53c4aSTejun Heo 		 */
275273f53c4aSTejun Heo 		wq->first_flusher = NULL;
275373f53c4aSTejun Heo 	}
275473f53c4aSTejun Heo 
275573f53c4aSTejun Heo out_unlock:
27563c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
27571da177e4SLinus Torvalds }
27581dadafa8STim Gardner EXPORT_SYMBOL(flush_workqueue);
27591da177e4SLinus Torvalds 
27609c5a2ba7STejun Heo /**
27619c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
27629c5a2ba7STejun Heo  * @wq: workqueue to drain
27639c5a2ba7STejun Heo  *
27649c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
27659c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
27669c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
2767b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
27689c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
27699c5a2ba7STejun Heo  * takes too long.
27709c5a2ba7STejun Heo  */
27719c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
27729c5a2ba7STejun Heo {
27739c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
277449e3cf44STejun Heo 	struct pool_workqueue *pwq;
27759c5a2ba7STejun Heo 
27769c5a2ba7STejun Heo 	/*
27779c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
27789c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
2779618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
27809c5a2ba7STejun Heo 	 */
278187fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
27829c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
2783618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
278487fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
27859c5a2ba7STejun Heo reflush:
27869c5a2ba7STejun Heo 	flush_workqueue(wq);
27879c5a2ba7STejun Heo 
2788b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
278976af4d93STejun Heo 
279049e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2791fa2563e4SThomas Tuttle 		bool drained;
27929c5a2ba7STejun Heo 
2793b09f4fd3SLai Jiangshan 		spin_lock_irq(&pwq->pool->lock);
2794112202d9STejun Heo 		drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2795b09f4fd3SLai Jiangshan 		spin_unlock_irq(&pwq->pool->lock);
2796fa2563e4SThomas Tuttle 
2797fa2563e4SThomas Tuttle 		if (drained)
27989c5a2ba7STejun Heo 			continue;
27999c5a2ba7STejun Heo 
28009c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
28019c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2802c5aa87bbSTejun Heo 			pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
28039c5a2ba7STejun Heo 				wq->name, flush_cnt);
280476af4d93STejun Heo 
2805b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
28069c5a2ba7STejun Heo 		goto reflush;
28079c5a2ba7STejun Heo 	}
28089c5a2ba7STejun Heo 
28099c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
2810618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
281187fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
28129c5a2ba7STejun Heo }
28139c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
28149c5a2ba7STejun Heo 
2815606a5020STejun Heo static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2816baf59022STejun Heo {
2817baf59022STejun Heo 	struct worker *worker = NULL;
2818c9e7cf27STejun Heo 	struct worker_pool *pool;
2819112202d9STejun Heo 	struct pool_workqueue *pwq;
2820baf59022STejun Heo 
2821baf59022STejun Heo 	might_sleep();
2822baf59022STejun Heo 
2823fa1b54e6STejun Heo 	local_irq_disable();
2824fa1b54e6STejun Heo 	pool = get_work_pool(work);
2825fa1b54e6STejun Heo 	if (!pool) {
2826fa1b54e6STejun Heo 		local_irq_enable();
2827fa1b54e6STejun Heo 		return false;
2828fa1b54e6STejun Heo 	}
2829fa1b54e6STejun Heo 
2830fa1b54e6STejun Heo 	spin_lock(&pool->lock);
28310b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
2832112202d9STejun Heo 	pwq = get_work_pwq(work);
2833112202d9STejun Heo 	if (pwq) {
2834112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
2835baf59022STejun Heo 			goto already_gone;
2836606a5020STejun Heo 	} else {
2837c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
2838baf59022STejun Heo 		if (!worker)
2839baf59022STejun Heo 			goto already_gone;
2840112202d9STejun Heo 		pwq = worker->current_pwq;
2841606a5020STejun Heo 	}
2842baf59022STejun Heo 
2843fca839c0STejun Heo 	check_flush_dependency(pwq->wq, work);
2844fca839c0STejun Heo 
2845112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
2846d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2847baf59022STejun Heo 
2848e159489bSTejun Heo 	/*
2849a1d14934SPeter Zijlstra 	 * Force a lock recursion deadlock when using flush_work() inside a
2850a1d14934SPeter Zijlstra 	 * single-threaded or rescuer equipped workqueue.
2851a1d14934SPeter Zijlstra 	 *
2852a1d14934SPeter Zijlstra 	 * For single threaded workqueues the deadlock happens when the work
2853a1d14934SPeter Zijlstra 	 * is after the work issuing the flush_work(). For rescuer equipped
2854a1d14934SPeter Zijlstra 	 * workqueues the deadlock happens when the rescuer stalls, blocking
2855a1d14934SPeter Zijlstra 	 * forward progress.
2856e159489bSTejun Heo 	 */
2857a1d14934SPeter Zijlstra 	if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer) {
2858112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
2859112202d9STejun Heo 		lock_map_release(&pwq->wq->lockdep_map);
2860a1d14934SPeter Zijlstra 	}
2861e159489bSTejun Heo 
2862baf59022STejun Heo 	return true;
2863baf59022STejun Heo already_gone:
2864d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2865baf59022STejun Heo 	return false;
2866baf59022STejun Heo }
2867baf59022STejun Heo 
2868db700897SOleg Nesterov /**
2869401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
2870401a8d04STejun Heo  * @work: the work to flush
2871db700897SOleg Nesterov  *
2872606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
2873606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
2874401a8d04STejun Heo  *
2875d185af30SYacine Belkadi  * Return:
2876401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2877401a8d04STejun Heo  * %false if it was already idle.
2878db700897SOleg Nesterov  */
2879401a8d04STejun Heo bool flush_work(struct work_struct *work)
2880db700897SOleg Nesterov {
288112997d1aSBjorn Helgaas 	struct wq_barrier barr;
288212997d1aSBjorn Helgaas 
28833347fa09STejun Heo 	if (WARN_ON(!wq_online))
28843347fa09STejun Heo 		return false;
28853347fa09STejun Heo 
28860976dfc1SStephen Boyd 	lock_map_acquire(&work->lockdep_map);
28870976dfc1SStephen Boyd 	lock_map_release(&work->lockdep_map);
28880976dfc1SStephen Boyd 
288912997d1aSBjorn Helgaas 	if (start_flush_work(work, &barr)) {
289012997d1aSBjorn Helgaas 		wait_for_completion(&barr.done);
289112997d1aSBjorn Helgaas 		destroy_work_on_stack(&barr.work);
289212997d1aSBjorn Helgaas 		return true;
289312997d1aSBjorn Helgaas 	} else {
289412997d1aSBjorn Helgaas 		return false;
289512997d1aSBjorn Helgaas 	}
2896606a5020STejun Heo }
2897db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
2898db700897SOleg Nesterov 
28998603e1b3STejun Heo struct cwt_wait {
2900ac6424b9SIngo Molnar 	wait_queue_entry_t		wait;
29018603e1b3STejun Heo 	struct work_struct	*work;
29028603e1b3STejun Heo };
29038603e1b3STejun Heo 
2904ac6424b9SIngo Molnar static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
29058603e1b3STejun Heo {
29068603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
29078603e1b3STejun Heo 
29088603e1b3STejun Heo 	if (cwait->work != key)
29098603e1b3STejun Heo 		return 0;
29108603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
29118603e1b3STejun Heo }
29128603e1b3STejun Heo 
291336e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2914401a8d04STejun Heo {
29158603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
2916bbb68dfaSTejun Heo 	unsigned long flags;
29171f1f642eSOleg Nesterov 	int ret;
29181f1f642eSOleg Nesterov 
29191f1f642eSOleg Nesterov 	do {
2920bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
2921bbb68dfaSTejun Heo 		/*
29228603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
29238603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
29248603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
29258603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
29268603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
29278603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
29288603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
29298603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
29308603e1b3STejun Heo 		 * we're hogging the CPU.
29318603e1b3STejun Heo 		 *
29328603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
29338603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
29348603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
29358603e1b3STejun Heo 		 * wait and wakeup.
2936bbb68dfaSTejun Heo 		 */
29378603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
29388603e1b3STejun Heo 			struct cwt_wait cwait;
29398603e1b3STejun Heo 
29408603e1b3STejun Heo 			init_wait(&cwait.wait);
29418603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
29428603e1b3STejun Heo 			cwait.work = work;
29438603e1b3STejun Heo 
29448603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
29458603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
29468603e1b3STejun Heo 			if (work_is_canceling(work))
29478603e1b3STejun Heo 				schedule();
29488603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
29498603e1b3STejun Heo 		}
29501f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
29511f1f642eSOleg Nesterov 
2952bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
2953bbb68dfaSTejun Heo 	mark_work_canceling(work);
2954bbb68dfaSTejun Heo 	local_irq_restore(flags);
2955bbb68dfaSTejun Heo 
29563347fa09STejun Heo 	/*
29573347fa09STejun Heo 	 * This allows canceling during early boot.  We know that @work
29583347fa09STejun Heo 	 * isn't executing.
29593347fa09STejun Heo 	 */
29603347fa09STejun Heo 	if (wq_online)
2961606a5020STejun Heo 		flush_work(work);
29623347fa09STejun Heo 
29637a22ad75STejun Heo 	clear_work_data(work);
29648603e1b3STejun Heo 
29658603e1b3STejun Heo 	/*
29668603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
29678603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
29688603e1b3STejun Heo 	 * visible there.
29698603e1b3STejun Heo 	 */
29708603e1b3STejun Heo 	smp_mb();
29718603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
29728603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
29738603e1b3STejun Heo 
29741f1f642eSOleg Nesterov 	return ret;
29751f1f642eSOleg Nesterov }
29761f1f642eSOleg Nesterov 
29776e84d644SOleg Nesterov /**
2978401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
2979401a8d04STejun Heo  * @work: the work to cancel
29806e84d644SOleg Nesterov  *
2981401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
2982401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
2983401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
2984401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
29851f1f642eSOleg Nesterov  *
2986401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
2987401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
29886e84d644SOleg Nesterov  *
2989401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
29906e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
2991401a8d04STejun Heo  *
2992d185af30SYacine Belkadi  * Return:
2993401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
29946e84d644SOleg Nesterov  */
2995401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
29966e84d644SOleg Nesterov {
299736e227d2STejun Heo 	return __cancel_work_timer(work, false);
2998b89deed3SOleg Nesterov }
299928e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
3000b89deed3SOleg Nesterov 
30016e84d644SOleg Nesterov /**
3002401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
3003401a8d04STejun Heo  * @dwork: the delayed work to flush
30046e84d644SOleg Nesterov  *
3005401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
3006401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
3007401a8d04STejun Heo  * considers the last queueing instance of @dwork.
30081f1f642eSOleg Nesterov  *
3009d185af30SYacine Belkadi  * Return:
3010401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3011401a8d04STejun Heo  * %false if it was already idle.
30126e84d644SOleg Nesterov  */
3013401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
3014401a8d04STejun Heo {
30158930cabaSTejun Heo 	local_irq_disable();
3016401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
301760c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
30188930cabaSTejun Heo 	local_irq_enable();
3019401a8d04STejun Heo 	return flush_work(&dwork->work);
3020401a8d04STejun Heo }
3021401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3022401a8d04STejun Heo 
3023f72b8792SJens Axboe static bool __cancel_work(struct work_struct *work, bool is_dwork)
3024f72b8792SJens Axboe {
3025f72b8792SJens Axboe 	unsigned long flags;
3026f72b8792SJens Axboe 	int ret;
3027f72b8792SJens Axboe 
3028f72b8792SJens Axboe 	do {
3029f72b8792SJens Axboe 		ret = try_to_grab_pending(work, is_dwork, &flags);
3030f72b8792SJens Axboe 	} while (unlikely(ret == -EAGAIN));
3031f72b8792SJens Axboe 
3032f72b8792SJens Axboe 	if (unlikely(ret < 0))
3033f72b8792SJens Axboe 		return false;
3034f72b8792SJens Axboe 
3035f72b8792SJens Axboe 	set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3036f72b8792SJens Axboe 	local_irq_restore(flags);
3037f72b8792SJens Axboe 	return ret;
3038f72b8792SJens Axboe }
3039f72b8792SJens Axboe 
3040f72b8792SJens Axboe /*
3041f72b8792SJens Axboe  * See cancel_delayed_work()
3042f72b8792SJens Axboe  */
3043f72b8792SJens Axboe bool cancel_work(struct work_struct *work)
3044f72b8792SJens Axboe {
3045f72b8792SJens Axboe 	return __cancel_work(work, false);
3046f72b8792SJens Axboe }
3047f72b8792SJens Axboe 
3048401a8d04STejun Heo /**
304957b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
305057b30ae7STejun Heo  * @dwork: delayed_work to cancel
305109383498STejun Heo  *
3052d185af30SYacine Belkadi  * Kill off a pending delayed_work.
3053d185af30SYacine Belkadi  *
3054d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
3055d185af30SYacine Belkadi  * pending.
3056d185af30SYacine Belkadi  *
3057d185af30SYacine Belkadi  * Note:
3058d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
3059d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
3060d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
306109383498STejun Heo  *
306257b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
306309383498STejun Heo  */
306457b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
306509383498STejun Heo {
3066f72b8792SJens Axboe 	return __cancel_work(&dwork->work, true);
306709383498STejun Heo }
306857b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
306909383498STejun Heo 
307009383498STejun Heo /**
3071401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3072401a8d04STejun Heo  * @dwork: the delayed work cancel
3073401a8d04STejun Heo  *
3074401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
3075401a8d04STejun Heo  *
3076d185af30SYacine Belkadi  * Return:
3077401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
3078401a8d04STejun Heo  */
3079401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
30806e84d644SOleg Nesterov {
308136e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
30826e84d644SOleg Nesterov }
3083f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
30841da177e4SLinus Torvalds 
30850fcb78c2SRolf Eike Beer /**
308631ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3087b6136773SAndrew Morton  * @func: the function to call
3088b6136773SAndrew Morton  *
308931ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
309031ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3091b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
309231ddd871STejun Heo  *
3093d185af30SYacine Belkadi  * Return:
309431ddd871STejun Heo  * 0 on success, -errno on failure.
3095b6136773SAndrew Morton  */
309665f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
309715316ba8SChristoph Lameter {
309815316ba8SChristoph Lameter 	int cpu;
309938f51568SNamhyung Kim 	struct work_struct __percpu *works;
310015316ba8SChristoph Lameter 
3101b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3102b6136773SAndrew Morton 	if (!works)
310315316ba8SChristoph Lameter 		return -ENOMEM;
3104b6136773SAndrew Morton 
310595402b38SGautham R Shenoy 	get_online_cpus();
310693981800STejun Heo 
310715316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
31089bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
31099bfb1839SIngo Molnar 
31109bfb1839SIngo Molnar 		INIT_WORK(work, func);
31118de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
311215316ba8SChristoph Lameter 	}
311393981800STejun Heo 
311493981800STejun Heo 	for_each_online_cpu(cpu)
31158616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
311693981800STejun Heo 
311795402b38SGautham R Shenoy 	put_online_cpus();
3118b6136773SAndrew Morton 	free_percpu(works);
311915316ba8SChristoph Lameter 	return 0;
312015316ba8SChristoph Lameter }
312115316ba8SChristoph Lameter 
3122eef6a7d5SAlan Stern /**
31231fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
31241fa44ecaSJames Bottomley  * @fn:		the function to execute
31251fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
31261fa44ecaSJames Bottomley  *		be available when the work executes)
31271fa44ecaSJames Bottomley  *
31281fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
31291fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
31301fa44ecaSJames Bottomley  *
3131d185af30SYacine Belkadi  * Return:	0 - function was executed
31321fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
31331fa44ecaSJames Bottomley  */
313465f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
31351fa44ecaSJames Bottomley {
31361fa44ecaSJames Bottomley 	if (!in_interrupt()) {
313765f27f38SDavid Howells 		fn(&ew->work);
31381fa44ecaSJames Bottomley 		return 0;
31391fa44ecaSJames Bottomley 	}
31401fa44ecaSJames Bottomley 
314165f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
31421fa44ecaSJames Bottomley 	schedule_work(&ew->work);
31431fa44ecaSJames Bottomley 
31441fa44ecaSJames Bottomley 	return 1;
31451fa44ecaSJames Bottomley }
31461fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
31471fa44ecaSJames Bottomley 
31487a4e344cSTejun Heo /**
31497a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
31507a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
31517a4e344cSTejun Heo  *
31527a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
31537a4e344cSTejun Heo  */
31547a4e344cSTejun Heo void free_workqueue_attrs(struct workqueue_attrs *attrs)
31557a4e344cSTejun Heo {
31567a4e344cSTejun Heo 	if (attrs) {
31577a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
31587a4e344cSTejun Heo 		kfree(attrs);
31597a4e344cSTejun Heo 	}
31607a4e344cSTejun Heo }
31617a4e344cSTejun Heo 
31627a4e344cSTejun Heo /**
31637a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
31647a4e344cSTejun Heo  * @gfp_mask: allocation mask to use
31657a4e344cSTejun Heo  *
31667a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3167d185af30SYacine Belkadi  * return it.
3168d185af30SYacine Belkadi  *
3169d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
31707a4e344cSTejun Heo  */
31717a4e344cSTejun Heo struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
31727a4e344cSTejun Heo {
31737a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
31747a4e344cSTejun Heo 
31757a4e344cSTejun Heo 	attrs = kzalloc(sizeof(*attrs), gfp_mask);
31767a4e344cSTejun Heo 	if (!attrs)
31777a4e344cSTejun Heo 		goto fail;
31787a4e344cSTejun Heo 	if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
31797a4e344cSTejun Heo 		goto fail;
31807a4e344cSTejun Heo 
318113e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
31827a4e344cSTejun Heo 	return attrs;
31837a4e344cSTejun Heo fail:
31847a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
31857a4e344cSTejun Heo 	return NULL;
31867a4e344cSTejun Heo }
31877a4e344cSTejun Heo 
318829c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
318929c91e99STejun Heo 				 const struct workqueue_attrs *from)
319029c91e99STejun Heo {
319129c91e99STejun Heo 	to->nice = from->nice;
319229c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
31932865a8fbSShaohua Li 	/*
31942865a8fbSShaohua Li 	 * Unlike hash and equality test, this function doesn't ignore
31952865a8fbSShaohua Li 	 * ->no_numa as it is used for both pool and wq attrs.  Instead,
31962865a8fbSShaohua Li 	 * get_unbound_pool() explicitly clears ->no_numa after copying.
31972865a8fbSShaohua Li 	 */
31982865a8fbSShaohua Li 	to->no_numa = from->no_numa;
319929c91e99STejun Heo }
320029c91e99STejun Heo 
320129c91e99STejun Heo /* hash value of the content of @attr */
320229c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
320329c91e99STejun Heo {
320429c91e99STejun Heo 	u32 hash = 0;
320529c91e99STejun Heo 
320629c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
320713e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
320813e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
320929c91e99STejun Heo 	return hash;
321029c91e99STejun Heo }
321129c91e99STejun Heo 
321229c91e99STejun Heo /* content equality test */
321329c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
321429c91e99STejun Heo 			  const struct workqueue_attrs *b)
321529c91e99STejun Heo {
321629c91e99STejun Heo 	if (a->nice != b->nice)
321729c91e99STejun Heo 		return false;
321829c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
321929c91e99STejun Heo 		return false;
322029c91e99STejun Heo 	return true;
322129c91e99STejun Heo }
322229c91e99STejun Heo 
32237a4e344cSTejun Heo /**
32247a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
32257a4e344cSTejun Heo  * @pool: worker_pool to initialize
32267a4e344cSTejun Heo  *
3227402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3228d185af30SYacine Belkadi  *
3229d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
323029c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
323129c91e99STejun Heo  * on @pool safely to release it.
32327a4e344cSTejun Heo  */
32337a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
32344e1a1f9aSTejun Heo {
32354e1a1f9aSTejun Heo 	spin_lock_init(&pool->lock);
323629c91e99STejun Heo 	pool->id = -1;
323729c91e99STejun Heo 	pool->cpu = -1;
3238f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
32394e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
324082607adcSTejun Heo 	pool->watchdog_ts = jiffies;
32414e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
32424e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
32434e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
32444e1a1f9aSTejun Heo 
3245c30fb26bSGeliang Tang 	setup_deferrable_timer(&pool->idle_timer, idle_worker_timeout,
3246c30fb26bSGeliang Tang 			       (unsigned long)pool);
32474e1a1f9aSTejun Heo 
32484e1a1f9aSTejun Heo 	setup_timer(&pool->mayday_timer, pool_mayday_timeout,
32494e1a1f9aSTejun Heo 		    (unsigned long)pool);
32504e1a1f9aSTejun Heo 
32514e1a1f9aSTejun Heo 	mutex_init(&pool->manager_arb);
325292f9c5c4SLai Jiangshan 	mutex_init(&pool->attach_mutex);
3253da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
32547a4e344cSTejun Heo 
32557cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
325629c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
325729c91e99STejun Heo 	pool->refcnt = 1;
325829c91e99STejun Heo 
325929c91e99STejun Heo 	/* shouldn't fail above this point */
32607a4e344cSTejun Heo 	pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
32617a4e344cSTejun Heo 	if (!pool->attrs)
32627a4e344cSTejun Heo 		return -ENOMEM;
32637a4e344cSTejun Heo 	return 0;
32644e1a1f9aSTejun Heo }
32654e1a1f9aSTejun Heo 
3266e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
3267e2dca7adSTejun Heo {
3268e2dca7adSTejun Heo 	struct workqueue_struct *wq =
3269e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
3270e2dca7adSTejun Heo 
3271e2dca7adSTejun Heo 	if (!(wq->flags & WQ_UNBOUND))
3272e2dca7adSTejun Heo 		free_percpu(wq->cpu_pwqs);
3273e2dca7adSTejun Heo 	else
3274e2dca7adSTejun Heo 		free_workqueue_attrs(wq->unbound_attrs);
3275e2dca7adSTejun Heo 
3276e2dca7adSTejun Heo 	kfree(wq->rescuer);
3277e2dca7adSTejun Heo 	kfree(wq);
3278e2dca7adSTejun Heo }
3279e2dca7adSTejun Heo 
328029c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
328129c91e99STejun Heo {
328229c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
328329c91e99STejun Heo 
32847cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
328529c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
328629c91e99STejun Heo 	kfree(pool);
328729c91e99STejun Heo }
328829c91e99STejun Heo 
328929c91e99STejun Heo /**
329029c91e99STejun Heo  * put_unbound_pool - put a worker_pool
329129c91e99STejun Heo  * @pool: worker_pool to put
329229c91e99STejun Heo  *
329329c91e99STejun Heo  * Put @pool.  If its refcnt reaches zero, it gets destroyed in sched-RCU
3294c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3295c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3296c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
3297a892caccSTejun Heo  *
3298a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
329929c91e99STejun Heo  */
330029c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
330129c91e99STejun Heo {
330260f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
330329c91e99STejun Heo 	struct worker *worker;
330429c91e99STejun Heo 
3305a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3306a892caccSTejun Heo 
3307a892caccSTejun Heo 	if (--pool->refcnt)
330829c91e99STejun Heo 		return;
330929c91e99STejun Heo 
331029c91e99STejun Heo 	/* sanity checks */
331161d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
3312a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
331329c91e99STejun Heo 		return;
331429c91e99STejun Heo 
331529c91e99STejun Heo 	/* release id and unhash */
331629c91e99STejun Heo 	if (pool->id >= 0)
331729c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
331829c91e99STejun Heo 	hash_del(&pool->hash_node);
331929c91e99STejun Heo 
3320c5aa87bbSTejun Heo 	/*
3321c5aa87bbSTejun Heo 	 * Become the manager and destroy all workers.  Grabbing
3322c5aa87bbSTejun Heo 	 * manager_arb prevents @pool's workers from blocking on
332392f9c5c4SLai Jiangshan 	 * attach_mutex.
3324c5aa87bbSTejun Heo 	 */
332529c91e99STejun Heo 	mutex_lock(&pool->manager_arb);
332629c91e99STejun Heo 
332760f5a4bcSLai Jiangshan 	spin_lock_irq(&pool->lock);
33281037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
332929c91e99STejun Heo 		destroy_worker(worker);
333029c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
333129c91e99STejun Heo 	spin_unlock_irq(&pool->lock);
333260f5a4bcSLai Jiangshan 
333392f9c5c4SLai Jiangshan 	mutex_lock(&pool->attach_mutex);
3334da028469SLai Jiangshan 	if (!list_empty(&pool->workers))
333560f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
333692f9c5c4SLai Jiangshan 	mutex_unlock(&pool->attach_mutex);
333760f5a4bcSLai Jiangshan 
333860f5a4bcSLai Jiangshan 	if (pool->detach_completion)
333960f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
334060f5a4bcSLai Jiangshan 
334129c91e99STejun Heo 	mutex_unlock(&pool->manager_arb);
334229c91e99STejun Heo 
334329c91e99STejun Heo 	/* shut down the timers */
334429c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
334529c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
334629c91e99STejun Heo 
334729c91e99STejun Heo 	/* sched-RCU protected to allow dereferences from get_work_pool() */
334829c91e99STejun Heo 	call_rcu_sched(&pool->rcu, rcu_free_pool);
334929c91e99STejun Heo }
335029c91e99STejun Heo 
335129c91e99STejun Heo /**
335229c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
335329c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
335429c91e99STejun Heo  *
335529c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
335629c91e99STejun Heo  * reference count and return it.  If there already is a matching
335729c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
3358d185af30SYacine Belkadi  * create a new one.
3359a892caccSTejun Heo  *
3360a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
3361d185af30SYacine Belkadi  *
3362d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
3363d185af30SYacine Belkadi  * On failure, %NULL.
336429c91e99STejun Heo  */
336529c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
336629c91e99STejun Heo {
336729c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
336829c91e99STejun Heo 	struct worker_pool *pool;
3369f3f90ad4STejun Heo 	int node;
3370e2273584SXunlei Pang 	int target_node = NUMA_NO_NODE;
337129c91e99STejun Heo 
3372a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
337329c91e99STejun Heo 
337429c91e99STejun Heo 	/* do we already have a matching pool? */
337529c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
337629c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
337729c91e99STejun Heo 			pool->refcnt++;
33783fb1823cSLai Jiangshan 			return pool;
337929c91e99STejun Heo 		}
338029c91e99STejun Heo 	}
338129c91e99STejun Heo 
3382e2273584SXunlei Pang 	/* if cpumask is contained inside a NUMA node, we belong to that node */
3383e2273584SXunlei Pang 	if (wq_numa_enabled) {
3384e2273584SXunlei Pang 		for_each_node(node) {
3385e2273584SXunlei Pang 			if (cpumask_subset(attrs->cpumask,
3386e2273584SXunlei Pang 					   wq_numa_possible_cpumask[node])) {
3387e2273584SXunlei Pang 				target_node = node;
3388e2273584SXunlei Pang 				break;
3389e2273584SXunlei Pang 			}
3390e2273584SXunlei Pang 		}
3391e2273584SXunlei Pang 	}
3392e2273584SXunlei Pang 
339329c91e99STejun Heo 	/* nope, create a new one */
3394e2273584SXunlei Pang 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
339529c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
339629c91e99STejun Heo 		goto fail;
339729c91e99STejun Heo 
33988864b4e5STejun Heo 	lockdep_set_subclass(&pool->lock, 1);	/* see put_pwq() */
339929c91e99STejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
3400e2273584SXunlei Pang 	pool->node = target_node;
340129c91e99STejun Heo 
34022865a8fbSShaohua Li 	/*
34032865a8fbSShaohua Li 	 * no_numa isn't a worker_pool attribute, always clear it.  See
34042865a8fbSShaohua Li 	 * 'struct workqueue_attrs' comments for detail.
34052865a8fbSShaohua Li 	 */
34062865a8fbSShaohua Li 	pool->attrs->no_numa = false;
34072865a8fbSShaohua Li 
340829c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
340929c91e99STejun Heo 		goto fail;
341029c91e99STejun Heo 
341129c91e99STejun Heo 	/* create and start the initial worker */
34123347fa09STejun Heo 	if (wq_online && !create_worker(pool))
341329c91e99STejun Heo 		goto fail;
341429c91e99STejun Heo 
341529c91e99STejun Heo 	/* install */
341629c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
34173fb1823cSLai Jiangshan 
341829c91e99STejun Heo 	return pool;
341929c91e99STejun Heo fail:
342029c91e99STejun Heo 	if (pool)
342129c91e99STejun Heo 		put_unbound_pool(pool);
342229c91e99STejun Heo 	return NULL;
342329c91e99STejun Heo }
342429c91e99STejun Heo 
34258864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
34268864b4e5STejun Heo {
34278864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
34288864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
34298864b4e5STejun Heo }
34308864b4e5STejun Heo 
34318864b4e5STejun Heo /*
34328864b4e5STejun Heo  * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
34338864b4e5STejun Heo  * and needs to be destroyed.
34348864b4e5STejun Heo  */
34358864b4e5STejun Heo static void pwq_unbound_release_workfn(struct work_struct *work)
34368864b4e5STejun Heo {
34378864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
34388864b4e5STejun Heo 						  unbound_release_work);
34398864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
34408864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
3441bc0caf09STejun Heo 	bool is_last;
34428864b4e5STejun Heo 
34438864b4e5STejun Heo 	if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
34448864b4e5STejun Heo 		return;
34458864b4e5STejun Heo 
34463c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
34478864b4e5STejun Heo 	list_del_rcu(&pwq->pwqs_node);
3448bc0caf09STejun Heo 	is_last = list_empty(&wq->pwqs);
34493c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
34508864b4e5STejun Heo 
3451a892caccSTejun Heo 	mutex_lock(&wq_pool_mutex);
34528864b4e5STejun Heo 	put_unbound_pool(pool);
3453a892caccSTejun Heo 	mutex_unlock(&wq_pool_mutex);
3454a892caccSTejun Heo 
34558864b4e5STejun Heo 	call_rcu_sched(&pwq->rcu, rcu_free_pwq);
34568864b4e5STejun Heo 
34578864b4e5STejun Heo 	/*
34588864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
3459e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
34608864b4e5STejun Heo 	 */
3461e2dca7adSTejun Heo 	if (is_last)
3462e2dca7adSTejun Heo 		call_rcu_sched(&wq->rcu, rcu_free_wq);
34636029a918STejun Heo }
34648864b4e5STejun Heo 
34650fbd95aaSTejun Heo /**
3466699ce097STejun Heo  * pwq_adjust_max_active - update a pwq's max_active to the current setting
34670fbd95aaSTejun Heo  * @pwq: target pool_workqueue
34680fbd95aaSTejun Heo  *
3469699ce097STejun Heo  * If @pwq isn't freezing, set @pwq->max_active to the associated
3470699ce097STejun Heo  * workqueue's saved_max_active and activate delayed work items
3471699ce097STejun Heo  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
34720fbd95aaSTejun Heo  */
3473699ce097STejun Heo static void pwq_adjust_max_active(struct pool_workqueue *pwq)
34740fbd95aaSTejun Heo {
3475699ce097STejun Heo 	struct workqueue_struct *wq = pwq->wq;
3476699ce097STejun Heo 	bool freezable = wq->flags & WQ_FREEZABLE;
34773347fa09STejun Heo 	unsigned long flags;
3478699ce097STejun Heo 
3479699ce097STejun Heo 	/* for @wq->saved_max_active */
3480a357fc03SLai Jiangshan 	lockdep_assert_held(&wq->mutex);
3481699ce097STejun Heo 
3482699ce097STejun Heo 	/* fast exit for non-freezable wqs */
3483699ce097STejun Heo 	if (!freezable && pwq->max_active == wq->saved_max_active)
3484699ce097STejun Heo 		return;
3485699ce097STejun Heo 
34863347fa09STejun Heo 	/* this function can be called during early boot w/ irq disabled */
34873347fa09STejun Heo 	spin_lock_irqsave(&pwq->pool->lock, flags);
3488699ce097STejun Heo 
348974b414eaSLai Jiangshan 	/*
349074b414eaSLai Jiangshan 	 * During [un]freezing, the caller is responsible for ensuring that
349174b414eaSLai Jiangshan 	 * this function is called at least once after @workqueue_freezing
349274b414eaSLai Jiangshan 	 * is updated and visible.
349374b414eaSLai Jiangshan 	 */
349474b414eaSLai Jiangshan 	if (!freezable || !workqueue_freezing) {
3495699ce097STejun Heo 		pwq->max_active = wq->saved_max_active;
34960fbd95aaSTejun Heo 
34970fbd95aaSTejun Heo 		while (!list_empty(&pwq->delayed_works) &&
34980fbd95aaSTejun Heo 		       pwq->nr_active < pwq->max_active)
34990fbd95aaSTejun Heo 			pwq_activate_first_delayed(pwq);
3500951a078aSLai Jiangshan 
3501951a078aSLai Jiangshan 		/*
3502951a078aSLai Jiangshan 		 * Need to kick a worker after thawed or an unbound wq's
3503951a078aSLai Jiangshan 		 * max_active is bumped.  It's a slow path.  Do it always.
3504951a078aSLai Jiangshan 		 */
3505951a078aSLai Jiangshan 		wake_up_worker(pwq->pool);
3506699ce097STejun Heo 	} else {
3507699ce097STejun Heo 		pwq->max_active = 0;
3508699ce097STejun Heo 	}
3509699ce097STejun Heo 
35103347fa09STejun Heo 	spin_unlock_irqrestore(&pwq->pool->lock, flags);
35110fbd95aaSTejun Heo }
35120fbd95aaSTejun Heo 
3513e50aba9aSTejun Heo /* initialize newly alloced @pwq which is associated with @wq and @pool */
3514f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3515f147f29eSTejun Heo 		     struct worker_pool *pool)
3516d2c1d404STejun Heo {
3517d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3518d2c1d404STejun Heo 
3519e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
3520e50aba9aSTejun Heo 
3521d2c1d404STejun Heo 	pwq->pool = pool;
3522d2c1d404STejun Heo 	pwq->wq = wq;
3523d2c1d404STejun Heo 	pwq->flush_color = -1;
35248864b4e5STejun Heo 	pwq->refcnt = 1;
3525d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->delayed_works);
35261befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
3527d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
35288864b4e5STejun Heo 	INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3529f147f29eSTejun Heo }
3530d2c1d404STejun Heo 
3531f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
35321befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
3533f147f29eSTejun Heo {
3534f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
3535f147f29eSTejun Heo 
3536f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
353775ccf595STejun Heo 
35381befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
35391befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
35401befcf30STejun Heo 		return;
35411befcf30STejun Heo 
354229b1cb41SLai Jiangshan 	/* set the matching work_color */
354375ccf595STejun Heo 	pwq->work_color = wq->work_color;
3544983ca25eSTejun Heo 
3545983ca25eSTejun Heo 	/* sync max_active to the current setting */
3546983ca25eSTejun Heo 	pwq_adjust_max_active(pwq);
3547983ca25eSTejun Heo 
3548983ca25eSTejun Heo 	/* link in @pwq */
35499e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3550df2d5ae4STejun Heo }
35516029a918STejun Heo 
3552f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3553f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3554f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
3555f147f29eSTejun Heo {
3556f147f29eSTejun Heo 	struct worker_pool *pool;
3557f147f29eSTejun Heo 	struct pool_workqueue *pwq;
3558f147f29eSTejun Heo 
3559f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3560f147f29eSTejun Heo 
3561f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
3562f147f29eSTejun Heo 	if (!pool)
3563f147f29eSTejun Heo 		return NULL;
3564f147f29eSTejun Heo 
3565e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3566f147f29eSTejun Heo 	if (!pwq) {
3567f147f29eSTejun Heo 		put_unbound_pool(pool);
3568f147f29eSTejun Heo 		return NULL;
3569f147f29eSTejun Heo 	}
3570f147f29eSTejun Heo 
3571f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
3572f147f29eSTejun Heo 	return pwq;
3573d2c1d404STejun Heo }
3574d2c1d404STejun Heo 
35754c16bd32STejun Heo /**
357630186c6fSGong Zhaogang  * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
3577042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
35784c16bd32STejun Heo  * @node: the target NUMA node
35794c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
35804c16bd32STejun Heo  * @cpumask: outarg, the resulting cpumask
35814c16bd32STejun Heo  *
35824c16bd32STejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @node.  If
35834c16bd32STejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during
3584d185af30SYacine Belkadi  * calculation.  The result is stored in @cpumask.
35854c16bd32STejun Heo  *
35864c16bd32STejun Heo  * If NUMA affinity is not enabled, @attrs->cpumask is always used.  If
35874c16bd32STejun Heo  * enabled and @node has online CPUs requested by @attrs, the returned
35884c16bd32STejun Heo  * cpumask is the intersection of the possible CPUs of @node and
35894c16bd32STejun Heo  * @attrs->cpumask.
35904c16bd32STejun Heo  *
35914c16bd32STejun Heo  * The caller is responsible for ensuring that the cpumask of @node stays
35924c16bd32STejun Heo  * stable.
3593d185af30SYacine Belkadi  *
3594d185af30SYacine Belkadi  * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3595d185af30SYacine Belkadi  * %false if equal.
35964c16bd32STejun Heo  */
35974c16bd32STejun Heo static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
35984c16bd32STejun Heo 				 int cpu_going_down, cpumask_t *cpumask)
35994c16bd32STejun Heo {
3600d55262c4STejun Heo 	if (!wq_numa_enabled || attrs->no_numa)
36014c16bd32STejun Heo 		goto use_dfl;
36024c16bd32STejun Heo 
36034c16bd32STejun Heo 	/* does @node have any online CPUs @attrs wants? */
36044c16bd32STejun Heo 	cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
36054c16bd32STejun Heo 	if (cpu_going_down >= 0)
36064c16bd32STejun Heo 		cpumask_clear_cpu(cpu_going_down, cpumask);
36074c16bd32STejun Heo 
36084c16bd32STejun Heo 	if (cpumask_empty(cpumask))
36094c16bd32STejun Heo 		goto use_dfl;
36104c16bd32STejun Heo 
36114c16bd32STejun Heo 	/* yeap, return possible CPUs in @node that @attrs wants */
36124c16bd32STejun Heo 	cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
36131ad0f0a7SMichael Bringmann 
36141ad0f0a7SMichael Bringmann 	if (cpumask_empty(cpumask)) {
36151ad0f0a7SMichael Bringmann 		pr_warn_once("WARNING: workqueue cpumask: online intersect > "
36161ad0f0a7SMichael Bringmann 				"possible intersect\n");
36171ad0f0a7SMichael Bringmann 		return false;
36181ad0f0a7SMichael Bringmann 	}
36191ad0f0a7SMichael Bringmann 
36204c16bd32STejun Heo 	return !cpumask_equal(cpumask, attrs->cpumask);
36214c16bd32STejun Heo 
36224c16bd32STejun Heo use_dfl:
36234c16bd32STejun Heo 	cpumask_copy(cpumask, attrs->cpumask);
36244c16bd32STejun Heo 	return false;
36254c16bd32STejun Heo }
36264c16bd32STejun Heo 
36271befcf30STejun Heo /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
36281befcf30STejun Heo static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
36291befcf30STejun Heo 						   int node,
36301befcf30STejun Heo 						   struct pool_workqueue *pwq)
36311befcf30STejun Heo {
36321befcf30STejun Heo 	struct pool_workqueue *old_pwq;
36331befcf30STejun Heo 
36345b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
36351befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
36361befcf30STejun Heo 
36371befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
36381befcf30STejun Heo 	link_pwq(pwq);
36391befcf30STejun Heo 
36401befcf30STejun Heo 	old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
36411befcf30STejun Heo 	rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
36421befcf30STejun Heo 	return old_pwq;
36431befcf30STejun Heo }
36441befcf30STejun Heo 
36452d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
36462d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
36472d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
36482d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
3649042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
36502d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
36512d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
36522d5f0764SLai Jiangshan };
36532d5f0764SLai Jiangshan 
36542d5f0764SLai Jiangshan /* free the resources after success or abort */
36552d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
36562d5f0764SLai Jiangshan {
36572d5f0764SLai Jiangshan 	if (ctx) {
36582d5f0764SLai Jiangshan 		int node;
36592d5f0764SLai Jiangshan 
36602d5f0764SLai Jiangshan 		for_each_node(node)
36612d5f0764SLai Jiangshan 			put_pwq_unlocked(ctx->pwq_tbl[node]);
36622d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
36632d5f0764SLai Jiangshan 
36642d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
36652d5f0764SLai Jiangshan 
36662d5f0764SLai Jiangshan 		kfree(ctx);
36672d5f0764SLai Jiangshan 	}
36682d5f0764SLai Jiangshan }
36692d5f0764SLai Jiangshan 
36702d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
36712d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
36722d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
36732d5f0764SLai Jiangshan 		      const struct workqueue_attrs *attrs)
36742d5f0764SLai Jiangshan {
36752d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
36762d5f0764SLai Jiangshan 	struct workqueue_attrs *new_attrs, *tmp_attrs;
36772d5f0764SLai Jiangshan 	int node;
36782d5f0764SLai Jiangshan 
36792d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
36802d5f0764SLai Jiangshan 
36812d5f0764SLai Jiangshan 	ctx = kzalloc(sizeof(*ctx) + nr_node_ids * sizeof(ctx->pwq_tbl[0]),
36822d5f0764SLai Jiangshan 		      GFP_KERNEL);
36832d5f0764SLai Jiangshan 
36842d5f0764SLai Jiangshan 	new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
36852d5f0764SLai Jiangshan 	tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
36862d5f0764SLai Jiangshan 	if (!ctx || !new_attrs || !tmp_attrs)
36872d5f0764SLai Jiangshan 		goto out_free;
36882d5f0764SLai Jiangshan 
3689042f7df1SLai Jiangshan 	/*
3690042f7df1SLai Jiangshan 	 * Calculate the attrs of the default pwq.
3691042f7df1SLai Jiangshan 	 * If the user configured cpumask doesn't overlap with the
3692042f7df1SLai Jiangshan 	 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
3693042f7df1SLai Jiangshan 	 */
36942d5f0764SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
3695b05a7928SFrederic Weisbecker 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, wq_unbound_cpumask);
3696042f7df1SLai Jiangshan 	if (unlikely(cpumask_empty(new_attrs->cpumask)))
3697042f7df1SLai Jiangshan 		cpumask_copy(new_attrs->cpumask, wq_unbound_cpumask);
36982d5f0764SLai Jiangshan 
36992d5f0764SLai Jiangshan 	/*
37002d5f0764SLai Jiangshan 	 * We may create multiple pwqs with differing cpumasks.  Make a
37012d5f0764SLai Jiangshan 	 * copy of @new_attrs which will be modified and used to obtain
37022d5f0764SLai Jiangshan 	 * pools.
37032d5f0764SLai Jiangshan 	 */
37042d5f0764SLai Jiangshan 	copy_workqueue_attrs(tmp_attrs, new_attrs);
37052d5f0764SLai Jiangshan 
37062d5f0764SLai Jiangshan 	/*
37072d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
37082d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
37092d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
37102d5f0764SLai Jiangshan 	 */
37112d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
37122d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
37132d5f0764SLai Jiangshan 		goto out_free;
37142d5f0764SLai Jiangshan 
37152d5f0764SLai Jiangshan 	for_each_node(node) {
3716042f7df1SLai Jiangshan 		if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
37172d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
37182d5f0764SLai Jiangshan 			if (!ctx->pwq_tbl[node])
37192d5f0764SLai Jiangshan 				goto out_free;
37202d5f0764SLai Jiangshan 		} else {
37212d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
37222d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = ctx->dfl_pwq;
37232d5f0764SLai Jiangshan 		}
37242d5f0764SLai Jiangshan 	}
37252d5f0764SLai Jiangshan 
3726042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
3727042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
3728042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
37292d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
3730042f7df1SLai Jiangshan 
37312d5f0764SLai Jiangshan 	ctx->wq = wq;
37322d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
37332d5f0764SLai Jiangshan 	return ctx;
37342d5f0764SLai Jiangshan 
37352d5f0764SLai Jiangshan out_free:
37362d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
37372d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
37382d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
37392d5f0764SLai Jiangshan 	return NULL;
37402d5f0764SLai Jiangshan }
37412d5f0764SLai Jiangshan 
37422d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
37432d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
37442d5f0764SLai Jiangshan {
37452d5f0764SLai Jiangshan 	int node;
37462d5f0764SLai Jiangshan 
37472d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
37482d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
37492d5f0764SLai Jiangshan 
37502d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
37512d5f0764SLai Jiangshan 
37522d5f0764SLai Jiangshan 	/* save the previous pwq and install the new one */
37532d5f0764SLai Jiangshan 	for_each_node(node)
37542d5f0764SLai Jiangshan 		ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
37552d5f0764SLai Jiangshan 							  ctx->pwq_tbl[node]);
37562d5f0764SLai Jiangshan 
37572d5f0764SLai Jiangshan 	/* @dfl_pwq might not have been used, ensure it's linked */
37582d5f0764SLai Jiangshan 	link_pwq(ctx->dfl_pwq);
37592d5f0764SLai Jiangshan 	swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
37602d5f0764SLai Jiangshan 
37612d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
37622d5f0764SLai Jiangshan }
37632d5f0764SLai Jiangshan 
3764a0111cf6SLai Jiangshan static void apply_wqattrs_lock(void)
3765a0111cf6SLai Jiangshan {
3766a0111cf6SLai Jiangshan 	/* CPUs should stay stable across pwq creations and installations */
3767a0111cf6SLai Jiangshan 	get_online_cpus();
3768a0111cf6SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
3769a0111cf6SLai Jiangshan }
3770a0111cf6SLai Jiangshan 
3771a0111cf6SLai Jiangshan static void apply_wqattrs_unlock(void)
3772a0111cf6SLai Jiangshan {
3773a0111cf6SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
3774a0111cf6SLai Jiangshan 	put_online_cpus();
3775a0111cf6SLai Jiangshan }
3776a0111cf6SLai Jiangshan 
3777a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
3778a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
3779a0111cf6SLai Jiangshan {
3780a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
3781a0111cf6SLai Jiangshan 
3782a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
3783a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
3784a0111cf6SLai Jiangshan 		return -EINVAL;
3785a0111cf6SLai Jiangshan 
3786a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
37870a94efb5STejun Heo 	if (!list_empty(&wq->pwqs)) {
37880a94efb5STejun Heo 		if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
3789a0111cf6SLai Jiangshan 			return -EINVAL;
3790a0111cf6SLai Jiangshan 
37910a94efb5STejun Heo 		wq->flags &= ~__WQ_ORDERED;
37920a94efb5STejun Heo 	}
37930a94efb5STejun Heo 
3794a0111cf6SLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs);
37956201171eSwanghaibin 	if (!ctx)
37966201171eSwanghaibin 		return -ENOMEM;
3797a0111cf6SLai Jiangshan 
3798a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
3799a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
3800a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
3801a0111cf6SLai Jiangshan 
38026201171eSwanghaibin 	return 0;
3803a0111cf6SLai Jiangshan }
3804a0111cf6SLai Jiangshan 
38059e8cd2f5STejun Heo /**
38069e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
38079e8cd2f5STejun Heo  * @wq: the target workqueue
38089e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
38099e8cd2f5STejun Heo  *
38104c16bd32STejun Heo  * Apply @attrs to an unbound workqueue @wq.  Unless disabled, on NUMA
38114c16bd32STejun Heo  * machines, this function maps a separate pwq to each NUMA node with
38124c16bd32STejun Heo  * possibles CPUs in @attrs->cpumask so that work items are affine to the
38134c16bd32STejun Heo  * NUMA node it was issued on.  Older pwqs are released as in-flight work
38144c16bd32STejun Heo  * items finish.  Note that a work item which repeatedly requeues itself
38154c16bd32STejun Heo  * back-to-back will stay on its current pwq.
38169e8cd2f5STejun Heo  *
3817d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
3818d185af30SYacine Belkadi  *
3819d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
38209e8cd2f5STejun Heo  */
38219e8cd2f5STejun Heo int apply_workqueue_attrs(struct workqueue_struct *wq,
38229e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
38239e8cd2f5STejun Heo {
3824a0111cf6SLai Jiangshan 	int ret;
38259e8cd2f5STejun Heo 
3826a0111cf6SLai Jiangshan 	apply_wqattrs_lock();
3827a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
3828a0111cf6SLai Jiangshan 	apply_wqattrs_unlock();
38292d5f0764SLai Jiangshan 
38302d5f0764SLai Jiangshan 	return ret;
38319e8cd2f5STejun Heo }
38329e8cd2f5STejun Heo 
38334c16bd32STejun Heo /**
38344c16bd32STejun Heo  * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
38354c16bd32STejun Heo  * @wq: the target workqueue
38364c16bd32STejun Heo  * @cpu: the CPU coming up or going down
38374c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
38384c16bd32STejun Heo  *
38394c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
38404c16bd32STejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update NUMA affinity of
38414c16bd32STejun Heo  * @wq accordingly.
38424c16bd32STejun Heo  *
38434c16bd32STejun Heo  * If NUMA affinity can't be adjusted due to memory allocation failure, it
38444c16bd32STejun Heo  * falls back to @wq->dfl_pwq which may not be optimal but is always
38454c16bd32STejun Heo  * correct.
38464c16bd32STejun Heo  *
38474c16bd32STejun Heo  * Note that when the last allowed CPU of a NUMA node goes offline for a
38484c16bd32STejun Heo  * workqueue with a cpumask spanning multiple nodes, the workers which were
38494c16bd32STejun Heo  * already executing the work items for the workqueue will lose their CPU
38504c16bd32STejun Heo  * affinity and may execute on any CPU.  This is similar to how per-cpu
38514c16bd32STejun Heo  * workqueues behave on CPU_DOWN.  If a workqueue user wants strict
38524c16bd32STejun Heo  * affinity, it's the user's responsibility to flush the work item from
38534c16bd32STejun Heo  * CPU_DOWN_PREPARE.
38544c16bd32STejun Heo  */
38554c16bd32STejun Heo static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
38564c16bd32STejun Heo 				   bool online)
38574c16bd32STejun Heo {
38584c16bd32STejun Heo 	int node = cpu_to_node(cpu);
38594c16bd32STejun Heo 	int cpu_off = online ? -1 : cpu;
38604c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
38614c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
38624c16bd32STejun Heo 	cpumask_t *cpumask;
38634c16bd32STejun Heo 
38644c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
38654c16bd32STejun Heo 
3866f7142ed4SLai Jiangshan 	if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
3867f7142ed4SLai Jiangshan 	    wq->unbound_attrs->no_numa)
38684c16bd32STejun Heo 		return;
38694c16bd32STejun Heo 
38704c16bd32STejun Heo 	/*
38714c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
38724c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
38734c16bd32STejun Heo 	 * CPU hotplug exclusion.
38744c16bd32STejun Heo 	 */
38754c16bd32STejun Heo 	target_attrs = wq_update_unbound_numa_attrs_buf;
38764c16bd32STejun Heo 	cpumask = target_attrs->cpumask;
38774c16bd32STejun Heo 
38784c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
38794c16bd32STejun Heo 	pwq = unbound_pwq_by_node(wq, node);
38804c16bd32STejun Heo 
38814c16bd32STejun Heo 	/*
38824c16bd32STejun Heo 	 * Let's determine what needs to be done.  If the target cpumask is
3883042f7df1SLai Jiangshan 	 * different from the default pwq's, we need to compare it to @pwq's
3884042f7df1SLai Jiangshan 	 * and create a new one if they don't match.  If the target cpumask
3885042f7df1SLai Jiangshan 	 * equals the default pwq's, the default pwq should be used.
38864c16bd32STejun Heo 	 */
3887042f7df1SLai Jiangshan 	if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
38884c16bd32STejun Heo 		if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
3889f7142ed4SLai Jiangshan 			return;
38904c16bd32STejun Heo 	} else {
38914c16bd32STejun Heo 		goto use_dfl_pwq;
38924c16bd32STejun Heo 	}
38934c16bd32STejun Heo 
38944c16bd32STejun Heo 	/* create a new pwq */
38954c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
38964c16bd32STejun Heo 	if (!pwq) {
38972d916033SFabian Frederick 		pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
38984c16bd32STejun Heo 			wq->name);
389977f300b1SDaeseok Youn 		goto use_dfl_pwq;
39004c16bd32STejun Heo 	}
39014c16bd32STejun Heo 
3902f7142ed4SLai Jiangshan 	/* Install the new pwq. */
39034c16bd32STejun Heo 	mutex_lock(&wq->mutex);
39044c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, pwq);
39054c16bd32STejun Heo 	goto out_unlock;
39064c16bd32STejun Heo 
39074c16bd32STejun Heo use_dfl_pwq:
3908f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
39094c16bd32STejun Heo 	spin_lock_irq(&wq->dfl_pwq->pool->lock);
39104c16bd32STejun Heo 	get_pwq(wq->dfl_pwq);
39114c16bd32STejun Heo 	spin_unlock_irq(&wq->dfl_pwq->pool->lock);
39124c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
39134c16bd32STejun Heo out_unlock:
39144c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
39154c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
39164c16bd32STejun Heo }
39174c16bd32STejun Heo 
391830cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
39191da177e4SLinus Torvalds {
392049e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
39218a2b7538STejun Heo 	int cpu, ret;
3922e1d8aa9fSFrederic Weisbecker 
392330cdf249STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
3924420c0ddbSTejun Heo 		wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
3925420c0ddbSTejun Heo 		if (!wq->cpu_pwqs)
392630cdf249STejun Heo 			return -ENOMEM;
392730cdf249STejun Heo 
392830cdf249STejun Heo 		for_each_possible_cpu(cpu) {
39297fb98ea7STejun Heo 			struct pool_workqueue *pwq =
39307fb98ea7STejun Heo 				per_cpu_ptr(wq->cpu_pwqs, cpu);
39317a62c2c8STejun Heo 			struct worker_pool *cpu_pools =
3932f02ae73aSTejun Heo 				per_cpu(cpu_worker_pools, cpu);
393330cdf249STejun Heo 
3934f147f29eSTejun Heo 			init_pwq(pwq, wq, &cpu_pools[highpri]);
3935f147f29eSTejun Heo 
3936f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
39371befcf30STejun Heo 			link_pwq(pwq);
3938f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
393930cdf249STejun Heo 		}
394030cdf249STejun Heo 		return 0;
39418a2b7538STejun Heo 	} else if (wq->flags & __WQ_ORDERED) {
39428a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
39438a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
39448a2b7538STejun Heo 		WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
39458a2b7538STejun Heo 			      wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
39468a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
39478a2b7538STejun Heo 		return ret;
39489e8cd2f5STejun Heo 	} else {
39499e8cd2f5STejun Heo 		return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
39509e8cd2f5STejun Heo 	}
39510f900049STejun Heo }
39520f900049STejun Heo 
3953f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
3954f3421797STejun Heo 			       const char *name)
3955b71ab8c2STejun Heo {
3956f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3957f3421797STejun Heo 
3958f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
3959044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3960f3421797STejun Heo 			max_active, name, 1, lim);
3961b71ab8c2STejun Heo 
3962f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
3963b71ab8c2STejun Heo }
3964b71ab8c2STejun Heo 
3965b196be89STejun Heo struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
396697e37d7bSTejun Heo 					       unsigned int flags,
39671e19ffc6STejun Heo 					       int max_active,
3968eb13ba87SJohannes Berg 					       struct lock_class_key *key,
3969b196be89STejun Heo 					       const char *lock_name, ...)
39703af24433SOleg Nesterov {
3971df2d5ae4STejun Heo 	size_t tbl_size = 0;
3972ecf6881fSTejun Heo 	va_list args;
39733af24433SOleg Nesterov 	struct workqueue_struct *wq;
397449e3cf44STejun Heo 	struct pool_workqueue *pwq;
3975b196be89STejun Heo 
39765c0338c6STejun Heo 	/*
39775c0338c6STejun Heo 	 * Unbound && max_active == 1 used to imply ordered, which is no
39785c0338c6STejun Heo 	 * longer the case on NUMA machines due to per-node pools.  While
39795c0338c6STejun Heo 	 * alloc_ordered_workqueue() is the right way to create an ordered
39805c0338c6STejun Heo 	 * workqueue, keep the previous behavior to avoid subtle breakages
39815c0338c6STejun Heo 	 * on NUMA.
39825c0338c6STejun Heo 	 */
39835c0338c6STejun Heo 	if ((flags & WQ_UNBOUND) && max_active == 1)
39845c0338c6STejun Heo 		flags |= __WQ_ORDERED;
39855c0338c6STejun Heo 
3986cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
3987cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
3988cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
3989cee22a15SViresh Kumar 
3990ecf6881fSTejun Heo 	/* allocate wq and format name */
3991df2d5ae4STejun Heo 	if (flags & WQ_UNBOUND)
3992ddcb57e2SLai Jiangshan 		tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
3993df2d5ae4STejun Heo 
3994df2d5ae4STejun Heo 	wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
3995b196be89STejun Heo 	if (!wq)
3996d2c1d404STejun Heo 		return NULL;
3997b196be89STejun Heo 
39986029a918STejun Heo 	if (flags & WQ_UNBOUND) {
39996029a918STejun Heo 		wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
40006029a918STejun Heo 		if (!wq->unbound_attrs)
40016029a918STejun Heo 			goto err_free_wq;
40026029a918STejun Heo 	}
40036029a918STejun Heo 
4004ecf6881fSTejun Heo 	va_start(args, lock_name);
4005ecf6881fSTejun Heo 	vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4006b196be89STejun Heo 	va_end(args);
40073af24433SOleg Nesterov 
4008d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
4009b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
40103af24433SOleg Nesterov 
4011b196be89STejun Heo 	/* init wq */
401297e37d7bSTejun Heo 	wq->flags = flags;
4013a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
40143c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
4015112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
401630cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
401773f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
401873f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
4019493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
40203af24433SOleg Nesterov 
4021eb13ba87SJohannes Berg 	lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
4022cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
40233af24433SOleg Nesterov 
402430cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
4025d2c1d404STejun Heo 		goto err_free_wq;
40261537663fSTejun Heo 
4027493008a8STejun Heo 	/*
4028493008a8STejun Heo 	 * Workqueues which may be used during memory reclaim should
4029493008a8STejun Heo 	 * have a rescuer to guarantee forward progress.
4030493008a8STejun Heo 	 */
4031493008a8STejun Heo 	if (flags & WQ_MEM_RECLAIM) {
4032e22bee78STejun Heo 		struct worker *rescuer;
4033e22bee78STejun Heo 
4034f7537df5SLai Jiangshan 		rescuer = alloc_worker(NUMA_NO_NODE);
4035e22bee78STejun Heo 		if (!rescuer)
4036d2c1d404STejun Heo 			goto err_destroy;
4037e22bee78STejun Heo 
4038111c225aSTejun Heo 		rescuer->rescue_wq = wq;
4039111c225aSTejun Heo 		rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
4040b196be89STejun Heo 					       wq->name);
4041d2c1d404STejun Heo 		if (IS_ERR(rescuer->task)) {
4042d2c1d404STejun Heo 			kfree(rescuer);
4043d2c1d404STejun Heo 			goto err_destroy;
4044d2c1d404STejun Heo 		}
4045e22bee78STejun Heo 
4046d2c1d404STejun Heo 		wq->rescuer = rescuer;
404725834c73SPeter Zijlstra 		kthread_bind_mask(rescuer->task, cpu_possible_mask);
4048e22bee78STejun Heo 		wake_up_process(rescuer->task);
40493af24433SOleg Nesterov 	}
40501537663fSTejun Heo 
4051226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4052226223abSTejun Heo 		goto err_destroy;
4053226223abSTejun Heo 
40543af24433SOleg Nesterov 	/*
405568e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
405668e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
405768e13a67SLai Jiangshan 	 * list.
40583af24433SOleg Nesterov 	 */
405968e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4060a0a1a5fdSTejun Heo 
4061a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
406249e3cf44STejun Heo 	for_each_pwq(pwq, wq)
4063699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4064a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4065a0a1a5fdSTejun Heo 
4066e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
4067a0a1a5fdSTejun Heo 
406868e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
40693af24433SOleg Nesterov 
40703af24433SOleg Nesterov 	return wq;
4071d2c1d404STejun Heo 
4072d2c1d404STejun Heo err_free_wq:
40736029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
40744690c4abSTejun Heo 	kfree(wq);
4075d2c1d404STejun Heo 	return NULL;
4076d2c1d404STejun Heo err_destroy:
4077d2c1d404STejun Heo 	destroy_workqueue(wq);
40784690c4abSTejun Heo 	return NULL;
40791da177e4SLinus Torvalds }
4080d320c038STejun Heo EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
40811da177e4SLinus Torvalds 
40823af24433SOleg Nesterov /**
40833af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
40843af24433SOleg Nesterov  * @wq: target workqueue
40853af24433SOleg Nesterov  *
40863af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
40873af24433SOleg Nesterov  */
40883af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
40893af24433SOleg Nesterov {
409049e3cf44STejun Heo 	struct pool_workqueue *pwq;
40914c16bd32STejun Heo 	int node;
40923af24433SOleg Nesterov 
40939c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
40949c5a2ba7STejun Heo 	drain_workqueue(wq);
4095c8efcc25STejun Heo 
40966183c009STejun Heo 	/* sanity checks */
4097b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
409849e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
40996183c009STejun Heo 		int i;
41006183c009STejun Heo 
410176af4d93STejun Heo 		for (i = 0; i < WORK_NR_COLORS; i++) {
410276af4d93STejun Heo 			if (WARN_ON(pwq->nr_in_flight[i])) {
4103b09f4fd3SLai Jiangshan 				mutex_unlock(&wq->mutex);
4104fa07fb6aSTejun Heo 				show_workqueue_state();
41056183c009STejun Heo 				return;
410676af4d93STejun Heo 			}
410776af4d93STejun Heo 		}
410876af4d93STejun Heo 
41095c529597SLai Jiangshan 		if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
41108864b4e5STejun Heo 		    WARN_ON(pwq->nr_active) ||
411176af4d93STejun Heo 		    WARN_ON(!list_empty(&pwq->delayed_works))) {
4112b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
4113fa07fb6aSTejun Heo 			show_workqueue_state();
41146183c009STejun Heo 			return;
41156183c009STejun Heo 		}
411676af4d93STejun Heo 	}
4117b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
41186183c009STejun Heo 
4119a0a1a5fdSTejun Heo 	/*
4120a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
4121a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
4122a0a1a5fdSTejun Heo 	 */
412368e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4124e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
412568e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
41263af24433SOleg Nesterov 
4127226223abSTejun Heo 	workqueue_sysfs_unregister(wq);
4128226223abSTejun Heo 
4129e2dca7adSTejun Heo 	if (wq->rescuer)
4130e22bee78STejun Heo 		kthread_stop(wq->rescuer->task);
4131e22bee78STejun Heo 
41328864b4e5STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
413329c91e99STejun Heo 		/*
41348864b4e5STejun Heo 		 * The base ref is never dropped on per-cpu pwqs.  Directly
4135e2dca7adSTejun Heo 		 * schedule RCU free.
413629c91e99STejun Heo 		 */
4137e2dca7adSTejun Heo 		call_rcu_sched(&wq->rcu, rcu_free_wq);
41388864b4e5STejun Heo 	} else {
41398864b4e5STejun Heo 		/*
41408864b4e5STejun Heo 		 * We're the sole accessor of @wq at this point.  Directly
41414c16bd32STejun Heo 		 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
41424c16bd32STejun Heo 		 * @wq will be freed when the last pwq is released.
41438864b4e5STejun Heo 		 */
41444c16bd32STejun Heo 		for_each_node(node) {
41454c16bd32STejun Heo 			pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
41464c16bd32STejun Heo 			RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
41474c16bd32STejun Heo 			put_pwq_unlocked(pwq);
41484c16bd32STejun Heo 		}
41494c16bd32STejun Heo 
41504c16bd32STejun Heo 		/*
41514c16bd32STejun Heo 		 * Put dfl_pwq.  @wq may be freed any time after dfl_pwq is
41524c16bd32STejun Heo 		 * put.  Don't access it afterwards.
41534c16bd32STejun Heo 		 */
41544c16bd32STejun Heo 		pwq = wq->dfl_pwq;
41554c16bd32STejun Heo 		wq->dfl_pwq = NULL;
4156dce90d47STejun Heo 		put_pwq_unlocked(pwq);
415729c91e99STejun Heo 	}
41583af24433SOleg Nesterov }
41593af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
41603af24433SOleg Nesterov 
4161dcd989cbSTejun Heo /**
4162dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
4163dcd989cbSTejun Heo  * @wq: target workqueue
4164dcd989cbSTejun Heo  * @max_active: new max_active value.
4165dcd989cbSTejun Heo  *
4166dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
4167dcd989cbSTejun Heo  *
4168dcd989cbSTejun Heo  * CONTEXT:
4169dcd989cbSTejun Heo  * Don't call from IRQ context.
4170dcd989cbSTejun Heo  */
4171dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4172dcd989cbSTejun Heo {
417349e3cf44STejun Heo 	struct pool_workqueue *pwq;
4174dcd989cbSTejun Heo 
41758719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
41760a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
41778719dceaSTejun Heo 		return;
41788719dceaSTejun Heo 
4179f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4180dcd989cbSTejun Heo 
4181a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4182dcd989cbSTejun Heo 
41830a94efb5STejun Heo 	wq->flags &= ~__WQ_ORDERED;
4184dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4185dcd989cbSTejun Heo 
4186699ce097STejun Heo 	for_each_pwq(pwq, wq)
4187699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4188dcd989cbSTejun Heo 
4189a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4190dcd989cbSTejun Heo }
4191dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4192dcd989cbSTejun Heo 
4193dcd989cbSTejun Heo /**
4194e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4195e6267616STejun Heo  *
4196e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4197e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4198d185af30SYacine Belkadi  *
4199d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
4200e6267616STejun Heo  */
4201e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4202e6267616STejun Heo {
4203e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4204e6267616STejun Heo 
42056a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
4206e6267616STejun Heo }
4207e6267616STejun Heo 
4208e6267616STejun Heo /**
4209dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4210dcd989cbSTejun Heo  * @cpu: CPU in question
4211dcd989cbSTejun Heo  * @wq: target workqueue
4212dcd989cbSTejun Heo  *
4213dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4214dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4215dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4216dcd989cbSTejun Heo  *
4217d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4218d3251859STejun Heo  * Note that both per-cpu and unbound workqueues may be associated with
4219d3251859STejun Heo  * multiple pool_workqueues which have separate congested states.  A
4220d3251859STejun Heo  * workqueue being congested on one CPU doesn't mean the workqueue is also
4221d3251859STejun Heo  * contested on other CPUs / NUMA nodes.
4222d3251859STejun Heo  *
4223d185af30SYacine Belkadi  * Return:
4224dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4225dcd989cbSTejun Heo  */
4226d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4227dcd989cbSTejun Heo {
42287fb98ea7STejun Heo 	struct pool_workqueue *pwq;
422976af4d93STejun Heo 	bool ret;
423076af4d93STejun Heo 
423188109453SLai Jiangshan 	rcu_read_lock_sched();
42327fb98ea7STejun Heo 
4233d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
4234d3251859STejun Heo 		cpu = smp_processor_id();
4235d3251859STejun Heo 
42367fb98ea7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
42377fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
42387fb98ea7STejun Heo 	else
4239df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4240dcd989cbSTejun Heo 
424176af4d93STejun Heo 	ret = !list_empty(&pwq->delayed_works);
424288109453SLai Jiangshan 	rcu_read_unlock_sched();
424376af4d93STejun Heo 
424476af4d93STejun Heo 	return ret;
4245dcd989cbSTejun Heo }
4246dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4247dcd989cbSTejun Heo 
4248dcd989cbSTejun Heo /**
4249dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4250dcd989cbSTejun Heo  * @work: the work to be tested
4251dcd989cbSTejun Heo  *
4252dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4253dcd989cbSTejun Heo  * synchronization around this function and the test result is
4254dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4255dcd989cbSTejun Heo  *
4256d185af30SYacine Belkadi  * Return:
4257dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
4258dcd989cbSTejun Heo  */
4259dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4260dcd989cbSTejun Heo {
4261fa1b54e6STejun Heo 	struct worker_pool *pool;
4262dcd989cbSTejun Heo 	unsigned long flags;
4263dcd989cbSTejun Heo 	unsigned int ret = 0;
4264dcd989cbSTejun Heo 
4265dcd989cbSTejun Heo 	if (work_pending(work))
4266dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
4267038366c5SLai Jiangshan 
4268fa1b54e6STejun Heo 	local_irq_save(flags);
4269fa1b54e6STejun Heo 	pool = get_work_pool(work);
4270038366c5SLai Jiangshan 	if (pool) {
4271fa1b54e6STejun Heo 		spin_lock(&pool->lock);
4272c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
4273dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
4274fa1b54e6STejun Heo 		spin_unlock(&pool->lock);
4275038366c5SLai Jiangshan 	}
4276fa1b54e6STejun Heo 	local_irq_restore(flags);
4277dcd989cbSTejun Heo 
4278dcd989cbSTejun Heo 	return ret;
4279dcd989cbSTejun Heo }
4280dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
4281dcd989cbSTejun Heo 
42823d1cb205STejun Heo /**
42833d1cb205STejun Heo  * set_worker_desc - set description for the current work item
42843d1cb205STejun Heo  * @fmt: printf-style format string
42853d1cb205STejun Heo  * @...: arguments for the format string
42863d1cb205STejun Heo  *
42873d1cb205STejun Heo  * This function can be called by a running work function to describe what
42883d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
42893d1cb205STejun Heo  * information will be printed out together to help debugging.  The
42903d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
42913d1cb205STejun Heo  */
42923d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
42933d1cb205STejun Heo {
42943d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
42953d1cb205STejun Heo 	va_list args;
42963d1cb205STejun Heo 
42973d1cb205STejun Heo 	if (worker) {
42983d1cb205STejun Heo 		va_start(args, fmt);
42993d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
43003d1cb205STejun Heo 		va_end(args);
43013d1cb205STejun Heo 		worker->desc_valid = true;
43023d1cb205STejun Heo 	}
43033d1cb205STejun Heo }
43043d1cb205STejun Heo 
43053d1cb205STejun Heo /**
43063d1cb205STejun Heo  * print_worker_info - print out worker information and description
43073d1cb205STejun Heo  * @log_lvl: the log level to use when printing
43083d1cb205STejun Heo  * @task: target task
43093d1cb205STejun Heo  *
43103d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
43113d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
43123d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
43133d1cb205STejun Heo  *
43143d1cb205STejun Heo  * This function can be safely called on any task as long as the
43153d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
43163d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
43173d1cb205STejun Heo  */
43183d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
43193d1cb205STejun Heo {
43203d1cb205STejun Heo 	work_func_t *fn = NULL;
43213d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
43223d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
43233d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
43243d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
43253d1cb205STejun Heo 	bool desc_valid = false;
43263d1cb205STejun Heo 	struct worker *worker;
43273d1cb205STejun Heo 
43283d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
43293d1cb205STejun Heo 		return;
43303d1cb205STejun Heo 
43313d1cb205STejun Heo 	/*
43323d1cb205STejun Heo 	 * This function is called without any synchronization and @task
43333d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
43343d1cb205STejun Heo 	 */
4335e700591aSPetr Mladek 	worker = kthread_probe_data(task);
43363d1cb205STejun Heo 
43373d1cb205STejun Heo 	/*
43383d1cb205STejun Heo 	 * Carefully copy the associated workqueue's workfn and name.  Keep
43393d1cb205STejun Heo 	 * the original last '\0' in case the original contains garbage.
43403d1cb205STejun Heo 	 */
43413d1cb205STejun Heo 	probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
43423d1cb205STejun Heo 	probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
43433d1cb205STejun Heo 	probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
43443d1cb205STejun Heo 	probe_kernel_read(name, wq->name, sizeof(name) - 1);
43453d1cb205STejun Heo 
43463d1cb205STejun Heo 	/* copy worker description */
43473d1cb205STejun Heo 	probe_kernel_read(&desc_valid, &worker->desc_valid, sizeof(desc_valid));
43483d1cb205STejun Heo 	if (desc_valid)
43493d1cb205STejun Heo 		probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
43503d1cb205STejun Heo 
43513d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
43523d1cb205STejun Heo 		printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
43533d1cb205STejun Heo 		if (desc[0])
43543d1cb205STejun Heo 			pr_cont(" (%s)", desc);
43553d1cb205STejun Heo 		pr_cont("\n");
43563d1cb205STejun Heo 	}
43573d1cb205STejun Heo }
43583d1cb205STejun Heo 
43593494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
43603494fc30STejun Heo {
43613494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
43623494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
43633494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
43643494fc30STejun Heo 	pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
43653494fc30STejun Heo }
43663494fc30STejun Heo 
43673494fc30STejun Heo static void pr_cont_work(bool comma, struct work_struct *work)
43683494fc30STejun Heo {
43693494fc30STejun Heo 	if (work->func == wq_barrier_func) {
43703494fc30STejun Heo 		struct wq_barrier *barr;
43713494fc30STejun Heo 
43723494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
43733494fc30STejun Heo 
43743494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
43753494fc30STejun Heo 			task_pid_nr(barr->task));
43763494fc30STejun Heo 	} else {
43773494fc30STejun Heo 		pr_cont("%s %pf", comma ? "," : "", work->func);
43783494fc30STejun Heo 	}
43793494fc30STejun Heo }
43803494fc30STejun Heo 
43813494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
43823494fc30STejun Heo {
43833494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
43843494fc30STejun Heo 	struct work_struct *work;
43853494fc30STejun Heo 	struct worker *worker;
43863494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
43873494fc30STejun Heo 	int bkt;
43883494fc30STejun Heo 
43893494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
43903494fc30STejun Heo 	pr_cont_pool_info(pool);
43913494fc30STejun Heo 
43923494fc30STejun Heo 	pr_cont(" active=%d/%d%s\n", pwq->nr_active, pwq->max_active,
43933494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
43943494fc30STejun Heo 
43953494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
43963494fc30STejun Heo 		if (worker->current_pwq == pwq) {
43973494fc30STejun Heo 			has_in_flight = true;
43983494fc30STejun Heo 			break;
43993494fc30STejun Heo 		}
44003494fc30STejun Heo 	}
44013494fc30STejun Heo 	if (has_in_flight) {
44023494fc30STejun Heo 		bool comma = false;
44033494fc30STejun Heo 
44043494fc30STejun Heo 		pr_info("    in-flight:");
44053494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
44063494fc30STejun Heo 			if (worker->current_pwq != pwq)
44073494fc30STejun Heo 				continue;
44083494fc30STejun Heo 
44093494fc30STejun Heo 			pr_cont("%s %d%s:%pf", comma ? "," : "",
44103494fc30STejun Heo 				task_pid_nr(worker->task),
44113494fc30STejun Heo 				worker == pwq->wq->rescuer ? "(RESCUER)" : "",
44123494fc30STejun Heo 				worker->current_func);
44133494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
44143494fc30STejun Heo 				pr_cont_work(false, work);
44153494fc30STejun Heo 			comma = true;
44163494fc30STejun Heo 		}
44173494fc30STejun Heo 		pr_cont("\n");
44183494fc30STejun Heo 	}
44193494fc30STejun Heo 
44203494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
44213494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
44223494fc30STejun Heo 			has_pending = true;
44233494fc30STejun Heo 			break;
44243494fc30STejun Heo 		}
44253494fc30STejun Heo 	}
44263494fc30STejun Heo 	if (has_pending) {
44273494fc30STejun Heo 		bool comma = false;
44283494fc30STejun Heo 
44293494fc30STejun Heo 		pr_info("    pending:");
44303494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
44313494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
44323494fc30STejun Heo 				continue;
44333494fc30STejun Heo 
44343494fc30STejun Heo 			pr_cont_work(comma, work);
44353494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
44363494fc30STejun Heo 		}
44373494fc30STejun Heo 		pr_cont("\n");
44383494fc30STejun Heo 	}
44393494fc30STejun Heo 
44403494fc30STejun Heo 	if (!list_empty(&pwq->delayed_works)) {
44413494fc30STejun Heo 		bool comma = false;
44423494fc30STejun Heo 
44433494fc30STejun Heo 		pr_info("    delayed:");
44443494fc30STejun Heo 		list_for_each_entry(work, &pwq->delayed_works, entry) {
44453494fc30STejun Heo 			pr_cont_work(comma, work);
44463494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
44473494fc30STejun Heo 		}
44483494fc30STejun Heo 		pr_cont("\n");
44493494fc30STejun Heo 	}
44503494fc30STejun Heo }
44513494fc30STejun Heo 
44523494fc30STejun Heo /**
44533494fc30STejun Heo  * show_workqueue_state - dump workqueue state
44543494fc30STejun Heo  *
44557b776af6SRoger Lu  * Called from a sysrq handler or try_to_freeze_tasks() and prints out
44567b776af6SRoger Lu  * all busy workqueues and pools.
44573494fc30STejun Heo  */
44583494fc30STejun Heo void show_workqueue_state(void)
44593494fc30STejun Heo {
44603494fc30STejun Heo 	struct workqueue_struct *wq;
44613494fc30STejun Heo 	struct worker_pool *pool;
44623494fc30STejun Heo 	unsigned long flags;
44633494fc30STejun Heo 	int pi;
44643494fc30STejun Heo 
44653494fc30STejun Heo 	rcu_read_lock_sched();
44663494fc30STejun Heo 
44673494fc30STejun Heo 	pr_info("Showing busy workqueues and worker pools:\n");
44683494fc30STejun Heo 
44693494fc30STejun Heo 	list_for_each_entry_rcu(wq, &workqueues, list) {
44703494fc30STejun Heo 		struct pool_workqueue *pwq;
44713494fc30STejun Heo 		bool idle = true;
44723494fc30STejun Heo 
44733494fc30STejun Heo 		for_each_pwq(pwq, wq) {
44743494fc30STejun Heo 			if (pwq->nr_active || !list_empty(&pwq->delayed_works)) {
44753494fc30STejun Heo 				idle = false;
44763494fc30STejun Heo 				break;
44773494fc30STejun Heo 			}
44783494fc30STejun Heo 		}
44793494fc30STejun Heo 		if (idle)
44803494fc30STejun Heo 			continue;
44813494fc30STejun Heo 
44823494fc30STejun Heo 		pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
44833494fc30STejun Heo 
44843494fc30STejun Heo 		for_each_pwq(pwq, wq) {
44853494fc30STejun Heo 			spin_lock_irqsave(&pwq->pool->lock, flags);
44863494fc30STejun Heo 			if (pwq->nr_active || !list_empty(&pwq->delayed_works))
44873494fc30STejun Heo 				show_pwq(pwq);
44883494fc30STejun Heo 			spin_unlock_irqrestore(&pwq->pool->lock, flags);
44893494fc30STejun Heo 		}
44903494fc30STejun Heo 	}
44913494fc30STejun Heo 
44923494fc30STejun Heo 	for_each_pool(pool, pi) {
44933494fc30STejun Heo 		struct worker *worker;
44943494fc30STejun Heo 		bool first = true;
44953494fc30STejun Heo 
44963494fc30STejun Heo 		spin_lock_irqsave(&pool->lock, flags);
44973494fc30STejun Heo 		if (pool->nr_workers == pool->nr_idle)
44983494fc30STejun Heo 			goto next_pool;
44993494fc30STejun Heo 
45003494fc30STejun Heo 		pr_info("pool %d:", pool->id);
45013494fc30STejun Heo 		pr_cont_pool_info(pool);
450282607adcSTejun Heo 		pr_cont(" hung=%us workers=%d",
450382607adcSTejun Heo 			jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000,
450482607adcSTejun Heo 			pool->nr_workers);
45053494fc30STejun Heo 		if (pool->manager)
45063494fc30STejun Heo 			pr_cont(" manager: %d",
45073494fc30STejun Heo 				task_pid_nr(pool->manager->task));
45083494fc30STejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry) {
45093494fc30STejun Heo 			pr_cont(" %s%d", first ? "idle: " : "",
45103494fc30STejun Heo 				task_pid_nr(worker->task));
45113494fc30STejun Heo 			first = false;
45123494fc30STejun Heo 		}
45133494fc30STejun Heo 		pr_cont("\n");
45143494fc30STejun Heo 	next_pool:
45153494fc30STejun Heo 		spin_unlock_irqrestore(&pool->lock, flags);
45163494fc30STejun Heo 	}
45173494fc30STejun Heo 
45183494fc30STejun Heo 	rcu_read_unlock_sched();
45193494fc30STejun Heo }
45203494fc30STejun Heo 
4521db7bccf4STejun Heo /*
4522db7bccf4STejun Heo  * CPU hotplug.
4523db7bccf4STejun Heo  *
4524e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
4525112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
4526706026c2STejun Heo  * pool which make migrating pending and scheduled works very
4527e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
452894cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
4529e22bee78STejun Heo  * blocked draining impractical.
4530e22bee78STejun Heo  *
453124647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
4532628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
4533628c78e7STejun Heo  * cpu comes back online.
4534db7bccf4STejun Heo  */
4535db7bccf4STejun Heo 
4536706026c2STejun Heo static void wq_unbind_fn(struct work_struct *work)
4537db7bccf4STejun Heo {
453838db41d9STejun Heo 	int cpu = smp_processor_id();
45394ce62e9eSTejun Heo 	struct worker_pool *pool;
4540db7bccf4STejun Heo 	struct worker *worker;
4541db7bccf4STejun Heo 
4542f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
454392f9c5c4SLai Jiangshan 		mutex_lock(&pool->attach_mutex);
454494cf58bbSTejun Heo 		spin_lock_irq(&pool->lock);
4545e22bee78STejun Heo 
4546f2d5a0eeSTejun Heo 		/*
454792f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
454894cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
454994cf58bbSTejun Heo 		 * except for the ones which are still executing works from
455094cf58bbSTejun Heo 		 * before the last CPU down must be on the cpu.  After
455194cf58bbSTejun Heo 		 * this, they may become diasporas.
4552f2d5a0eeSTejun Heo 		 */
4553da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
4554403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
4555db7bccf4STejun Heo 
455624647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
4557f2d5a0eeSTejun Heo 
455894cf58bbSTejun Heo 		spin_unlock_irq(&pool->lock);
455992f9c5c4SLai Jiangshan 		mutex_unlock(&pool->attach_mutex);
4560e22bee78STejun Heo 
4561e22bee78STejun Heo 		/*
4562eb283428SLai Jiangshan 		 * Call schedule() so that we cross rq->lock and thus can
4563eb283428SLai Jiangshan 		 * guarantee sched callbacks see the %WORKER_UNBOUND flag.
4564eb283428SLai Jiangshan 		 * This is necessary as scheduler callbacks may be invoked
4565eb283428SLai Jiangshan 		 * from other cpus.
4566628c78e7STejun Heo 		 */
4567628c78e7STejun Heo 		schedule();
4568628c78e7STejun Heo 
4569628c78e7STejun Heo 		/*
4570eb283428SLai Jiangshan 		 * Sched callbacks are disabled now.  Zap nr_running.
4571eb283428SLai Jiangshan 		 * After this, nr_running stays zero and need_more_worker()
4572eb283428SLai Jiangshan 		 * and keep_working() are always true as long as the
4573eb283428SLai Jiangshan 		 * worklist is not empty.  This pool now behaves as an
4574eb283428SLai Jiangshan 		 * unbound (in terms of concurrency management) pool which
4575eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
4576e22bee78STejun Heo 		 */
4577e19e397aSTejun Heo 		atomic_set(&pool->nr_running, 0);
4578eb283428SLai Jiangshan 
4579eb283428SLai Jiangshan 		/*
4580eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
4581eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
4582eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
4583eb283428SLai Jiangshan 		 */
4584eb283428SLai Jiangshan 		spin_lock_irq(&pool->lock);
4585eb283428SLai Jiangshan 		wake_up_worker(pool);
4586eb283428SLai Jiangshan 		spin_unlock_irq(&pool->lock);
4587eb283428SLai Jiangshan 	}
4588db7bccf4STejun Heo }
4589db7bccf4STejun Heo 
4590bd7c089eSTejun Heo /**
4591bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
4592bd7c089eSTejun Heo  * @pool: pool of interest
4593bd7c089eSTejun Heo  *
4594a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
4595bd7c089eSTejun Heo  */
4596bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
4597bd7c089eSTejun Heo {
4598a9ab775bSTejun Heo 	struct worker *worker;
4599bd7c089eSTejun Heo 
460092f9c5c4SLai Jiangshan 	lockdep_assert_held(&pool->attach_mutex);
4601bd7c089eSTejun Heo 
4602bd7c089eSTejun Heo 	/*
4603a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
4604a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
4605402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
4606a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
4607a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
4608bd7c089eSTejun Heo 	 */
4609da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
4610a9ab775bSTejun Heo 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4611a9ab775bSTejun Heo 						  pool->attrs->cpumask) < 0);
4612a9ab775bSTejun Heo 
4613a9ab775bSTejun Heo 	spin_lock_irq(&pool->lock);
4614f7c17d26SWanpeng Li 
4615f7c17d26SWanpeng Li 	/*
4616f7c17d26SWanpeng Li 	 * XXX: CPU hotplug notifiers are weird and can call DOWN_FAILED
4617f7c17d26SWanpeng Li 	 * w/o preceding DOWN_PREPARE.  Work around it.  CPU hotplug is
4618f7c17d26SWanpeng Li 	 * being reworked and this can go away in time.
4619f7c17d26SWanpeng Li 	 */
4620f7c17d26SWanpeng Li 	if (!(pool->flags & POOL_DISASSOCIATED)) {
4621f7c17d26SWanpeng Li 		spin_unlock_irq(&pool->lock);
4622f7c17d26SWanpeng Li 		return;
4623f7c17d26SWanpeng Li 	}
4624f7c17d26SWanpeng Li 
46253de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
4626a9ab775bSTejun Heo 
4627da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
4628a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
4629a9ab775bSTejun Heo 
4630a9ab775bSTejun Heo 		/*
4631a9ab775bSTejun Heo 		 * A bound idle worker should actually be on the runqueue
4632a9ab775bSTejun Heo 		 * of the associated CPU for local wake-ups targeting it to
4633a9ab775bSTejun Heo 		 * work.  Kick all idle workers so that they migrate to the
4634a9ab775bSTejun Heo 		 * associated CPU.  Doing this in the same loop as
4635a9ab775bSTejun Heo 		 * replacing UNBOUND with REBOUND is safe as no worker will
4636a9ab775bSTejun Heo 		 * be bound before @pool->lock is released.
4637a9ab775bSTejun Heo 		 */
4638a9ab775bSTejun Heo 		if (worker_flags & WORKER_IDLE)
4639bd7c089eSTejun Heo 			wake_up_process(worker->task);
4640bd7c089eSTejun Heo 
4641bd7c089eSTejun Heo 		/*
4642a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
4643a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
4644a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4645a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
4646a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
4647a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
4648a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
4649a9ab775bSTejun Heo 		 *
4650a9ab775bSTejun Heo 		 * ACCESS_ONCE() is necessary because @worker->flags may be
4651a9ab775bSTejun Heo 		 * tested without holding any lock in
4652a9ab775bSTejun Heo 		 * wq_worker_waking_up().  Without it, NOT_RUNNING test may
4653a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
4654a9ab775bSTejun Heo 		 * management operations.
4655bd7c089eSTejun Heo 		 */
4656a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4657a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
4658a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
4659a9ab775bSTejun Heo 		ACCESS_ONCE(worker->flags) = worker_flags;
4660bd7c089eSTejun Heo 	}
4661a9ab775bSTejun Heo 
4662a9ab775bSTejun Heo 	spin_unlock_irq(&pool->lock);
4663bd7c089eSTejun Heo }
4664bd7c089eSTejun Heo 
46657dbc725eSTejun Heo /**
46667dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
46677dbc725eSTejun Heo  * @pool: unbound pool of interest
46687dbc725eSTejun Heo  * @cpu: the CPU which is coming up
46697dbc725eSTejun Heo  *
46707dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
46717dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
46727dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
46737dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
46747dbc725eSTejun Heo  */
46757dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
46767dbc725eSTejun Heo {
46777dbc725eSTejun Heo 	static cpumask_t cpumask;
46787dbc725eSTejun Heo 	struct worker *worker;
46797dbc725eSTejun Heo 
468092f9c5c4SLai Jiangshan 	lockdep_assert_held(&pool->attach_mutex);
46817dbc725eSTejun Heo 
46827dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
46837dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
46847dbc725eSTejun Heo 		return;
46857dbc725eSTejun Heo 
46867dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
46877dbc725eSTejun Heo 
46887dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
4689da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
4690d945b5e9SPeter Zijlstra 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
46917dbc725eSTejun Heo }
46927dbc725eSTejun Heo 
46937ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
46941da177e4SLinus Torvalds {
46954ce62e9eSTejun Heo 	struct worker_pool *pool;
46961da177e4SLinus Torvalds 
4697f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
46983ce63377STejun Heo 		if (pool->nr_workers)
46993ce63377STejun Heo 			continue;
4700051e1850SLai Jiangshan 		if (!create_worker(pool))
47017ee681b2SThomas Gleixner 			return -ENOMEM;
47023af24433SOleg Nesterov 	}
47037ee681b2SThomas Gleixner 	return 0;
47047ee681b2SThomas Gleixner }
47051da177e4SLinus Torvalds 
47067ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
47077ee681b2SThomas Gleixner {
47087ee681b2SThomas Gleixner 	struct worker_pool *pool;
47097ee681b2SThomas Gleixner 	struct workqueue_struct *wq;
47107ee681b2SThomas Gleixner 	int pi;
47117ee681b2SThomas Gleixner 
471268e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
47137dbc725eSTejun Heo 
47147dbc725eSTejun Heo 	for_each_pool(pool, pi) {
471592f9c5c4SLai Jiangshan 		mutex_lock(&pool->attach_mutex);
471694cf58bbSTejun Heo 
4717f05b558dSLai Jiangshan 		if (pool->cpu == cpu)
471894cf58bbSTejun Heo 			rebind_workers(pool);
4719f05b558dSLai Jiangshan 		else if (pool->cpu < 0)
47207dbc725eSTejun Heo 			restore_unbound_workers_cpumask(pool, cpu);
472194cf58bbSTejun Heo 
472292f9c5c4SLai Jiangshan 		mutex_unlock(&pool->attach_mutex);
472394cf58bbSTejun Heo 	}
47247dbc725eSTejun Heo 
47254c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
47264c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
47274c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, true);
47284c16bd32STejun Heo 
472968e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
47307ee681b2SThomas Gleixner 	return 0;
473165758202STejun Heo }
473265758202STejun Heo 
47337ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
473465758202STejun Heo {
47358db25e78STejun Heo 	struct work_struct unbind_work;
47364c16bd32STejun Heo 	struct workqueue_struct *wq;
47378db25e78STejun Heo 
47384c16bd32STejun Heo 	/* unbinding per-cpu workers should happen on the local CPU */
4739706026c2STejun Heo 	INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
47407635d2fdSJoonsoo Kim 	queue_work_on(cpu, system_highpri_wq, &unbind_work);
47414c16bd32STejun Heo 
47424c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
47434c16bd32STejun Heo 	mutex_lock(&wq_pool_mutex);
47444c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
47454c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, false);
47464c16bd32STejun Heo 	mutex_unlock(&wq_pool_mutex);
47474c16bd32STejun Heo 
47484c16bd32STejun Heo 	/* wait for per-cpu unbinding to finish */
47498db25e78STejun Heo 	flush_work(&unbind_work);
4750440a1136SChuansheng Liu 	destroy_work_on_stack(&unbind_work);
47517ee681b2SThomas Gleixner 	return 0;
475265758202STejun Heo }
475365758202STejun Heo 
47542d3854a3SRusty Russell #ifdef CONFIG_SMP
47558ccad40dSRusty Russell 
47562d3854a3SRusty Russell struct work_for_cpu {
4757ed48ece2STejun Heo 	struct work_struct work;
47582d3854a3SRusty Russell 	long (*fn)(void *);
47592d3854a3SRusty Russell 	void *arg;
47602d3854a3SRusty Russell 	long ret;
47612d3854a3SRusty Russell };
47622d3854a3SRusty Russell 
4763ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
47642d3854a3SRusty Russell {
4765ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4766ed48ece2STejun Heo 
47672d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
47682d3854a3SRusty Russell }
47692d3854a3SRusty Russell 
47702d3854a3SRusty Russell /**
477122aceb31SAnna-Maria Gleixner  * work_on_cpu - run a function in thread context on a particular cpu
47722d3854a3SRusty Russell  * @cpu: the cpu to run on
47732d3854a3SRusty Russell  * @fn: the function to run
47742d3854a3SRusty Russell  * @arg: the function arg
47752d3854a3SRusty Russell  *
477631ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
47776b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
4778d185af30SYacine Belkadi  *
4779d185af30SYacine Belkadi  * Return: The value @fn returns.
47802d3854a3SRusty Russell  */
4781d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
47822d3854a3SRusty Russell {
4783ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
47842d3854a3SRusty Russell 
4785ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4786ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
478712997d1aSBjorn Helgaas 	flush_work(&wfc.work);
4788440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
47892d3854a3SRusty Russell 	return wfc.ret;
47902d3854a3SRusty Russell }
47912d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
47920e8d6a93SThomas Gleixner 
47930e8d6a93SThomas Gleixner /**
47940e8d6a93SThomas Gleixner  * work_on_cpu_safe - run a function in thread context on a particular cpu
47950e8d6a93SThomas Gleixner  * @cpu: the cpu to run on
47960e8d6a93SThomas Gleixner  * @fn:  the function to run
47970e8d6a93SThomas Gleixner  * @arg: the function argument
47980e8d6a93SThomas Gleixner  *
47990e8d6a93SThomas Gleixner  * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
48000e8d6a93SThomas Gleixner  * any locks which would prevent @fn from completing.
48010e8d6a93SThomas Gleixner  *
48020e8d6a93SThomas Gleixner  * Return: The value @fn returns.
48030e8d6a93SThomas Gleixner  */
48040e8d6a93SThomas Gleixner long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
48050e8d6a93SThomas Gleixner {
48060e8d6a93SThomas Gleixner 	long ret = -ENODEV;
48070e8d6a93SThomas Gleixner 
48080e8d6a93SThomas Gleixner 	get_online_cpus();
48090e8d6a93SThomas Gleixner 	if (cpu_online(cpu))
48100e8d6a93SThomas Gleixner 		ret = work_on_cpu(cpu, fn, arg);
48110e8d6a93SThomas Gleixner 	put_online_cpus();
48120e8d6a93SThomas Gleixner 	return ret;
48130e8d6a93SThomas Gleixner }
48140e8d6a93SThomas Gleixner EXPORT_SYMBOL_GPL(work_on_cpu_safe);
48152d3854a3SRusty Russell #endif /* CONFIG_SMP */
48162d3854a3SRusty Russell 
4817a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
4818e7577c50SRusty Russell 
4819a0a1a5fdSTejun Heo /**
4820a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
4821a0a1a5fdSTejun Heo  *
482258a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
4823c5aa87bbSTejun Heo  * workqueues will queue new works to their delayed_works list instead of
4824706026c2STejun Heo  * pool->worklist.
4825a0a1a5fdSTejun Heo  *
4826a0a1a5fdSTejun Heo  * CONTEXT:
4827a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4828a0a1a5fdSTejun Heo  */
4829a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
4830a0a1a5fdSTejun Heo {
483124b8a847STejun Heo 	struct workqueue_struct *wq;
483224b8a847STejun Heo 	struct pool_workqueue *pwq;
4833a0a1a5fdSTejun Heo 
483468e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4835a0a1a5fdSTejun Heo 
48366183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
4837a0a1a5fdSTejun Heo 	workqueue_freezing = true;
4838a0a1a5fdSTejun Heo 
483924b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
4840a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
4841699ce097STejun Heo 		for_each_pwq(pwq, wq)
4842699ce097STejun Heo 			pwq_adjust_max_active(pwq);
4843a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
4844a1056305STejun Heo 	}
48455bcab335STejun Heo 
484668e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4847a0a1a5fdSTejun Heo }
4848a0a1a5fdSTejun Heo 
4849a0a1a5fdSTejun Heo /**
485058a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
4851a0a1a5fdSTejun Heo  *
4852a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
4853a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
4854a0a1a5fdSTejun Heo  *
4855a0a1a5fdSTejun Heo  * CONTEXT:
485668e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
4857a0a1a5fdSTejun Heo  *
4858d185af30SYacine Belkadi  * Return:
485958a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
486058a69cb4STejun Heo  * is complete.
4861a0a1a5fdSTejun Heo  */
4862a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
4863a0a1a5fdSTejun Heo {
4864a0a1a5fdSTejun Heo 	bool busy = false;
486524b8a847STejun Heo 	struct workqueue_struct *wq;
486624b8a847STejun Heo 	struct pool_workqueue *pwq;
4867a0a1a5fdSTejun Heo 
486868e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4869a0a1a5fdSTejun Heo 
48706183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
4871a0a1a5fdSTejun Heo 
487224b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
487324b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
487424b8a847STejun Heo 			continue;
4875a0a1a5fdSTejun Heo 		/*
4876a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
4877a0a1a5fdSTejun Heo 		 * to peek without lock.
4878a0a1a5fdSTejun Heo 		 */
487988109453SLai Jiangshan 		rcu_read_lock_sched();
488024b8a847STejun Heo 		for_each_pwq(pwq, wq) {
48816183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
4882112202d9STejun Heo 			if (pwq->nr_active) {
4883a0a1a5fdSTejun Heo 				busy = true;
488488109453SLai Jiangshan 				rcu_read_unlock_sched();
4885a0a1a5fdSTejun Heo 				goto out_unlock;
4886a0a1a5fdSTejun Heo 			}
4887a0a1a5fdSTejun Heo 		}
488888109453SLai Jiangshan 		rcu_read_unlock_sched();
4889a0a1a5fdSTejun Heo 	}
4890a0a1a5fdSTejun Heo out_unlock:
489168e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4892a0a1a5fdSTejun Heo 	return busy;
4893a0a1a5fdSTejun Heo }
4894a0a1a5fdSTejun Heo 
4895a0a1a5fdSTejun Heo /**
4896a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
4897a0a1a5fdSTejun Heo  *
4898a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
4899706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
4900a0a1a5fdSTejun Heo  *
4901a0a1a5fdSTejun Heo  * CONTEXT:
4902a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4903a0a1a5fdSTejun Heo  */
4904a0a1a5fdSTejun Heo void thaw_workqueues(void)
4905a0a1a5fdSTejun Heo {
490624b8a847STejun Heo 	struct workqueue_struct *wq;
490724b8a847STejun Heo 	struct pool_workqueue *pwq;
4908a0a1a5fdSTejun Heo 
490968e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4910a0a1a5fdSTejun Heo 
4911a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
4912a0a1a5fdSTejun Heo 		goto out_unlock;
4913a0a1a5fdSTejun Heo 
491474b414eaSLai Jiangshan 	workqueue_freezing = false;
491524b8a847STejun Heo 
491624b8a847STejun Heo 	/* restore max_active and repopulate worklist */
491724b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
4918a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
4919699ce097STejun Heo 		for_each_pwq(pwq, wq)
4920699ce097STejun Heo 			pwq_adjust_max_active(pwq);
4921a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
492224b8a847STejun Heo 	}
492324b8a847STejun Heo 
4924a0a1a5fdSTejun Heo out_unlock:
492568e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4926a0a1a5fdSTejun Heo }
4927a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
4928a0a1a5fdSTejun Heo 
4929042f7df1SLai Jiangshan static int workqueue_apply_unbound_cpumask(void)
4930042f7df1SLai Jiangshan {
4931042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
4932042f7df1SLai Jiangshan 	int ret = 0;
4933042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
4934042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
4935042f7df1SLai Jiangshan 
4936042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
4937042f7df1SLai Jiangshan 
4938042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
4939042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
4940042f7df1SLai Jiangshan 			continue;
4941042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
4942042f7df1SLai Jiangshan 		if (wq->flags & __WQ_ORDERED)
4943042f7df1SLai Jiangshan 			continue;
4944042f7df1SLai Jiangshan 
4945042f7df1SLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs);
4946042f7df1SLai Jiangshan 		if (!ctx) {
4947042f7df1SLai Jiangshan 			ret = -ENOMEM;
4948042f7df1SLai Jiangshan 			break;
4949042f7df1SLai Jiangshan 		}
4950042f7df1SLai Jiangshan 
4951042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
4952042f7df1SLai Jiangshan 	}
4953042f7df1SLai Jiangshan 
4954042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
4955042f7df1SLai Jiangshan 		if (!ret)
4956042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
4957042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
4958042f7df1SLai Jiangshan 	}
4959042f7df1SLai Jiangshan 
4960042f7df1SLai Jiangshan 	return ret;
4961042f7df1SLai Jiangshan }
4962042f7df1SLai Jiangshan 
4963042f7df1SLai Jiangshan /**
4964042f7df1SLai Jiangshan  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
4965042f7df1SLai Jiangshan  *  @cpumask: the cpumask to set
4966042f7df1SLai Jiangshan  *
4967042f7df1SLai Jiangshan  *  The low-level workqueues cpumask is a global cpumask that limits
4968042f7df1SLai Jiangshan  *  the affinity of all unbound workqueues.  This function check the @cpumask
4969042f7df1SLai Jiangshan  *  and apply it to all unbound workqueues and updates all pwqs of them.
4970042f7df1SLai Jiangshan  *
4971042f7df1SLai Jiangshan  *  Retun:	0	- Success
4972042f7df1SLai Jiangshan  *  		-EINVAL	- Invalid @cpumask
4973042f7df1SLai Jiangshan  *  		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
4974042f7df1SLai Jiangshan  */
4975042f7df1SLai Jiangshan int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
4976042f7df1SLai Jiangshan {
4977042f7df1SLai Jiangshan 	int ret = -EINVAL;
4978042f7df1SLai Jiangshan 	cpumask_var_t saved_cpumask;
4979042f7df1SLai Jiangshan 
4980042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&saved_cpumask, GFP_KERNEL))
4981042f7df1SLai Jiangshan 		return -ENOMEM;
4982042f7df1SLai Jiangshan 
4983042f7df1SLai Jiangshan 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
4984042f7df1SLai Jiangshan 	if (!cpumask_empty(cpumask)) {
4985a0111cf6SLai Jiangshan 		apply_wqattrs_lock();
4986042f7df1SLai Jiangshan 
4987042f7df1SLai Jiangshan 		/* save the old wq_unbound_cpumask. */
4988042f7df1SLai Jiangshan 		cpumask_copy(saved_cpumask, wq_unbound_cpumask);
4989042f7df1SLai Jiangshan 
4990042f7df1SLai Jiangshan 		/* update wq_unbound_cpumask at first and apply it to wqs. */
4991042f7df1SLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, cpumask);
4992042f7df1SLai Jiangshan 		ret = workqueue_apply_unbound_cpumask();
4993042f7df1SLai Jiangshan 
4994042f7df1SLai Jiangshan 		/* restore the wq_unbound_cpumask when failed. */
4995042f7df1SLai Jiangshan 		if (ret < 0)
4996042f7df1SLai Jiangshan 			cpumask_copy(wq_unbound_cpumask, saved_cpumask);
4997042f7df1SLai Jiangshan 
4998a0111cf6SLai Jiangshan 		apply_wqattrs_unlock();
4999042f7df1SLai Jiangshan 	}
5000042f7df1SLai Jiangshan 
5001042f7df1SLai Jiangshan 	free_cpumask_var(saved_cpumask);
5002042f7df1SLai Jiangshan 	return ret;
5003042f7df1SLai Jiangshan }
5004042f7df1SLai Jiangshan 
50056ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
50066ba94429SFrederic Weisbecker /*
50076ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
50086ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
50096ba94429SFrederic Weisbecker  * following attributes.
50106ba94429SFrederic Weisbecker  *
50116ba94429SFrederic Weisbecker  *  per_cpu	RO bool	: whether the workqueue is per-cpu or unbound
50126ba94429SFrederic Weisbecker  *  max_active	RW int	: maximum number of in-flight work items
50136ba94429SFrederic Weisbecker  *
50146ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
50156ba94429SFrederic Weisbecker  *
50166ba94429SFrederic Weisbecker  *  id		RO int	: the associated pool ID
50176ba94429SFrederic Weisbecker  *  nice	RW int	: nice value of the workers
50186ba94429SFrederic Weisbecker  *  cpumask	RW mask	: bitmask of allowed CPUs for the workers
50196ba94429SFrederic Weisbecker  */
50206ba94429SFrederic Weisbecker struct wq_device {
50216ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
50226ba94429SFrederic Weisbecker 	struct device			dev;
50236ba94429SFrederic Weisbecker };
50246ba94429SFrederic Weisbecker 
50256ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
50266ba94429SFrederic Weisbecker {
50276ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
50286ba94429SFrederic Weisbecker 
50296ba94429SFrederic Weisbecker 	return wq_dev->wq;
50306ba94429SFrederic Weisbecker }
50316ba94429SFrederic Weisbecker 
50326ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
50336ba94429SFrederic Weisbecker 			    char *buf)
50346ba94429SFrederic Weisbecker {
50356ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
50366ba94429SFrederic Weisbecker 
50376ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
50386ba94429SFrederic Weisbecker }
50396ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
50406ba94429SFrederic Weisbecker 
50416ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
50426ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
50436ba94429SFrederic Weisbecker {
50446ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
50456ba94429SFrederic Weisbecker 
50466ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
50476ba94429SFrederic Weisbecker }
50486ba94429SFrederic Weisbecker 
50496ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
50506ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
50516ba94429SFrederic Weisbecker 				size_t count)
50526ba94429SFrederic Weisbecker {
50536ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
50546ba94429SFrederic Weisbecker 	int val;
50556ba94429SFrederic Weisbecker 
50566ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
50576ba94429SFrederic Weisbecker 		return -EINVAL;
50586ba94429SFrederic Weisbecker 
50596ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
50606ba94429SFrederic Weisbecker 	return count;
50616ba94429SFrederic Weisbecker }
50626ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
50636ba94429SFrederic Weisbecker 
50646ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
50656ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
50666ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
50676ba94429SFrederic Weisbecker 	NULL,
50686ba94429SFrederic Weisbecker };
50696ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
50706ba94429SFrederic Weisbecker 
50716ba94429SFrederic Weisbecker static ssize_t wq_pool_ids_show(struct device *dev,
50726ba94429SFrederic Weisbecker 				struct device_attribute *attr, char *buf)
50736ba94429SFrederic Weisbecker {
50746ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
50756ba94429SFrederic Weisbecker 	const char *delim = "";
50766ba94429SFrederic Weisbecker 	int node, written = 0;
50776ba94429SFrederic Weisbecker 
50786ba94429SFrederic Weisbecker 	rcu_read_lock_sched();
50796ba94429SFrederic Weisbecker 	for_each_node(node) {
50806ba94429SFrederic Weisbecker 		written += scnprintf(buf + written, PAGE_SIZE - written,
50816ba94429SFrederic Weisbecker 				     "%s%d:%d", delim, node,
50826ba94429SFrederic Weisbecker 				     unbound_pwq_by_node(wq, node)->pool->id);
50836ba94429SFrederic Weisbecker 		delim = " ";
50846ba94429SFrederic Weisbecker 	}
50856ba94429SFrederic Weisbecker 	written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
50866ba94429SFrederic Weisbecker 	rcu_read_unlock_sched();
50876ba94429SFrederic Weisbecker 
50886ba94429SFrederic Weisbecker 	return written;
50896ba94429SFrederic Weisbecker }
50906ba94429SFrederic Weisbecker 
50916ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
50926ba94429SFrederic Weisbecker 			    char *buf)
50936ba94429SFrederic Weisbecker {
50946ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
50956ba94429SFrederic Weisbecker 	int written;
50966ba94429SFrederic Weisbecker 
50976ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
50986ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
50996ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
51006ba94429SFrederic Weisbecker 
51016ba94429SFrederic Weisbecker 	return written;
51026ba94429SFrederic Weisbecker }
51036ba94429SFrederic Weisbecker 
51046ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
51056ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
51066ba94429SFrederic Weisbecker {
51076ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
51086ba94429SFrederic Weisbecker 
5109899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5110899a94feSLai Jiangshan 
51116ba94429SFrederic Weisbecker 	attrs = alloc_workqueue_attrs(GFP_KERNEL);
51126ba94429SFrederic Weisbecker 	if (!attrs)
51136ba94429SFrederic Weisbecker 		return NULL;
51146ba94429SFrederic Weisbecker 
51156ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
51166ba94429SFrederic Weisbecker 	return attrs;
51176ba94429SFrederic Weisbecker }
51186ba94429SFrederic Weisbecker 
51196ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
51206ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
51216ba94429SFrederic Weisbecker {
51226ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
51236ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5124d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5125d4d3e257SLai Jiangshan 
5126d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
51276ba94429SFrederic Weisbecker 
51286ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
51296ba94429SFrederic Weisbecker 	if (!attrs)
5130d4d3e257SLai Jiangshan 		goto out_unlock;
51316ba94429SFrederic Weisbecker 
51326ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
51336ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5134d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
51356ba94429SFrederic Weisbecker 	else
51366ba94429SFrederic Weisbecker 		ret = -EINVAL;
51376ba94429SFrederic Weisbecker 
5138d4d3e257SLai Jiangshan out_unlock:
5139d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
51406ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
51416ba94429SFrederic Weisbecker 	return ret ?: count;
51426ba94429SFrederic Weisbecker }
51436ba94429SFrederic Weisbecker 
51446ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
51456ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
51466ba94429SFrederic Weisbecker {
51476ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
51486ba94429SFrederic Weisbecker 	int written;
51496ba94429SFrederic Weisbecker 
51506ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
51516ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
51526ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
51536ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
51546ba94429SFrederic Weisbecker 	return written;
51556ba94429SFrederic Weisbecker }
51566ba94429SFrederic Weisbecker 
51576ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
51586ba94429SFrederic Weisbecker 				struct device_attribute *attr,
51596ba94429SFrederic Weisbecker 				const char *buf, size_t count)
51606ba94429SFrederic Weisbecker {
51616ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
51626ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5163d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5164d4d3e257SLai Jiangshan 
5165d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
51666ba94429SFrederic Weisbecker 
51676ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
51686ba94429SFrederic Weisbecker 	if (!attrs)
5169d4d3e257SLai Jiangshan 		goto out_unlock;
51706ba94429SFrederic Weisbecker 
51716ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
51726ba94429SFrederic Weisbecker 	if (!ret)
5173d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
51746ba94429SFrederic Weisbecker 
5175d4d3e257SLai Jiangshan out_unlock:
5176d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
51776ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
51786ba94429SFrederic Weisbecker 	return ret ?: count;
51796ba94429SFrederic Weisbecker }
51806ba94429SFrederic Weisbecker 
51816ba94429SFrederic Weisbecker static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
51826ba94429SFrederic Weisbecker 			    char *buf)
51836ba94429SFrederic Weisbecker {
51846ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
51856ba94429SFrederic Weisbecker 	int written;
51866ba94429SFrederic Weisbecker 
51876ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
51886ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n",
51896ba94429SFrederic Weisbecker 			    !wq->unbound_attrs->no_numa);
51906ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
51916ba94429SFrederic Weisbecker 
51926ba94429SFrederic Weisbecker 	return written;
51936ba94429SFrederic Weisbecker }
51946ba94429SFrederic Weisbecker 
51956ba94429SFrederic Weisbecker static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
51966ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
51976ba94429SFrederic Weisbecker {
51986ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
51996ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5200d4d3e257SLai Jiangshan 	int v, ret = -ENOMEM;
5201d4d3e257SLai Jiangshan 
5202d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
52036ba94429SFrederic Weisbecker 
52046ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
52056ba94429SFrederic Weisbecker 	if (!attrs)
5206d4d3e257SLai Jiangshan 		goto out_unlock;
52076ba94429SFrederic Weisbecker 
52086ba94429SFrederic Weisbecker 	ret = -EINVAL;
52096ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &v) == 1) {
52106ba94429SFrederic Weisbecker 		attrs->no_numa = !v;
5211d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
52126ba94429SFrederic Weisbecker 	}
52136ba94429SFrederic Weisbecker 
5214d4d3e257SLai Jiangshan out_unlock:
5215d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
52166ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
52176ba94429SFrederic Weisbecker 	return ret ?: count;
52186ba94429SFrederic Weisbecker }
52196ba94429SFrederic Weisbecker 
52206ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
52216ba94429SFrederic Weisbecker 	__ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
52226ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
52236ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
52246ba94429SFrederic Weisbecker 	__ATTR(numa, 0644, wq_numa_show, wq_numa_store),
52256ba94429SFrederic Weisbecker 	__ATTR_NULL,
52266ba94429SFrederic Weisbecker };
52276ba94429SFrederic Weisbecker 
52286ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
52296ba94429SFrederic Weisbecker 	.name				= "workqueue",
52306ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
52316ba94429SFrederic Weisbecker };
52326ba94429SFrederic Weisbecker 
5233b05a7928SFrederic Weisbecker static ssize_t wq_unbound_cpumask_show(struct device *dev,
5234b05a7928SFrederic Weisbecker 		struct device_attribute *attr, char *buf)
5235b05a7928SFrederic Weisbecker {
5236b05a7928SFrederic Weisbecker 	int written;
5237b05a7928SFrederic Weisbecker 
5238042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5239b05a7928SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5240b05a7928SFrederic Weisbecker 			    cpumask_pr_args(wq_unbound_cpumask));
5241042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5242b05a7928SFrederic Weisbecker 
5243b05a7928SFrederic Weisbecker 	return written;
5244b05a7928SFrederic Weisbecker }
5245b05a7928SFrederic Weisbecker 
5246042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
5247042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
5248042f7df1SLai Jiangshan {
5249042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
5250042f7df1SLai Jiangshan 	int ret;
5251042f7df1SLai Jiangshan 
5252042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5253042f7df1SLai Jiangshan 		return -ENOMEM;
5254042f7df1SLai Jiangshan 
5255042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
5256042f7df1SLai Jiangshan 	if (!ret)
5257042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
5258042f7df1SLai Jiangshan 
5259042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
5260042f7df1SLai Jiangshan 	return ret ? ret : count;
5261042f7df1SLai Jiangshan }
5262042f7df1SLai Jiangshan 
5263b05a7928SFrederic Weisbecker static struct device_attribute wq_sysfs_cpumask_attr =
5264042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5265042f7df1SLai Jiangshan 	       wq_unbound_cpumask_store);
5266b05a7928SFrederic Weisbecker 
52676ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
52686ba94429SFrederic Weisbecker {
5269b05a7928SFrederic Weisbecker 	int err;
5270b05a7928SFrederic Weisbecker 
5271b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
5272b05a7928SFrederic Weisbecker 	if (err)
5273b05a7928SFrederic Weisbecker 		return err;
5274b05a7928SFrederic Weisbecker 
5275b05a7928SFrederic Weisbecker 	return device_create_file(wq_subsys.dev_root, &wq_sysfs_cpumask_attr);
52766ba94429SFrederic Weisbecker }
52776ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
52786ba94429SFrederic Weisbecker 
52796ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
52806ba94429SFrederic Weisbecker {
52816ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
52826ba94429SFrederic Weisbecker 
52836ba94429SFrederic Weisbecker 	kfree(wq_dev);
52846ba94429SFrederic Weisbecker }
52856ba94429SFrederic Weisbecker 
52866ba94429SFrederic Weisbecker /**
52876ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
52886ba94429SFrederic Weisbecker  * @wq: the workqueue to register
52896ba94429SFrederic Weisbecker  *
52906ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
52916ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
52926ba94429SFrederic Weisbecker  * which is the preferred method.
52936ba94429SFrederic Weisbecker  *
52946ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
52956ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
52966ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
52976ba94429SFrederic Weisbecker  * attributes.
52986ba94429SFrederic Weisbecker  *
52996ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
53006ba94429SFrederic Weisbecker  */
53016ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
53026ba94429SFrederic Weisbecker {
53036ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
53046ba94429SFrederic Weisbecker 	int ret;
53056ba94429SFrederic Weisbecker 
53066ba94429SFrederic Weisbecker 	/*
5307402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
53086ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
53096ba94429SFrederic Weisbecker 	 * workqueues.
53106ba94429SFrederic Weisbecker 	 */
53110a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
53126ba94429SFrederic Weisbecker 		return -EINVAL;
53136ba94429SFrederic Weisbecker 
53146ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
53156ba94429SFrederic Weisbecker 	if (!wq_dev)
53166ba94429SFrederic Weisbecker 		return -ENOMEM;
53176ba94429SFrederic Weisbecker 
53186ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
53196ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
53206ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
532123217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
53226ba94429SFrederic Weisbecker 
53236ba94429SFrederic Weisbecker 	/*
53246ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
53256ba94429SFrederic Weisbecker 	 * everything is ready.
53266ba94429SFrederic Weisbecker 	 */
53276ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
53286ba94429SFrederic Weisbecker 
53296ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
53306ba94429SFrederic Weisbecker 	if (ret) {
53316ba94429SFrederic Weisbecker 		kfree(wq_dev);
53326ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
53336ba94429SFrederic Weisbecker 		return ret;
53346ba94429SFrederic Weisbecker 	}
53356ba94429SFrederic Weisbecker 
53366ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
53376ba94429SFrederic Weisbecker 		struct device_attribute *attr;
53386ba94429SFrederic Weisbecker 
53396ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
53406ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
53416ba94429SFrederic Weisbecker 			if (ret) {
53426ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
53436ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
53446ba94429SFrederic Weisbecker 				return ret;
53456ba94429SFrederic Weisbecker 			}
53466ba94429SFrederic Weisbecker 		}
53476ba94429SFrederic Weisbecker 	}
53486ba94429SFrederic Weisbecker 
53496ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
53506ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
53516ba94429SFrederic Weisbecker 	return 0;
53526ba94429SFrederic Weisbecker }
53536ba94429SFrederic Weisbecker 
53546ba94429SFrederic Weisbecker /**
53556ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
53566ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
53576ba94429SFrederic Weisbecker  *
53586ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
53596ba94429SFrederic Weisbecker  */
53606ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
53616ba94429SFrederic Weisbecker {
53626ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
53636ba94429SFrederic Weisbecker 
53646ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
53656ba94429SFrederic Weisbecker 		return;
53666ba94429SFrederic Weisbecker 
53676ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
53686ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
53696ba94429SFrederic Weisbecker }
53706ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
53716ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
53726ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
53736ba94429SFrederic Weisbecker 
537482607adcSTejun Heo /*
537582607adcSTejun Heo  * Workqueue watchdog.
537682607adcSTejun Heo  *
537782607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
537882607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
537982607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
538082607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
538182607adcSTejun Heo  * largely opaque.
538282607adcSTejun Heo  *
538382607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
538482607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
538582607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
538682607adcSTejun Heo  *
538782607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
538882607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
538982607adcSTejun Heo  * corresponding sysfs parameter file.
539082607adcSTejun Heo  */
539182607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
539282607adcSTejun Heo 
539382607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
5394*5cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
539582607adcSTejun Heo 
539682607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
539782607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
539882607adcSTejun Heo 
539982607adcSTejun Heo static void wq_watchdog_reset_touched(void)
540082607adcSTejun Heo {
540182607adcSTejun Heo 	int cpu;
540282607adcSTejun Heo 
540382607adcSTejun Heo 	wq_watchdog_touched = jiffies;
540482607adcSTejun Heo 	for_each_possible_cpu(cpu)
540582607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
540682607adcSTejun Heo }
540782607adcSTejun Heo 
5408*5cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
540982607adcSTejun Heo {
541082607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
541182607adcSTejun Heo 	bool lockup_detected = false;
541282607adcSTejun Heo 	struct worker_pool *pool;
541382607adcSTejun Heo 	int pi;
541482607adcSTejun Heo 
541582607adcSTejun Heo 	if (!thresh)
541682607adcSTejun Heo 		return;
541782607adcSTejun Heo 
541882607adcSTejun Heo 	rcu_read_lock();
541982607adcSTejun Heo 
542082607adcSTejun Heo 	for_each_pool(pool, pi) {
542182607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
542282607adcSTejun Heo 
542382607adcSTejun Heo 		if (list_empty(&pool->worklist))
542482607adcSTejun Heo 			continue;
542582607adcSTejun Heo 
542682607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
542782607adcSTejun Heo 		pool_ts = READ_ONCE(pool->watchdog_ts);
542882607adcSTejun Heo 		touched = READ_ONCE(wq_watchdog_touched);
542982607adcSTejun Heo 
543082607adcSTejun Heo 		if (time_after(pool_ts, touched))
543182607adcSTejun Heo 			ts = pool_ts;
543282607adcSTejun Heo 		else
543382607adcSTejun Heo 			ts = touched;
543482607adcSTejun Heo 
543582607adcSTejun Heo 		if (pool->cpu >= 0) {
543682607adcSTejun Heo 			unsigned long cpu_touched =
543782607adcSTejun Heo 				READ_ONCE(per_cpu(wq_watchdog_touched_cpu,
543882607adcSTejun Heo 						  pool->cpu));
543982607adcSTejun Heo 			if (time_after(cpu_touched, ts))
544082607adcSTejun Heo 				ts = cpu_touched;
544182607adcSTejun Heo 		}
544282607adcSTejun Heo 
544382607adcSTejun Heo 		/* did we stall? */
544482607adcSTejun Heo 		if (time_after(jiffies, ts + thresh)) {
544582607adcSTejun Heo 			lockup_detected = true;
544682607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
544782607adcSTejun Heo 			pr_cont_pool_info(pool);
544882607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
544982607adcSTejun Heo 				jiffies_to_msecs(jiffies - pool_ts) / 1000);
545082607adcSTejun Heo 		}
545182607adcSTejun Heo 	}
545282607adcSTejun Heo 
545382607adcSTejun Heo 	rcu_read_unlock();
545482607adcSTejun Heo 
545582607adcSTejun Heo 	if (lockup_detected)
545682607adcSTejun Heo 		show_workqueue_state();
545782607adcSTejun Heo 
545882607adcSTejun Heo 	wq_watchdog_reset_touched();
545982607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
546082607adcSTejun Heo }
546182607adcSTejun Heo 
546282607adcSTejun Heo void wq_watchdog_touch(int cpu)
546382607adcSTejun Heo {
546482607adcSTejun Heo 	if (cpu >= 0)
546582607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
546682607adcSTejun Heo 	else
546782607adcSTejun Heo 		wq_watchdog_touched = jiffies;
546882607adcSTejun Heo }
546982607adcSTejun Heo 
547082607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
547182607adcSTejun Heo {
547282607adcSTejun Heo 	wq_watchdog_thresh = 0;
547382607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
547482607adcSTejun Heo 
547582607adcSTejun Heo 	if (thresh) {
547682607adcSTejun Heo 		wq_watchdog_thresh = thresh;
547782607adcSTejun Heo 		wq_watchdog_reset_touched();
547882607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
547982607adcSTejun Heo 	}
548082607adcSTejun Heo }
548182607adcSTejun Heo 
548282607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
548382607adcSTejun Heo 					const struct kernel_param *kp)
548482607adcSTejun Heo {
548582607adcSTejun Heo 	unsigned long thresh;
548682607adcSTejun Heo 	int ret;
548782607adcSTejun Heo 
548882607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
548982607adcSTejun Heo 	if (ret)
549082607adcSTejun Heo 		return ret;
549182607adcSTejun Heo 
549282607adcSTejun Heo 	if (system_wq)
549382607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
549482607adcSTejun Heo 	else
549582607adcSTejun Heo 		wq_watchdog_thresh = thresh;
549682607adcSTejun Heo 
549782607adcSTejun Heo 	return 0;
549882607adcSTejun Heo }
549982607adcSTejun Heo 
550082607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
550182607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
550282607adcSTejun Heo 	.get	= param_get_ulong,
550382607adcSTejun Heo };
550482607adcSTejun Heo 
550582607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
550682607adcSTejun Heo 		0644);
550782607adcSTejun Heo 
550882607adcSTejun Heo static void wq_watchdog_init(void)
550982607adcSTejun Heo {
5510*5cd79d6aSKees Cook 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
551182607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
551282607adcSTejun Heo }
551382607adcSTejun Heo 
551482607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
551582607adcSTejun Heo 
551682607adcSTejun Heo static inline void wq_watchdog_init(void) { }
551782607adcSTejun Heo 
551882607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
551982607adcSTejun Heo 
5520bce90380STejun Heo static void __init wq_numa_init(void)
5521bce90380STejun Heo {
5522bce90380STejun Heo 	cpumask_var_t *tbl;
5523bce90380STejun Heo 	int node, cpu;
5524bce90380STejun Heo 
5525bce90380STejun Heo 	if (num_possible_nodes() <= 1)
5526bce90380STejun Heo 		return;
5527bce90380STejun Heo 
5528d55262c4STejun Heo 	if (wq_disable_numa) {
5529d55262c4STejun Heo 		pr_info("workqueue: NUMA affinity support disabled\n");
5530d55262c4STejun Heo 		return;
5531d55262c4STejun Heo 	}
5532d55262c4STejun Heo 
55334c16bd32STejun Heo 	wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
55344c16bd32STejun Heo 	BUG_ON(!wq_update_unbound_numa_attrs_buf);
55354c16bd32STejun Heo 
5536bce90380STejun Heo 	/*
5537bce90380STejun Heo 	 * We want masks of possible CPUs of each node which isn't readily
5538bce90380STejun Heo 	 * available.  Build one from cpu_to_node() which should have been
5539bce90380STejun Heo 	 * fully initialized by now.
5540bce90380STejun Heo 	 */
5541ddcb57e2SLai Jiangshan 	tbl = kzalloc(nr_node_ids * sizeof(tbl[0]), GFP_KERNEL);
5542bce90380STejun Heo 	BUG_ON(!tbl);
5543bce90380STejun Heo 
5544bce90380STejun Heo 	for_each_node(node)
55455a6024f1SYasuaki Ishimatsu 		BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
55461be0c25dSTejun Heo 				node_online(node) ? node : NUMA_NO_NODE));
5547bce90380STejun Heo 
5548bce90380STejun Heo 	for_each_possible_cpu(cpu) {
5549bce90380STejun Heo 		node = cpu_to_node(cpu);
5550bce90380STejun Heo 		if (WARN_ON(node == NUMA_NO_NODE)) {
5551bce90380STejun Heo 			pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
5552bce90380STejun Heo 			/* happens iff arch is bonkers, let's just proceed */
5553bce90380STejun Heo 			return;
5554bce90380STejun Heo 		}
5555bce90380STejun Heo 		cpumask_set_cpu(cpu, tbl[node]);
5556bce90380STejun Heo 	}
5557bce90380STejun Heo 
5558bce90380STejun Heo 	wq_numa_possible_cpumask = tbl;
5559bce90380STejun Heo 	wq_numa_enabled = true;
5560bce90380STejun Heo }
5561bce90380STejun Heo 
55623347fa09STejun Heo /**
55633347fa09STejun Heo  * workqueue_init_early - early init for workqueue subsystem
55643347fa09STejun Heo  *
55653347fa09STejun Heo  * This is the first half of two-staged workqueue subsystem initialization
55663347fa09STejun Heo  * and invoked as soon as the bare basics - memory allocation, cpumasks and
55673347fa09STejun Heo  * idr are up.  It sets up all the data structures and system workqueues
55683347fa09STejun Heo  * and allows early boot code to create workqueues and queue/cancel work
55693347fa09STejun Heo  * items.  Actual work item execution starts only after kthreads can be
55703347fa09STejun Heo  * created and scheduled right before early initcalls.
55713347fa09STejun Heo  */
55723347fa09STejun Heo int __init workqueue_init_early(void)
55731da177e4SLinus Torvalds {
55747a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
55757a4e344cSTejun Heo 	int i, cpu;
5576c34056a3STejun Heo 
5577e904e6c2STejun Heo 	WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
5578e904e6c2STejun Heo 
5579b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
5580b05a7928SFrederic Weisbecker 	cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
5581b05a7928SFrederic Weisbecker 
5582e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
5583e904e6c2STejun Heo 
5584706026c2STejun Heo 	/* initialize CPU pools */
558529c91e99STejun Heo 	for_each_possible_cpu(cpu) {
55864ce62e9eSTejun Heo 		struct worker_pool *pool;
55878b03ae3cSTejun Heo 
55887a4e344cSTejun Heo 		i = 0;
5589f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
55907a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
5591ec22ca5eSTejun Heo 			pool->cpu = cpu;
55927a4e344cSTejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
55937a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
5594f3f90ad4STejun Heo 			pool->node = cpu_to_node(cpu);
55957a4e344cSTejun Heo 
55969daf9e67STejun Heo 			/* alloc pool ID */
559768e13a67SLai Jiangshan 			mutex_lock(&wq_pool_mutex);
55989daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
559968e13a67SLai Jiangshan 			mutex_unlock(&wq_pool_mutex);
56004ce62e9eSTejun Heo 		}
56018b03ae3cSTejun Heo 	}
56028b03ae3cSTejun Heo 
56038a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
560429c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
560529c91e99STejun Heo 		struct workqueue_attrs *attrs;
560629c91e99STejun Heo 
560729c91e99STejun Heo 		BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
560829c91e99STejun Heo 		attrs->nice = std_nice[i];
560929c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
56108a2b7538STejun Heo 
56118a2b7538STejun Heo 		/*
56128a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
56138a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
56148a2b7538STejun Heo 		 * Turn off NUMA so that dfl_pwq is used for all nodes.
56158a2b7538STejun Heo 		 */
56168a2b7538STejun Heo 		BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
56178a2b7538STejun Heo 		attrs->nice = std_nice[i];
56188a2b7538STejun Heo 		attrs->no_numa = true;
56198a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
562029c91e99STejun Heo 	}
562129c91e99STejun Heo 
5622d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
56231aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
5624d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
5625f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
5626f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
562724d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
562824d51addSTejun Heo 					      WQ_FREEZABLE, 0);
56290668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
56300668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
56310668106cSViresh Kumar 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
56320668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
56330668106cSViresh Kumar 					      0);
56341aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
56350668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
56360668106cSViresh Kumar 	       !system_power_efficient_wq ||
56370668106cSViresh Kumar 	       !system_freezable_power_efficient_wq);
563882607adcSTejun Heo 
56393347fa09STejun Heo 	return 0;
56403347fa09STejun Heo }
56413347fa09STejun Heo 
56423347fa09STejun Heo /**
56433347fa09STejun Heo  * workqueue_init - bring workqueue subsystem fully online
56443347fa09STejun Heo  *
56453347fa09STejun Heo  * This is the latter half of two-staged workqueue subsystem initialization
56463347fa09STejun Heo  * and invoked as soon as kthreads can be created and scheduled.
56473347fa09STejun Heo  * Workqueues have been created and work items queued on them, but there
56483347fa09STejun Heo  * are no kworkers executing the work items yet.  Populate the worker pools
56493347fa09STejun Heo  * with the initial workers and enable future kworker creations.
56503347fa09STejun Heo  */
56513347fa09STejun Heo int __init workqueue_init(void)
56523347fa09STejun Heo {
56532186d9f9STejun Heo 	struct workqueue_struct *wq;
56543347fa09STejun Heo 	struct worker_pool *pool;
56553347fa09STejun Heo 	int cpu, bkt;
56563347fa09STejun Heo 
56572186d9f9STejun Heo 	/*
56582186d9f9STejun Heo 	 * It'd be simpler to initialize NUMA in workqueue_init_early() but
56592186d9f9STejun Heo 	 * CPU to node mapping may not be available that early on some
56602186d9f9STejun Heo 	 * archs such as power and arm64.  As per-cpu pools created
56612186d9f9STejun Heo 	 * previously could be missing node hint and unbound pools NUMA
56622186d9f9STejun Heo 	 * affinity, fix them up.
56632186d9f9STejun Heo 	 */
56642186d9f9STejun Heo 	wq_numa_init();
56652186d9f9STejun Heo 
56662186d9f9STejun Heo 	mutex_lock(&wq_pool_mutex);
56672186d9f9STejun Heo 
56682186d9f9STejun Heo 	for_each_possible_cpu(cpu) {
56692186d9f9STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
56702186d9f9STejun Heo 			pool->node = cpu_to_node(cpu);
56712186d9f9STejun Heo 		}
56722186d9f9STejun Heo 	}
56732186d9f9STejun Heo 
56742186d9f9STejun Heo 	list_for_each_entry(wq, &workqueues, list)
56752186d9f9STejun Heo 		wq_update_unbound_numa(wq, smp_processor_id(), true);
56762186d9f9STejun Heo 
56772186d9f9STejun Heo 	mutex_unlock(&wq_pool_mutex);
56782186d9f9STejun Heo 
56793347fa09STejun Heo 	/* create the initial workers */
56803347fa09STejun Heo 	for_each_online_cpu(cpu) {
56813347fa09STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
56823347fa09STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
56833347fa09STejun Heo 			BUG_ON(!create_worker(pool));
56843347fa09STejun Heo 		}
56853347fa09STejun Heo 	}
56863347fa09STejun Heo 
56873347fa09STejun Heo 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
56883347fa09STejun Heo 		BUG_ON(!create_worker(pool));
56893347fa09STejun Heo 
56903347fa09STejun Heo 	wq_online = true;
569182607adcSTejun Heo 	wq_watchdog_init();
569282607adcSTejun Heo 
56936ee0578bSSuresh Siddha 	return 0;
56941da177e4SLinus Torvalds }
5695