xref: /linux-6.15/kernel/workqueue.c (revision ef557180)
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  *
24c54fce6eSTejun Heo  * Please read Documentation/workqueue.txt 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 
293bce90380STejun Heo static bool wq_numa_enabled;		/* unbound NUMA affinity enabled */
294bce90380STejun Heo 
2954c16bd32STejun Heo /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
2964c16bd32STejun Heo static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
2974c16bd32STejun Heo 
29868e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
2992e109a28STejun Heo static DEFINE_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
3005bcab335STejun Heo 
301e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
30268e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
3037d19c5ceSTejun Heo 
304*ef557180SMike Galbraith /* PL: allowable cpus for unbound wqs and work items */
305*ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
306*ef557180SMike Galbraith 
307*ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
308*ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
309b05a7928SFrederic Weisbecker 
3107d19c5ceSTejun Heo /* the per-cpu worker pools */
3117d19c5ceSTejun Heo static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
3127d19c5ceSTejun Heo 				     cpu_worker_pools);
3137d19c5ceSTejun Heo 
31468e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
3157d19c5ceSTejun Heo 
31668e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
31729c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
31829c91e99STejun Heo 
319c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
32029c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
32129c91e99STejun Heo 
3228a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
3238a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
3248a2b7538STejun Heo 
325d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
326ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
327044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
3281aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
329044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
330d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
331044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
332f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
333044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
33424d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
3350668106cSViresh Kumar struct workqueue_struct *system_power_efficient_wq __read_mostly;
3360668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
3370668106cSViresh Kumar struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
3380668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
339d320c038STejun Heo 
3407d19c5ceSTejun Heo static int worker_thread(void *__worker);
3416ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
3427d19c5ceSTejun Heo 
34397bd2347STejun Heo #define CREATE_TRACE_POINTS
34497bd2347STejun Heo #include <trace/events/workqueue.h>
34597bd2347STejun Heo 
34668e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
347f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
348f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
34968e13a67SLai Jiangshan 			 "sched RCU or wq_pool_mutex should be held")
3505bcab335STejun Heo 
351b09f4fd3SLai Jiangshan #define assert_rcu_or_wq_mutex(wq)					\
352f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
353f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex),			\
354b09f4fd3SLai Jiangshan 			 "sched RCU or wq->mutex should be held")
35576af4d93STejun Heo 
3565b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
357f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
358f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
359f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
3605b95e1afSLai Jiangshan 			 "sched RCU, wq->mutex or wq_pool_mutex should be held")
3615b95e1afSLai Jiangshan 
362f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
363f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
364f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
3657a62c2c8STejun Heo 	     (pool)++)
3664ce62e9eSTejun Heo 
36749e3cf44STejun Heo /**
36817116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
36917116969STejun Heo  * @pool: iteration cursor
370611c92a0STejun Heo  * @pi: integer used for iteration
371fa1b54e6STejun Heo  *
37268e13a67SLai Jiangshan  * This must be called either with wq_pool_mutex held or sched RCU read
37368e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
37468e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
375fa1b54e6STejun Heo  *
376fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
377fa1b54e6STejun Heo  * ignored.
37817116969STejun Heo  */
379611c92a0STejun Heo #define for_each_pool(pool, pi)						\
380611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
38168e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
382fa1b54e6STejun Heo 		else
38317116969STejun Heo 
38417116969STejun Heo /**
385822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
386822d8405STejun Heo  * @worker: iteration cursor
387822d8405STejun Heo  * @pool: worker_pool to iterate workers of
388822d8405STejun Heo  *
38992f9c5c4SLai Jiangshan  * This must be called with @pool->attach_mutex.
390822d8405STejun Heo  *
391822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
392822d8405STejun Heo  * ignored.
393822d8405STejun Heo  */
394da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
395da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
39692f9c5c4SLai Jiangshan 		if (({ lockdep_assert_held(&pool->attach_mutex); false; })) { } \
397822d8405STejun Heo 		else
398822d8405STejun Heo 
399822d8405STejun Heo /**
40049e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
40149e3cf44STejun Heo  * @pwq: iteration cursor
40249e3cf44STejun Heo  * @wq: the target workqueue
40376af4d93STejun Heo  *
404b09f4fd3SLai Jiangshan  * This must be called either with wq->mutex held or sched RCU read locked.
405794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
406794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
40776af4d93STejun Heo  *
40876af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
40976af4d93STejun Heo  * ignored.
41049e3cf44STejun Heo  */
41149e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
41276af4d93STejun Heo 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node)		\
413b09f4fd3SLai Jiangshan 		if (({ assert_rcu_or_wq_mutex(wq); false; })) { }	\
41476af4d93STejun Heo 		else
415f3421797STejun Heo 
416dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
417dc186ad7SThomas Gleixner 
418dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr;
419dc186ad7SThomas Gleixner 
42099777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
42199777288SStanislaw Gruszka {
42299777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
42399777288SStanislaw Gruszka }
42499777288SStanislaw Gruszka 
425dc186ad7SThomas Gleixner /*
426dc186ad7SThomas Gleixner  * fixup_init is called when:
427dc186ad7SThomas Gleixner  * - an active object is initialized
428dc186ad7SThomas Gleixner  */
429dc186ad7SThomas Gleixner static int work_fixup_init(void *addr, enum debug_obj_state state)
430dc186ad7SThomas Gleixner {
431dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
432dc186ad7SThomas Gleixner 
433dc186ad7SThomas Gleixner 	switch (state) {
434dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
435dc186ad7SThomas Gleixner 		cancel_work_sync(work);
436dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
437dc186ad7SThomas Gleixner 		return 1;
438dc186ad7SThomas Gleixner 	default:
439dc186ad7SThomas Gleixner 		return 0;
440dc186ad7SThomas Gleixner 	}
441dc186ad7SThomas Gleixner }
442dc186ad7SThomas Gleixner 
443dc186ad7SThomas Gleixner /*
444dc186ad7SThomas Gleixner  * fixup_activate is called when:
445dc186ad7SThomas Gleixner  * - an active object is activated
446dc186ad7SThomas Gleixner  * - an unknown object is activated (might be a statically initialized object)
447dc186ad7SThomas Gleixner  */
448dc186ad7SThomas Gleixner static int work_fixup_activate(void *addr, enum debug_obj_state state)
449dc186ad7SThomas Gleixner {
450dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
451dc186ad7SThomas Gleixner 
452dc186ad7SThomas Gleixner 	switch (state) {
453dc186ad7SThomas Gleixner 
454dc186ad7SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
455dc186ad7SThomas Gleixner 		/*
456dc186ad7SThomas Gleixner 		 * This is not really a fixup. The work struct was
457dc186ad7SThomas Gleixner 		 * statically initialized. We just make sure that it
458dc186ad7SThomas Gleixner 		 * is tracked in the object tracker.
459dc186ad7SThomas Gleixner 		 */
46022df02bbSTejun Heo 		if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
461dc186ad7SThomas Gleixner 			debug_object_init(work, &work_debug_descr);
462dc186ad7SThomas Gleixner 			debug_object_activate(work, &work_debug_descr);
463dc186ad7SThomas Gleixner 			return 0;
464dc186ad7SThomas Gleixner 		}
465dc186ad7SThomas Gleixner 		WARN_ON_ONCE(1);
466dc186ad7SThomas Gleixner 		return 0;
467dc186ad7SThomas Gleixner 
468dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
469dc186ad7SThomas Gleixner 		WARN_ON(1);
470dc186ad7SThomas Gleixner 
471dc186ad7SThomas Gleixner 	default:
472dc186ad7SThomas Gleixner 		return 0;
473dc186ad7SThomas Gleixner 	}
474dc186ad7SThomas Gleixner }
475dc186ad7SThomas Gleixner 
476dc186ad7SThomas Gleixner /*
477dc186ad7SThomas Gleixner  * fixup_free is called when:
478dc186ad7SThomas Gleixner  * - an active object is freed
479dc186ad7SThomas Gleixner  */
480dc186ad7SThomas Gleixner static int work_fixup_free(void *addr, enum debug_obj_state state)
481dc186ad7SThomas Gleixner {
482dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
483dc186ad7SThomas Gleixner 
484dc186ad7SThomas Gleixner 	switch (state) {
485dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
486dc186ad7SThomas Gleixner 		cancel_work_sync(work);
487dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
488dc186ad7SThomas Gleixner 		return 1;
489dc186ad7SThomas Gleixner 	default:
490dc186ad7SThomas Gleixner 		return 0;
491dc186ad7SThomas Gleixner 	}
492dc186ad7SThomas Gleixner }
493dc186ad7SThomas Gleixner 
494dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr = {
495dc186ad7SThomas Gleixner 	.name		= "work_struct",
49699777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
497dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
498dc186ad7SThomas Gleixner 	.fixup_activate	= work_fixup_activate,
499dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
500dc186ad7SThomas Gleixner };
501dc186ad7SThomas Gleixner 
502dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
503dc186ad7SThomas Gleixner {
504dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
505dc186ad7SThomas Gleixner }
506dc186ad7SThomas Gleixner 
507dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
508dc186ad7SThomas Gleixner {
509dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
510dc186ad7SThomas Gleixner }
511dc186ad7SThomas Gleixner 
512dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
513dc186ad7SThomas Gleixner {
514dc186ad7SThomas Gleixner 	if (onstack)
515dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
516dc186ad7SThomas Gleixner 	else
517dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
518dc186ad7SThomas Gleixner }
519dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
520dc186ad7SThomas Gleixner 
521dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
522dc186ad7SThomas Gleixner {
523dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
524dc186ad7SThomas Gleixner }
525dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
526dc186ad7SThomas Gleixner 
527ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
528ea2e64f2SThomas Gleixner {
529ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
530ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
531ea2e64f2SThomas Gleixner }
532ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
533ea2e64f2SThomas Gleixner 
534dc186ad7SThomas Gleixner #else
535dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
536dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
537dc186ad7SThomas Gleixner #endif
538dc186ad7SThomas Gleixner 
5394e8b22bdSLi Bin /**
5404e8b22bdSLi Bin  * worker_pool_assign_id - allocate ID and assing it to @pool
5414e8b22bdSLi Bin  * @pool: the pool pointer of interest
5424e8b22bdSLi Bin  *
5434e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
5444e8b22bdSLi Bin  * successfully, -errno on failure.
5454e8b22bdSLi Bin  */
5469daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
5479daf9e67STejun Heo {
5489daf9e67STejun Heo 	int ret;
5499daf9e67STejun Heo 
55068e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5515bcab335STejun Heo 
5524e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
5534e8b22bdSLi Bin 			GFP_KERNEL);
554229641a6STejun Heo 	if (ret >= 0) {
555e68035fbSTejun Heo 		pool->id = ret;
556229641a6STejun Heo 		return 0;
557229641a6STejun Heo 	}
5589daf9e67STejun Heo 	return ret;
5599daf9e67STejun Heo }
5609daf9e67STejun Heo 
56176af4d93STejun Heo /**
562df2d5ae4STejun Heo  * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
563df2d5ae4STejun Heo  * @wq: the target workqueue
564df2d5ae4STejun Heo  * @node: the node ID
565df2d5ae4STejun Heo  *
5665b95e1afSLai Jiangshan  * This must be called with any of wq_pool_mutex, wq->mutex or sched RCU
5675b95e1afSLai Jiangshan  * read locked.
568df2d5ae4STejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
569df2d5ae4STejun Heo  * responsible for guaranteeing that the pwq stays online.
570d185af30SYacine Belkadi  *
571d185af30SYacine Belkadi  * Return: The unbound pool_workqueue for @node.
572df2d5ae4STejun Heo  */
573df2d5ae4STejun Heo static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
574df2d5ae4STejun Heo 						  int node)
575df2d5ae4STejun Heo {
5765b95e1afSLai Jiangshan 	assert_rcu_or_wq_mutex_or_pool_mutex(wq);
577df2d5ae4STejun Heo 	return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
578df2d5ae4STejun Heo }
579df2d5ae4STejun Heo 
58073f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
58173f53c4aSTejun Heo {
58273f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
58373f53c4aSTejun Heo }
58473f53c4aSTejun Heo 
58573f53c4aSTejun Heo static int get_work_color(struct work_struct *work)
58673f53c4aSTejun Heo {
58773f53c4aSTejun Heo 	return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
58873f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
58973f53c4aSTejun Heo }
59073f53c4aSTejun Heo 
59173f53c4aSTejun Heo static int work_next_color(int color)
59273f53c4aSTejun Heo {
59373f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
594a848e3b6SOleg Nesterov }
595a848e3b6SOleg Nesterov 
5964594bf15SDavid Howells /*
597112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
598112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
5997c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
6007a22ad75STejun Heo  *
601112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
602112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
603bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
604bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
6057a22ad75STejun Heo  *
606112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6077c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
608112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
6097c3eed5cSTejun Heo  * available only while the work item is queued.
610bbb68dfaSTejun Heo  *
611bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
612bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
613bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
614bbb68dfaSTejun Heo  * try to steal the PENDING bit.
6154594bf15SDavid Howells  */
6167a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6177a22ad75STejun Heo 				 unsigned long flags)
6187a22ad75STejun Heo {
6196183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
6207a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
6217a22ad75STejun Heo }
6227a22ad75STejun Heo 
623112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6244690c4abSTejun Heo 			 unsigned long extra_flags)
625365970a1SDavid Howells {
626112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
627112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
628365970a1SDavid Howells }
629365970a1SDavid Howells 
6304468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6314468a00fSLai Jiangshan 					   int pool_id)
6324468a00fSLai Jiangshan {
6334468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6344468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6354468a00fSLai Jiangshan }
6364468a00fSLai Jiangshan 
6377c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6387c3eed5cSTejun Heo 					    int pool_id)
6394d707b9fSOleg Nesterov {
64023657bb1STejun Heo 	/*
64123657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
64223657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
64323657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
64423657bb1STejun Heo 	 * owner.
64523657bb1STejun Heo 	 */
64623657bb1STejun Heo 	smp_wmb();
6477c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
6484d707b9fSOleg Nesterov }
6494d707b9fSOleg Nesterov 
6507a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
651365970a1SDavid Howells {
6527c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
6537c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
6547a22ad75STejun Heo }
6557a22ad75STejun Heo 
656112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
6577a22ad75STejun Heo {
658e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
6597a22ad75STejun Heo 
660112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
661e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
662e120153dSTejun Heo 	else
663e120153dSTejun Heo 		return NULL;
6647a22ad75STejun Heo }
6657a22ad75STejun Heo 
6667c3eed5cSTejun Heo /**
6677c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
6687c3eed5cSTejun Heo  * @work: the work item of interest
6697c3eed5cSTejun Heo  *
67068e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
67168e13a67SLai Jiangshan  * access under sched-RCU read lock.  As such, this function should be
67268e13a67SLai Jiangshan  * called under wq_pool_mutex or with preemption disabled.
673fa1b54e6STejun Heo  *
674fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
675fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
676fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
677fa1b54e6STejun Heo  * returned pool is and stays online.
678d185af30SYacine Belkadi  *
679d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
6807c3eed5cSTejun Heo  */
6817c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
6827a22ad75STejun Heo {
683e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
6847c3eed5cSTejun Heo 	int pool_id;
6857a22ad75STejun Heo 
68668e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
687fa1b54e6STejun Heo 
688112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
689112202d9STejun Heo 		return ((struct pool_workqueue *)
6907c3eed5cSTejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool;
6917a22ad75STejun Heo 
6927c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
6937c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
6947a22ad75STejun Heo 		return NULL;
6957a22ad75STejun Heo 
696fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
6977c3eed5cSTejun Heo }
6987c3eed5cSTejun Heo 
6997c3eed5cSTejun Heo /**
7007c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
7017c3eed5cSTejun Heo  * @work: the work item of interest
7027c3eed5cSTejun Heo  *
703d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
7047c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
7057c3eed5cSTejun Heo  */
7067c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
7077c3eed5cSTejun Heo {
70854d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
7097c3eed5cSTejun Heo 
710112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
711112202d9STejun Heo 		return ((struct pool_workqueue *)
71254d5b7d0SLai Jiangshan 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
71354d5b7d0SLai Jiangshan 
71454d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
7157c3eed5cSTejun Heo }
7167c3eed5cSTejun Heo 
717bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
718bbb68dfaSTejun Heo {
7197c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
720bbb68dfaSTejun Heo 
7217c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
7227c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
723bbb68dfaSTejun Heo }
724bbb68dfaSTejun Heo 
725bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
726bbb68dfaSTejun Heo {
727bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
728bbb68dfaSTejun Heo 
729112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
730bbb68dfaSTejun Heo }
731bbb68dfaSTejun Heo 
732e22bee78STejun Heo /*
7333270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
7343270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
735d565ed63STejun Heo  * they're being called with pool->lock held.
736e22bee78STejun Heo  */
737e22bee78STejun Heo 
73863d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
739649027d7STejun Heo {
740e19e397aSTejun Heo 	return !atomic_read(&pool->nr_running);
741649027d7STejun Heo }
742649027d7STejun Heo 
743e22bee78STejun Heo /*
744e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
745e22bee78STejun Heo  * running workers.
746974271c4STejun Heo  *
747974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
748706026c2STejun Heo  * function will always return %true for unbound pools as long as the
749974271c4STejun Heo  * worklist isn't empty.
750e22bee78STejun Heo  */
75163d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
752e22bee78STejun Heo {
75363d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
754e22bee78STejun Heo }
755e22bee78STejun Heo 
756e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
75763d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
758e22bee78STejun Heo {
75963d95a91STejun Heo 	return pool->nr_idle;
760e22bee78STejun Heo }
761e22bee78STejun Heo 
762e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
76363d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
764e22bee78STejun Heo {
765e19e397aSTejun Heo 	return !list_empty(&pool->worklist) &&
766e19e397aSTejun Heo 		atomic_read(&pool->nr_running) <= 1;
767e22bee78STejun Heo }
768e22bee78STejun Heo 
769e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
77063d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
771e22bee78STejun Heo {
77263d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
773e22bee78STejun Heo }
774e22bee78STejun Heo 
775e22bee78STejun Heo /* Do we have too many workers and should some go away? */
77663d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
777e22bee78STejun Heo {
77834a06bd6STejun Heo 	bool managing = mutex_is_locked(&pool->manager_arb);
77963d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
78063d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
781e22bee78STejun Heo 
782e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
783e22bee78STejun Heo }
784e22bee78STejun Heo 
785e22bee78STejun Heo /*
786e22bee78STejun Heo  * Wake up functions.
787e22bee78STejun Heo  */
788e22bee78STejun Heo 
7891037de36SLai Jiangshan /* Return the first idle worker.  Safe with preemption disabled */
7901037de36SLai Jiangshan static struct worker *first_idle_worker(struct worker_pool *pool)
7917e11629dSTejun Heo {
79263d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
7937e11629dSTejun Heo 		return NULL;
7947e11629dSTejun Heo 
79563d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
7967e11629dSTejun Heo }
7977e11629dSTejun Heo 
7987e11629dSTejun Heo /**
7997e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
80063d95a91STejun Heo  * @pool: worker pool to wake worker from
8017e11629dSTejun Heo  *
80263d95a91STejun Heo  * Wake up the first idle worker of @pool.
8037e11629dSTejun Heo  *
8047e11629dSTejun Heo  * CONTEXT:
805d565ed63STejun Heo  * spin_lock_irq(pool->lock).
8067e11629dSTejun Heo  */
80763d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
8087e11629dSTejun Heo {
8091037de36SLai Jiangshan 	struct worker *worker = first_idle_worker(pool);
8107e11629dSTejun Heo 
8117e11629dSTejun Heo 	if (likely(worker))
8127e11629dSTejun Heo 		wake_up_process(worker->task);
8137e11629dSTejun Heo }
8147e11629dSTejun Heo 
8154690c4abSTejun Heo /**
816e22bee78STejun Heo  * wq_worker_waking_up - a worker is waking up
817e22bee78STejun Heo  * @task: task waking up
818e22bee78STejun Heo  * @cpu: CPU @task is waking up to
819e22bee78STejun Heo  *
820e22bee78STejun Heo  * This function is called during try_to_wake_up() when a worker is
821e22bee78STejun Heo  * being awoken.
822e22bee78STejun Heo  *
823e22bee78STejun Heo  * CONTEXT:
824e22bee78STejun Heo  * spin_lock_irq(rq->lock)
825e22bee78STejun Heo  */
826d84ff051STejun Heo void wq_worker_waking_up(struct task_struct *task, int cpu)
827e22bee78STejun Heo {
828e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
829e22bee78STejun Heo 
83036576000SJoonsoo Kim 	if (!(worker->flags & WORKER_NOT_RUNNING)) {
831ec22ca5eSTejun Heo 		WARN_ON_ONCE(worker->pool->cpu != cpu);
832e19e397aSTejun Heo 		atomic_inc(&worker->pool->nr_running);
833e22bee78STejun Heo 	}
83436576000SJoonsoo Kim }
835e22bee78STejun Heo 
836e22bee78STejun Heo /**
837e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
838e22bee78STejun Heo  * @task: task going to sleep
839e22bee78STejun Heo  * @cpu: CPU in question, must be the current CPU number
840e22bee78STejun Heo  *
841e22bee78STejun Heo  * This function is called during schedule() when a busy worker is
842e22bee78STejun Heo  * going to sleep.  Worker on the same cpu can be woken up by
843e22bee78STejun Heo  * returning pointer to its task.
844e22bee78STejun Heo  *
845e22bee78STejun Heo  * CONTEXT:
846e22bee78STejun Heo  * spin_lock_irq(rq->lock)
847e22bee78STejun Heo  *
848d185af30SYacine Belkadi  * Return:
849e22bee78STejun Heo  * Worker task on @cpu to wake up, %NULL if none.
850e22bee78STejun Heo  */
851d84ff051STejun Heo struct task_struct *wq_worker_sleeping(struct task_struct *task, int cpu)
852e22bee78STejun Heo {
853e22bee78STejun Heo 	struct worker *worker = kthread_data(task), *to_wakeup = NULL;
854111c225aSTejun Heo 	struct worker_pool *pool;
855e22bee78STejun Heo 
856111c225aSTejun Heo 	/*
857111c225aSTejun Heo 	 * Rescuers, which may not have all the fields set up like normal
858111c225aSTejun Heo 	 * workers, also reach here, let's not access anything before
859111c225aSTejun Heo 	 * checking NOT_RUNNING.
860111c225aSTejun Heo 	 */
8612d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
862e22bee78STejun Heo 		return NULL;
863e22bee78STejun Heo 
864111c225aSTejun Heo 	pool = worker->pool;
865111c225aSTejun Heo 
866e22bee78STejun Heo 	/* this can only happen on the local cpu */
86792b69f50SLai Jiangshan 	if (WARN_ON_ONCE(cpu != raw_smp_processor_id() || pool->cpu != cpu))
8686183c009STejun Heo 		return NULL;
869e22bee78STejun Heo 
870e22bee78STejun Heo 	/*
871e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
872e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
873e22bee78STejun Heo 	 * Please read comment there.
874e22bee78STejun Heo 	 *
875628c78e7STejun Heo 	 * NOT_RUNNING is clear.  This means that we're bound to and
876628c78e7STejun Heo 	 * running on the local cpu w/ rq lock held and preemption
877628c78e7STejun Heo 	 * disabled, which in turn means that none else could be
878d565ed63STejun Heo 	 * manipulating idle_list, so dereferencing idle_list without pool
879628c78e7STejun Heo 	 * lock is safe.
880e22bee78STejun Heo 	 */
881e19e397aSTejun Heo 	if (atomic_dec_and_test(&pool->nr_running) &&
882e19e397aSTejun Heo 	    !list_empty(&pool->worklist))
8831037de36SLai Jiangshan 		to_wakeup = first_idle_worker(pool);
884e22bee78STejun Heo 	return to_wakeup ? to_wakeup->task : NULL;
885e22bee78STejun Heo }
886e22bee78STejun Heo 
887e22bee78STejun Heo /**
888e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
889cb444766STejun Heo  * @worker: self
890d302f017STejun Heo  * @flags: flags to set
891d302f017STejun Heo  *
892228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
893d302f017STejun Heo  *
894cb444766STejun Heo  * CONTEXT:
895d565ed63STejun Heo  * spin_lock_irq(pool->lock)
896d302f017STejun Heo  */
897228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
898d302f017STejun Heo {
899bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
900e22bee78STejun Heo 
901cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
902cb444766STejun Heo 
903228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
904e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
905e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
906e19e397aSTejun Heo 		atomic_dec(&pool->nr_running);
907e22bee78STejun Heo 	}
908e22bee78STejun Heo 
909d302f017STejun Heo 	worker->flags |= flags;
910d302f017STejun Heo }
911d302f017STejun Heo 
912d302f017STejun Heo /**
913e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
914cb444766STejun Heo  * @worker: self
915d302f017STejun Heo  * @flags: flags to clear
916d302f017STejun Heo  *
917e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
918d302f017STejun Heo  *
919cb444766STejun Heo  * CONTEXT:
920d565ed63STejun Heo  * spin_lock_irq(pool->lock)
921d302f017STejun Heo  */
922d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
923d302f017STejun Heo {
92463d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
925e22bee78STejun Heo 	unsigned int oflags = worker->flags;
926e22bee78STejun Heo 
927cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
928cb444766STejun Heo 
929d302f017STejun Heo 	worker->flags &= ~flags;
930e22bee78STejun Heo 
93142c025f3STejun Heo 	/*
93242c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
93342c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
93442c025f3STejun Heo 	 * of multiple flags, not a single flag.
93542c025f3STejun Heo 	 */
936e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
937e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
938e19e397aSTejun Heo 			atomic_inc(&pool->nr_running);
939d302f017STejun Heo }
940d302f017STejun Heo 
941d302f017STejun Heo /**
9428cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
943c9e7cf27STejun Heo  * @pool: pool of interest
9448cca0eeaSTejun Heo  * @work: work to find worker for
9458cca0eeaSTejun Heo  *
946c9e7cf27STejun Heo  * Find a worker which is executing @work on @pool by searching
947c9e7cf27STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
948a2c1c57bSTejun Heo  * to match, its current execution should match the address of @work and
949a2c1c57bSTejun Heo  * its work function.  This is to avoid unwanted dependency between
950a2c1c57bSTejun Heo  * unrelated work executions through a work item being recycled while still
951a2c1c57bSTejun Heo  * being executed.
952a2c1c57bSTejun Heo  *
953a2c1c57bSTejun Heo  * This is a bit tricky.  A work item may be freed once its execution
954a2c1c57bSTejun Heo  * starts and nothing prevents the freed area from being recycled for
955a2c1c57bSTejun Heo  * another work item.  If the same work item address ends up being reused
956a2c1c57bSTejun Heo  * before the original execution finishes, workqueue will identify the
957a2c1c57bSTejun Heo  * recycled work item as currently executing and make it wait until the
958a2c1c57bSTejun Heo  * current execution finishes, introducing an unwanted dependency.
959a2c1c57bSTejun Heo  *
960c5aa87bbSTejun Heo  * This function checks the work item address and work function to avoid
961c5aa87bbSTejun Heo  * false positives.  Note that this isn't complete as one may construct a
962c5aa87bbSTejun Heo  * work function which can introduce dependency onto itself through a
963c5aa87bbSTejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
964c5aa87bbSTejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
965c5aa87bbSTejun Heo  * actually occurs, it should be easy to locate the culprit work function.
9668cca0eeaSTejun Heo  *
9678cca0eeaSTejun Heo  * CONTEXT:
968d565ed63STejun Heo  * spin_lock_irq(pool->lock).
9698cca0eeaSTejun Heo  *
970d185af30SYacine Belkadi  * Return:
971d185af30SYacine Belkadi  * Pointer to worker which is executing @work if found, %NULL
9728cca0eeaSTejun Heo  * otherwise.
9738cca0eeaSTejun Heo  */
974c9e7cf27STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
9758cca0eeaSTejun Heo 						 struct work_struct *work)
9768cca0eeaSTejun Heo {
97742f8570fSSasha Levin 	struct worker *worker;
97842f8570fSSasha Levin 
979b67bfe0dSSasha Levin 	hash_for_each_possible(pool->busy_hash, worker, hentry,
980a2c1c57bSTejun Heo 			       (unsigned long)work)
981a2c1c57bSTejun Heo 		if (worker->current_work == work &&
982a2c1c57bSTejun Heo 		    worker->current_func == work->func)
98342f8570fSSasha Levin 			return worker;
98442f8570fSSasha Levin 
98542f8570fSSasha Levin 	return NULL;
9868cca0eeaSTejun Heo }
9878cca0eeaSTejun Heo 
9888cca0eeaSTejun Heo /**
989bf4ede01STejun Heo  * move_linked_works - move linked works to a list
990bf4ede01STejun Heo  * @work: start of series of works to be scheduled
991bf4ede01STejun Heo  * @head: target list to append @work to
992402dd89dSShailendra Verma  * @nextp: out parameter for nested worklist walking
993bf4ede01STejun Heo  *
994bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
995bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
996bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
997bf4ede01STejun Heo  *
998bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
999bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
1000bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
1001bf4ede01STejun Heo  *
1002bf4ede01STejun Heo  * CONTEXT:
1003d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1004bf4ede01STejun Heo  */
1005bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1006bf4ede01STejun Heo 			      struct work_struct **nextp)
1007bf4ede01STejun Heo {
1008bf4ede01STejun Heo 	struct work_struct *n;
1009bf4ede01STejun Heo 
1010bf4ede01STejun Heo 	/*
1011bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
1012bf4ede01STejun Heo 	 * use NULL for list head.
1013bf4ede01STejun Heo 	 */
1014bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1015bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
1016bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1017bf4ede01STejun Heo 			break;
1018bf4ede01STejun Heo 	}
1019bf4ede01STejun Heo 
1020bf4ede01STejun Heo 	/*
1021bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
1022bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
1023bf4ede01STejun Heo 	 * needs to be updated.
1024bf4ede01STejun Heo 	 */
1025bf4ede01STejun Heo 	if (nextp)
1026bf4ede01STejun Heo 		*nextp = n;
1027bf4ede01STejun Heo }
1028bf4ede01STejun Heo 
10298864b4e5STejun Heo /**
10308864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
10318864b4e5STejun Heo  * @pwq: pool_workqueue to get
10328864b4e5STejun Heo  *
10338864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
10348864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
10358864b4e5STejun Heo  */
10368864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
10378864b4e5STejun Heo {
10388864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
10398864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
10408864b4e5STejun Heo 	pwq->refcnt++;
10418864b4e5STejun Heo }
10428864b4e5STejun Heo 
10438864b4e5STejun Heo /**
10448864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
10458864b4e5STejun Heo  * @pwq: pool_workqueue to put
10468864b4e5STejun Heo  *
10478864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
10488864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
10498864b4e5STejun Heo  */
10508864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
10518864b4e5STejun Heo {
10528864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
10538864b4e5STejun Heo 	if (likely(--pwq->refcnt))
10548864b4e5STejun Heo 		return;
10558864b4e5STejun Heo 	if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
10568864b4e5STejun Heo 		return;
10578864b4e5STejun Heo 	/*
10588864b4e5STejun Heo 	 * @pwq can't be released under pool->lock, bounce to
10598864b4e5STejun Heo 	 * pwq_unbound_release_workfn().  This never recurses on the same
10608864b4e5STejun Heo 	 * pool->lock as this path is taken only for unbound workqueues and
10618864b4e5STejun Heo 	 * the release work item is scheduled on a per-cpu workqueue.  To
10628864b4e5STejun Heo 	 * avoid lockdep warning, unbound pool->locks are given lockdep
10638864b4e5STejun Heo 	 * subclass of 1 in get_unbound_pool().
10648864b4e5STejun Heo 	 */
10658864b4e5STejun Heo 	schedule_work(&pwq->unbound_release_work);
10668864b4e5STejun Heo }
10678864b4e5STejun Heo 
1068dce90d47STejun Heo /**
1069dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1070dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1071dce90d47STejun Heo  *
1072dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1073dce90d47STejun Heo  */
1074dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1075dce90d47STejun Heo {
1076dce90d47STejun Heo 	if (pwq) {
1077dce90d47STejun Heo 		/*
1078dce90d47STejun Heo 		 * As both pwqs and pools are sched-RCU protected, the
1079dce90d47STejun Heo 		 * following lock operations are safe.
1080dce90d47STejun Heo 		 */
1081dce90d47STejun Heo 		spin_lock_irq(&pwq->pool->lock);
1082dce90d47STejun Heo 		put_pwq(pwq);
1083dce90d47STejun Heo 		spin_unlock_irq(&pwq->pool->lock);
1084dce90d47STejun Heo 	}
1085dce90d47STejun Heo }
1086dce90d47STejun Heo 
1087112202d9STejun Heo static void pwq_activate_delayed_work(struct work_struct *work)
1088bf4ede01STejun Heo {
1089112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1090bf4ede01STejun Heo 
1091bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
109282607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
109382607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1094112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
1095bf4ede01STejun Heo 	__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1096112202d9STejun Heo 	pwq->nr_active++;
1097bf4ede01STejun Heo }
1098bf4ede01STejun Heo 
1099112202d9STejun Heo static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
11003aa62497SLai Jiangshan {
1101112202d9STejun Heo 	struct work_struct *work = list_first_entry(&pwq->delayed_works,
11023aa62497SLai Jiangshan 						    struct work_struct, entry);
11033aa62497SLai Jiangshan 
1104112202d9STejun Heo 	pwq_activate_delayed_work(work);
11053aa62497SLai Jiangshan }
11063aa62497SLai Jiangshan 
1107bf4ede01STejun Heo /**
1108112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1109112202d9STejun Heo  * @pwq: pwq of interest
1110bf4ede01STejun Heo  * @color: color of work which left the queue
1111bf4ede01STejun Heo  *
1112bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1113112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1114bf4ede01STejun Heo  *
1115bf4ede01STejun Heo  * CONTEXT:
1116d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1117bf4ede01STejun Heo  */
1118112202d9STejun Heo static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1119bf4ede01STejun Heo {
11208864b4e5STejun Heo 	/* uncolored work items don't participate in flushing or nr_active */
1121bf4ede01STejun Heo 	if (color == WORK_NO_COLOR)
11228864b4e5STejun Heo 		goto out_put;
1123bf4ede01STejun Heo 
1124112202d9STejun Heo 	pwq->nr_in_flight[color]--;
1125bf4ede01STejun Heo 
1126112202d9STejun Heo 	pwq->nr_active--;
1127112202d9STejun Heo 	if (!list_empty(&pwq->delayed_works)) {
1128bf4ede01STejun Heo 		/* one down, submit a delayed one */
1129112202d9STejun Heo 		if (pwq->nr_active < pwq->max_active)
1130112202d9STejun Heo 			pwq_activate_first_delayed(pwq);
1131bf4ede01STejun Heo 	}
1132bf4ede01STejun Heo 
1133bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1134112202d9STejun Heo 	if (likely(pwq->flush_color != color))
11358864b4e5STejun Heo 		goto out_put;
1136bf4ede01STejun Heo 
1137bf4ede01STejun Heo 	/* are there still in-flight works? */
1138112202d9STejun Heo 	if (pwq->nr_in_flight[color])
11398864b4e5STejun Heo 		goto out_put;
1140bf4ede01STejun Heo 
1141112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1142112202d9STejun Heo 	pwq->flush_color = -1;
1143bf4ede01STejun Heo 
1144bf4ede01STejun Heo 	/*
1145112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1146bf4ede01STejun Heo 	 * will handle the rest.
1147bf4ede01STejun Heo 	 */
1148112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1149112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
11508864b4e5STejun Heo out_put:
11518864b4e5STejun Heo 	put_pwq(pwq);
1152bf4ede01STejun Heo }
1153bf4ede01STejun Heo 
115436e227d2STejun Heo /**
1155bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
115636e227d2STejun Heo  * @work: work item to steal
115736e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1158bbb68dfaSTejun Heo  * @flags: place to store irq state
115936e227d2STejun Heo  *
116036e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1161d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
116236e227d2STejun Heo  *
1163d185af30SYacine Belkadi  * Return:
116436e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
116536e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
116636e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1167bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1168bbb68dfaSTejun Heo  *		for arbitrarily long
116936e227d2STejun Heo  *
1170d185af30SYacine Belkadi  * Note:
1171bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1172e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1173e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1174e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1175bbb68dfaSTejun Heo  *
1176bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1177bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1178bbb68dfaSTejun Heo  *
1179e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1180bf4ede01STejun Heo  */
1181bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1182bbb68dfaSTejun Heo 			       unsigned long *flags)
1183bf4ede01STejun Heo {
1184d565ed63STejun Heo 	struct worker_pool *pool;
1185112202d9STejun Heo 	struct pool_workqueue *pwq;
1186bf4ede01STejun Heo 
1187bbb68dfaSTejun Heo 	local_irq_save(*flags);
1188bbb68dfaSTejun Heo 
118936e227d2STejun Heo 	/* try to steal the timer if it exists */
119036e227d2STejun Heo 	if (is_dwork) {
119136e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
119236e227d2STejun Heo 
1193e0aecdd8STejun Heo 		/*
1194e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1195e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1196e0aecdd8STejun Heo 		 * running on the local CPU.
1197e0aecdd8STejun Heo 		 */
119836e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
119936e227d2STejun Heo 			return 1;
120036e227d2STejun Heo 	}
120136e227d2STejun Heo 
120236e227d2STejun Heo 	/* try to claim PENDING the normal way */
1203bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1204bf4ede01STejun Heo 		return 0;
1205bf4ede01STejun Heo 
1206bf4ede01STejun Heo 	/*
1207bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1208bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1209bf4ede01STejun Heo 	 */
1210d565ed63STejun Heo 	pool = get_work_pool(work);
1211d565ed63STejun Heo 	if (!pool)
1212bbb68dfaSTejun Heo 		goto fail;
1213bf4ede01STejun Heo 
1214d565ed63STejun Heo 	spin_lock(&pool->lock);
1215bf4ede01STejun Heo 	/*
1216112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1217112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1218112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1219112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1220112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
12210b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1222bf4ede01STejun Heo 	 */
1223112202d9STejun Heo 	pwq = get_work_pwq(work);
1224112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1225bf4ede01STejun Heo 		debug_work_deactivate(work);
12263aa62497SLai Jiangshan 
12273aa62497SLai Jiangshan 		/*
122816062836STejun Heo 		 * A delayed work item cannot be grabbed directly because
122916062836STejun Heo 		 * it might have linked NO_COLOR work items which, if left
1230112202d9STejun Heo 		 * on the delayed_list, will confuse pwq->nr_active
123116062836STejun Heo 		 * management later on and cause stall.  Make sure the work
123216062836STejun Heo 		 * item is activated before grabbing.
12333aa62497SLai Jiangshan 		 */
12343aa62497SLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1235112202d9STejun Heo 			pwq_activate_delayed_work(work);
12363aa62497SLai Jiangshan 
1237bf4ede01STejun Heo 		list_del_init(&work->entry);
12389c34a704SLai Jiangshan 		pwq_dec_nr_in_flight(pwq, get_work_color(work));
123936e227d2STejun Heo 
1240112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
12414468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
12424468a00fSLai Jiangshan 
1243d565ed63STejun Heo 		spin_unlock(&pool->lock);
124436e227d2STejun Heo 		return 1;
1245bf4ede01STejun Heo 	}
1246d565ed63STejun Heo 	spin_unlock(&pool->lock);
1247bbb68dfaSTejun Heo fail:
1248bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1249bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1250bbb68dfaSTejun Heo 		return -ENOENT;
1251bbb68dfaSTejun Heo 	cpu_relax();
125236e227d2STejun Heo 	return -EAGAIN;
1253bf4ede01STejun Heo }
1254bf4ede01STejun Heo 
1255bf4ede01STejun Heo /**
1256706026c2STejun Heo  * insert_work - insert a work into a pool
1257112202d9STejun Heo  * @pwq: pwq @work belongs to
12584690c4abSTejun Heo  * @work: work to insert
12594690c4abSTejun Heo  * @head: insertion point
12604690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
12614690c4abSTejun Heo  *
1262112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1263706026c2STejun Heo  * work_struct flags.
12644690c4abSTejun Heo  *
12654690c4abSTejun Heo  * CONTEXT:
1266d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1267365970a1SDavid Howells  */
1268112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1269112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1270b89deed3SOleg Nesterov {
1271112202d9STejun Heo 	struct worker_pool *pool = pwq->pool;
1272e1d8aa9fSFrederic Weisbecker 
12734690c4abSTejun Heo 	/* we own @work, set data and link */
1274112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
12751a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
12768864b4e5STejun Heo 	get_pwq(pwq);
1277e22bee78STejun Heo 
1278e22bee78STejun Heo 	/*
1279c5aa87bbSTejun Heo 	 * Ensure either wq_worker_sleeping() sees the above
1280c5aa87bbSTejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers lying
1281c5aa87bbSTejun Heo 	 * around lazily while there are works to be processed.
1282e22bee78STejun Heo 	 */
1283e22bee78STejun Heo 	smp_mb();
1284e22bee78STejun Heo 
128563d95a91STejun Heo 	if (__need_more_worker(pool))
128663d95a91STejun Heo 		wake_up_worker(pool);
1287b89deed3SOleg Nesterov }
1288b89deed3SOleg Nesterov 
1289c8efcc25STejun Heo /*
1290c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
12918d03ecfeSTejun Heo  * same workqueue.
1292c8efcc25STejun Heo  */
1293c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1294c8efcc25STejun Heo {
1295c8efcc25STejun Heo 	struct worker *worker;
1296c8efcc25STejun Heo 
12978d03ecfeSTejun Heo 	worker = current_wq_worker();
1298c8efcc25STejun Heo 	/*
12998d03ecfeSTejun Heo 	 * Return %true iff I'm a worker execuing a work item on @wq.  If
13008d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1301c8efcc25STejun Heo 	 */
1302112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1303c8efcc25STejun Heo }
1304c8efcc25STejun Heo 
1305*ef557180SMike Galbraith /*
1306*ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
1307*ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
1308*ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
1309*ef557180SMike Galbraith  */
1310*ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1311*ef557180SMike Galbraith {
1312*ef557180SMike Galbraith 	int new_cpu;
1313*ef557180SMike Galbraith 
1314*ef557180SMike Galbraith 	if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1315*ef557180SMike Galbraith 		return cpu;
1316*ef557180SMike Galbraith 	if (cpumask_empty(wq_unbound_cpumask))
1317*ef557180SMike Galbraith 		return cpu;
1318*ef557180SMike Galbraith 
1319*ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
1320*ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1321*ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
1322*ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1323*ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
1324*ef557180SMike Galbraith 			return cpu;
1325*ef557180SMike Galbraith 	}
1326*ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
1327*ef557180SMike Galbraith 
1328*ef557180SMike Galbraith 	return new_cpu;
1329*ef557180SMike Galbraith }
1330*ef557180SMike Galbraith 
1331d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
13321da177e4SLinus Torvalds 			 struct work_struct *work)
13331da177e4SLinus Torvalds {
1334112202d9STejun Heo 	struct pool_workqueue *pwq;
1335c9178087STejun Heo 	struct worker_pool *last_pool;
13361e19ffc6STejun Heo 	struct list_head *worklist;
13378a2e8e5dSTejun Heo 	unsigned int work_flags;
1338b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
13398930cabaSTejun Heo 
13408930cabaSTejun Heo 	/*
13418930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
13428930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
13438930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
13448930cabaSTejun Heo 	 * happen with IRQ disabled.
13458930cabaSTejun Heo 	 */
13468930cabaSTejun Heo 	WARN_ON_ONCE(!irqs_disabled());
13471da177e4SLinus Torvalds 
1348dc186ad7SThomas Gleixner 	debug_work_activate(work);
13491e19ffc6STejun Heo 
13509ef28a73SLi Bin 	/* if draining, only works from the same workqueue are allowed */
1351618b01ebSTejun Heo 	if (unlikely(wq->flags & __WQ_DRAINING) &&
1352c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
1353e41e704bSTejun Heo 		return;
13549e8cd2f5STejun Heo retry:
1355df2d5ae4STejun Heo 	if (req_cpu == WORK_CPU_UNBOUND)
1356*ef557180SMike Galbraith 		cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1357df2d5ae4STejun Heo 
1358df2d5ae4STejun Heo 	/* pwq which will be used unless @work is executing elsewhere */
1359df2d5ae4STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
1360c9178087STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1361df2d5ae4STejun Heo 	else
1362df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1363f3421797STejun Heo 
136418aa9effSTejun Heo 	/*
1365c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1366c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1367c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
136818aa9effSTejun Heo 	 */
1369c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1370112202d9STejun Heo 	if (last_pool && last_pool != pwq->pool) {
137118aa9effSTejun Heo 		struct worker *worker;
137218aa9effSTejun Heo 
1373d565ed63STejun Heo 		spin_lock(&last_pool->lock);
137418aa9effSTejun Heo 
1375c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
137618aa9effSTejun Heo 
1377112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1378c9178087STejun Heo 			pwq = worker->current_pwq;
13798594fadeSLai Jiangshan 		} else {
138018aa9effSTejun Heo 			/* meh... not running there, queue here */
1381d565ed63STejun Heo 			spin_unlock(&last_pool->lock);
1382112202d9STejun Heo 			spin_lock(&pwq->pool->lock);
138318aa9effSTejun Heo 		}
13848930cabaSTejun Heo 	} else {
1385112202d9STejun Heo 		spin_lock(&pwq->pool->lock);
13868930cabaSTejun Heo 	}
1387502ca9d8STejun Heo 
13889e8cd2f5STejun Heo 	/*
13899e8cd2f5STejun Heo 	 * pwq is determined and locked.  For unbound pools, we could have
13909e8cd2f5STejun Heo 	 * raced with pwq release and it could already be dead.  If its
13919e8cd2f5STejun Heo 	 * refcnt is zero, repeat pwq selection.  Note that pwqs never die
1392df2d5ae4STejun Heo 	 * without another pwq replacing it in the numa_pwq_tbl or while
1393df2d5ae4STejun Heo 	 * work items are executing on it, so the retrying is guaranteed to
13949e8cd2f5STejun Heo 	 * make forward-progress.
13959e8cd2f5STejun Heo 	 */
13969e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
13979e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
13989e8cd2f5STejun Heo 			spin_unlock(&pwq->pool->lock);
13999e8cd2f5STejun Heo 			cpu_relax();
14009e8cd2f5STejun Heo 			goto retry;
14019e8cd2f5STejun Heo 		}
14029e8cd2f5STejun Heo 		/* oops */
14039e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
14049e8cd2f5STejun Heo 			  wq->name, cpu);
14059e8cd2f5STejun Heo 	}
14069e8cd2f5STejun Heo 
1407112202d9STejun Heo 	/* pwq determined, queue */
1408112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1409502ca9d8STejun Heo 
1410f5b2552bSDan Carpenter 	if (WARN_ON(!list_empty(&work->entry))) {
1411112202d9STejun Heo 		spin_unlock(&pwq->pool->lock);
1412f5b2552bSDan Carpenter 		return;
1413f5b2552bSDan Carpenter 	}
14141e19ffc6STejun Heo 
1415112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1416112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
14171e19ffc6STejun Heo 
1418112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1419cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1420112202d9STejun Heo 		pwq->nr_active++;
1421112202d9STejun Heo 		worklist = &pwq->pool->worklist;
142282607adcSTejun Heo 		if (list_empty(worklist))
142382607adcSTejun Heo 			pwq->pool->watchdog_ts = jiffies;
14248a2e8e5dSTejun Heo 	} else {
14258a2e8e5dSTejun Heo 		work_flags |= WORK_STRUCT_DELAYED;
1426112202d9STejun Heo 		worklist = &pwq->delayed_works;
14278a2e8e5dSTejun Heo 	}
14281e19ffc6STejun Heo 
1429112202d9STejun Heo 	insert_work(pwq, work, worklist, work_flags);
14301e19ffc6STejun Heo 
1431112202d9STejun Heo 	spin_unlock(&pwq->pool->lock);
14321da177e4SLinus Torvalds }
14331da177e4SLinus Torvalds 
14340fcb78c2SRolf Eike Beer /**
1435c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1436c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1437c1a220e7SZhang Rui  * @wq: workqueue to use
1438c1a220e7SZhang Rui  * @work: work to queue
1439c1a220e7SZhang Rui  *
1440c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1441c1a220e7SZhang Rui  * can't go away.
1442d185af30SYacine Belkadi  *
1443d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
1444c1a220e7SZhang Rui  */
1445d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1446d4283e93STejun Heo 		   struct work_struct *work)
1447c1a220e7SZhang Rui {
1448d4283e93STejun Heo 	bool ret = false;
14498930cabaSTejun Heo 	unsigned long flags;
14508930cabaSTejun Heo 
14518930cabaSTejun Heo 	local_irq_save(flags);
1452c1a220e7SZhang Rui 
145322df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
14544690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1455d4283e93STejun Heo 		ret = true;
1456c1a220e7SZhang Rui 	}
14578930cabaSTejun Heo 
14588930cabaSTejun Heo 	local_irq_restore(flags);
1459c1a220e7SZhang Rui 	return ret;
1460c1a220e7SZhang Rui }
1461ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1462c1a220e7SZhang Rui 
1463d8e794dfSTejun Heo void delayed_work_timer_fn(unsigned long __data)
14641da177e4SLinus Torvalds {
146552bad64dSDavid Howells 	struct delayed_work *dwork = (struct delayed_work *)__data;
14661da177e4SLinus Torvalds 
1467e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
146860c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
14691da177e4SLinus Torvalds }
14701438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
14711da177e4SLinus Torvalds 
14727beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
147352bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
14741da177e4SLinus Torvalds {
14757beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
14767beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
14771da177e4SLinus Torvalds 
14787beb2edfSTejun Heo 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
14797beb2edfSTejun Heo 		     timer->data != (unsigned long)dwork);
1480fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1481fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
14827beb2edfSTejun Heo 
14838852aac2STejun Heo 	/*
14848852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
14858852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
14868852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
14878852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
14888852aac2STejun Heo 	 */
14898852aac2STejun Heo 	if (!delay) {
14908852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
14918852aac2STejun Heo 		return;
14928852aac2STejun Heo 	}
14938852aac2STejun Heo 
14947beb2edfSTejun Heo 	timer_stats_timer_set_start_info(&dwork->timer);
14957beb2edfSTejun Heo 
149660c057bcSLai Jiangshan 	dwork->wq = wq;
14971265057fSTejun Heo 	dwork->cpu = cpu;
14987beb2edfSTejun Heo 	timer->expires = jiffies + delay;
14997beb2edfSTejun Heo 
1500041bd12eSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
15017beb2edfSTejun Heo 		add_timer_on(timer, cpu);
1502041bd12eSTejun Heo 	else
1503041bd12eSTejun Heo 		add_timer(timer);
15047beb2edfSTejun Heo }
15051da177e4SLinus Torvalds 
15060fcb78c2SRolf Eike Beer /**
15070fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
15080fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
15090fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1510af9997e4SRandy Dunlap  * @dwork: work to queue
15110fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
15120fcb78c2SRolf Eike Beer  *
1513d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
1514715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1515715f1300STejun Heo  * execution.
15160fcb78c2SRolf Eike Beer  */
1517d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
151852bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
15197a6bc1cdSVenkatesh Pallipadi {
152052bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1521d4283e93STejun Heo 	bool ret = false;
15228930cabaSTejun Heo 	unsigned long flags;
15238930cabaSTejun Heo 
15248930cabaSTejun Heo 	/* read the comment in __queue_work() */
15258930cabaSTejun Heo 	local_irq_save(flags);
15267a6bc1cdSVenkatesh Pallipadi 
152722df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
15287beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1529d4283e93STejun Heo 		ret = true;
15307a6bc1cdSVenkatesh Pallipadi 	}
15318930cabaSTejun Heo 
15328930cabaSTejun Heo 	local_irq_restore(flags);
15337a6bc1cdSVenkatesh Pallipadi 	return ret;
15347a6bc1cdSVenkatesh Pallipadi }
1535ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
15361da177e4SLinus Torvalds 
1537c8e55f36STejun Heo /**
15388376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
15398376fe22STejun Heo  * @cpu: CPU number to execute work on
15408376fe22STejun Heo  * @wq: workqueue to use
15418376fe22STejun Heo  * @dwork: work to queue
15428376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
15438376fe22STejun Heo  *
15448376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
15458376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
15468376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
15478376fe22STejun Heo  * current state.
15488376fe22STejun Heo  *
1549d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
15508376fe22STejun Heo  * pending and its timer was modified.
15518376fe22STejun Heo  *
1552e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
15538376fe22STejun Heo  * See try_to_grab_pending() for details.
15548376fe22STejun Heo  */
15558376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
15568376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
15578376fe22STejun Heo {
15588376fe22STejun Heo 	unsigned long flags;
15598376fe22STejun Heo 	int ret;
15608376fe22STejun Heo 
15618376fe22STejun Heo 	do {
15628376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
15638376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
15648376fe22STejun Heo 
15658376fe22STejun Heo 	if (likely(ret >= 0)) {
15668376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
15678376fe22STejun Heo 		local_irq_restore(flags);
15688376fe22STejun Heo 	}
15698376fe22STejun Heo 
15708376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
15718376fe22STejun Heo 	return ret;
15728376fe22STejun Heo }
15738376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
15748376fe22STejun Heo 
15758376fe22STejun Heo /**
1576c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1577c8e55f36STejun Heo  * @worker: worker which is entering idle state
1578c8e55f36STejun Heo  *
1579c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1580c8e55f36STejun Heo  * necessary.
1581c8e55f36STejun Heo  *
1582c8e55f36STejun Heo  * LOCKING:
1583d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1584c8e55f36STejun Heo  */
1585c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
15861da177e4SLinus Torvalds {
1587bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1588c8e55f36STejun Heo 
15896183c009STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
15906183c009STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
15916183c009STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
15926183c009STejun Heo 		return;
1593c8e55f36STejun Heo 
1594051e1850SLai Jiangshan 	/* can't use worker_set_flags(), also called from create_worker() */
1595cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1596bd7bdd43STejun Heo 	pool->nr_idle++;
1597e22bee78STejun Heo 	worker->last_active = jiffies;
1598c8e55f36STejun Heo 
1599c8e55f36STejun Heo 	/* idle_list is LIFO */
1600bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1601db7bccf4STejun Heo 
160263d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1603628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1604cb444766STejun Heo 
1605544ecf31STejun Heo 	/*
1606706026c2STejun Heo 	 * Sanity check nr_running.  Because wq_unbind_fn() releases
1607d565ed63STejun Heo 	 * pool->lock between setting %WORKER_UNBOUND and zapping
1608628c78e7STejun Heo 	 * nr_running, the warning may trigger spuriously.  Check iff
1609628c78e7STejun Heo 	 * unbind is not in progress.
1610544ecf31STejun Heo 	 */
161124647570STejun Heo 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1612bd7bdd43STejun Heo 		     pool->nr_workers == pool->nr_idle &&
1613e19e397aSTejun Heo 		     atomic_read(&pool->nr_running));
1614c8e55f36STejun Heo }
1615c8e55f36STejun Heo 
1616c8e55f36STejun Heo /**
1617c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1618c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1619c8e55f36STejun Heo  *
1620c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1621c8e55f36STejun Heo  *
1622c8e55f36STejun Heo  * LOCKING:
1623d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1624c8e55f36STejun Heo  */
1625c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1626c8e55f36STejun Heo {
1627bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1628c8e55f36STejun Heo 
16296183c009STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
16306183c009STejun Heo 		return;
1631d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1632bd7bdd43STejun Heo 	pool->nr_idle--;
1633c8e55f36STejun Heo 	list_del_init(&worker->entry);
1634c8e55f36STejun Heo }
1635c8e55f36STejun Heo 
1636f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
1637c34056a3STejun Heo {
1638c34056a3STejun Heo 	struct worker *worker;
1639c34056a3STejun Heo 
1640f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1641c8e55f36STejun Heo 	if (worker) {
1642c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1643affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
1644da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
1645e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1646e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1647c8e55f36STejun Heo 	}
1648c34056a3STejun Heo 	return worker;
1649c34056a3STejun Heo }
1650c34056a3STejun Heo 
1651c34056a3STejun Heo /**
16524736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
16534736cbf7SLai Jiangshan  * @worker: worker to be attached
16544736cbf7SLai Jiangshan  * @pool: the target pool
16554736cbf7SLai Jiangshan  *
16564736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
16574736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
16584736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
16594736cbf7SLai Jiangshan  */
16604736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
16614736cbf7SLai Jiangshan 				   struct worker_pool *pool)
16624736cbf7SLai Jiangshan {
16634736cbf7SLai Jiangshan 	mutex_lock(&pool->attach_mutex);
16644736cbf7SLai Jiangshan 
16654736cbf7SLai Jiangshan 	/*
16664736cbf7SLai Jiangshan 	 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
16674736cbf7SLai Jiangshan 	 * online CPUs.  It'll be re-applied when any of the CPUs come up.
16684736cbf7SLai Jiangshan 	 */
16694736cbf7SLai Jiangshan 	set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
16704736cbf7SLai Jiangshan 
16714736cbf7SLai Jiangshan 	/*
16724736cbf7SLai Jiangshan 	 * The pool->attach_mutex ensures %POOL_DISASSOCIATED remains
16734736cbf7SLai Jiangshan 	 * stable across this function.  See the comments above the
16744736cbf7SLai Jiangshan 	 * flag definition for details.
16754736cbf7SLai Jiangshan 	 */
16764736cbf7SLai Jiangshan 	if (pool->flags & POOL_DISASSOCIATED)
16774736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
16784736cbf7SLai Jiangshan 
16794736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
16804736cbf7SLai Jiangshan 
16814736cbf7SLai Jiangshan 	mutex_unlock(&pool->attach_mutex);
16824736cbf7SLai Jiangshan }
16834736cbf7SLai Jiangshan 
16844736cbf7SLai Jiangshan /**
168560f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
168660f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
168760f5a4bcSLai Jiangshan  * @pool: the pool @worker is attached to
168860f5a4bcSLai Jiangshan  *
16894736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
16904736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
16914736cbf7SLai Jiangshan  * other reference to the pool.
169260f5a4bcSLai Jiangshan  */
169360f5a4bcSLai Jiangshan static void worker_detach_from_pool(struct worker *worker,
169460f5a4bcSLai Jiangshan 				    struct worker_pool *pool)
169560f5a4bcSLai Jiangshan {
169660f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
169760f5a4bcSLai Jiangshan 
169892f9c5c4SLai Jiangshan 	mutex_lock(&pool->attach_mutex);
1699da028469SLai Jiangshan 	list_del(&worker->node);
1700da028469SLai Jiangshan 	if (list_empty(&pool->workers))
170160f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
170292f9c5c4SLai Jiangshan 	mutex_unlock(&pool->attach_mutex);
170360f5a4bcSLai Jiangshan 
1704b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
1705b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1706b62c0751SLai Jiangshan 
170760f5a4bcSLai Jiangshan 	if (detach_completion)
170860f5a4bcSLai Jiangshan 		complete(detach_completion);
170960f5a4bcSLai Jiangshan }
171060f5a4bcSLai Jiangshan 
171160f5a4bcSLai Jiangshan /**
1712c34056a3STejun Heo  * create_worker - create a new workqueue worker
171363d95a91STejun Heo  * @pool: pool the new worker will belong to
1714c34056a3STejun Heo  *
1715051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
1716c34056a3STejun Heo  *
1717c34056a3STejun Heo  * CONTEXT:
1718c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1719c34056a3STejun Heo  *
1720d185af30SYacine Belkadi  * Return:
1721c34056a3STejun Heo  * Pointer to the newly created worker.
1722c34056a3STejun Heo  */
1723bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1724c34056a3STejun Heo {
1725c34056a3STejun Heo 	struct worker *worker = NULL;
1726f3421797STejun Heo 	int id = -1;
1727e3c916a4STejun Heo 	char id_buf[16];
1728c34056a3STejun Heo 
17297cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
17307cda9aaeSLai Jiangshan 	id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL);
1731822d8405STejun Heo 	if (id < 0)
1732c34056a3STejun Heo 		goto fail;
1733c34056a3STejun Heo 
1734f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
1735c34056a3STejun Heo 	if (!worker)
1736c34056a3STejun Heo 		goto fail;
1737c34056a3STejun Heo 
1738bd7bdd43STejun Heo 	worker->pool = pool;
1739c34056a3STejun Heo 	worker->id = id;
1740c34056a3STejun Heo 
174129c91e99STejun Heo 	if (pool->cpu >= 0)
1742e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1743e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
1744f3421797STejun Heo 	else
1745e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1746e3c916a4STejun Heo 
1747f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1748e3c916a4STejun Heo 					      "kworker/%s", id_buf);
1749c34056a3STejun Heo 	if (IS_ERR(worker->task))
1750c34056a3STejun Heo 		goto fail;
1751c34056a3STejun Heo 
175291151228SOleg Nesterov 	set_user_nice(worker->task, pool->attrs->nice);
175325834c73SPeter Zijlstra 	kthread_bind_mask(worker->task, pool->attrs->cpumask);
175491151228SOleg Nesterov 
1755da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
17564736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
1757822d8405STejun Heo 
1758051e1850SLai Jiangshan 	/* start the newly created worker */
1759051e1850SLai Jiangshan 	spin_lock_irq(&pool->lock);
1760051e1850SLai Jiangshan 	worker->pool->nr_workers++;
1761051e1850SLai Jiangshan 	worker_enter_idle(worker);
1762051e1850SLai Jiangshan 	wake_up_process(worker->task);
1763051e1850SLai Jiangshan 	spin_unlock_irq(&pool->lock);
1764051e1850SLai Jiangshan 
1765c34056a3STejun Heo 	return worker;
1766822d8405STejun Heo 
1767c34056a3STejun Heo fail:
17689625ab17SLai Jiangshan 	if (id >= 0)
17697cda9aaeSLai Jiangshan 		ida_simple_remove(&pool->worker_ida, id);
1770c34056a3STejun Heo 	kfree(worker);
1771c34056a3STejun Heo 	return NULL;
1772c34056a3STejun Heo }
1773c34056a3STejun Heo 
1774c34056a3STejun Heo /**
1775c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1776c34056a3STejun Heo  * @worker: worker to be destroyed
1777c34056a3STejun Heo  *
177873eb7fe7SLai Jiangshan  * Destroy @worker and adjust @pool stats accordingly.  The worker should
177973eb7fe7SLai Jiangshan  * be idle.
1780c8e55f36STejun Heo  *
1781c8e55f36STejun Heo  * CONTEXT:
178260f5a4bcSLai Jiangshan  * spin_lock_irq(pool->lock).
1783c34056a3STejun Heo  */
1784c34056a3STejun Heo static void destroy_worker(struct worker *worker)
1785c34056a3STejun Heo {
1786bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1787c34056a3STejun Heo 
1788cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
1789cd549687STejun Heo 
1790c34056a3STejun Heo 	/* sanity check frenzy */
17916183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
179273eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
179373eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
17946183c009STejun Heo 		return;
1795c34056a3STejun Heo 
1796bd7bdd43STejun Heo 	pool->nr_workers--;
1797bd7bdd43STejun Heo 	pool->nr_idle--;
1798c8e55f36STejun Heo 
1799c8e55f36STejun Heo 	list_del_init(&worker->entry);
1800cb444766STejun Heo 	worker->flags |= WORKER_DIE;
180160f5a4bcSLai Jiangshan 	wake_up_process(worker->task);
1802c34056a3STejun Heo }
1803c34056a3STejun Heo 
180463d95a91STejun Heo static void idle_worker_timeout(unsigned long __pool)
1805e22bee78STejun Heo {
180663d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
1807e22bee78STejun Heo 
1808d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1809e22bee78STejun Heo 
18103347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
1811e22bee78STejun Heo 		struct worker *worker;
1812e22bee78STejun Heo 		unsigned long expires;
1813e22bee78STejun Heo 
1814e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
181563d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1816e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1817e22bee78STejun Heo 
18183347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
181963d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
18203347fc9fSLai Jiangshan 			break;
1821e22bee78STejun Heo 		}
18223347fc9fSLai Jiangshan 
18233347fc9fSLai Jiangshan 		destroy_worker(worker);
1824e22bee78STejun Heo 	}
1825e22bee78STejun Heo 
1826d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1827e22bee78STejun Heo }
1828e22bee78STejun Heo 
1829493a1724STejun Heo static void send_mayday(struct work_struct *work)
1830e22bee78STejun Heo {
1831112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1832112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
1833493a1724STejun Heo 
18342e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
1835e22bee78STejun Heo 
1836493008a8STejun Heo 	if (!wq->rescuer)
1837493a1724STejun Heo 		return;
1838e22bee78STejun Heo 
1839e22bee78STejun Heo 	/* mayday mayday mayday */
1840493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
184177668c8bSLai Jiangshan 		/*
184277668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
184377668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
184477668c8bSLai Jiangshan 		 * rescuer is done with it.
184577668c8bSLai Jiangshan 		 */
184677668c8bSLai Jiangshan 		get_pwq(pwq);
1847493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
1848e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
1849493a1724STejun Heo 	}
1850e22bee78STejun Heo }
1851e22bee78STejun Heo 
1852706026c2STejun Heo static void pool_mayday_timeout(unsigned long __pool)
1853e22bee78STejun Heo {
185463d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
1855e22bee78STejun Heo 	struct work_struct *work;
1856e22bee78STejun Heo 
1857b2d82909STejun Heo 	spin_lock_irq(&pool->lock);
1858b2d82909STejun Heo 	spin_lock(&wq_mayday_lock);		/* for wq->maydays */
1859e22bee78STejun Heo 
186063d95a91STejun Heo 	if (need_to_create_worker(pool)) {
1861e22bee78STejun Heo 		/*
1862e22bee78STejun Heo 		 * We've been trying to create a new worker but
1863e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
1864e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
1865e22bee78STejun Heo 		 * rescuers.
1866e22bee78STejun Heo 		 */
186763d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
1868e22bee78STejun Heo 			send_mayday(work);
1869e22bee78STejun Heo 	}
1870e22bee78STejun Heo 
1871b2d82909STejun Heo 	spin_unlock(&wq_mayday_lock);
1872b2d82909STejun Heo 	spin_unlock_irq(&pool->lock);
1873e22bee78STejun Heo 
187463d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1875e22bee78STejun Heo }
1876e22bee78STejun Heo 
1877e22bee78STejun Heo /**
1878e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
187963d95a91STejun Heo  * @pool: pool to create a new worker for
1880e22bee78STejun Heo  *
188163d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
1882e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
1883e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
188463d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
1885e22bee78STejun Heo  * possible allocation deadlock.
1886e22bee78STejun Heo  *
1887c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
1888c5aa87bbSTejun Heo  * may_start_working() %true.
1889e22bee78STejun Heo  *
1890e22bee78STejun Heo  * LOCKING:
1891d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
1892e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
1893e22bee78STejun Heo  * manager.
1894e22bee78STejun Heo  */
189529187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
1896d565ed63STejun Heo __releases(&pool->lock)
1897d565ed63STejun Heo __acquires(&pool->lock)
1898e22bee78STejun Heo {
1899e22bee78STejun Heo restart:
1900d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
19019f9c2364STejun Heo 
1902e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
190363d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1904e22bee78STejun Heo 
1905e22bee78STejun Heo 	while (true) {
1906051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
1907e22bee78STejun Heo 			break;
1908e22bee78STejun Heo 
1909e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
19109f9c2364STejun Heo 
191163d95a91STejun Heo 		if (!need_to_create_worker(pool))
1912e22bee78STejun Heo 			break;
1913e22bee78STejun Heo 	}
1914e22bee78STejun Heo 
191563d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
1916d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1917051e1850SLai Jiangshan 	/*
1918051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
1919051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
1920051e1850SLai Jiangshan 	 * already become busy.
1921051e1850SLai Jiangshan 	 */
192263d95a91STejun Heo 	if (need_to_create_worker(pool))
1923e22bee78STejun Heo 		goto restart;
1924e22bee78STejun Heo }
1925e22bee78STejun Heo 
1926e22bee78STejun Heo /**
1927e22bee78STejun Heo  * manage_workers - manage worker pool
1928e22bee78STejun Heo  * @worker: self
1929e22bee78STejun Heo  *
1930706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
1931e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
1932706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
1933e22bee78STejun Heo  *
1934e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
1935e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
1936e22bee78STejun Heo  * and may_start_working() is true.
1937e22bee78STejun Heo  *
1938e22bee78STejun Heo  * CONTEXT:
1939d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
1940e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
1941e22bee78STejun Heo  *
1942d185af30SYacine Belkadi  * Return:
194329187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
194429187a9eSTejun Heo  * start processing works, %true if management function was performed and
194529187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
194629187a9eSTejun Heo  * no longer be true.
1947e22bee78STejun Heo  */
1948e22bee78STejun Heo static bool manage_workers(struct worker *worker)
1949e22bee78STejun Heo {
195063d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
1951e22bee78STejun Heo 
1952bc3a1afcSTejun Heo 	/*
1953bc3a1afcSTejun Heo 	 * Anyone who successfully grabs manager_arb wins the arbitration
1954bc3a1afcSTejun Heo 	 * and becomes the manager.  mutex_trylock() on pool->manager_arb
1955bc3a1afcSTejun Heo 	 * failure while holding pool->lock reliably indicates that someone
1956bc3a1afcSTejun Heo 	 * else is managing the pool and the worker which failed trylock
1957bc3a1afcSTejun Heo 	 * can proceed to executing work items.  This means that anyone
1958bc3a1afcSTejun Heo 	 * grabbing manager_arb is responsible for actually performing
1959bc3a1afcSTejun Heo 	 * manager duties.  If manager_arb is grabbed and released without
1960bc3a1afcSTejun Heo 	 * actual management, the pool may stall indefinitely.
1961bc3a1afcSTejun Heo 	 */
196234a06bd6STejun Heo 	if (!mutex_trylock(&pool->manager_arb))
196329187a9eSTejun Heo 		return false;
19642607d7a6STejun Heo 	pool->manager = worker;
1965e22bee78STejun Heo 
196629187a9eSTejun Heo 	maybe_create_worker(pool);
1967e22bee78STejun Heo 
19682607d7a6STejun Heo 	pool->manager = NULL;
196934a06bd6STejun Heo 	mutex_unlock(&pool->manager_arb);
197029187a9eSTejun Heo 	return true;
1971e22bee78STejun Heo }
1972e22bee78STejun Heo 
1973a62428c0STejun Heo /**
1974a62428c0STejun Heo  * process_one_work - process single work
1975c34056a3STejun Heo  * @worker: self
1976a62428c0STejun Heo  * @work: work to process
1977a62428c0STejun Heo  *
1978a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
1979a62428c0STejun Heo  * process a single work including synchronization against and
1980a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
1981a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
1982a62428c0STejun Heo  * call this function to process a work.
1983a62428c0STejun Heo  *
1984a62428c0STejun Heo  * CONTEXT:
1985d565ed63STejun Heo  * spin_lock_irq(pool->lock) which is released and regrabbed.
1986a62428c0STejun Heo  */
1987c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
1988d565ed63STejun Heo __releases(&pool->lock)
1989d565ed63STejun Heo __acquires(&pool->lock)
19901da177e4SLinus Torvalds {
1991112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1992bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1993112202d9STejun Heo 	bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
199473f53c4aSTejun Heo 	int work_color;
19957e11629dSTejun Heo 	struct worker *collision;
19964e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
19974e6045f1SJohannes Berg 	/*
1998a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
1999a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2000a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2001a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2002a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
20034e6045f1SJohannes Berg 	 */
20044d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
20054d82a1deSPeter Zijlstra 
20064d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
20074e6045f1SJohannes Berg #endif
2008807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
200985327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2010ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
201125511a47STejun Heo 
20127e11629dSTejun Heo 	/*
20137e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
20147e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
20157e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
20167e11629dSTejun Heo 	 * currently executing one.
20177e11629dSTejun Heo 	 */
2018c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
20197e11629dSTejun Heo 	if (unlikely(collision)) {
20207e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
20217e11629dSTejun Heo 		return;
20227e11629dSTejun Heo 	}
20231da177e4SLinus Torvalds 
20248930cabaSTejun Heo 	/* claim and dequeue */
20251da177e4SLinus Torvalds 	debug_work_deactivate(work);
2026c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2027c34056a3STejun Heo 	worker->current_work = work;
2028a2c1c57bSTejun Heo 	worker->current_func = work->func;
2029112202d9STejun Heo 	worker->current_pwq = pwq;
203073f53c4aSTejun Heo 	work_color = get_work_color(work);
20317a22ad75STejun Heo 
2032a62428c0STejun Heo 	list_del_init(&work->entry);
2033a62428c0STejun Heo 
2034649027d7STejun Heo 	/*
2035228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
2036228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
2037228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
2038228f1d00SLai Jiangshan 	 * execution of the pending work items.
2039fb0e7bebSTejun Heo 	 */
2040fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2041228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2042fb0e7bebSTejun Heo 
2043974271c4STejun Heo 	/*
2044a489a03eSLai Jiangshan 	 * Wake up another worker if necessary.  The condition is always
2045a489a03eSLai Jiangshan 	 * false for normal per-cpu workers since nr_running would always
2046a489a03eSLai Jiangshan 	 * be >= 1 at this point.  This is used to chain execution of the
2047a489a03eSLai Jiangshan 	 * pending work items for WORKER_NOT_RUNNING workers such as the
2048228f1d00SLai Jiangshan 	 * UNBOUND and CPU_INTENSIVE ones.
2049974271c4STejun Heo 	 */
2050a489a03eSLai Jiangshan 	if (need_more_worker(pool))
205163d95a91STejun Heo 		wake_up_worker(pool);
2052974271c4STejun Heo 
20538930cabaSTejun Heo 	/*
20547c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2055d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
205623657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
205723657bb1STejun Heo 	 * disabled.
20588930cabaSTejun Heo 	 */
20597c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
20601da177e4SLinus Torvalds 
2061d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2062365970a1SDavid Howells 
2063112202d9STejun Heo 	lock_map_acquire_read(&pwq->wq->lockdep_map);
20643295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2065e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2066a2c1c57bSTejun Heo 	worker->current_func(work);
2067e36c886aSArjan van de Ven 	/*
2068e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2069e36c886aSArjan van de Ven 	 * point will only record its address.
2070e36c886aSArjan van de Ven 	 */
2071e36c886aSArjan van de Ven 	trace_workqueue_execute_end(work);
20723295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2073112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
20741da177e4SLinus Torvalds 
2075d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2076044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2077044c782cSValentin Ilie 		       "     last function: %pf\n",
2078a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2079a2c1c57bSTejun Heo 		       worker->current_func);
2080d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2081d5abe669SPeter Zijlstra 		dump_stack();
2082d5abe669SPeter Zijlstra 	}
2083d5abe669SPeter Zijlstra 
2084b22ce278STejun Heo 	/*
2085b22ce278STejun Heo 	 * The following prevents a kworker from hogging CPU on !PREEMPT
2086b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
2087b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
2088b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
2089789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
2090789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
2091b22ce278STejun Heo 	 */
20923e28e377SJoe Lawrence 	cond_resched_rcu_qs();
2093b22ce278STejun Heo 
2094d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2095a62428c0STejun Heo 
2096fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2097fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2098fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2099fb0e7bebSTejun Heo 
2100a62428c0STejun Heo 	/* we're done with it, release */
210142f8570fSSasha Levin 	hash_del(&worker->hentry);
2102c34056a3STejun Heo 	worker->current_work = NULL;
2103a2c1c57bSTejun Heo 	worker->current_func = NULL;
2104112202d9STejun Heo 	worker->current_pwq = NULL;
21053d1cb205STejun Heo 	worker->desc_valid = false;
2106112202d9STejun Heo 	pwq_dec_nr_in_flight(pwq, work_color);
21071da177e4SLinus Torvalds }
21081da177e4SLinus Torvalds 
2109affee4b2STejun Heo /**
2110affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2111affee4b2STejun Heo  * @worker: self
2112affee4b2STejun Heo  *
2113affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2114affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2115affee4b2STejun Heo  * fetches a work from the top and executes it.
2116affee4b2STejun Heo  *
2117affee4b2STejun Heo  * CONTEXT:
2118d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2119affee4b2STejun Heo  * multiple times.
2120affee4b2STejun Heo  */
2121affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
21221da177e4SLinus Torvalds {
2123affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2124affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2125a62428c0STejun Heo 						struct work_struct, entry);
2126c34056a3STejun Heo 		process_one_work(worker, work);
2127a62428c0STejun Heo 	}
21281da177e4SLinus Torvalds }
21291da177e4SLinus Torvalds 
21304690c4abSTejun Heo /**
21314690c4abSTejun Heo  * worker_thread - the worker thread function
2132c34056a3STejun Heo  * @__worker: self
21334690c4abSTejun Heo  *
2134c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2135c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2136c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2137c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2138c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
2139d185af30SYacine Belkadi  *
2140d185af30SYacine Belkadi  * Return: 0
21414690c4abSTejun Heo  */
2142c34056a3STejun Heo static int worker_thread(void *__worker)
21431da177e4SLinus Torvalds {
2144c34056a3STejun Heo 	struct worker *worker = __worker;
2145bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
21461da177e4SLinus Torvalds 
2147e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2148e22bee78STejun Heo 	worker->task->flags |= PF_WQ_WORKER;
2149c8e55f36STejun Heo woke_up:
2150d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2151affee4b2STejun Heo 
2152a9ab775bSTejun Heo 	/* am I supposed to die? */
2153a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2154d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
2155a9ab775bSTejun Heo 		WARN_ON_ONCE(!list_empty(&worker->entry));
2156e22bee78STejun Heo 		worker->task->flags &= ~PF_WQ_WORKER;
215760f5a4bcSLai Jiangshan 
215860f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
21597cda9aaeSLai Jiangshan 		ida_simple_remove(&pool->worker_ida, worker->id);
216060f5a4bcSLai Jiangshan 		worker_detach_from_pool(worker, pool);
216160f5a4bcSLai Jiangshan 		kfree(worker);
2162c8e55f36STejun Heo 		return 0;
2163c8e55f36STejun Heo 	}
2164c8e55f36STejun Heo 
2165c8e55f36STejun Heo 	worker_leave_idle(worker);
2166db7bccf4STejun Heo recheck:
2167e22bee78STejun Heo 	/* no more worker necessary? */
216863d95a91STejun Heo 	if (!need_more_worker(pool))
2169e22bee78STejun Heo 		goto sleep;
2170e22bee78STejun Heo 
2171e22bee78STejun Heo 	/* do we need to manage? */
217263d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2173e22bee78STejun Heo 		goto recheck;
2174e22bee78STejun Heo 
2175c8e55f36STejun Heo 	/*
2176c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2177c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2178c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2179c8e55f36STejun Heo 	 */
21806183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2181c8e55f36STejun Heo 
2182e22bee78STejun Heo 	/*
2183a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2184a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2185a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2186a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2187a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2188e22bee78STejun Heo 	 */
2189a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2190e22bee78STejun Heo 
2191e22bee78STejun Heo 	do {
2192affee4b2STejun Heo 		struct work_struct *work =
2193bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2194affee4b2STejun Heo 					 struct work_struct, entry);
2195affee4b2STejun Heo 
219682607adcSTejun Heo 		pool->watchdog_ts = jiffies;
219782607adcSTejun Heo 
2198c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2199affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2200affee4b2STejun Heo 			process_one_work(worker, work);
2201affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2202affee4b2STejun Heo 				process_scheduled_works(worker);
2203affee4b2STejun Heo 		} else {
2204c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2205affee4b2STejun Heo 			process_scheduled_works(worker);
2206affee4b2STejun Heo 		}
220763d95a91STejun Heo 	} while (keep_working(pool));
2208affee4b2STejun Heo 
2209228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
2210d313dd85STejun Heo sleep:
2211c8e55f36STejun Heo 	/*
2212d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2213d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2214d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2215d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2216d565ed63STejun Heo 	 * event.
2217c8e55f36STejun Heo 	 */
2218c8e55f36STejun Heo 	worker_enter_idle(worker);
2219c8e55f36STejun Heo 	__set_current_state(TASK_INTERRUPTIBLE);
2220d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
22211da177e4SLinus Torvalds 	schedule();
2222c8e55f36STejun Heo 	goto woke_up;
22231da177e4SLinus Torvalds }
22241da177e4SLinus Torvalds 
2225e22bee78STejun Heo /**
2226e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2227111c225aSTejun Heo  * @__rescuer: self
2228e22bee78STejun Heo  *
2229e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2230493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2231e22bee78STejun Heo  *
2232706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2233e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2234e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2235e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2236e22bee78STejun Heo  * the problem rescuer solves.
2237e22bee78STejun Heo  *
2238706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2239706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2240e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2241e22bee78STejun Heo  *
2242e22bee78STejun Heo  * This should happen rarely.
2243d185af30SYacine Belkadi  *
2244d185af30SYacine Belkadi  * Return: 0
2245e22bee78STejun Heo  */
2246111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2247e22bee78STejun Heo {
2248111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2249111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2250e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
22514d595b86SLai Jiangshan 	bool should_stop;
2252e22bee78STejun Heo 
2253e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2254111c225aSTejun Heo 
2255111c225aSTejun Heo 	/*
2256111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2257111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2258111c225aSTejun Heo 	 */
2259111c225aSTejun Heo 	rescuer->task->flags |= PF_WQ_WORKER;
2260e22bee78STejun Heo repeat:
2261e22bee78STejun Heo 	set_current_state(TASK_INTERRUPTIBLE);
22621da177e4SLinus Torvalds 
22634d595b86SLai Jiangshan 	/*
22644d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
22654d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
22664d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
22674d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
22684d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
22694d595b86SLai Jiangshan 	 * list is always empty on exit.
22704d595b86SLai Jiangshan 	 */
22714d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
22721da177e4SLinus Torvalds 
2273493a1724STejun Heo 	/* see whether any pwq is asking for help */
22742e109a28STejun Heo 	spin_lock_irq(&wq_mayday_lock);
2275493a1724STejun Heo 
2276493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2277493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2278493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2279112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2280e22bee78STejun Heo 		struct work_struct *work, *n;
228182607adcSTejun Heo 		bool first = true;
2282e22bee78STejun Heo 
2283e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2284493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2285493a1724STejun Heo 
22862e109a28STejun Heo 		spin_unlock_irq(&wq_mayday_lock);
2287e22bee78STejun Heo 
228851697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
228951697d39SLai Jiangshan 
229051697d39SLai Jiangshan 		spin_lock_irq(&pool->lock);
2291b3104104SLai Jiangshan 		rescuer->pool = pool;
2292e22bee78STejun Heo 
2293e22bee78STejun Heo 		/*
2294e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2295e22bee78STejun Heo 		 * process'em.
2296e22bee78STejun Heo 		 */
22970479c8c5STejun Heo 		WARN_ON_ONCE(!list_empty(scheduled));
229882607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
229982607adcSTejun Heo 			if (get_work_pwq(work) == pwq) {
230082607adcSTejun Heo 				if (first)
230182607adcSTejun Heo 					pool->watchdog_ts = jiffies;
2302e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
230382607adcSTejun Heo 			}
230482607adcSTejun Heo 			first = false;
230582607adcSTejun Heo 		}
2306e22bee78STejun Heo 
2307008847f6SNeilBrown 		if (!list_empty(scheduled)) {
2308e22bee78STejun Heo 			process_scheduled_works(rescuer);
23097576958aSTejun Heo 
23107576958aSTejun Heo 			/*
2311008847f6SNeilBrown 			 * The above execution of rescued work items could
2312008847f6SNeilBrown 			 * have created more to rescue through
2313008847f6SNeilBrown 			 * pwq_activate_first_delayed() or chained
2314008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
2315008847f6SNeilBrown 			 * that such back-to-back work items, which may be
2316008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
2317008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
2318008847f6SNeilBrown 			 */
2319008847f6SNeilBrown 			if (need_to_create_worker(pool)) {
2320008847f6SNeilBrown 				spin_lock(&wq_mayday_lock);
2321008847f6SNeilBrown 				get_pwq(pwq);
2322008847f6SNeilBrown 				list_move_tail(&pwq->mayday_node, &wq->maydays);
2323008847f6SNeilBrown 				spin_unlock(&wq_mayday_lock);
2324008847f6SNeilBrown 			}
2325008847f6SNeilBrown 		}
2326008847f6SNeilBrown 
2327008847f6SNeilBrown 		/*
232877668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
232913b1d625SLai Jiangshan 		 * go away while we're still attached to it.
233077668c8bSLai Jiangshan 		 */
233177668c8bSLai Jiangshan 		put_pwq(pwq);
233277668c8bSLai Jiangshan 
233377668c8bSLai Jiangshan 		/*
2334d8ca83e6SLai Jiangshan 		 * Leave this pool.  If need_more_worker() is %true, notify a
23357576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
23367576958aSTejun Heo 		 * and stalling the execution.
23377576958aSTejun Heo 		 */
2338d8ca83e6SLai Jiangshan 		if (need_more_worker(pool))
233963d95a91STejun Heo 			wake_up_worker(pool);
23407576958aSTejun Heo 
2341b3104104SLai Jiangshan 		rescuer->pool = NULL;
234213b1d625SLai Jiangshan 		spin_unlock_irq(&pool->lock);
234313b1d625SLai Jiangshan 
234413b1d625SLai Jiangshan 		worker_detach_from_pool(rescuer, pool);
234513b1d625SLai Jiangshan 
234613b1d625SLai Jiangshan 		spin_lock_irq(&wq_mayday_lock);
23471da177e4SLinus Torvalds 	}
23481da177e4SLinus Torvalds 
23492e109a28STejun Heo 	spin_unlock_irq(&wq_mayday_lock);
2350493a1724STejun Heo 
23514d595b86SLai Jiangshan 	if (should_stop) {
23524d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
23534d595b86SLai Jiangshan 		rescuer->task->flags &= ~PF_WQ_WORKER;
23544d595b86SLai Jiangshan 		return 0;
23554d595b86SLai Jiangshan 	}
23564d595b86SLai Jiangshan 
2357111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2358111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2359e22bee78STejun Heo 	schedule();
2360e22bee78STejun Heo 	goto repeat;
23611da177e4SLinus Torvalds }
23621da177e4SLinus Torvalds 
2363fca839c0STejun Heo /**
2364fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
2365fca839c0STejun Heo  * @target_wq: workqueue being flushed
2366fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
2367fca839c0STejun Heo  *
2368fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
2369fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2370fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
2371fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2372fca839c0STejun Heo  * a deadlock.
2373fca839c0STejun Heo  */
2374fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
2375fca839c0STejun Heo 				   struct work_struct *target_work)
2376fca839c0STejun Heo {
2377fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
2378fca839c0STejun Heo 	struct worker *worker;
2379fca839c0STejun Heo 
2380fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
2381fca839c0STejun Heo 		return;
2382fca839c0STejun Heo 
2383fca839c0STejun Heo 	worker = current_wq_worker();
2384fca839c0STejun Heo 
2385fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
2386fca839c0STejun Heo 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%pf",
2387fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
238823d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
238923d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2390fca839c0STejun Heo 		  "workqueue: WQ_MEM_RECLAIM %s:%pf is flushing !WQ_MEM_RECLAIM %s:%pf",
2391fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
2392fca839c0STejun Heo 		  target_wq->name, target_func);
2393fca839c0STejun Heo }
2394fca839c0STejun Heo 
2395fc2e4d70SOleg Nesterov struct wq_barrier {
2396fc2e4d70SOleg Nesterov 	struct work_struct	work;
2397fc2e4d70SOleg Nesterov 	struct completion	done;
23982607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
2399fc2e4d70SOleg Nesterov };
2400fc2e4d70SOleg Nesterov 
2401fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2402fc2e4d70SOleg Nesterov {
2403fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2404fc2e4d70SOleg Nesterov 	complete(&barr->done);
2405fc2e4d70SOleg Nesterov }
2406fc2e4d70SOleg Nesterov 
24074690c4abSTejun Heo /**
24084690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2409112202d9STejun Heo  * @pwq: pwq to insert barrier into
24104690c4abSTejun Heo  * @barr: wq_barrier to insert
2411affee4b2STejun Heo  * @target: target work to attach @barr to
2412affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
24134690c4abSTejun Heo  *
2414affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2415affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2416affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2417affee4b2STejun Heo  * cpu.
2418affee4b2STejun Heo  *
2419affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2420affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2421affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2422affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2423affee4b2STejun Heo  * after a work with LINKED flag set.
2424affee4b2STejun Heo  *
2425affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2426112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
24274690c4abSTejun Heo  *
24284690c4abSTejun Heo  * CONTEXT:
2429d565ed63STejun Heo  * spin_lock_irq(pool->lock).
24304690c4abSTejun Heo  */
2431112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2432affee4b2STejun Heo 			      struct wq_barrier *barr,
2433affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2434fc2e4d70SOleg Nesterov {
2435affee4b2STejun Heo 	struct list_head *head;
2436affee4b2STejun Heo 	unsigned int linked = 0;
2437affee4b2STejun Heo 
2438dc186ad7SThomas Gleixner 	/*
2439d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2440dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2441dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2442dc186ad7SThomas Gleixner 	 * might deadlock.
2443dc186ad7SThomas Gleixner 	 */
2444ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
244522df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2446fc2e4d70SOleg Nesterov 	init_completion(&barr->done);
24472607d7a6STejun Heo 	barr->task = current;
244883c22520SOleg Nesterov 
2449affee4b2STejun Heo 	/*
2450affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2451affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2452affee4b2STejun Heo 	 */
2453affee4b2STejun Heo 	if (worker)
2454affee4b2STejun Heo 		head = worker->scheduled.next;
2455affee4b2STejun Heo 	else {
2456affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2457affee4b2STejun Heo 
2458affee4b2STejun Heo 		head = target->entry.next;
2459affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2460affee4b2STejun Heo 		linked = *bits & WORK_STRUCT_LINKED;
2461affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2462affee4b2STejun Heo 	}
2463affee4b2STejun Heo 
2464dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2465112202d9STejun Heo 	insert_work(pwq, &barr->work, head,
2466affee4b2STejun Heo 		    work_color_to_flags(WORK_NO_COLOR) | linked);
2467fc2e4d70SOleg Nesterov }
2468fc2e4d70SOleg Nesterov 
246973f53c4aSTejun Heo /**
2470112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
247173f53c4aSTejun Heo  * @wq: workqueue being flushed
247273f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
247373f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
247473f53c4aSTejun Heo  *
2475112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
247673f53c4aSTejun Heo  *
2477112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
2478112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
2479112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
2480112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
2481112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
248273f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
248373f53c4aSTejun Heo  *
248473f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
248573f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
248673f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
248773f53c4aSTejun Heo  * is returned.
248873f53c4aSTejun Heo  *
2489112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
249073f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
249173f53c4aSTejun Heo  * advanced to @work_color.
249273f53c4aSTejun Heo  *
249373f53c4aSTejun Heo  * CONTEXT:
24943c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
249573f53c4aSTejun Heo  *
2496d185af30SYacine Belkadi  * Return:
249773f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
249873f53c4aSTejun Heo  * otherwise.
249973f53c4aSTejun Heo  */
2500112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
250173f53c4aSTejun Heo 				      int flush_color, int work_color)
25021da177e4SLinus Torvalds {
250373f53c4aSTejun Heo 	bool wait = false;
250449e3cf44STejun Heo 	struct pool_workqueue *pwq;
25051da177e4SLinus Torvalds 
250673f53c4aSTejun Heo 	if (flush_color >= 0) {
25076183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2508112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
2509dc186ad7SThomas Gleixner 	}
251014441960SOleg Nesterov 
251149e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2512112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
25131da177e4SLinus Torvalds 
2514b09f4fd3SLai Jiangshan 		spin_lock_irq(&pool->lock);
251573f53c4aSTejun Heo 
251673f53c4aSTejun Heo 		if (flush_color >= 0) {
25176183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
251873f53c4aSTejun Heo 
2519112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
2520112202d9STejun Heo 				pwq->flush_color = flush_color;
2521112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
252273f53c4aSTejun Heo 				wait = true;
25231da177e4SLinus Torvalds 			}
252473f53c4aSTejun Heo 		}
252573f53c4aSTejun Heo 
252673f53c4aSTejun Heo 		if (work_color >= 0) {
25276183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2528112202d9STejun Heo 			pwq->work_color = work_color;
252973f53c4aSTejun Heo 		}
253073f53c4aSTejun Heo 
2531b09f4fd3SLai Jiangshan 		spin_unlock_irq(&pool->lock);
25321da177e4SLinus Torvalds 	}
25331da177e4SLinus Torvalds 
2534112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
253573f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
253673f53c4aSTejun Heo 
253773f53c4aSTejun Heo 	return wait;
253883c22520SOleg Nesterov }
25391da177e4SLinus Torvalds 
25400fcb78c2SRolf Eike Beer /**
25411da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
25420fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
25431da177e4SLinus Torvalds  *
2544c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
2545c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
25461da177e4SLinus Torvalds  */
25477ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
25481da177e4SLinus Torvalds {
254973f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
255073f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
255173f53c4aSTejun Heo 		.flush_color = -1,
255273f53c4aSTejun Heo 		.done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
255373f53c4aSTejun Heo 	};
255473f53c4aSTejun Heo 	int next_color;
2555b1f4ec17SOleg Nesterov 
25563295f0efSIngo Molnar 	lock_map_acquire(&wq->lockdep_map);
25573295f0efSIngo Molnar 	lock_map_release(&wq->lockdep_map);
255873f53c4aSTejun Heo 
25593c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
256073f53c4aSTejun Heo 
256173f53c4aSTejun Heo 	/*
256273f53c4aSTejun Heo 	 * Start-to-wait phase
256373f53c4aSTejun Heo 	 */
256473f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
256573f53c4aSTejun Heo 
256673f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
256773f53c4aSTejun Heo 		/*
256873f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
256973f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
257073f53c4aSTejun Heo 		 * by one.
257173f53c4aSTejun Heo 		 */
25726183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
257373f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
257473f53c4aSTejun Heo 		wq->work_color = next_color;
257573f53c4aSTejun Heo 
257673f53c4aSTejun Heo 		if (!wq->first_flusher) {
257773f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
25786183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
257973f53c4aSTejun Heo 
258073f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
258173f53c4aSTejun Heo 
2582112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
258373f53c4aSTejun Heo 						       wq->work_color)) {
258473f53c4aSTejun Heo 				/* nothing to flush, done */
258573f53c4aSTejun Heo 				wq->flush_color = next_color;
258673f53c4aSTejun Heo 				wq->first_flusher = NULL;
258773f53c4aSTejun Heo 				goto out_unlock;
258873f53c4aSTejun Heo 			}
258973f53c4aSTejun Heo 		} else {
259073f53c4aSTejun Heo 			/* wait in queue */
25916183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
259273f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
2593112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
259473f53c4aSTejun Heo 		}
259573f53c4aSTejun Heo 	} else {
259673f53c4aSTejun Heo 		/*
259773f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
259873f53c4aSTejun Heo 		 * The next flush completion will assign us
259973f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
260073f53c4aSTejun Heo 		 */
260173f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
260273f53c4aSTejun Heo 	}
260373f53c4aSTejun Heo 
2604fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
2605fca839c0STejun Heo 
26063c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
260773f53c4aSTejun Heo 
260873f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
260973f53c4aSTejun Heo 
261073f53c4aSTejun Heo 	/*
261173f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
261273f53c4aSTejun Heo 	 *
261373f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
261473f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
261573f53c4aSTejun Heo 	 */
261673f53c4aSTejun Heo 	if (wq->first_flusher != &this_flusher)
261773f53c4aSTejun Heo 		return;
261873f53c4aSTejun Heo 
26193c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
262073f53c4aSTejun Heo 
26214ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
26224ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
26234ce48b37STejun Heo 		goto out_unlock;
26244ce48b37STejun Heo 
262573f53c4aSTejun Heo 	wq->first_flusher = NULL;
262673f53c4aSTejun Heo 
26276183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
26286183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
262973f53c4aSTejun Heo 
263073f53c4aSTejun Heo 	while (true) {
263173f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
263273f53c4aSTejun Heo 
263373f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
263473f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
263573f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
263673f53c4aSTejun Heo 				break;
263773f53c4aSTejun Heo 			list_del_init(&next->list);
263873f53c4aSTejun Heo 			complete(&next->done);
263973f53c4aSTejun Heo 		}
264073f53c4aSTejun Heo 
26416183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
264273f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
264373f53c4aSTejun Heo 
264473f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
264573f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
264673f53c4aSTejun Heo 
264773f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
264873f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
264973f53c4aSTejun Heo 			/*
265073f53c4aSTejun Heo 			 * Assign the same color to all overflowed
265173f53c4aSTejun Heo 			 * flushers, advance work_color and append to
265273f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
265373f53c4aSTejun Heo 			 * phase for these overflowed flushers.
265473f53c4aSTejun Heo 			 */
265573f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
265673f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
265773f53c4aSTejun Heo 
265873f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
265973f53c4aSTejun Heo 
266073f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
266173f53c4aSTejun Heo 					      &wq->flusher_queue);
2662112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
266373f53c4aSTejun Heo 		}
266473f53c4aSTejun Heo 
266573f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
26666183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
266773f53c4aSTejun Heo 			break;
266873f53c4aSTejun Heo 		}
266973f53c4aSTejun Heo 
267073f53c4aSTejun Heo 		/*
267173f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
2672112202d9STejun Heo 		 * the new first flusher and arm pwqs.
267373f53c4aSTejun Heo 		 */
26746183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
26756183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
267673f53c4aSTejun Heo 
267773f53c4aSTejun Heo 		list_del_init(&next->list);
267873f53c4aSTejun Heo 		wq->first_flusher = next;
267973f53c4aSTejun Heo 
2680112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
268173f53c4aSTejun Heo 			break;
268273f53c4aSTejun Heo 
268373f53c4aSTejun Heo 		/*
268473f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
268573f53c4aSTejun Heo 		 * flusher and repeat cascading.
268673f53c4aSTejun Heo 		 */
268773f53c4aSTejun Heo 		wq->first_flusher = NULL;
268873f53c4aSTejun Heo 	}
268973f53c4aSTejun Heo 
269073f53c4aSTejun Heo out_unlock:
26913c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
26921da177e4SLinus Torvalds }
26931dadafa8STim Gardner EXPORT_SYMBOL(flush_workqueue);
26941da177e4SLinus Torvalds 
26959c5a2ba7STejun Heo /**
26969c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
26979c5a2ba7STejun Heo  * @wq: workqueue to drain
26989c5a2ba7STejun Heo  *
26999c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
27009c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
27019c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
2702b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
27039c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
27049c5a2ba7STejun Heo  * takes too long.
27059c5a2ba7STejun Heo  */
27069c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
27079c5a2ba7STejun Heo {
27089c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
270949e3cf44STejun Heo 	struct pool_workqueue *pwq;
27109c5a2ba7STejun Heo 
27119c5a2ba7STejun Heo 	/*
27129c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
27139c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
2714618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
27159c5a2ba7STejun Heo 	 */
271687fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
27179c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
2718618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
271987fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
27209c5a2ba7STejun Heo reflush:
27219c5a2ba7STejun Heo 	flush_workqueue(wq);
27229c5a2ba7STejun Heo 
2723b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
272476af4d93STejun Heo 
272549e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2726fa2563e4SThomas Tuttle 		bool drained;
27279c5a2ba7STejun Heo 
2728b09f4fd3SLai Jiangshan 		spin_lock_irq(&pwq->pool->lock);
2729112202d9STejun Heo 		drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2730b09f4fd3SLai Jiangshan 		spin_unlock_irq(&pwq->pool->lock);
2731fa2563e4SThomas Tuttle 
2732fa2563e4SThomas Tuttle 		if (drained)
27339c5a2ba7STejun Heo 			continue;
27349c5a2ba7STejun Heo 
27359c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
27369c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2737c5aa87bbSTejun Heo 			pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
27389c5a2ba7STejun Heo 				wq->name, flush_cnt);
273976af4d93STejun Heo 
2740b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
27419c5a2ba7STejun Heo 		goto reflush;
27429c5a2ba7STejun Heo 	}
27439c5a2ba7STejun Heo 
27449c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
2745618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
274687fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
27479c5a2ba7STejun Heo }
27489c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
27499c5a2ba7STejun Heo 
2750606a5020STejun Heo static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2751baf59022STejun Heo {
2752baf59022STejun Heo 	struct worker *worker = NULL;
2753c9e7cf27STejun Heo 	struct worker_pool *pool;
2754112202d9STejun Heo 	struct pool_workqueue *pwq;
2755baf59022STejun Heo 
2756baf59022STejun Heo 	might_sleep();
2757baf59022STejun Heo 
2758fa1b54e6STejun Heo 	local_irq_disable();
2759fa1b54e6STejun Heo 	pool = get_work_pool(work);
2760fa1b54e6STejun Heo 	if (!pool) {
2761fa1b54e6STejun Heo 		local_irq_enable();
2762fa1b54e6STejun Heo 		return false;
2763fa1b54e6STejun Heo 	}
2764fa1b54e6STejun Heo 
2765fa1b54e6STejun Heo 	spin_lock(&pool->lock);
27660b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
2767112202d9STejun Heo 	pwq = get_work_pwq(work);
2768112202d9STejun Heo 	if (pwq) {
2769112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
2770baf59022STejun Heo 			goto already_gone;
2771606a5020STejun Heo 	} else {
2772c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
2773baf59022STejun Heo 		if (!worker)
2774baf59022STejun Heo 			goto already_gone;
2775112202d9STejun Heo 		pwq = worker->current_pwq;
2776606a5020STejun Heo 	}
2777baf59022STejun Heo 
2778fca839c0STejun Heo 	check_flush_dependency(pwq->wq, work);
2779fca839c0STejun Heo 
2780112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
2781d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2782baf59022STejun Heo 
2783e159489bSTejun Heo 	/*
2784e159489bSTejun Heo 	 * If @max_active is 1 or rescuer is in use, flushing another work
2785e159489bSTejun Heo 	 * item on the same workqueue may lead to deadlock.  Make sure the
2786e159489bSTejun Heo 	 * flusher is not running on the same workqueue by verifying write
2787e159489bSTejun Heo 	 * access.
2788e159489bSTejun Heo 	 */
2789493008a8STejun Heo 	if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
2790112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
2791e159489bSTejun Heo 	else
2792112202d9STejun Heo 		lock_map_acquire_read(&pwq->wq->lockdep_map);
2793112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
2794e159489bSTejun Heo 
2795baf59022STejun Heo 	return true;
2796baf59022STejun Heo already_gone:
2797d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2798baf59022STejun Heo 	return false;
2799baf59022STejun Heo }
2800baf59022STejun Heo 
2801db700897SOleg Nesterov /**
2802401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
2803401a8d04STejun Heo  * @work: the work to flush
2804db700897SOleg Nesterov  *
2805606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
2806606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
2807401a8d04STejun Heo  *
2808d185af30SYacine Belkadi  * Return:
2809401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2810401a8d04STejun Heo  * %false if it was already idle.
2811db700897SOleg Nesterov  */
2812401a8d04STejun Heo bool flush_work(struct work_struct *work)
2813db700897SOleg Nesterov {
281412997d1aSBjorn Helgaas 	struct wq_barrier barr;
281512997d1aSBjorn Helgaas 
28160976dfc1SStephen Boyd 	lock_map_acquire(&work->lockdep_map);
28170976dfc1SStephen Boyd 	lock_map_release(&work->lockdep_map);
28180976dfc1SStephen Boyd 
281912997d1aSBjorn Helgaas 	if (start_flush_work(work, &barr)) {
282012997d1aSBjorn Helgaas 		wait_for_completion(&barr.done);
282112997d1aSBjorn Helgaas 		destroy_work_on_stack(&barr.work);
282212997d1aSBjorn Helgaas 		return true;
282312997d1aSBjorn Helgaas 	} else {
282412997d1aSBjorn Helgaas 		return false;
282512997d1aSBjorn Helgaas 	}
2826606a5020STejun Heo }
2827db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
2828db700897SOleg Nesterov 
28298603e1b3STejun Heo struct cwt_wait {
28308603e1b3STejun Heo 	wait_queue_t		wait;
28318603e1b3STejun Heo 	struct work_struct	*work;
28328603e1b3STejun Heo };
28338603e1b3STejun Heo 
28348603e1b3STejun Heo static int cwt_wakefn(wait_queue_t *wait, unsigned mode, int sync, void *key)
28358603e1b3STejun Heo {
28368603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
28378603e1b3STejun Heo 
28388603e1b3STejun Heo 	if (cwait->work != key)
28398603e1b3STejun Heo 		return 0;
28408603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
28418603e1b3STejun Heo }
28428603e1b3STejun Heo 
284336e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2844401a8d04STejun Heo {
28458603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
2846bbb68dfaSTejun Heo 	unsigned long flags;
28471f1f642eSOleg Nesterov 	int ret;
28481f1f642eSOleg Nesterov 
28491f1f642eSOleg Nesterov 	do {
2850bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
2851bbb68dfaSTejun Heo 		/*
28528603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
28538603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
28548603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
28558603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
28568603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
28578603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
28588603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
28598603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
28608603e1b3STejun Heo 		 * we're hogging the CPU.
28618603e1b3STejun Heo 		 *
28628603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
28638603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
28648603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
28658603e1b3STejun Heo 		 * wait and wakeup.
2866bbb68dfaSTejun Heo 		 */
28678603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
28688603e1b3STejun Heo 			struct cwt_wait cwait;
28698603e1b3STejun Heo 
28708603e1b3STejun Heo 			init_wait(&cwait.wait);
28718603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
28728603e1b3STejun Heo 			cwait.work = work;
28738603e1b3STejun Heo 
28748603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
28758603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
28768603e1b3STejun Heo 			if (work_is_canceling(work))
28778603e1b3STejun Heo 				schedule();
28788603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
28798603e1b3STejun Heo 		}
28801f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
28811f1f642eSOleg Nesterov 
2882bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
2883bbb68dfaSTejun Heo 	mark_work_canceling(work);
2884bbb68dfaSTejun Heo 	local_irq_restore(flags);
2885bbb68dfaSTejun Heo 
2886606a5020STejun Heo 	flush_work(work);
28877a22ad75STejun Heo 	clear_work_data(work);
28888603e1b3STejun Heo 
28898603e1b3STejun Heo 	/*
28908603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
28918603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
28928603e1b3STejun Heo 	 * visible there.
28938603e1b3STejun Heo 	 */
28948603e1b3STejun Heo 	smp_mb();
28958603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
28968603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
28978603e1b3STejun Heo 
28981f1f642eSOleg Nesterov 	return ret;
28991f1f642eSOleg Nesterov }
29001f1f642eSOleg Nesterov 
29016e84d644SOleg Nesterov /**
2902401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
2903401a8d04STejun Heo  * @work: the work to cancel
29046e84d644SOleg Nesterov  *
2905401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
2906401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
2907401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
2908401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
29091f1f642eSOleg Nesterov  *
2910401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
2911401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
29126e84d644SOleg Nesterov  *
2913401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
29146e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
2915401a8d04STejun Heo  *
2916d185af30SYacine Belkadi  * Return:
2917401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
29186e84d644SOleg Nesterov  */
2919401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
29206e84d644SOleg Nesterov {
292136e227d2STejun Heo 	return __cancel_work_timer(work, false);
2922b89deed3SOleg Nesterov }
292328e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
2924b89deed3SOleg Nesterov 
29256e84d644SOleg Nesterov /**
2926401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
2927401a8d04STejun Heo  * @dwork: the delayed work to flush
29286e84d644SOleg Nesterov  *
2929401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
2930401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
2931401a8d04STejun Heo  * considers the last queueing instance of @dwork.
29321f1f642eSOleg Nesterov  *
2933d185af30SYacine Belkadi  * Return:
2934401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2935401a8d04STejun Heo  * %false if it was already idle.
29366e84d644SOleg Nesterov  */
2937401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
2938401a8d04STejun Heo {
29398930cabaSTejun Heo 	local_irq_disable();
2940401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
294160c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
29428930cabaSTejun Heo 	local_irq_enable();
2943401a8d04STejun Heo 	return flush_work(&dwork->work);
2944401a8d04STejun Heo }
2945401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
2946401a8d04STejun Heo 
2947401a8d04STejun Heo /**
294857b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
294957b30ae7STejun Heo  * @dwork: delayed_work to cancel
295009383498STejun Heo  *
2951d185af30SYacine Belkadi  * Kill off a pending delayed_work.
2952d185af30SYacine Belkadi  *
2953d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
2954d185af30SYacine Belkadi  * pending.
2955d185af30SYacine Belkadi  *
2956d185af30SYacine Belkadi  * Note:
2957d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
2958d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
2959d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
296009383498STejun Heo  *
296157b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
296209383498STejun Heo  */
296357b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
296409383498STejun Heo {
296557b30ae7STejun Heo 	unsigned long flags;
296657b30ae7STejun Heo 	int ret;
296757b30ae7STejun Heo 
296857b30ae7STejun Heo 	do {
296957b30ae7STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
297057b30ae7STejun Heo 	} while (unlikely(ret == -EAGAIN));
297157b30ae7STejun Heo 
297257b30ae7STejun Heo 	if (unlikely(ret < 0))
297357b30ae7STejun Heo 		return false;
297457b30ae7STejun Heo 
29757c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(&dwork->work,
29767c3eed5cSTejun Heo 					get_work_pool_id(&dwork->work));
297757b30ae7STejun Heo 	local_irq_restore(flags);
2978c0158ca6SDan Magenheimer 	return ret;
297909383498STejun Heo }
298057b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
298109383498STejun Heo 
298209383498STejun Heo /**
2983401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2984401a8d04STejun Heo  * @dwork: the delayed work cancel
2985401a8d04STejun Heo  *
2986401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
2987401a8d04STejun Heo  *
2988d185af30SYacine Belkadi  * Return:
2989401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
2990401a8d04STejun Heo  */
2991401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
29926e84d644SOleg Nesterov {
299336e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
29946e84d644SOleg Nesterov }
2995f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
29961da177e4SLinus Torvalds 
29970fcb78c2SRolf Eike Beer /**
299831ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
2999b6136773SAndrew Morton  * @func: the function to call
3000b6136773SAndrew Morton  *
300131ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
300231ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3003b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
300431ddd871STejun Heo  *
3005d185af30SYacine Belkadi  * Return:
300631ddd871STejun Heo  * 0 on success, -errno on failure.
3007b6136773SAndrew Morton  */
300865f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
300915316ba8SChristoph Lameter {
301015316ba8SChristoph Lameter 	int cpu;
301138f51568SNamhyung Kim 	struct work_struct __percpu *works;
301215316ba8SChristoph Lameter 
3013b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3014b6136773SAndrew Morton 	if (!works)
301515316ba8SChristoph Lameter 		return -ENOMEM;
3016b6136773SAndrew Morton 
301795402b38SGautham R Shenoy 	get_online_cpus();
301893981800STejun Heo 
301915316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
30209bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
30219bfb1839SIngo Molnar 
30229bfb1839SIngo Molnar 		INIT_WORK(work, func);
30238de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
302415316ba8SChristoph Lameter 	}
302593981800STejun Heo 
302693981800STejun Heo 	for_each_online_cpu(cpu)
30278616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
302893981800STejun Heo 
302995402b38SGautham R Shenoy 	put_online_cpus();
3030b6136773SAndrew Morton 	free_percpu(works);
303115316ba8SChristoph Lameter 	return 0;
303215316ba8SChristoph Lameter }
303315316ba8SChristoph Lameter 
3034eef6a7d5SAlan Stern /**
30351fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
30361fa44ecaSJames Bottomley  * @fn:		the function to execute
30371fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
30381fa44ecaSJames Bottomley  *		be available when the work executes)
30391fa44ecaSJames Bottomley  *
30401fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
30411fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
30421fa44ecaSJames Bottomley  *
3043d185af30SYacine Belkadi  * Return:	0 - function was executed
30441fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
30451fa44ecaSJames Bottomley  */
304665f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
30471fa44ecaSJames Bottomley {
30481fa44ecaSJames Bottomley 	if (!in_interrupt()) {
304965f27f38SDavid Howells 		fn(&ew->work);
30501fa44ecaSJames Bottomley 		return 0;
30511fa44ecaSJames Bottomley 	}
30521fa44ecaSJames Bottomley 
305365f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
30541fa44ecaSJames Bottomley 	schedule_work(&ew->work);
30551fa44ecaSJames Bottomley 
30561fa44ecaSJames Bottomley 	return 1;
30571fa44ecaSJames Bottomley }
30581fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
30591fa44ecaSJames Bottomley 
30607a4e344cSTejun Heo /**
30617a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
30627a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
30637a4e344cSTejun Heo  *
30647a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
30657a4e344cSTejun Heo  */
30667a4e344cSTejun Heo void free_workqueue_attrs(struct workqueue_attrs *attrs)
30677a4e344cSTejun Heo {
30687a4e344cSTejun Heo 	if (attrs) {
30697a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
30707a4e344cSTejun Heo 		kfree(attrs);
30717a4e344cSTejun Heo 	}
30727a4e344cSTejun Heo }
30737a4e344cSTejun Heo 
30747a4e344cSTejun Heo /**
30757a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
30767a4e344cSTejun Heo  * @gfp_mask: allocation mask to use
30777a4e344cSTejun Heo  *
30787a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3079d185af30SYacine Belkadi  * return it.
3080d185af30SYacine Belkadi  *
3081d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
30827a4e344cSTejun Heo  */
30837a4e344cSTejun Heo struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
30847a4e344cSTejun Heo {
30857a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
30867a4e344cSTejun Heo 
30877a4e344cSTejun Heo 	attrs = kzalloc(sizeof(*attrs), gfp_mask);
30887a4e344cSTejun Heo 	if (!attrs)
30897a4e344cSTejun Heo 		goto fail;
30907a4e344cSTejun Heo 	if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
30917a4e344cSTejun Heo 		goto fail;
30927a4e344cSTejun Heo 
309313e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
30947a4e344cSTejun Heo 	return attrs;
30957a4e344cSTejun Heo fail:
30967a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
30977a4e344cSTejun Heo 	return NULL;
30987a4e344cSTejun Heo }
30997a4e344cSTejun Heo 
310029c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
310129c91e99STejun Heo 				 const struct workqueue_attrs *from)
310229c91e99STejun Heo {
310329c91e99STejun Heo 	to->nice = from->nice;
310429c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
31052865a8fbSShaohua Li 	/*
31062865a8fbSShaohua Li 	 * Unlike hash and equality test, this function doesn't ignore
31072865a8fbSShaohua Li 	 * ->no_numa as it is used for both pool and wq attrs.  Instead,
31082865a8fbSShaohua Li 	 * get_unbound_pool() explicitly clears ->no_numa after copying.
31092865a8fbSShaohua Li 	 */
31102865a8fbSShaohua Li 	to->no_numa = from->no_numa;
311129c91e99STejun Heo }
311229c91e99STejun Heo 
311329c91e99STejun Heo /* hash value of the content of @attr */
311429c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
311529c91e99STejun Heo {
311629c91e99STejun Heo 	u32 hash = 0;
311729c91e99STejun Heo 
311829c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
311913e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
312013e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
312129c91e99STejun Heo 	return hash;
312229c91e99STejun Heo }
312329c91e99STejun Heo 
312429c91e99STejun Heo /* content equality test */
312529c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
312629c91e99STejun Heo 			  const struct workqueue_attrs *b)
312729c91e99STejun Heo {
312829c91e99STejun Heo 	if (a->nice != b->nice)
312929c91e99STejun Heo 		return false;
313029c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
313129c91e99STejun Heo 		return false;
313229c91e99STejun Heo 	return true;
313329c91e99STejun Heo }
313429c91e99STejun Heo 
31357a4e344cSTejun Heo /**
31367a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
31377a4e344cSTejun Heo  * @pool: worker_pool to initialize
31387a4e344cSTejun Heo  *
3139402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3140d185af30SYacine Belkadi  *
3141d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
314229c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
314329c91e99STejun Heo  * on @pool safely to release it.
31447a4e344cSTejun Heo  */
31457a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
31464e1a1f9aSTejun Heo {
31474e1a1f9aSTejun Heo 	spin_lock_init(&pool->lock);
314829c91e99STejun Heo 	pool->id = -1;
314929c91e99STejun Heo 	pool->cpu = -1;
3150f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
31514e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
315282607adcSTejun Heo 	pool->watchdog_ts = jiffies;
31534e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
31544e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
31554e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
31564e1a1f9aSTejun Heo 
31574e1a1f9aSTejun Heo 	init_timer_deferrable(&pool->idle_timer);
31584e1a1f9aSTejun Heo 	pool->idle_timer.function = idle_worker_timeout;
31594e1a1f9aSTejun Heo 	pool->idle_timer.data = (unsigned long)pool;
31604e1a1f9aSTejun Heo 
31614e1a1f9aSTejun Heo 	setup_timer(&pool->mayday_timer, pool_mayday_timeout,
31624e1a1f9aSTejun Heo 		    (unsigned long)pool);
31634e1a1f9aSTejun Heo 
31644e1a1f9aSTejun Heo 	mutex_init(&pool->manager_arb);
316592f9c5c4SLai Jiangshan 	mutex_init(&pool->attach_mutex);
3166da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
31677a4e344cSTejun Heo 
31687cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
316929c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
317029c91e99STejun Heo 	pool->refcnt = 1;
317129c91e99STejun Heo 
317229c91e99STejun Heo 	/* shouldn't fail above this point */
31737a4e344cSTejun Heo 	pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
31747a4e344cSTejun Heo 	if (!pool->attrs)
31757a4e344cSTejun Heo 		return -ENOMEM;
31767a4e344cSTejun Heo 	return 0;
31774e1a1f9aSTejun Heo }
31784e1a1f9aSTejun Heo 
3179e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
3180e2dca7adSTejun Heo {
3181e2dca7adSTejun Heo 	struct workqueue_struct *wq =
3182e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
3183e2dca7adSTejun Heo 
3184e2dca7adSTejun Heo 	if (!(wq->flags & WQ_UNBOUND))
3185e2dca7adSTejun Heo 		free_percpu(wq->cpu_pwqs);
3186e2dca7adSTejun Heo 	else
3187e2dca7adSTejun Heo 		free_workqueue_attrs(wq->unbound_attrs);
3188e2dca7adSTejun Heo 
3189e2dca7adSTejun Heo 	kfree(wq->rescuer);
3190e2dca7adSTejun Heo 	kfree(wq);
3191e2dca7adSTejun Heo }
3192e2dca7adSTejun Heo 
319329c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
319429c91e99STejun Heo {
319529c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
319629c91e99STejun Heo 
31977cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
319829c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
319929c91e99STejun Heo 	kfree(pool);
320029c91e99STejun Heo }
320129c91e99STejun Heo 
320229c91e99STejun Heo /**
320329c91e99STejun Heo  * put_unbound_pool - put a worker_pool
320429c91e99STejun Heo  * @pool: worker_pool to put
320529c91e99STejun Heo  *
320629c91e99STejun Heo  * Put @pool.  If its refcnt reaches zero, it gets destroyed in sched-RCU
3207c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3208c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3209c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
3210a892caccSTejun Heo  *
3211a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
321229c91e99STejun Heo  */
321329c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
321429c91e99STejun Heo {
321560f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
321629c91e99STejun Heo 	struct worker *worker;
321729c91e99STejun Heo 
3218a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3219a892caccSTejun Heo 
3220a892caccSTejun Heo 	if (--pool->refcnt)
322129c91e99STejun Heo 		return;
322229c91e99STejun Heo 
322329c91e99STejun Heo 	/* sanity checks */
322461d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
3225a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
322629c91e99STejun Heo 		return;
322729c91e99STejun Heo 
322829c91e99STejun Heo 	/* release id and unhash */
322929c91e99STejun Heo 	if (pool->id >= 0)
323029c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
323129c91e99STejun Heo 	hash_del(&pool->hash_node);
323229c91e99STejun Heo 
3233c5aa87bbSTejun Heo 	/*
3234c5aa87bbSTejun Heo 	 * Become the manager and destroy all workers.  Grabbing
3235c5aa87bbSTejun Heo 	 * manager_arb prevents @pool's workers from blocking on
323692f9c5c4SLai Jiangshan 	 * attach_mutex.
3237c5aa87bbSTejun Heo 	 */
323829c91e99STejun Heo 	mutex_lock(&pool->manager_arb);
323929c91e99STejun Heo 
324060f5a4bcSLai Jiangshan 	spin_lock_irq(&pool->lock);
32411037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
324229c91e99STejun Heo 		destroy_worker(worker);
324329c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
324429c91e99STejun Heo 	spin_unlock_irq(&pool->lock);
324560f5a4bcSLai Jiangshan 
324692f9c5c4SLai Jiangshan 	mutex_lock(&pool->attach_mutex);
3247da028469SLai Jiangshan 	if (!list_empty(&pool->workers))
324860f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
324992f9c5c4SLai Jiangshan 	mutex_unlock(&pool->attach_mutex);
325060f5a4bcSLai Jiangshan 
325160f5a4bcSLai Jiangshan 	if (pool->detach_completion)
325260f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
325360f5a4bcSLai Jiangshan 
325429c91e99STejun Heo 	mutex_unlock(&pool->manager_arb);
325529c91e99STejun Heo 
325629c91e99STejun Heo 	/* shut down the timers */
325729c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
325829c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
325929c91e99STejun Heo 
326029c91e99STejun Heo 	/* sched-RCU protected to allow dereferences from get_work_pool() */
326129c91e99STejun Heo 	call_rcu_sched(&pool->rcu, rcu_free_pool);
326229c91e99STejun Heo }
326329c91e99STejun Heo 
326429c91e99STejun Heo /**
326529c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
326629c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
326729c91e99STejun Heo  *
326829c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
326929c91e99STejun Heo  * reference count and return it.  If there already is a matching
327029c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
3271d185af30SYacine Belkadi  * create a new one.
3272a892caccSTejun Heo  *
3273a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
3274d185af30SYacine Belkadi  *
3275d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
3276d185af30SYacine Belkadi  * On failure, %NULL.
327729c91e99STejun Heo  */
327829c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
327929c91e99STejun Heo {
328029c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
328129c91e99STejun Heo 	struct worker_pool *pool;
3282f3f90ad4STejun Heo 	int node;
3283e2273584SXunlei Pang 	int target_node = NUMA_NO_NODE;
328429c91e99STejun Heo 
3285a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
328629c91e99STejun Heo 
328729c91e99STejun Heo 	/* do we already have a matching pool? */
328829c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
328929c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
329029c91e99STejun Heo 			pool->refcnt++;
32913fb1823cSLai Jiangshan 			return pool;
329229c91e99STejun Heo 		}
329329c91e99STejun Heo 	}
329429c91e99STejun Heo 
3295e2273584SXunlei Pang 	/* if cpumask is contained inside a NUMA node, we belong to that node */
3296e2273584SXunlei Pang 	if (wq_numa_enabled) {
3297e2273584SXunlei Pang 		for_each_node(node) {
3298e2273584SXunlei Pang 			if (cpumask_subset(attrs->cpumask,
3299e2273584SXunlei Pang 					   wq_numa_possible_cpumask[node])) {
3300e2273584SXunlei Pang 				target_node = node;
3301e2273584SXunlei Pang 				break;
3302e2273584SXunlei Pang 			}
3303e2273584SXunlei Pang 		}
3304e2273584SXunlei Pang 	}
3305e2273584SXunlei Pang 
330629c91e99STejun Heo 	/* nope, create a new one */
3307e2273584SXunlei Pang 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
330829c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
330929c91e99STejun Heo 		goto fail;
331029c91e99STejun Heo 
33118864b4e5STejun Heo 	lockdep_set_subclass(&pool->lock, 1);	/* see put_pwq() */
331229c91e99STejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
3313e2273584SXunlei Pang 	pool->node = target_node;
331429c91e99STejun Heo 
33152865a8fbSShaohua Li 	/*
33162865a8fbSShaohua Li 	 * no_numa isn't a worker_pool attribute, always clear it.  See
33172865a8fbSShaohua Li 	 * 'struct workqueue_attrs' comments for detail.
33182865a8fbSShaohua Li 	 */
33192865a8fbSShaohua Li 	pool->attrs->no_numa = false;
33202865a8fbSShaohua Li 
332129c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
332229c91e99STejun Heo 		goto fail;
332329c91e99STejun Heo 
332429c91e99STejun Heo 	/* create and start the initial worker */
3325051e1850SLai Jiangshan 	if (!create_worker(pool))
332629c91e99STejun Heo 		goto fail;
332729c91e99STejun Heo 
332829c91e99STejun Heo 	/* install */
332929c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
33303fb1823cSLai Jiangshan 
333129c91e99STejun Heo 	return pool;
333229c91e99STejun Heo fail:
333329c91e99STejun Heo 	if (pool)
333429c91e99STejun Heo 		put_unbound_pool(pool);
333529c91e99STejun Heo 	return NULL;
333629c91e99STejun Heo }
333729c91e99STejun Heo 
33388864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
33398864b4e5STejun Heo {
33408864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
33418864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
33428864b4e5STejun Heo }
33438864b4e5STejun Heo 
33448864b4e5STejun Heo /*
33458864b4e5STejun Heo  * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
33468864b4e5STejun Heo  * and needs to be destroyed.
33478864b4e5STejun Heo  */
33488864b4e5STejun Heo static void pwq_unbound_release_workfn(struct work_struct *work)
33498864b4e5STejun Heo {
33508864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
33518864b4e5STejun Heo 						  unbound_release_work);
33528864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
33538864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
3354bc0caf09STejun Heo 	bool is_last;
33558864b4e5STejun Heo 
33568864b4e5STejun Heo 	if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
33578864b4e5STejun Heo 		return;
33588864b4e5STejun Heo 
33593c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
33608864b4e5STejun Heo 	list_del_rcu(&pwq->pwqs_node);
3361bc0caf09STejun Heo 	is_last = list_empty(&wq->pwqs);
33623c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
33638864b4e5STejun Heo 
3364a892caccSTejun Heo 	mutex_lock(&wq_pool_mutex);
33658864b4e5STejun Heo 	put_unbound_pool(pool);
3366a892caccSTejun Heo 	mutex_unlock(&wq_pool_mutex);
3367a892caccSTejun Heo 
33688864b4e5STejun Heo 	call_rcu_sched(&pwq->rcu, rcu_free_pwq);
33698864b4e5STejun Heo 
33708864b4e5STejun Heo 	/*
33718864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
3372e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
33738864b4e5STejun Heo 	 */
3374e2dca7adSTejun Heo 	if (is_last)
3375e2dca7adSTejun Heo 		call_rcu_sched(&wq->rcu, rcu_free_wq);
33766029a918STejun Heo }
33778864b4e5STejun Heo 
33780fbd95aaSTejun Heo /**
3379699ce097STejun Heo  * pwq_adjust_max_active - update a pwq's max_active to the current setting
33800fbd95aaSTejun Heo  * @pwq: target pool_workqueue
33810fbd95aaSTejun Heo  *
3382699ce097STejun Heo  * If @pwq isn't freezing, set @pwq->max_active to the associated
3383699ce097STejun Heo  * workqueue's saved_max_active and activate delayed work items
3384699ce097STejun Heo  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
33850fbd95aaSTejun Heo  */
3386699ce097STejun Heo static void pwq_adjust_max_active(struct pool_workqueue *pwq)
33870fbd95aaSTejun Heo {
3388699ce097STejun Heo 	struct workqueue_struct *wq = pwq->wq;
3389699ce097STejun Heo 	bool freezable = wq->flags & WQ_FREEZABLE;
3390699ce097STejun Heo 
3391699ce097STejun Heo 	/* for @wq->saved_max_active */
3392a357fc03SLai Jiangshan 	lockdep_assert_held(&wq->mutex);
3393699ce097STejun Heo 
3394699ce097STejun Heo 	/* fast exit for non-freezable wqs */
3395699ce097STejun Heo 	if (!freezable && pwq->max_active == wq->saved_max_active)
3396699ce097STejun Heo 		return;
3397699ce097STejun Heo 
3398a357fc03SLai Jiangshan 	spin_lock_irq(&pwq->pool->lock);
3399699ce097STejun Heo 
340074b414eaSLai Jiangshan 	/*
340174b414eaSLai Jiangshan 	 * During [un]freezing, the caller is responsible for ensuring that
340274b414eaSLai Jiangshan 	 * this function is called at least once after @workqueue_freezing
340374b414eaSLai Jiangshan 	 * is updated and visible.
340474b414eaSLai Jiangshan 	 */
340574b414eaSLai Jiangshan 	if (!freezable || !workqueue_freezing) {
3406699ce097STejun Heo 		pwq->max_active = wq->saved_max_active;
34070fbd95aaSTejun Heo 
34080fbd95aaSTejun Heo 		while (!list_empty(&pwq->delayed_works) &&
34090fbd95aaSTejun Heo 		       pwq->nr_active < pwq->max_active)
34100fbd95aaSTejun Heo 			pwq_activate_first_delayed(pwq);
3411951a078aSLai Jiangshan 
3412951a078aSLai Jiangshan 		/*
3413951a078aSLai Jiangshan 		 * Need to kick a worker after thawed or an unbound wq's
3414951a078aSLai Jiangshan 		 * max_active is bumped.  It's a slow path.  Do it always.
3415951a078aSLai Jiangshan 		 */
3416951a078aSLai Jiangshan 		wake_up_worker(pwq->pool);
3417699ce097STejun Heo 	} else {
3418699ce097STejun Heo 		pwq->max_active = 0;
3419699ce097STejun Heo 	}
3420699ce097STejun Heo 
3421a357fc03SLai Jiangshan 	spin_unlock_irq(&pwq->pool->lock);
34220fbd95aaSTejun Heo }
34230fbd95aaSTejun Heo 
3424e50aba9aSTejun Heo /* initialize newly alloced @pwq which is associated with @wq and @pool */
3425f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3426f147f29eSTejun Heo 		     struct worker_pool *pool)
3427d2c1d404STejun Heo {
3428d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3429d2c1d404STejun Heo 
3430e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
3431e50aba9aSTejun Heo 
3432d2c1d404STejun Heo 	pwq->pool = pool;
3433d2c1d404STejun Heo 	pwq->wq = wq;
3434d2c1d404STejun Heo 	pwq->flush_color = -1;
34358864b4e5STejun Heo 	pwq->refcnt = 1;
3436d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->delayed_works);
34371befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
3438d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
34398864b4e5STejun Heo 	INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3440f147f29eSTejun Heo }
3441d2c1d404STejun Heo 
3442f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
34431befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
3444f147f29eSTejun Heo {
3445f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
3446f147f29eSTejun Heo 
3447f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
344875ccf595STejun Heo 
34491befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
34501befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
34511befcf30STejun Heo 		return;
34521befcf30STejun Heo 
345329b1cb41SLai Jiangshan 	/* set the matching work_color */
345475ccf595STejun Heo 	pwq->work_color = wq->work_color;
3455983ca25eSTejun Heo 
3456983ca25eSTejun Heo 	/* sync max_active to the current setting */
3457983ca25eSTejun Heo 	pwq_adjust_max_active(pwq);
3458983ca25eSTejun Heo 
3459983ca25eSTejun Heo 	/* link in @pwq */
34609e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3461df2d5ae4STejun Heo }
34626029a918STejun Heo 
3463f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3464f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3465f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
3466f147f29eSTejun Heo {
3467f147f29eSTejun Heo 	struct worker_pool *pool;
3468f147f29eSTejun Heo 	struct pool_workqueue *pwq;
3469f147f29eSTejun Heo 
3470f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3471f147f29eSTejun Heo 
3472f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
3473f147f29eSTejun Heo 	if (!pool)
3474f147f29eSTejun Heo 		return NULL;
3475f147f29eSTejun Heo 
3476e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3477f147f29eSTejun Heo 	if (!pwq) {
3478f147f29eSTejun Heo 		put_unbound_pool(pool);
3479f147f29eSTejun Heo 		return NULL;
3480f147f29eSTejun Heo 	}
3481f147f29eSTejun Heo 
3482f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
3483f147f29eSTejun Heo 	return pwq;
3484d2c1d404STejun Heo }
3485d2c1d404STejun Heo 
34864c16bd32STejun Heo /**
348730186c6fSGong Zhaogang  * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
3488042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
34894c16bd32STejun Heo  * @node: the target NUMA node
34904c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
34914c16bd32STejun Heo  * @cpumask: outarg, the resulting cpumask
34924c16bd32STejun Heo  *
34934c16bd32STejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @node.  If
34944c16bd32STejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during
3495d185af30SYacine Belkadi  * calculation.  The result is stored in @cpumask.
34964c16bd32STejun Heo  *
34974c16bd32STejun Heo  * If NUMA affinity is not enabled, @attrs->cpumask is always used.  If
34984c16bd32STejun Heo  * enabled and @node has online CPUs requested by @attrs, the returned
34994c16bd32STejun Heo  * cpumask is the intersection of the possible CPUs of @node and
35004c16bd32STejun Heo  * @attrs->cpumask.
35014c16bd32STejun Heo  *
35024c16bd32STejun Heo  * The caller is responsible for ensuring that the cpumask of @node stays
35034c16bd32STejun Heo  * stable.
3504d185af30SYacine Belkadi  *
3505d185af30SYacine Belkadi  * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3506d185af30SYacine Belkadi  * %false if equal.
35074c16bd32STejun Heo  */
35084c16bd32STejun Heo static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
35094c16bd32STejun Heo 				 int cpu_going_down, cpumask_t *cpumask)
35104c16bd32STejun Heo {
3511d55262c4STejun Heo 	if (!wq_numa_enabled || attrs->no_numa)
35124c16bd32STejun Heo 		goto use_dfl;
35134c16bd32STejun Heo 
35144c16bd32STejun Heo 	/* does @node have any online CPUs @attrs wants? */
35154c16bd32STejun Heo 	cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
35164c16bd32STejun Heo 	if (cpu_going_down >= 0)
35174c16bd32STejun Heo 		cpumask_clear_cpu(cpu_going_down, cpumask);
35184c16bd32STejun Heo 
35194c16bd32STejun Heo 	if (cpumask_empty(cpumask))
35204c16bd32STejun Heo 		goto use_dfl;
35214c16bd32STejun Heo 
35224c16bd32STejun Heo 	/* yeap, return possible CPUs in @node that @attrs wants */
35234c16bd32STejun Heo 	cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
35244c16bd32STejun Heo 	return !cpumask_equal(cpumask, attrs->cpumask);
35254c16bd32STejun Heo 
35264c16bd32STejun Heo use_dfl:
35274c16bd32STejun Heo 	cpumask_copy(cpumask, attrs->cpumask);
35284c16bd32STejun Heo 	return false;
35294c16bd32STejun Heo }
35304c16bd32STejun Heo 
35311befcf30STejun Heo /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
35321befcf30STejun Heo static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
35331befcf30STejun Heo 						   int node,
35341befcf30STejun Heo 						   struct pool_workqueue *pwq)
35351befcf30STejun Heo {
35361befcf30STejun Heo 	struct pool_workqueue *old_pwq;
35371befcf30STejun Heo 
35385b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
35391befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
35401befcf30STejun Heo 
35411befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
35421befcf30STejun Heo 	link_pwq(pwq);
35431befcf30STejun Heo 
35441befcf30STejun Heo 	old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
35451befcf30STejun Heo 	rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
35461befcf30STejun Heo 	return old_pwq;
35471befcf30STejun Heo }
35481befcf30STejun Heo 
35492d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
35502d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
35512d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
35522d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
3553042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
35542d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
35552d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
35562d5f0764SLai Jiangshan };
35572d5f0764SLai Jiangshan 
35582d5f0764SLai Jiangshan /* free the resources after success or abort */
35592d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
35602d5f0764SLai Jiangshan {
35612d5f0764SLai Jiangshan 	if (ctx) {
35622d5f0764SLai Jiangshan 		int node;
35632d5f0764SLai Jiangshan 
35642d5f0764SLai Jiangshan 		for_each_node(node)
35652d5f0764SLai Jiangshan 			put_pwq_unlocked(ctx->pwq_tbl[node]);
35662d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
35672d5f0764SLai Jiangshan 
35682d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
35692d5f0764SLai Jiangshan 
35702d5f0764SLai Jiangshan 		kfree(ctx);
35712d5f0764SLai Jiangshan 	}
35722d5f0764SLai Jiangshan }
35732d5f0764SLai Jiangshan 
35742d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
35752d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
35762d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
35772d5f0764SLai Jiangshan 		      const struct workqueue_attrs *attrs)
35782d5f0764SLai Jiangshan {
35792d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
35802d5f0764SLai Jiangshan 	struct workqueue_attrs *new_attrs, *tmp_attrs;
35812d5f0764SLai Jiangshan 	int node;
35822d5f0764SLai Jiangshan 
35832d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
35842d5f0764SLai Jiangshan 
35852d5f0764SLai Jiangshan 	ctx = kzalloc(sizeof(*ctx) + nr_node_ids * sizeof(ctx->pwq_tbl[0]),
35862d5f0764SLai Jiangshan 		      GFP_KERNEL);
35872d5f0764SLai Jiangshan 
35882d5f0764SLai Jiangshan 	new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
35892d5f0764SLai Jiangshan 	tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
35902d5f0764SLai Jiangshan 	if (!ctx || !new_attrs || !tmp_attrs)
35912d5f0764SLai Jiangshan 		goto out_free;
35922d5f0764SLai Jiangshan 
3593042f7df1SLai Jiangshan 	/*
3594042f7df1SLai Jiangshan 	 * Calculate the attrs of the default pwq.
3595042f7df1SLai Jiangshan 	 * If the user configured cpumask doesn't overlap with the
3596042f7df1SLai Jiangshan 	 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
3597042f7df1SLai Jiangshan 	 */
35982d5f0764SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
3599b05a7928SFrederic Weisbecker 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, wq_unbound_cpumask);
3600042f7df1SLai Jiangshan 	if (unlikely(cpumask_empty(new_attrs->cpumask)))
3601042f7df1SLai Jiangshan 		cpumask_copy(new_attrs->cpumask, wq_unbound_cpumask);
36022d5f0764SLai Jiangshan 
36032d5f0764SLai Jiangshan 	/*
36042d5f0764SLai Jiangshan 	 * We may create multiple pwqs with differing cpumasks.  Make a
36052d5f0764SLai Jiangshan 	 * copy of @new_attrs which will be modified and used to obtain
36062d5f0764SLai Jiangshan 	 * pools.
36072d5f0764SLai Jiangshan 	 */
36082d5f0764SLai Jiangshan 	copy_workqueue_attrs(tmp_attrs, new_attrs);
36092d5f0764SLai Jiangshan 
36102d5f0764SLai Jiangshan 	/*
36112d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
36122d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
36132d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
36142d5f0764SLai Jiangshan 	 */
36152d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
36162d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
36172d5f0764SLai Jiangshan 		goto out_free;
36182d5f0764SLai Jiangshan 
36192d5f0764SLai Jiangshan 	for_each_node(node) {
3620042f7df1SLai Jiangshan 		if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
36212d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
36222d5f0764SLai Jiangshan 			if (!ctx->pwq_tbl[node])
36232d5f0764SLai Jiangshan 				goto out_free;
36242d5f0764SLai Jiangshan 		} else {
36252d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
36262d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = ctx->dfl_pwq;
36272d5f0764SLai Jiangshan 		}
36282d5f0764SLai Jiangshan 	}
36292d5f0764SLai Jiangshan 
3630042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
3631042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
3632042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
36332d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
3634042f7df1SLai Jiangshan 
36352d5f0764SLai Jiangshan 	ctx->wq = wq;
36362d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
36372d5f0764SLai Jiangshan 	return ctx;
36382d5f0764SLai Jiangshan 
36392d5f0764SLai Jiangshan out_free:
36402d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
36412d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
36422d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
36432d5f0764SLai Jiangshan 	return NULL;
36442d5f0764SLai Jiangshan }
36452d5f0764SLai Jiangshan 
36462d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
36472d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
36482d5f0764SLai Jiangshan {
36492d5f0764SLai Jiangshan 	int node;
36502d5f0764SLai Jiangshan 
36512d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
36522d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
36532d5f0764SLai Jiangshan 
36542d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
36552d5f0764SLai Jiangshan 
36562d5f0764SLai Jiangshan 	/* save the previous pwq and install the new one */
36572d5f0764SLai Jiangshan 	for_each_node(node)
36582d5f0764SLai Jiangshan 		ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
36592d5f0764SLai Jiangshan 							  ctx->pwq_tbl[node]);
36602d5f0764SLai Jiangshan 
36612d5f0764SLai Jiangshan 	/* @dfl_pwq might not have been used, ensure it's linked */
36622d5f0764SLai Jiangshan 	link_pwq(ctx->dfl_pwq);
36632d5f0764SLai Jiangshan 	swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
36642d5f0764SLai Jiangshan 
36652d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
36662d5f0764SLai Jiangshan }
36672d5f0764SLai Jiangshan 
3668a0111cf6SLai Jiangshan static void apply_wqattrs_lock(void)
3669a0111cf6SLai Jiangshan {
3670a0111cf6SLai Jiangshan 	/* CPUs should stay stable across pwq creations and installations */
3671a0111cf6SLai Jiangshan 	get_online_cpus();
3672a0111cf6SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
3673a0111cf6SLai Jiangshan }
3674a0111cf6SLai Jiangshan 
3675a0111cf6SLai Jiangshan static void apply_wqattrs_unlock(void)
3676a0111cf6SLai Jiangshan {
3677a0111cf6SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
3678a0111cf6SLai Jiangshan 	put_online_cpus();
3679a0111cf6SLai Jiangshan }
3680a0111cf6SLai Jiangshan 
3681a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
3682a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
3683a0111cf6SLai Jiangshan {
3684a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
3685a0111cf6SLai Jiangshan 
3686a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
3687a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
3688a0111cf6SLai Jiangshan 		return -EINVAL;
3689a0111cf6SLai Jiangshan 
3690a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
3691a0111cf6SLai Jiangshan 	if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
3692a0111cf6SLai Jiangshan 		return -EINVAL;
3693a0111cf6SLai Jiangshan 
3694a0111cf6SLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs);
36956201171eSwanghaibin 	if (!ctx)
36966201171eSwanghaibin 		return -ENOMEM;
3697a0111cf6SLai Jiangshan 
3698a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
3699a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
3700a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
3701a0111cf6SLai Jiangshan 
37026201171eSwanghaibin 	return 0;
3703a0111cf6SLai Jiangshan }
3704a0111cf6SLai Jiangshan 
37059e8cd2f5STejun Heo /**
37069e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
37079e8cd2f5STejun Heo  * @wq: the target workqueue
37089e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
37099e8cd2f5STejun Heo  *
37104c16bd32STejun Heo  * Apply @attrs to an unbound workqueue @wq.  Unless disabled, on NUMA
37114c16bd32STejun Heo  * machines, this function maps a separate pwq to each NUMA node with
37124c16bd32STejun Heo  * possibles CPUs in @attrs->cpumask so that work items are affine to the
37134c16bd32STejun Heo  * NUMA node it was issued on.  Older pwqs are released as in-flight work
37144c16bd32STejun Heo  * items finish.  Note that a work item which repeatedly requeues itself
37154c16bd32STejun Heo  * back-to-back will stay on its current pwq.
37169e8cd2f5STejun Heo  *
3717d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
3718d185af30SYacine Belkadi  *
3719d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
37209e8cd2f5STejun Heo  */
37219e8cd2f5STejun Heo int apply_workqueue_attrs(struct workqueue_struct *wq,
37229e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
37239e8cd2f5STejun Heo {
3724a0111cf6SLai Jiangshan 	int ret;
37259e8cd2f5STejun Heo 
3726a0111cf6SLai Jiangshan 	apply_wqattrs_lock();
3727a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
3728a0111cf6SLai Jiangshan 	apply_wqattrs_unlock();
37292d5f0764SLai Jiangshan 
37302d5f0764SLai Jiangshan 	return ret;
37319e8cd2f5STejun Heo }
37329e8cd2f5STejun Heo 
37334c16bd32STejun Heo /**
37344c16bd32STejun Heo  * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
37354c16bd32STejun Heo  * @wq: the target workqueue
37364c16bd32STejun Heo  * @cpu: the CPU coming up or going down
37374c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
37384c16bd32STejun Heo  *
37394c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
37404c16bd32STejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update NUMA affinity of
37414c16bd32STejun Heo  * @wq accordingly.
37424c16bd32STejun Heo  *
37434c16bd32STejun Heo  * If NUMA affinity can't be adjusted due to memory allocation failure, it
37444c16bd32STejun Heo  * falls back to @wq->dfl_pwq which may not be optimal but is always
37454c16bd32STejun Heo  * correct.
37464c16bd32STejun Heo  *
37474c16bd32STejun Heo  * Note that when the last allowed CPU of a NUMA node goes offline for a
37484c16bd32STejun Heo  * workqueue with a cpumask spanning multiple nodes, the workers which were
37494c16bd32STejun Heo  * already executing the work items for the workqueue will lose their CPU
37504c16bd32STejun Heo  * affinity and may execute on any CPU.  This is similar to how per-cpu
37514c16bd32STejun Heo  * workqueues behave on CPU_DOWN.  If a workqueue user wants strict
37524c16bd32STejun Heo  * affinity, it's the user's responsibility to flush the work item from
37534c16bd32STejun Heo  * CPU_DOWN_PREPARE.
37544c16bd32STejun Heo  */
37554c16bd32STejun Heo static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
37564c16bd32STejun Heo 				   bool online)
37574c16bd32STejun Heo {
37584c16bd32STejun Heo 	int node = cpu_to_node(cpu);
37594c16bd32STejun Heo 	int cpu_off = online ? -1 : cpu;
37604c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
37614c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
37624c16bd32STejun Heo 	cpumask_t *cpumask;
37634c16bd32STejun Heo 
37644c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
37654c16bd32STejun Heo 
3766f7142ed4SLai Jiangshan 	if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
3767f7142ed4SLai Jiangshan 	    wq->unbound_attrs->no_numa)
37684c16bd32STejun Heo 		return;
37694c16bd32STejun Heo 
37704c16bd32STejun Heo 	/*
37714c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
37724c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
37734c16bd32STejun Heo 	 * CPU hotplug exclusion.
37744c16bd32STejun Heo 	 */
37754c16bd32STejun Heo 	target_attrs = wq_update_unbound_numa_attrs_buf;
37764c16bd32STejun Heo 	cpumask = target_attrs->cpumask;
37774c16bd32STejun Heo 
37784c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
37794c16bd32STejun Heo 	pwq = unbound_pwq_by_node(wq, node);
37804c16bd32STejun Heo 
37814c16bd32STejun Heo 	/*
37824c16bd32STejun Heo 	 * Let's determine what needs to be done.  If the target cpumask is
3783042f7df1SLai Jiangshan 	 * different from the default pwq's, we need to compare it to @pwq's
3784042f7df1SLai Jiangshan 	 * and create a new one if they don't match.  If the target cpumask
3785042f7df1SLai Jiangshan 	 * equals the default pwq's, the default pwq should be used.
37864c16bd32STejun Heo 	 */
3787042f7df1SLai Jiangshan 	if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
37884c16bd32STejun Heo 		if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
3789f7142ed4SLai Jiangshan 			return;
37904c16bd32STejun Heo 	} else {
37914c16bd32STejun Heo 		goto use_dfl_pwq;
37924c16bd32STejun Heo 	}
37934c16bd32STejun Heo 
37944c16bd32STejun Heo 	/* create a new pwq */
37954c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
37964c16bd32STejun Heo 	if (!pwq) {
37972d916033SFabian Frederick 		pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
37984c16bd32STejun Heo 			wq->name);
379977f300b1SDaeseok Youn 		goto use_dfl_pwq;
38004c16bd32STejun Heo 	}
38014c16bd32STejun Heo 
3802f7142ed4SLai Jiangshan 	/* Install the new pwq. */
38034c16bd32STejun Heo 	mutex_lock(&wq->mutex);
38044c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, pwq);
38054c16bd32STejun Heo 	goto out_unlock;
38064c16bd32STejun Heo 
38074c16bd32STejun Heo use_dfl_pwq:
3808f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
38094c16bd32STejun Heo 	spin_lock_irq(&wq->dfl_pwq->pool->lock);
38104c16bd32STejun Heo 	get_pwq(wq->dfl_pwq);
38114c16bd32STejun Heo 	spin_unlock_irq(&wq->dfl_pwq->pool->lock);
38124c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
38134c16bd32STejun Heo out_unlock:
38144c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
38154c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
38164c16bd32STejun Heo }
38174c16bd32STejun Heo 
381830cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
38191da177e4SLinus Torvalds {
382049e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
38218a2b7538STejun Heo 	int cpu, ret;
3822e1d8aa9fSFrederic Weisbecker 
382330cdf249STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
3824420c0ddbSTejun Heo 		wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
3825420c0ddbSTejun Heo 		if (!wq->cpu_pwqs)
382630cdf249STejun Heo 			return -ENOMEM;
382730cdf249STejun Heo 
382830cdf249STejun Heo 		for_each_possible_cpu(cpu) {
38297fb98ea7STejun Heo 			struct pool_workqueue *pwq =
38307fb98ea7STejun Heo 				per_cpu_ptr(wq->cpu_pwqs, cpu);
38317a62c2c8STejun Heo 			struct worker_pool *cpu_pools =
3832f02ae73aSTejun Heo 				per_cpu(cpu_worker_pools, cpu);
383330cdf249STejun Heo 
3834f147f29eSTejun Heo 			init_pwq(pwq, wq, &cpu_pools[highpri]);
3835f147f29eSTejun Heo 
3836f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
38371befcf30STejun Heo 			link_pwq(pwq);
3838f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
383930cdf249STejun Heo 		}
384030cdf249STejun Heo 		return 0;
38418a2b7538STejun Heo 	} else if (wq->flags & __WQ_ORDERED) {
38428a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
38438a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
38448a2b7538STejun Heo 		WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
38458a2b7538STejun Heo 			      wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
38468a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
38478a2b7538STejun Heo 		return ret;
38489e8cd2f5STejun Heo 	} else {
38499e8cd2f5STejun Heo 		return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
38509e8cd2f5STejun Heo 	}
38510f900049STejun Heo }
38520f900049STejun Heo 
3853f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
3854f3421797STejun Heo 			       const char *name)
3855b71ab8c2STejun Heo {
3856f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3857f3421797STejun Heo 
3858f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
3859044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3860f3421797STejun Heo 			max_active, name, 1, lim);
3861b71ab8c2STejun Heo 
3862f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
3863b71ab8c2STejun Heo }
3864b71ab8c2STejun Heo 
3865b196be89STejun Heo struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
386697e37d7bSTejun Heo 					       unsigned int flags,
38671e19ffc6STejun Heo 					       int max_active,
3868eb13ba87SJohannes Berg 					       struct lock_class_key *key,
3869b196be89STejun Heo 					       const char *lock_name, ...)
38703af24433SOleg Nesterov {
3871df2d5ae4STejun Heo 	size_t tbl_size = 0;
3872ecf6881fSTejun Heo 	va_list args;
38733af24433SOleg Nesterov 	struct workqueue_struct *wq;
387449e3cf44STejun Heo 	struct pool_workqueue *pwq;
3875b196be89STejun Heo 
3876cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
3877cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
3878cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
3879cee22a15SViresh Kumar 
3880ecf6881fSTejun Heo 	/* allocate wq and format name */
3881df2d5ae4STejun Heo 	if (flags & WQ_UNBOUND)
3882ddcb57e2SLai Jiangshan 		tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
3883df2d5ae4STejun Heo 
3884df2d5ae4STejun Heo 	wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
3885b196be89STejun Heo 	if (!wq)
3886d2c1d404STejun Heo 		return NULL;
3887b196be89STejun Heo 
38886029a918STejun Heo 	if (flags & WQ_UNBOUND) {
38896029a918STejun Heo 		wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
38906029a918STejun Heo 		if (!wq->unbound_attrs)
38916029a918STejun Heo 			goto err_free_wq;
38926029a918STejun Heo 	}
38936029a918STejun Heo 
3894ecf6881fSTejun Heo 	va_start(args, lock_name);
3895ecf6881fSTejun Heo 	vsnprintf(wq->name, sizeof(wq->name), fmt, args);
3896b196be89STejun Heo 	va_end(args);
38973af24433SOleg Nesterov 
3898d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
3899b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
39003af24433SOleg Nesterov 
3901b196be89STejun Heo 	/* init wq */
390297e37d7bSTejun Heo 	wq->flags = flags;
3903a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
39043c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
3905112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
390630cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
390773f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
390873f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
3909493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
39103af24433SOleg Nesterov 
3911eb13ba87SJohannes Berg 	lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3912cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
39133af24433SOleg Nesterov 
391430cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
3915d2c1d404STejun Heo 		goto err_free_wq;
39161537663fSTejun Heo 
3917493008a8STejun Heo 	/*
3918493008a8STejun Heo 	 * Workqueues which may be used during memory reclaim should
3919493008a8STejun Heo 	 * have a rescuer to guarantee forward progress.
3920493008a8STejun Heo 	 */
3921493008a8STejun Heo 	if (flags & WQ_MEM_RECLAIM) {
3922e22bee78STejun Heo 		struct worker *rescuer;
3923e22bee78STejun Heo 
3924f7537df5SLai Jiangshan 		rescuer = alloc_worker(NUMA_NO_NODE);
3925e22bee78STejun Heo 		if (!rescuer)
3926d2c1d404STejun Heo 			goto err_destroy;
3927e22bee78STejun Heo 
3928111c225aSTejun Heo 		rescuer->rescue_wq = wq;
3929111c225aSTejun Heo 		rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3930b196be89STejun Heo 					       wq->name);
3931d2c1d404STejun Heo 		if (IS_ERR(rescuer->task)) {
3932d2c1d404STejun Heo 			kfree(rescuer);
3933d2c1d404STejun Heo 			goto err_destroy;
3934d2c1d404STejun Heo 		}
3935e22bee78STejun Heo 
3936d2c1d404STejun Heo 		wq->rescuer = rescuer;
393725834c73SPeter Zijlstra 		kthread_bind_mask(rescuer->task, cpu_possible_mask);
3938e22bee78STejun Heo 		wake_up_process(rescuer->task);
39393af24433SOleg Nesterov 	}
39401537663fSTejun Heo 
3941226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
3942226223abSTejun Heo 		goto err_destroy;
3943226223abSTejun Heo 
39443af24433SOleg Nesterov 	/*
394568e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
394668e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
394768e13a67SLai Jiangshan 	 * list.
39483af24433SOleg Nesterov 	 */
394968e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
3950a0a1a5fdSTejun Heo 
3951a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
395249e3cf44STejun Heo 	for_each_pwq(pwq, wq)
3953699ce097STejun Heo 		pwq_adjust_max_active(pwq);
3954a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
3955a0a1a5fdSTejun Heo 
3956e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
3957a0a1a5fdSTejun Heo 
395868e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
39593af24433SOleg Nesterov 
39603af24433SOleg Nesterov 	return wq;
3961d2c1d404STejun Heo 
3962d2c1d404STejun Heo err_free_wq:
39636029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
39644690c4abSTejun Heo 	kfree(wq);
3965d2c1d404STejun Heo 	return NULL;
3966d2c1d404STejun Heo err_destroy:
3967d2c1d404STejun Heo 	destroy_workqueue(wq);
39684690c4abSTejun Heo 	return NULL;
39691da177e4SLinus Torvalds }
3970d320c038STejun Heo EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
39711da177e4SLinus Torvalds 
39723af24433SOleg Nesterov /**
39733af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
39743af24433SOleg Nesterov  * @wq: target workqueue
39753af24433SOleg Nesterov  *
39763af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
39773af24433SOleg Nesterov  */
39783af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
39793af24433SOleg Nesterov {
398049e3cf44STejun Heo 	struct pool_workqueue *pwq;
39814c16bd32STejun Heo 	int node;
39823af24433SOleg Nesterov 
39839c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
39849c5a2ba7STejun Heo 	drain_workqueue(wq);
3985c8efcc25STejun Heo 
39866183c009STejun Heo 	/* sanity checks */
3987b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
398849e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
39896183c009STejun Heo 		int i;
39906183c009STejun Heo 
399176af4d93STejun Heo 		for (i = 0; i < WORK_NR_COLORS; i++) {
399276af4d93STejun Heo 			if (WARN_ON(pwq->nr_in_flight[i])) {
3993b09f4fd3SLai Jiangshan 				mutex_unlock(&wq->mutex);
39946183c009STejun Heo 				return;
399576af4d93STejun Heo 			}
399676af4d93STejun Heo 		}
399776af4d93STejun Heo 
39985c529597SLai Jiangshan 		if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
39998864b4e5STejun Heo 		    WARN_ON(pwq->nr_active) ||
400076af4d93STejun Heo 		    WARN_ON(!list_empty(&pwq->delayed_works))) {
4001b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
40026183c009STejun Heo 			return;
40036183c009STejun Heo 		}
400476af4d93STejun Heo 	}
4005b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
40066183c009STejun Heo 
4007a0a1a5fdSTejun Heo 	/*
4008a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
4009a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
4010a0a1a5fdSTejun Heo 	 */
401168e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4012e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
401368e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
40143af24433SOleg Nesterov 
4015226223abSTejun Heo 	workqueue_sysfs_unregister(wq);
4016226223abSTejun Heo 
4017e2dca7adSTejun Heo 	if (wq->rescuer)
4018e22bee78STejun Heo 		kthread_stop(wq->rescuer->task);
4019e22bee78STejun Heo 
40208864b4e5STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
402129c91e99STejun Heo 		/*
40228864b4e5STejun Heo 		 * The base ref is never dropped on per-cpu pwqs.  Directly
4023e2dca7adSTejun Heo 		 * schedule RCU free.
402429c91e99STejun Heo 		 */
4025e2dca7adSTejun Heo 		call_rcu_sched(&wq->rcu, rcu_free_wq);
40268864b4e5STejun Heo 	} else {
40278864b4e5STejun Heo 		/*
40288864b4e5STejun Heo 		 * We're the sole accessor of @wq at this point.  Directly
40294c16bd32STejun Heo 		 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
40304c16bd32STejun Heo 		 * @wq will be freed when the last pwq is released.
40318864b4e5STejun Heo 		 */
40324c16bd32STejun Heo 		for_each_node(node) {
40334c16bd32STejun Heo 			pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
40344c16bd32STejun Heo 			RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
40354c16bd32STejun Heo 			put_pwq_unlocked(pwq);
40364c16bd32STejun Heo 		}
40374c16bd32STejun Heo 
40384c16bd32STejun Heo 		/*
40394c16bd32STejun Heo 		 * Put dfl_pwq.  @wq may be freed any time after dfl_pwq is
40404c16bd32STejun Heo 		 * put.  Don't access it afterwards.
40414c16bd32STejun Heo 		 */
40424c16bd32STejun Heo 		pwq = wq->dfl_pwq;
40434c16bd32STejun Heo 		wq->dfl_pwq = NULL;
4044dce90d47STejun Heo 		put_pwq_unlocked(pwq);
404529c91e99STejun Heo 	}
40463af24433SOleg Nesterov }
40473af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
40483af24433SOleg Nesterov 
4049dcd989cbSTejun Heo /**
4050dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
4051dcd989cbSTejun Heo  * @wq: target workqueue
4052dcd989cbSTejun Heo  * @max_active: new max_active value.
4053dcd989cbSTejun Heo  *
4054dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
4055dcd989cbSTejun Heo  *
4056dcd989cbSTejun Heo  * CONTEXT:
4057dcd989cbSTejun Heo  * Don't call from IRQ context.
4058dcd989cbSTejun Heo  */
4059dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4060dcd989cbSTejun Heo {
406149e3cf44STejun Heo 	struct pool_workqueue *pwq;
4062dcd989cbSTejun Heo 
40638719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
40648719dceaSTejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED))
40658719dceaSTejun Heo 		return;
40668719dceaSTejun Heo 
4067f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4068dcd989cbSTejun Heo 
4069a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4070dcd989cbSTejun Heo 
4071dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4072dcd989cbSTejun Heo 
4073699ce097STejun Heo 	for_each_pwq(pwq, wq)
4074699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4075dcd989cbSTejun Heo 
4076a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4077dcd989cbSTejun Heo }
4078dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4079dcd989cbSTejun Heo 
4080dcd989cbSTejun Heo /**
4081e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4082e6267616STejun Heo  *
4083e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4084e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4085d185af30SYacine Belkadi  *
4086d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
4087e6267616STejun Heo  */
4088e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4089e6267616STejun Heo {
4090e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4091e6267616STejun Heo 
40926a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
4093e6267616STejun Heo }
4094e6267616STejun Heo 
4095e6267616STejun Heo /**
4096dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4097dcd989cbSTejun Heo  * @cpu: CPU in question
4098dcd989cbSTejun Heo  * @wq: target workqueue
4099dcd989cbSTejun Heo  *
4100dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4101dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4102dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4103dcd989cbSTejun Heo  *
4104d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4105d3251859STejun Heo  * Note that both per-cpu and unbound workqueues may be associated with
4106d3251859STejun Heo  * multiple pool_workqueues which have separate congested states.  A
4107d3251859STejun Heo  * workqueue being congested on one CPU doesn't mean the workqueue is also
4108d3251859STejun Heo  * contested on other CPUs / NUMA nodes.
4109d3251859STejun Heo  *
4110d185af30SYacine Belkadi  * Return:
4111dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4112dcd989cbSTejun Heo  */
4113d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4114dcd989cbSTejun Heo {
41157fb98ea7STejun Heo 	struct pool_workqueue *pwq;
411676af4d93STejun Heo 	bool ret;
411776af4d93STejun Heo 
411888109453SLai Jiangshan 	rcu_read_lock_sched();
41197fb98ea7STejun Heo 
4120d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
4121d3251859STejun Heo 		cpu = smp_processor_id();
4122d3251859STejun Heo 
41237fb98ea7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
41247fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
41257fb98ea7STejun Heo 	else
4126df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4127dcd989cbSTejun Heo 
412876af4d93STejun Heo 	ret = !list_empty(&pwq->delayed_works);
412988109453SLai Jiangshan 	rcu_read_unlock_sched();
413076af4d93STejun Heo 
413176af4d93STejun Heo 	return ret;
4132dcd989cbSTejun Heo }
4133dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4134dcd989cbSTejun Heo 
4135dcd989cbSTejun Heo /**
4136dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4137dcd989cbSTejun Heo  * @work: the work to be tested
4138dcd989cbSTejun Heo  *
4139dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4140dcd989cbSTejun Heo  * synchronization around this function and the test result is
4141dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4142dcd989cbSTejun Heo  *
4143d185af30SYacine Belkadi  * Return:
4144dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
4145dcd989cbSTejun Heo  */
4146dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4147dcd989cbSTejun Heo {
4148fa1b54e6STejun Heo 	struct worker_pool *pool;
4149dcd989cbSTejun Heo 	unsigned long flags;
4150dcd989cbSTejun Heo 	unsigned int ret = 0;
4151dcd989cbSTejun Heo 
4152dcd989cbSTejun Heo 	if (work_pending(work))
4153dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
4154038366c5SLai Jiangshan 
4155fa1b54e6STejun Heo 	local_irq_save(flags);
4156fa1b54e6STejun Heo 	pool = get_work_pool(work);
4157038366c5SLai Jiangshan 	if (pool) {
4158fa1b54e6STejun Heo 		spin_lock(&pool->lock);
4159c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
4160dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
4161fa1b54e6STejun Heo 		spin_unlock(&pool->lock);
4162038366c5SLai Jiangshan 	}
4163fa1b54e6STejun Heo 	local_irq_restore(flags);
4164dcd989cbSTejun Heo 
4165dcd989cbSTejun Heo 	return ret;
4166dcd989cbSTejun Heo }
4167dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
4168dcd989cbSTejun Heo 
41693d1cb205STejun Heo /**
41703d1cb205STejun Heo  * set_worker_desc - set description for the current work item
41713d1cb205STejun Heo  * @fmt: printf-style format string
41723d1cb205STejun Heo  * @...: arguments for the format string
41733d1cb205STejun Heo  *
41743d1cb205STejun Heo  * This function can be called by a running work function to describe what
41753d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
41763d1cb205STejun Heo  * information will be printed out together to help debugging.  The
41773d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
41783d1cb205STejun Heo  */
41793d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
41803d1cb205STejun Heo {
41813d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
41823d1cb205STejun Heo 	va_list args;
41833d1cb205STejun Heo 
41843d1cb205STejun Heo 	if (worker) {
41853d1cb205STejun Heo 		va_start(args, fmt);
41863d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
41873d1cb205STejun Heo 		va_end(args);
41883d1cb205STejun Heo 		worker->desc_valid = true;
41893d1cb205STejun Heo 	}
41903d1cb205STejun Heo }
41913d1cb205STejun Heo 
41923d1cb205STejun Heo /**
41933d1cb205STejun Heo  * print_worker_info - print out worker information and description
41943d1cb205STejun Heo  * @log_lvl: the log level to use when printing
41953d1cb205STejun Heo  * @task: target task
41963d1cb205STejun Heo  *
41973d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
41983d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
41993d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
42003d1cb205STejun Heo  *
42013d1cb205STejun Heo  * This function can be safely called on any task as long as the
42023d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
42033d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
42043d1cb205STejun Heo  */
42053d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
42063d1cb205STejun Heo {
42073d1cb205STejun Heo 	work_func_t *fn = NULL;
42083d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
42093d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
42103d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
42113d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
42123d1cb205STejun Heo 	bool desc_valid = false;
42133d1cb205STejun Heo 	struct worker *worker;
42143d1cb205STejun Heo 
42153d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
42163d1cb205STejun Heo 		return;
42173d1cb205STejun Heo 
42183d1cb205STejun Heo 	/*
42193d1cb205STejun Heo 	 * This function is called without any synchronization and @task
42203d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
42213d1cb205STejun Heo 	 */
42223d1cb205STejun Heo 	worker = probe_kthread_data(task);
42233d1cb205STejun Heo 
42243d1cb205STejun Heo 	/*
42253d1cb205STejun Heo 	 * Carefully copy the associated workqueue's workfn and name.  Keep
42263d1cb205STejun Heo 	 * the original last '\0' in case the original contains garbage.
42273d1cb205STejun Heo 	 */
42283d1cb205STejun Heo 	probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
42293d1cb205STejun Heo 	probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
42303d1cb205STejun Heo 	probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
42313d1cb205STejun Heo 	probe_kernel_read(name, wq->name, sizeof(name) - 1);
42323d1cb205STejun Heo 
42333d1cb205STejun Heo 	/* copy worker description */
42343d1cb205STejun Heo 	probe_kernel_read(&desc_valid, &worker->desc_valid, sizeof(desc_valid));
42353d1cb205STejun Heo 	if (desc_valid)
42363d1cb205STejun Heo 		probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
42373d1cb205STejun Heo 
42383d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
42393d1cb205STejun Heo 		printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
42403d1cb205STejun Heo 		if (desc[0])
42413d1cb205STejun Heo 			pr_cont(" (%s)", desc);
42423d1cb205STejun Heo 		pr_cont("\n");
42433d1cb205STejun Heo 	}
42443d1cb205STejun Heo }
42453d1cb205STejun Heo 
42463494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
42473494fc30STejun Heo {
42483494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
42493494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
42503494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
42513494fc30STejun Heo 	pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
42523494fc30STejun Heo }
42533494fc30STejun Heo 
42543494fc30STejun Heo static void pr_cont_work(bool comma, struct work_struct *work)
42553494fc30STejun Heo {
42563494fc30STejun Heo 	if (work->func == wq_barrier_func) {
42573494fc30STejun Heo 		struct wq_barrier *barr;
42583494fc30STejun Heo 
42593494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
42603494fc30STejun Heo 
42613494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
42623494fc30STejun Heo 			task_pid_nr(barr->task));
42633494fc30STejun Heo 	} else {
42643494fc30STejun Heo 		pr_cont("%s %pf", comma ? "," : "", work->func);
42653494fc30STejun Heo 	}
42663494fc30STejun Heo }
42673494fc30STejun Heo 
42683494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
42693494fc30STejun Heo {
42703494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
42713494fc30STejun Heo 	struct work_struct *work;
42723494fc30STejun Heo 	struct worker *worker;
42733494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
42743494fc30STejun Heo 	int bkt;
42753494fc30STejun Heo 
42763494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
42773494fc30STejun Heo 	pr_cont_pool_info(pool);
42783494fc30STejun Heo 
42793494fc30STejun Heo 	pr_cont(" active=%d/%d%s\n", pwq->nr_active, pwq->max_active,
42803494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
42813494fc30STejun Heo 
42823494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
42833494fc30STejun Heo 		if (worker->current_pwq == pwq) {
42843494fc30STejun Heo 			has_in_flight = true;
42853494fc30STejun Heo 			break;
42863494fc30STejun Heo 		}
42873494fc30STejun Heo 	}
42883494fc30STejun Heo 	if (has_in_flight) {
42893494fc30STejun Heo 		bool comma = false;
42903494fc30STejun Heo 
42913494fc30STejun Heo 		pr_info("    in-flight:");
42923494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
42933494fc30STejun Heo 			if (worker->current_pwq != pwq)
42943494fc30STejun Heo 				continue;
42953494fc30STejun Heo 
42963494fc30STejun Heo 			pr_cont("%s %d%s:%pf", comma ? "," : "",
42973494fc30STejun Heo 				task_pid_nr(worker->task),
42983494fc30STejun Heo 				worker == pwq->wq->rescuer ? "(RESCUER)" : "",
42993494fc30STejun Heo 				worker->current_func);
43003494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
43013494fc30STejun Heo 				pr_cont_work(false, work);
43023494fc30STejun Heo 			comma = true;
43033494fc30STejun Heo 		}
43043494fc30STejun Heo 		pr_cont("\n");
43053494fc30STejun Heo 	}
43063494fc30STejun Heo 
43073494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
43083494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
43093494fc30STejun Heo 			has_pending = true;
43103494fc30STejun Heo 			break;
43113494fc30STejun Heo 		}
43123494fc30STejun Heo 	}
43133494fc30STejun Heo 	if (has_pending) {
43143494fc30STejun Heo 		bool comma = false;
43153494fc30STejun Heo 
43163494fc30STejun Heo 		pr_info("    pending:");
43173494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
43183494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
43193494fc30STejun Heo 				continue;
43203494fc30STejun Heo 
43213494fc30STejun Heo 			pr_cont_work(comma, work);
43223494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
43233494fc30STejun Heo 		}
43243494fc30STejun Heo 		pr_cont("\n");
43253494fc30STejun Heo 	}
43263494fc30STejun Heo 
43273494fc30STejun Heo 	if (!list_empty(&pwq->delayed_works)) {
43283494fc30STejun Heo 		bool comma = false;
43293494fc30STejun Heo 
43303494fc30STejun Heo 		pr_info("    delayed:");
43313494fc30STejun Heo 		list_for_each_entry(work, &pwq->delayed_works, entry) {
43323494fc30STejun Heo 			pr_cont_work(comma, work);
43333494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
43343494fc30STejun Heo 		}
43353494fc30STejun Heo 		pr_cont("\n");
43363494fc30STejun Heo 	}
43373494fc30STejun Heo }
43383494fc30STejun Heo 
43393494fc30STejun Heo /**
43403494fc30STejun Heo  * show_workqueue_state - dump workqueue state
43413494fc30STejun Heo  *
43423494fc30STejun Heo  * Called from a sysrq handler and prints out all busy workqueues and
43433494fc30STejun Heo  * pools.
43443494fc30STejun Heo  */
43453494fc30STejun Heo void show_workqueue_state(void)
43463494fc30STejun Heo {
43473494fc30STejun Heo 	struct workqueue_struct *wq;
43483494fc30STejun Heo 	struct worker_pool *pool;
43493494fc30STejun Heo 	unsigned long flags;
43503494fc30STejun Heo 	int pi;
43513494fc30STejun Heo 
43523494fc30STejun Heo 	rcu_read_lock_sched();
43533494fc30STejun Heo 
43543494fc30STejun Heo 	pr_info("Showing busy workqueues and worker pools:\n");
43553494fc30STejun Heo 
43563494fc30STejun Heo 	list_for_each_entry_rcu(wq, &workqueues, list) {
43573494fc30STejun Heo 		struct pool_workqueue *pwq;
43583494fc30STejun Heo 		bool idle = true;
43593494fc30STejun Heo 
43603494fc30STejun Heo 		for_each_pwq(pwq, wq) {
43613494fc30STejun Heo 			if (pwq->nr_active || !list_empty(&pwq->delayed_works)) {
43623494fc30STejun Heo 				idle = false;
43633494fc30STejun Heo 				break;
43643494fc30STejun Heo 			}
43653494fc30STejun Heo 		}
43663494fc30STejun Heo 		if (idle)
43673494fc30STejun Heo 			continue;
43683494fc30STejun Heo 
43693494fc30STejun Heo 		pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
43703494fc30STejun Heo 
43713494fc30STejun Heo 		for_each_pwq(pwq, wq) {
43723494fc30STejun Heo 			spin_lock_irqsave(&pwq->pool->lock, flags);
43733494fc30STejun Heo 			if (pwq->nr_active || !list_empty(&pwq->delayed_works))
43743494fc30STejun Heo 				show_pwq(pwq);
43753494fc30STejun Heo 			spin_unlock_irqrestore(&pwq->pool->lock, flags);
43763494fc30STejun Heo 		}
43773494fc30STejun Heo 	}
43783494fc30STejun Heo 
43793494fc30STejun Heo 	for_each_pool(pool, pi) {
43803494fc30STejun Heo 		struct worker *worker;
43813494fc30STejun Heo 		bool first = true;
43823494fc30STejun Heo 
43833494fc30STejun Heo 		spin_lock_irqsave(&pool->lock, flags);
43843494fc30STejun Heo 		if (pool->nr_workers == pool->nr_idle)
43853494fc30STejun Heo 			goto next_pool;
43863494fc30STejun Heo 
43873494fc30STejun Heo 		pr_info("pool %d:", pool->id);
43883494fc30STejun Heo 		pr_cont_pool_info(pool);
438982607adcSTejun Heo 		pr_cont(" hung=%us workers=%d",
439082607adcSTejun Heo 			jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000,
439182607adcSTejun Heo 			pool->nr_workers);
43923494fc30STejun Heo 		if (pool->manager)
43933494fc30STejun Heo 			pr_cont(" manager: %d",
43943494fc30STejun Heo 				task_pid_nr(pool->manager->task));
43953494fc30STejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry) {
43963494fc30STejun Heo 			pr_cont(" %s%d", first ? "idle: " : "",
43973494fc30STejun Heo 				task_pid_nr(worker->task));
43983494fc30STejun Heo 			first = false;
43993494fc30STejun Heo 		}
44003494fc30STejun Heo 		pr_cont("\n");
44013494fc30STejun Heo 	next_pool:
44023494fc30STejun Heo 		spin_unlock_irqrestore(&pool->lock, flags);
44033494fc30STejun Heo 	}
44043494fc30STejun Heo 
44053494fc30STejun Heo 	rcu_read_unlock_sched();
44063494fc30STejun Heo }
44073494fc30STejun Heo 
4408db7bccf4STejun Heo /*
4409db7bccf4STejun Heo  * CPU hotplug.
4410db7bccf4STejun Heo  *
4411e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
4412112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
4413706026c2STejun Heo  * pool which make migrating pending and scheduled works very
4414e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
441594cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
4416e22bee78STejun Heo  * blocked draining impractical.
4417e22bee78STejun Heo  *
441824647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
4419628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
4420628c78e7STejun Heo  * cpu comes back online.
4421db7bccf4STejun Heo  */
4422db7bccf4STejun Heo 
4423706026c2STejun Heo static void wq_unbind_fn(struct work_struct *work)
4424db7bccf4STejun Heo {
442538db41d9STejun Heo 	int cpu = smp_processor_id();
44264ce62e9eSTejun Heo 	struct worker_pool *pool;
4427db7bccf4STejun Heo 	struct worker *worker;
4428db7bccf4STejun Heo 
4429f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
443092f9c5c4SLai Jiangshan 		mutex_lock(&pool->attach_mutex);
443194cf58bbSTejun Heo 		spin_lock_irq(&pool->lock);
4432e22bee78STejun Heo 
4433f2d5a0eeSTejun Heo 		/*
443492f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
443594cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
443694cf58bbSTejun Heo 		 * except for the ones which are still executing works from
443794cf58bbSTejun Heo 		 * before the last CPU down must be on the cpu.  After
443894cf58bbSTejun Heo 		 * this, they may become diasporas.
4439f2d5a0eeSTejun Heo 		 */
4440da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
4441403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
4442db7bccf4STejun Heo 
444324647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
4444f2d5a0eeSTejun Heo 
444594cf58bbSTejun Heo 		spin_unlock_irq(&pool->lock);
444692f9c5c4SLai Jiangshan 		mutex_unlock(&pool->attach_mutex);
4447e22bee78STejun Heo 
4448e22bee78STejun Heo 		/*
4449eb283428SLai Jiangshan 		 * Call schedule() so that we cross rq->lock and thus can
4450eb283428SLai Jiangshan 		 * guarantee sched callbacks see the %WORKER_UNBOUND flag.
4451eb283428SLai Jiangshan 		 * This is necessary as scheduler callbacks may be invoked
4452eb283428SLai Jiangshan 		 * from other cpus.
4453628c78e7STejun Heo 		 */
4454628c78e7STejun Heo 		schedule();
4455628c78e7STejun Heo 
4456628c78e7STejun Heo 		/*
4457eb283428SLai Jiangshan 		 * Sched callbacks are disabled now.  Zap nr_running.
4458eb283428SLai Jiangshan 		 * After this, nr_running stays zero and need_more_worker()
4459eb283428SLai Jiangshan 		 * and keep_working() are always true as long as the
4460eb283428SLai Jiangshan 		 * worklist is not empty.  This pool now behaves as an
4461eb283428SLai Jiangshan 		 * unbound (in terms of concurrency management) pool which
4462eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
4463e22bee78STejun Heo 		 */
4464e19e397aSTejun Heo 		atomic_set(&pool->nr_running, 0);
4465eb283428SLai Jiangshan 
4466eb283428SLai Jiangshan 		/*
4467eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
4468eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
4469eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
4470eb283428SLai Jiangshan 		 */
4471eb283428SLai Jiangshan 		spin_lock_irq(&pool->lock);
4472eb283428SLai Jiangshan 		wake_up_worker(pool);
4473eb283428SLai Jiangshan 		spin_unlock_irq(&pool->lock);
4474eb283428SLai Jiangshan 	}
4475db7bccf4STejun Heo }
4476db7bccf4STejun Heo 
4477bd7c089eSTejun Heo /**
4478bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
4479bd7c089eSTejun Heo  * @pool: pool of interest
4480bd7c089eSTejun Heo  *
4481a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
4482bd7c089eSTejun Heo  */
4483bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
4484bd7c089eSTejun Heo {
4485a9ab775bSTejun Heo 	struct worker *worker;
4486bd7c089eSTejun Heo 
448792f9c5c4SLai Jiangshan 	lockdep_assert_held(&pool->attach_mutex);
4488bd7c089eSTejun Heo 
4489bd7c089eSTejun Heo 	/*
4490a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
4491a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
4492402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
4493a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
4494a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
4495bd7c089eSTejun Heo 	 */
4496da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
4497a9ab775bSTejun Heo 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4498a9ab775bSTejun Heo 						  pool->attrs->cpumask) < 0);
4499a9ab775bSTejun Heo 
4500a9ab775bSTejun Heo 	spin_lock_irq(&pool->lock);
45013de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
4502a9ab775bSTejun Heo 
4503da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
4504a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
4505a9ab775bSTejun Heo 
4506a9ab775bSTejun Heo 		/*
4507a9ab775bSTejun Heo 		 * A bound idle worker should actually be on the runqueue
4508a9ab775bSTejun Heo 		 * of the associated CPU for local wake-ups targeting it to
4509a9ab775bSTejun Heo 		 * work.  Kick all idle workers so that they migrate to the
4510a9ab775bSTejun Heo 		 * associated CPU.  Doing this in the same loop as
4511a9ab775bSTejun Heo 		 * replacing UNBOUND with REBOUND is safe as no worker will
4512a9ab775bSTejun Heo 		 * be bound before @pool->lock is released.
4513a9ab775bSTejun Heo 		 */
4514a9ab775bSTejun Heo 		if (worker_flags & WORKER_IDLE)
4515bd7c089eSTejun Heo 			wake_up_process(worker->task);
4516bd7c089eSTejun Heo 
4517bd7c089eSTejun Heo 		/*
4518a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
4519a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
4520a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4521a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
4522a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
4523a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
4524a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
4525a9ab775bSTejun Heo 		 *
4526a9ab775bSTejun Heo 		 * ACCESS_ONCE() is necessary because @worker->flags may be
4527a9ab775bSTejun Heo 		 * tested without holding any lock in
4528a9ab775bSTejun Heo 		 * wq_worker_waking_up().  Without it, NOT_RUNNING test may
4529a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
4530a9ab775bSTejun Heo 		 * management operations.
4531bd7c089eSTejun Heo 		 */
4532a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4533a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
4534a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
4535a9ab775bSTejun Heo 		ACCESS_ONCE(worker->flags) = worker_flags;
4536bd7c089eSTejun Heo 	}
4537a9ab775bSTejun Heo 
4538a9ab775bSTejun Heo 	spin_unlock_irq(&pool->lock);
4539bd7c089eSTejun Heo }
4540bd7c089eSTejun Heo 
45417dbc725eSTejun Heo /**
45427dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
45437dbc725eSTejun Heo  * @pool: unbound pool of interest
45447dbc725eSTejun Heo  * @cpu: the CPU which is coming up
45457dbc725eSTejun Heo  *
45467dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
45477dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
45487dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
45497dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
45507dbc725eSTejun Heo  */
45517dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
45527dbc725eSTejun Heo {
45537dbc725eSTejun Heo 	static cpumask_t cpumask;
45547dbc725eSTejun Heo 	struct worker *worker;
45557dbc725eSTejun Heo 
455692f9c5c4SLai Jiangshan 	lockdep_assert_held(&pool->attach_mutex);
45577dbc725eSTejun Heo 
45587dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
45597dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
45607dbc725eSTejun Heo 		return;
45617dbc725eSTejun Heo 
45627dbc725eSTejun Heo 	/* is @cpu the only online CPU? */
45637dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
45647dbc725eSTejun Heo 	if (cpumask_weight(&cpumask) != 1)
45657dbc725eSTejun Heo 		return;
45667dbc725eSTejun Heo 
45677dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
4568da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
45697dbc725eSTejun Heo 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
45707dbc725eSTejun Heo 						  pool->attrs->cpumask) < 0);
45717dbc725eSTejun Heo }
45727dbc725eSTejun Heo 
45738db25e78STejun Heo /*
45748db25e78STejun Heo  * Workqueues should be brought up before normal priority CPU notifiers.
45758db25e78STejun Heo  * This will be registered high priority CPU notifier.
45768db25e78STejun Heo  */
45770db0628dSPaul Gortmaker static int workqueue_cpu_up_callback(struct notifier_block *nfb,
45781da177e4SLinus Torvalds 					       unsigned long action,
45791da177e4SLinus Torvalds 					       void *hcpu)
45801da177e4SLinus Torvalds {
4581d84ff051STejun Heo 	int cpu = (unsigned long)hcpu;
45824ce62e9eSTejun Heo 	struct worker_pool *pool;
45834c16bd32STejun Heo 	struct workqueue_struct *wq;
45847dbc725eSTejun Heo 	int pi;
45851da177e4SLinus Torvalds 
45868db25e78STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
45873af24433SOleg Nesterov 	case CPU_UP_PREPARE:
4588f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
45893ce63377STejun Heo 			if (pool->nr_workers)
45903ce63377STejun Heo 				continue;
4591051e1850SLai Jiangshan 			if (!create_worker(pool))
45923ce63377STejun Heo 				return NOTIFY_BAD;
45933af24433SOleg Nesterov 		}
45941da177e4SLinus Torvalds 		break;
45951da177e4SLinus Torvalds 
459665758202STejun Heo 	case CPU_DOWN_FAILED:
459765758202STejun Heo 	case CPU_ONLINE:
459868e13a67SLai Jiangshan 		mutex_lock(&wq_pool_mutex);
45997dbc725eSTejun Heo 
46007dbc725eSTejun Heo 		for_each_pool(pool, pi) {
460192f9c5c4SLai Jiangshan 			mutex_lock(&pool->attach_mutex);
460294cf58bbSTejun Heo 
4603f05b558dSLai Jiangshan 			if (pool->cpu == cpu)
460494cf58bbSTejun Heo 				rebind_workers(pool);
4605f05b558dSLai Jiangshan 			else if (pool->cpu < 0)
46067dbc725eSTejun Heo 				restore_unbound_workers_cpumask(pool, cpu);
460794cf58bbSTejun Heo 
460892f9c5c4SLai Jiangshan 			mutex_unlock(&pool->attach_mutex);
460994cf58bbSTejun Heo 		}
46107dbc725eSTejun Heo 
46114c16bd32STejun Heo 		/* update NUMA affinity of unbound workqueues */
46124c16bd32STejun Heo 		list_for_each_entry(wq, &workqueues, list)
46134c16bd32STejun Heo 			wq_update_unbound_numa(wq, cpu, true);
46144c16bd32STejun Heo 
461568e13a67SLai Jiangshan 		mutex_unlock(&wq_pool_mutex);
46168db25e78STejun Heo 		break;
461765758202STejun Heo 	}
461865758202STejun Heo 	return NOTIFY_OK;
461965758202STejun Heo }
462065758202STejun Heo 
462165758202STejun Heo /*
462265758202STejun Heo  * Workqueues should be brought down after normal priority CPU notifiers.
462365758202STejun Heo  * This will be registered as low priority CPU notifier.
462465758202STejun Heo  */
46250db0628dSPaul Gortmaker static int workqueue_cpu_down_callback(struct notifier_block *nfb,
462665758202STejun Heo 						 unsigned long action,
462765758202STejun Heo 						 void *hcpu)
462865758202STejun Heo {
4629d84ff051STejun Heo 	int cpu = (unsigned long)hcpu;
46308db25e78STejun Heo 	struct work_struct unbind_work;
46314c16bd32STejun Heo 	struct workqueue_struct *wq;
46328db25e78STejun Heo 
463365758202STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
463465758202STejun Heo 	case CPU_DOWN_PREPARE:
46354c16bd32STejun Heo 		/* unbinding per-cpu workers should happen on the local CPU */
4636706026c2STejun Heo 		INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
46377635d2fdSJoonsoo Kim 		queue_work_on(cpu, system_highpri_wq, &unbind_work);
46384c16bd32STejun Heo 
46394c16bd32STejun Heo 		/* update NUMA affinity of unbound workqueues */
46404c16bd32STejun Heo 		mutex_lock(&wq_pool_mutex);
46414c16bd32STejun Heo 		list_for_each_entry(wq, &workqueues, list)
46424c16bd32STejun Heo 			wq_update_unbound_numa(wq, cpu, false);
46434c16bd32STejun Heo 		mutex_unlock(&wq_pool_mutex);
46444c16bd32STejun Heo 
46454c16bd32STejun Heo 		/* wait for per-cpu unbinding to finish */
46468db25e78STejun Heo 		flush_work(&unbind_work);
4647440a1136SChuansheng Liu 		destroy_work_on_stack(&unbind_work);
46488db25e78STejun Heo 		break;
464965758202STejun Heo 	}
465065758202STejun Heo 	return NOTIFY_OK;
465165758202STejun Heo }
465265758202STejun Heo 
46532d3854a3SRusty Russell #ifdef CONFIG_SMP
46548ccad40dSRusty Russell 
46552d3854a3SRusty Russell struct work_for_cpu {
4656ed48ece2STejun Heo 	struct work_struct work;
46572d3854a3SRusty Russell 	long (*fn)(void *);
46582d3854a3SRusty Russell 	void *arg;
46592d3854a3SRusty Russell 	long ret;
46602d3854a3SRusty Russell };
46612d3854a3SRusty Russell 
4662ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
46632d3854a3SRusty Russell {
4664ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4665ed48ece2STejun Heo 
46662d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
46672d3854a3SRusty Russell }
46682d3854a3SRusty Russell 
46692d3854a3SRusty Russell /**
46702d3854a3SRusty Russell  * work_on_cpu - run a function in user context on a particular cpu
46712d3854a3SRusty Russell  * @cpu: the cpu to run on
46722d3854a3SRusty Russell  * @fn: the function to run
46732d3854a3SRusty Russell  * @arg: the function arg
46742d3854a3SRusty Russell  *
467531ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
46766b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
4677d185af30SYacine Belkadi  *
4678d185af30SYacine Belkadi  * Return: The value @fn returns.
46792d3854a3SRusty Russell  */
4680d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
46812d3854a3SRusty Russell {
4682ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
46832d3854a3SRusty Russell 
4684ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4685ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
468612997d1aSBjorn Helgaas 	flush_work(&wfc.work);
4687440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
46882d3854a3SRusty Russell 	return wfc.ret;
46892d3854a3SRusty Russell }
46902d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
46912d3854a3SRusty Russell #endif /* CONFIG_SMP */
46922d3854a3SRusty Russell 
4693a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
4694e7577c50SRusty Russell 
4695a0a1a5fdSTejun Heo /**
4696a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
4697a0a1a5fdSTejun Heo  *
469858a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
4699c5aa87bbSTejun Heo  * workqueues will queue new works to their delayed_works list instead of
4700706026c2STejun Heo  * pool->worklist.
4701a0a1a5fdSTejun Heo  *
4702a0a1a5fdSTejun Heo  * CONTEXT:
4703a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4704a0a1a5fdSTejun Heo  */
4705a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
4706a0a1a5fdSTejun Heo {
470724b8a847STejun Heo 	struct workqueue_struct *wq;
470824b8a847STejun Heo 	struct pool_workqueue *pwq;
4709a0a1a5fdSTejun Heo 
471068e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4711a0a1a5fdSTejun Heo 
47126183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
4713a0a1a5fdSTejun Heo 	workqueue_freezing = true;
4714a0a1a5fdSTejun Heo 
471524b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
4716a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
4717699ce097STejun Heo 		for_each_pwq(pwq, wq)
4718699ce097STejun Heo 			pwq_adjust_max_active(pwq);
4719a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
4720a1056305STejun Heo 	}
47215bcab335STejun Heo 
472268e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4723a0a1a5fdSTejun Heo }
4724a0a1a5fdSTejun Heo 
4725a0a1a5fdSTejun Heo /**
472658a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
4727a0a1a5fdSTejun Heo  *
4728a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
4729a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
4730a0a1a5fdSTejun Heo  *
4731a0a1a5fdSTejun Heo  * CONTEXT:
473268e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
4733a0a1a5fdSTejun Heo  *
4734d185af30SYacine Belkadi  * Return:
473558a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
473658a69cb4STejun Heo  * is complete.
4737a0a1a5fdSTejun Heo  */
4738a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
4739a0a1a5fdSTejun Heo {
4740a0a1a5fdSTejun Heo 	bool busy = false;
474124b8a847STejun Heo 	struct workqueue_struct *wq;
474224b8a847STejun Heo 	struct pool_workqueue *pwq;
4743a0a1a5fdSTejun Heo 
474468e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4745a0a1a5fdSTejun Heo 
47466183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
4747a0a1a5fdSTejun Heo 
474824b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
474924b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
475024b8a847STejun Heo 			continue;
4751a0a1a5fdSTejun Heo 		/*
4752a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
4753a0a1a5fdSTejun Heo 		 * to peek without lock.
4754a0a1a5fdSTejun Heo 		 */
475588109453SLai Jiangshan 		rcu_read_lock_sched();
475624b8a847STejun Heo 		for_each_pwq(pwq, wq) {
47576183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
4758112202d9STejun Heo 			if (pwq->nr_active) {
4759a0a1a5fdSTejun Heo 				busy = true;
476088109453SLai Jiangshan 				rcu_read_unlock_sched();
4761a0a1a5fdSTejun Heo 				goto out_unlock;
4762a0a1a5fdSTejun Heo 			}
4763a0a1a5fdSTejun Heo 		}
476488109453SLai Jiangshan 		rcu_read_unlock_sched();
4765a0a1a5fdSTejun Heo 	}
4766a0a1a5fdSTejun Heo out_unlock:
476768e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4768a0a1a5fdSTejun Heo 	return busy;
4769a0a1a5fdSTejun Heo }
4770a0a1a5fdSTejun Heo 
4771a0a1a5fdSTejun Heo /**
4772a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
4773a0a1a5fdSTejun Heo  *
4774a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
4775706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
4776a0a1a5fdSTejun Heo  *
4777a0a1a5fdSTejun Heo  * CONTEXT:
4778a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4779a0a1a5fdSTejun Heo  */
4780a0a1a5fdSTejun Heo void thaw_workqueues(void)
4781a0a1a5fdSTejun Heo {
478224b8a847STejun Heo 	struct workqueue_struct *wq;
478324b8a847STejun Heo 	struct pool_workqueue *pwq;
4784a0a1a5fdSTejun Heo 
478568e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4786a0a1a5fdSTejun Heo 
4787a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
4788a0a1a5fdSTejun Heo 		goto out_unlock;
4789a0a1a5fdSTejun Heo 
479074b414eaSLai Jiangshan 	workqueue_freezing = false;
479124b8a847STejun Heo 
479224b8a847STejun Heo 	/* restore max_active and repopulate worklist */
479324b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
4794a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
4795699ce097STejun Heo 		for_each_pwq(pwq, wq)
4796699ce097STejun Heo 			pwq_adjust_max_active(pwq);
4797a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
479824b8a847STejun Heo 	}
479924b8a847STejun Heo 
4800a0a1a5fdSTejun Heo out_unlock:
480168e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4802a0a1a5fdSTejun Heo }
4803a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
4804a0a1a5fdSTejun Heo 
4805042f7df1SLai Jiangshan static int workqueue_apply_unbound_cpumask(void)
4806042f7df1SLai Jiangshan {
4807042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
4808042f7df1SLai Jiangshan 	int ret = 0;
4809042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
4810042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
4811042f7df1SLai Jiangshan 
4812042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
4813042f7df1SLai Jiangshan 
4814042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
4815042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
4816042f7df1SLai Jiangshan 			continue;
4817042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
4818042f7df1SLai Jiangshan 		if (wq->flags & __WQ_ORDERED)
4819042f7df1SLai Jiangshan 			continue;
4820042f7df1SLai Jiangshan 
4821042f7df1SLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs);
4822042f7df1SLai Jiangshan 		if (!ctx) {
4823042f7df1SLai Jiangshan 			ret = -ENOMEM;
4824042f7df1SLai Jiangshan 			break;
4825042f7df1SLai Jiangshan 		}
4826042f7df1SLai Jiangshan 
4827042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
4828042f7df1SLai Jiangshan 	}
4829042f7df1SLai Jiangshan 
4830042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
4831042f7df1SLai Jiangshan 		if (!ret)
4832042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
4833042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
4834042f7df1SLai Jiangshan 	}
4835042f7df1SLai Jiangshan 
4836042f7df1SLai Jiangshan 	return ret;
4837042f7df1SLai Jiangshan }
4838042f7df1SLai Jiangshan 
4839042f7df1SLai Jiangshan /**
4840042f7df1SLai Jiangshan  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
4841042f7df1SLai Jiangshan  *  @cpumask: the cpumask to set
4842042f7df1SLai Jiangshan  *
4843042f7df1SLai Jiangshan  *  The low-level workqueues cpumask is a global cpumask that limits
4844042f7df1SLai Jiangshan  *  the affinity of all unbound workqueues.  This function check the @cpumask
4845042f7df1SLai Jiangshan  *  and apply it to all unbound workqueues and updates all pwqs of them.
4846042f7df1SLai Jiangshan  *
4847042f7df1SLai Jiangshan  *  Retun:	0	- Success
4848042f7df1SLai Jiangshan  *  		-EINVAL	- Invalid @cpumask
4849042f7df1SLai Jiangshan  *  		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
4850042f7df1SLai Jiangshan  */
4851042f7df1SLai Jiangshan int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
4852042f7df1SLai Jiangshan {
4853042f7df1SLai Jiangshan 	int ret = -EINVAL;
4854042f7df1SLai Jiangshan 	cpumask_var_t saved_cpumask;
4855042f7df1SLai Jiangshan 
4856042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&saved_cpumask, GFP_KERNEL))
4857042f7df1SLai Jiangshan 		return -ENOMEM;
4858042f7df1SLai Jiangshan 
4859042f7df1SLai Jiangshan 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
4860042f7df1SLai Jiangshan 	if (!cpumask_empty(cpumask)) {
4861a0111cf6SLai Jiangshan 		apply_wqattrs_lock();
4862042f7df1SLai Jiangshan 
4863042f7df1SLai Jiangshan 		/* save the old wq_unbound_cpumask. */
4864042f7df1SLai Jiangshan 		cpumask_copy(saved_cpumask, wq_unbound_cpumask);
4865042f7df1SLai Jiangshan 
4866042f7df1SLai Jiangshan 		/* update wq_unbound_cpumask at first and apply it to wqs. */
4867042f7df1SLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, cpumask);
4868042f7df1SLai Jiangshan 		ret = workqueue_apply_unbound_cpumask();
4869042f7df1SLai Jiangshan 
4870042f7df1SLai Jiangshan 		/* restore the wq_unbound_cpumask when failed. */
4871042f7df1SLai Jiangshan 		if (ret < 0)
4872042f7df1SLai Jiangshan 			cpumask_copy(wq_unbound_cpumask, saved_cpumask);
4873042f7df1SLai Jiangshan 
4874a0111cf6SLai Jiangshan 		apply_wqattrs_unlock();
4875042f7df1SLai Jiangshan 	}
4876042f7df1SLai Jiangshan 
4877042f7df1SLai Jiangshan 	free_cpumask_var(saved_cpumask);
4878042f7df1SLai Jiangshan 	return ret;
4879042f7df1SLai Jiangshan }
4880042f7df1SLai Jiangshan 
48816ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
48826ba94429SFrederic Weisbecker /*
48836ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
48846ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
48856ba94429SFrederic Weisbecker  * following attributes.
48866ba94429SFrederic Weisbecker  *
48876ba94429SFrederic Weisbecker  *  per_cpu	RO bool	: whether the workqueue is per-cpu or unbound
48886ba94429SFrederic Weisbecker  *  max_active	RW int	: maximum number of in-flight work items
48896ba94429SFrederic Weisbecker  *
48906ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
48916ba94429SFrederic Weisbecker  *
48926ba94429SFrederic Weisbecker  *  id		RO int	: the associated pool ID
48936ba94429SFrederic Weisbecker  *  nice	RW int	: nice value of the workers
48946ba94429SFrederic Weisbecker  *  cpumask	RW mask	: bitmask of allowed CPUs for the workers
48956ba94429SFrederic Weisbecker  */
48966ba94429SFrederic Weisbecker struct wq_device {
48976ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
48986ba94429SFrederic Weisbecker 	struct device			dev;
48996ba94429SFrederic Weisbecker };
49006ba94429SFrederic Weisbecker 
49016ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
49026ba94429SFrederic Weisbecker {
49036ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
49046ba94429SFrederic Weisbecker 
49056ba94429SFrederic Weisbecker 	return wq_dev->wq;
49066ba94429SFrederic Weisbecker }
49076ba94429SFrederic Weisbecker 
49086ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
49096ba94429SFrederic Weisbecker 			    char *buf)
49106ba94429SFrederic Weisbecker {
49116ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
49126ba94429SFrederic Weisbecker 
49136ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
49146ba94429SFrederic Weisbecker }
49156ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
49166ba94429SFrederic Weisbecker 
49176ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
49186ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
49196ba94429SFrederic Weisbecker {
49206ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
49216ba94429SFrederic Weisbecker 
49226ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
49236ba94429SFrederic Weisbecker }
49246ba94429SFrederic Weisbecker 
49256ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
49266ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
49276ba94429SFrederic Weisbecker 				size_t count)
49286ba94429SFrederic Weisbecker {
49296ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
49306ba94429SFrederic Weisbecker 	int val;
49316ba94429SFrederic Weisbecker 
49326ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
49336ba94429SFrederic Weisbecker 		return -EINVAL;
49346ba94429SFrederic Weisbecker 
49356ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
49366ba94429SFrederic Weisbecker 	return count;
49376ba94429SFrederic Weisbecker }
49386ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
49396ba94429SFrederic Weisbecker 
49406ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
49416ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
49426ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
49436ba94429SFrederic Weisbecker 	NULL,
49446ba94429SFrederic Weisbecker };
49456ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
49466ba94429SFrederic Weisbecker 
49476ba94429SFrederic Weisbecker static ssize_t wq_pool_ids_show(struct device *dev,
49486ba94429SFrederic Weisbecker 				struct device_attribute *attr, char *buf)
49496ba94429SFrederic Weisbecker {
49506ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
49516ba94429SFrederic Weisbecker 	const char *delim = "";
49526ba94429SFrederic Weisbecker 	int node, written = 0;
49536ba94429SFrederic Weisbecker 
49546ba94429SFrederic Weisbecker 	rcu_read_lock_sched();
49556ba94429SFrederic Weisbecker 	for_each_node(node) {
49566ba94429SFrederic Weisbecker 		written += scnprintf(buf + written, PAGE_SIZE - written,
49576ba94429SFrederic Weisbecker 				     "%s%d:%d", delim, node,
49586ba94429SFrederic Weisbecker 				     unbound_pwq_by_node(wq, node)->pool->id);
49596ba94429SFrederic Weisbecker 		delim = " ";
49606ba94429SFrederic Weisbecker 	}
49616ba94429SFrederic Weisbecker 	written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
49626ba94429SFrederic Weisbecker 	rcu_read_unlock_sched();
49636ba94429SFrederic Weisbecker 
49646ba94429SFrederic Weisbecker 	return written;
49656ba94429SFrederic Weisbecker }
49666ba94429SFrederic Weisbecker 
49676ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
49686ba94429SFrederic Weisbecker 			    char *buf)
49696ba94429SFrederic Weisbecker {
49706ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
49716ba94429SFrederic Weisbecker 	int written;
49726ba94429SFrederic Weisbecker 
49736ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
49746ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
49756ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
49766ba94429SFrederic Weisbecker 
49776ba94429SFrederic Weisbecker 	return written;
49786ba94429SFrederic Weisbecker }
49796ba94429SFrederic Weisbecker 
49806ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
49816ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
49826ba94429SFrederic Weisbecker {
49836ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
49846ba94429SFrederic Weisbecker 
4985899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
4986899a94feSLai Jiangshan 
49876ba94429SFrederic Weisbecker 	attrs = alloc_workqueue_attrs(GFP_KERNEL);
49886ba94429SFrederic Weisbecker 	if (!attrs)
49896ba94429SFrederic Weisbecker 		return NULL;
49906ba94429SFrederic Weisbecker 
49916ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
49926ba94429SFrederic Weisbecker 	return attrs;
49936ba94429SFrederic Weisbecker }
49946ba94429SFrederic Weisbecker 
49956ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
49966ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
49976ba94429SFrederic Weisbecker {
49986ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
49996ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5000d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5001d4d3e257SLai Jiangshan 
5002d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
50036ba94429SFrederic Weisbecker 
50046ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
50056ba94429SFrederic Weisbecker 	if (!attrs)
5006d4d3e257SLai Jiangshan 		goto out_unlock;
50076ba94429SFrederic Weisbecker 
50086ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
50096ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5010d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
50116ba94429SFrederic Weisbecker 	else
50126ba94429SFrederic Weisbecker 		ret = -EINVAL;
50136ba94429SFrederic Weisbecker 
5014d4d3e257SLai Jiangshan out_unlock:
5015d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
50166ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
50176ba94429SFrederic Weisbecker 	return ret ?: count;
50186ba94429SFrederic Weisbecker }
50196ba94429SFrederic Weisbecker 
50206ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
50216ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
50226ba94429SFrederic Weisbecker {
50236ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
50246ba94429SFrederic Weisbecker 	int written;
50256ba94429SFrederic Weisbecker 
50266ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
50276ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
50286ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
50296ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
50306ba94429SFrederic Weisbecker 	return written;
50316ba94429SFrederic Weisbecker }
50326ba94429SFrederic Weisbecker 
50336ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
50346ba94429SFrederic Weisbecker 				struct device_attribute *attr,
50356ba94429SFrederic Weisbecker 				const char *buf, size_t count)
50366ba94429SFrederic Weisbecker {
50376ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
50386ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5039d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5040d4d3e257SLai Jiangshan 
5041d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
50426ba94429SFrederic Weisbecker 
50436ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
50446ba94429SFrederic Weisbecker 	if (!attrs)
5045d4d3e257SLai Jiangshan 		goto out_unlock;
50466ba94429SFrederic Weisbecker 
50476ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
50486ba94429SFrederic Weisbecker 	if (!ret)
5049d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
50506ba94429SFrederic Weisbecker 
5051d4d3e257SLai Jiangshan out_unlock:
5052d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
50536ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
50546ba94429SFrederic Weisbecker 	return ret ?: count;
50556ba94429SFrederic Weisbecker }
50566ba94429SFrederic Weisbecker 
50576ba94429SFrederic Weisbecker static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
50586ba94429SFrederic Weisbecker 			    char *buf)
50596ba94429SFrederic Weisbecker {
50606ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
50616ba94429SFrederic Weisbecker 	int written;
50626ba94429SFrederic Weisbecker 
50636ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
50646ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n",
50656ba94429SFrederic Weisbecker 			    !wq->unbound_attrs->no_numa);
50666ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
50676ba94429SFrederic Weisbecker 
50686ba94429SFrederic Weisbecker 	return written;
50696ba94429SFrederic Weisbecker }
50706ba94429SFrederic Weisbecker 
50716ba94429SFrederic Weisbecker static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
50726ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
50736ba94429SFrederic Weisbecker {
50746ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
50756ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5076d4d3e257SLai Jiangshan 	int v, ret = -ENOMEM;
5077d4d3e257SLai Jiangshan 
5078d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
50796ba94429SFrederic Weisbecker 
50806ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
50816ba94429SFrederic Weisbecker 	if (!attrs)
5082d4d3e257SLai Jiangshan 		goto out_unlock;
50836ba94429SFrederic Weisbecker 
50846ba94429SFrederic Weisbecker 	ret = -EINVAL;
50856ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &v) == 1) {
50866ba94429SFrederic Weisbecker 		attrs->no_numa = !v;
5087d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
50886ba94429SFrederic Weisbecker 	}
50896ba94429SFrederic Weisbecker 
5090d4d3e257SLai Jiangshan out_unlock:
5091d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
50926ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
50936ba94429SFrederic Weisbecker 	return ret ?: count;
50946ba94429SFrederic Weisbecker }
50956ba94429SFrederic Weisbecker 
50966ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
50976ba94429SFrederic Weisbecker 	__ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
50986ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
50996ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
51006ba94429SFrederic Weisbecker 	__ATTR(numa, 0644, wq_numa_show, wq_numa_store),
51016ba94429SFrederic Weisbecker 	__ATTR_NULL,
51026ba94429SFrederic Weisbecker };
51036ba94429SFrederic Weisbecker 
51046ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
51056ba94429SFrederic Weisbecker 	.name				= "workqueue",
51066ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
51076ba94429SFrederic Weisbecker };
51086ba94429SFrederic Weisbecker 
5109b05a7928SFrederic Weisbecker static ssize_t wq_unbound_cpumask_show(struct device *dev,
5110b05a7928SFrederic Weisbecker 		struct device_attribute *attr, char *buf)
5111b05a7928SFrederic Weisbecker {
5112b05a7928SFrederic Weisbecker 	int written;
5113b05a7928SFrederic Weisbecker 
5114042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5115b05a7928SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5116b05a7928SFrederic Weisbecker 			    cpumask_pr_args(wq_unbound_cpumask));
5117042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5118b05a7928SFrederic Weisbecker 
5119b05a7928SFrederic Weisbecker 	return written;
5120b05a7928SFrederic Weisbecker }
5121b05a7928SFrederic Weisbecker 
5122042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
5123042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
5124042f7df1SLai Jiangshan {
5125042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
5126042f7df1SLai Jiangshan 	int ret;
5127042f7df1SLai Jiangshan 
5128042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5129042f7df1SLai Jiangshan 		return -ENOMEM;
5130042f7df1SLai Jiangshan 
5131042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
5132042f7df1SLai Jiangshan 	if (!ret)
5133042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
5134042f7df1SLai Jiangshan 
5135042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
5136042f7df1SLai Jiangshan 	return ret ? ret : count;
5137042f7df1SLai Jiangshan }
5138042f7df1SLai Jiangshan 
5139b05a7928SFrederic Weisbecker static struct device_attribute wq_sysfs_cpumask_attr =
5140042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5141042f7df1SLai Jiangshan 	       wq_unbound_cpumask_store);
5142b05a7928SFrederic Weisbecker 
51436ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
51446ba94429SFrederic Weisbecker {
5145b05a7928SFrederic Weisbecker 	int err;
5146b05a7928SFrederic Weisbecker 
5147b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
5148b05a7928SFrederic Weisbecker 	if (err)
5149b05a7928SFrederic Weisbecker 		return err;
5150b05a7928SFrederic Weisbecker 
5151b05a7928SFrederic Weisbecker 	return device_create_file(wq_subsys.dev_root, &wq_sysfs_cpumask_attr);
51526ba94429SFrederic Weisbecker }
51536ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
51546ba94429SFrederic Weisbecker 
51556ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
51566ba94429SFrederic Weisbecker {
51576ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
51586ba94429SFrederic Weisbecker 
51596ba94429SFrederic Weisbecker 	kfree(wq_dev);
51606ba94429SFrederic Weisbecker }
51616ba94429SFrederic Weisbecker 
51626ba94429SFrederic Weisbecker /**
51636ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
51646ba94429SFrederic Weisbecker  * @wq: the workqueue to register
51656ba94429SFrederic Weisbecker  *
51666ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
51676ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
51686ba94429SFrederic Weisbecker  * which is the preferred method.
51696ba94429SFrederic Weisbecker  *
51706ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
51716ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
51726ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
51736ba94429SFrederic Weisbecker  * attributes.
51746ba94429SFrederic Weisbecker  *
51756ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
51766ba94429SFrederic Weisbecker  */
51776ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
51786ba94429SFrederic Weisbecker {
51796ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
51806ba94429SFrederic Weisbecker 	int ret;
51816ba94429SFrederic Weisbecker 
51826ba94429SFrederic Weisbecker 	/*
5183402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
51846ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
51856ba94429SFrederic Weisbecker 	 * workqueues.
51866ba94429SFrederic Weisbecker 	 */
51876ba94429SFrederic Weisbecker 	if (WARN_ON(wq->flags & __WQ_ORDERED))
51886ba94429SFrederic Weisbecker 		return -EINVAL;
51896ba94429SFrederic Weisbecker 
51906ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
51916ba94429SFrederic Weisbecker 	if (!wq_dev)
51926ba94429SFrederic Weisbecker 		return -ENOMEM;
51936ba94429SFrederic Weisbecker 
51946ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
51956ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
51966ba94429SFrederic Weisbecker 	wq_dev->dev.init_name = wq->name;
51976ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
51986ba94429SFrederic Weisbecker 
51996ba94429SFrederic Weisbecker 	/*
52006ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
52016ba94429SFrederic Weisbecker 	 * everything is ready.
52026ba94429SFrederic Weisbecker 	 */
52036ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
52046ba94429SFrederic Weisbecker 
52056ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
52066ba94429SFrederic Weisbecker 	if (ret) {
52076ba94429SFrederic Weisbecker 		kfree(wq_dev);
52086ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
52096ba94429SFrederic Weisbecker 		return ret;
52106ba94429SFrederic Weisbecker 	}
52116ba94429SFrederic Weisbecker 
52126ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
52136ba94429SFrederic Weisbecker 		struct device_attribute *attr;
52146ba94429SFrederic Weisbecker 
52156ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
52166ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
52176ba94429SFrederic Weisbecker 			if (ret) {
52186ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
52196ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
52206ba94429SFrederic Weisbecker 				return ret;
52216ba94429SFrederic Weisbecker 			}
52226ba94429SFrederic Weisbecker 		}
52236ba94429SFrederic Weisbecker 	}
52246ba94429SFrederic Weisbecker 
52256ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
52266ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
52276ba94429SFrederic Weisbecker 	return 0;
52286ba94429SFrederic Weisbecker }
52296ba94429SFrederic Weisbecker 
52306ba94429SFrederic Weisbecker /**
52316ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
52326ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
52336ba94429SFrederic Weisbecker  *
52346ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
52356ba94429SFrederic Weisbecker  */
52366ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
52376ba94429SFrederic Weisbecker {
52386ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
52396ba94429SFrederic Weisbecker 
52406ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
52416ba94429SFrederic Weisbecker 		return;
52426ba94429SFrederic Weisbecker 
52436ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
52446ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
52456ba94429SFrederic Weisbecker }
52466ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
52476ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
52486ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
52496ba94429SFrederic Weisbecker 
525082607adcSTejun Heo /*
525182607adcSTejun Heo  * Workqueue watchdog.
525282607adcSTejun Heo  *
525382607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
525482607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
525582607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
525682607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
525782607adcSTejun Heo  * largely opaque.
525882607adcSTejun Heo  *
525982607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
526082607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
526182607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
526282607adcSTejun Heo  *
526382607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
526482607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
526582607adcSTejun Heo  * corresponding sysfs parameter file.
526682607adcSTejun Heo  */
526782607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
526882607adcSTejun Heo 
526982607adcSTejun Heo static void wq_watchdog_timer_fn(unsigned long data);
527082607adcSTejun Heo 
527182607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
527282607adcSTejun Heo static struct timer_list wq_watchdog_timer =
527382607adcSTejun Heo 	TIMER_DEFERRED_INITIALIZER(wq_watchdog_timer_fn, 0, 0);
527482607adcSTejun Heo 
527582607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
527682607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
527782607adcSTejun Heo 
527882607adcSTejun Heo static void wq_watchdog_reset_touched(void)
527982607adcSTejun Heo {
528082607adcSTejun Heo 	int cpu;
528182607adcSTejun Heo 
528282607adcSTejun Heo 	wq_watchdog_touched = jiffies;
528382607adcSTejun Heo 	for_each_possible_cpu(cpu)
528482607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
528582607adcSTejun Heo }
528682607adcSTejun Heo 
528782607adcSTejun Heo static void wq_watchdog_timer_fn(unsigned long data)
528882607adcSTejun Heo {
528982607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
529082607adcSTejun Heo 	bool lockup_detected = false;
529182607adcSTejun Heo 	struct worker_pool *pool;
529282607adcSTejun Heo 	int pi;
529382607adcSTejun Heo 
529482607adcSTejun Heo 	if (!thresh)
529582607adcSTejun Heo 		return;
529682607adcSTejun Heo 
529782607adcSTejun Heo 	rcu_read_lock();
529882607adcSTejun Heo 
529982607adcSTejun Heo 	for_each_pool(pool, pi) {
530082607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
530182607adcSTejun Heo 
530282607adcSTejun Heo 		if (list_empty(&pool->worklist))
530382607adcSTejun Heo 			continue;
530482607adcSTejun Heo 
530582607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
530682607adcSTejun Heo 		pool_ts = READ_ONCE(pool->watchdog_ts);
530782607adcSTejun Heo 		touched = READ_ONCE(wq_watchdog_touched);
530882607adcSTejun Heo 
530982607adcSTejun Heo 		if (time_after(pool_ts, touched))
531082607adcSTejun Heo 			ts = pool_ts;
531182607adcSTejun Heo 		else
531282607adcSTejun Heo 			ts = touched;
531382607adcSTejun Heo 
531482607adcSTejun Heo 		if (pool->cpu >= 0) {
531582607adcSTejun Heo 			unsigned long cpu_touched =
531682607adcSTejun Heo 				READ_ONCE(per_cpu(wq_watchdog_touched_cpu,
531782607adcSTejun Heo 						  pool->cpu));
531882607adcSTejun Heo 			if (time_after(cpu_touched, ts))
531982607adcSTejun Heo 				ts = cpu_touched;
532082607adcSTejun Heo 		}
532182607adcSTejun Heo 
532282607adcSTejun Heo 		/* did we stall? */
532382607adcSTejun Heo 		if (time_after(jiffies, ts + thresh)) {
532482607adcSTejun Heo 			lockup_detected = true;
532582607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
532682607adcSTejun Heo 			pr_cont_pool_info(pool);
532782607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
532882607adcSTejun Heo 				jiffies_to_msecs(jiffies - pool_ts) / 1000);
532982607adcSTejun Heo 		}
533082607adcSTejun Heo 	}
533182607adcSTejun Heo 
533282607adcSTejun Heo 	rcu_read_unlock();
533382607adcSTejun Heo 
533482607adcSTejun Heo 	if (lockup_detected)
533582607adcSTejun Heo 		show_workqueue_state();
533682607adcSTejun Heo 
533782607adcSTejun Heo 	wq_watchdog_reset_touched();
533882607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
533982607adcSTejun Heo }
534082607adcSTejun Heo 
534182607adcSTejun Heo void wq_watchdog_touch(int cpu)
534282607adcSTejun Heo {
534382607adcSTejun Heo 	if (cpu >= 0)
534482607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
534582607adcSTejun Heo 	else
534682607adcSTejun Heo 		wq_watchdog_touched = jiffies;
534782607adcSTejun Heo }
534882607adcSTejun Heo 
534982607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
535082607adcSTejun Heo {
535182607adcSTejun Heo 	wq_watchdog_thresh = 0;
535282607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
535382607adcSTejun Heo 
535482607adcSTejun Heo 	if (thresh) {
535582607adcSTejun Heo 		wq_watchdog_thresh = thresh;
535682607adcSTejun Heo 		wq_watchdog_reset_touched();
535782607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
535882607adcSTejun Heo 	}
535982607adcSTejun Heo }
536082607adcSTejun Heo 
536182607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
536282607adcSTejun Heo 					const struct kernel_param *kp)
536382607adcSTejun Heo {
536482607adcSTejun Heo 	unsigned long thresh;
536582607adcSTejun Heo 	int ret;
536682607adcSTejun Heo 
536782607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
536882607adcSTejun Heo 	if (ret)
536982607adcSTejun Heo 		return ret;
537082607adcSTejun Heo 
537182607adcSTejun Heo 	if (system_wq)
537282607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
537382607adcSTejun Heo 	else
537482607adcSTejun Heo 		wq_watchdog_thresh = thresh;
537582607adcSTejun Heo 
537682607adcSTejun Heo 	return 0;
537782607adcSTejun Heo }
537882607adcSTejun Heo 
537982607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
538082607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
538182607adcSTejun Heo 	.get	= param_get_ulong,
538282607adcSTejun Heo };
538382607adcSTejun Heo 
538482607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
538582607adcSTejun Heo 		0644);
538682607adcSTejun Heo 
538782607adcSTejun Heo static void wq_watchdog_init(void)
538882607adcSTejun Heo {
538982607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
539082607adcSTejun Heo }
539182607adcSTejun Heo 
539282607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
539382607adcSTejun Heo 
539482607adcSTejun Heo static inline void wq_watchdog_init(void) { }
539582607adcSTejun Heo 
539682607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
539782607adcSTejun Heo 
5398bce90380STejun Heo static void __init wq_numa_init(void)
5399bce90380STejun Heo {
5400bce90380STejun Heo 	cpumask_var_t *tbl;
5401bce90380STejun Heo 	int node, cpu;
5402bce90380STejun Heo 
5403bce90380STejun Heo 	if (num_possible_nodes() <= 1)
5404bce90380STejun Heo 		return;
5405bce90380STejun Heo 
5406d55262c4STejun Heo 	if (wq_disable_numa) {
5407d55262c4STejun Heo 		pr_info("workqueue: NUMA affinity support disabled\n");
5408d55262c4STejun Heo 		return;
5409d55262c4STejun Heo 	}
5410d55262c4STejun Heo 
54114c16bd32STejun Heo 	wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
54124c16bd32STejun Heo 	BUG_ON(!wq_update_unbound_numa_attrs_buf);
54134c16bd32STejun Heo 
5414bce90380STejun Heo 	/*
5415bce90380STejun Heo 	 * We want masks of possible CPUs of each node which isn't readily
5416bce90380STejun Heo 	 * available.  Build one from cpu_to_node() which should have been
5417bce90380STejun Heo 	 * fully initialized by now.
5418bce90380STejun Heo 	 */
5419ddcb57e2SLai Jiangshan 	tbl = kzalloc(nr_node_ids * sizeof(tbl[0]), GFP_KERNEL);
5420bce90380STejun Heo 	BUG_ON(!tbl);
5421bce90380STejun Heo 
5422bce90380STejun Heo 	for_each_node(node)
54235a6024f1SYasuaki Ishimatsu 		BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
54241be0c25dSTejun Heo 				node_online(node) ? node : NUMA_NO_NODE));
5425bce90380STejun Heo 
5426bce90380STejun Heo 	for_each_possible_cpu(cpu) {
5427bce90380STejun Heo 		node = cpu_to_node(cpu);
5428bce90380STejun Heo 		if (WARN_ON(node == NUMA_NO_NODE)) {
5429bce90380STejun Heo 			pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
5430bce90380STejun Heo 			/* happens iff arch is bonkers, let's just proceed */
5431bce90380STejun Heo 			return;
5432bce90380STejun Heo 		}
5433bce90380STejun Heo 		cpumask_set_cpu(cpu, tbl[node]);
5434bce90380STejun Heo 	}
5435bce90380STejun Heo 
5436bce90380STejun Heo 	wq_numa_possible_cpumask = tbl;
5437bce90380STejun Heo 	wq_numa_enabled = true;
5438bce90380STejun Heo }
5439bce90380STejun Heo 
54406ee0578bSSuresh Siddha static int __init init_workqueues(void)
54411da177e4SLinus Torvalds {
54427a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
54437a4e344cSTejun Heo 	int i, cpu;
5444c34056a3STejun Heo 
5445e904e6c2STejun Heo 	WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
5446e904e6c2STejun Heo 
5447b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
5448b05a7928SFrederic Weisbecker 	cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
5449b05a7928SFrederic Weisbecker 
5450e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
5451e904e6c2STejun Heo 
545265758202STejun Heo 	cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
5453a5b4e57dSLai Jiangshan 	hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
54548b03ae3cSTejun Heo 
5455bce90380STejun Heo 	wq_numa_init();
5456bce90380STejun Heo 
5457706026c2STejun Heo 	/* initialize CPU pools */
545829c91e99STejun Heo 	for_each_possible_cpu(cpu) {
54594ce62e9eSTejun Heo 		struct worker_pool *pool;
54608b03ae3cSTejun Heo 
54617a4e344cSTejun Heo 		i = 0;
5462f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
54637a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
5464ec22ca5eSTejun Heo 			pool->cpu = cpu;
54657a4e344cSTejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
54667a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
5467f3f90ad4STejun Heo 			pool->node = cpu_to_node(cpu);
54687a4e344cSTejun Heo 
54699daf9e67STejun Heo 			/* alloc pool ID */
547068e13a67SLai Jiangshan 			mutex_lock(&wq_pool_mutex);
54719daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
547268e13a67SLai Jiangshan 			mutex_unlock(&wq_pool_mutex);
54734ce62e9eSTejun Heo 		}
54748b03ae3cSTejun Heo 	}
54758b03ae3cSTejun Heo 
5476e22bee78STejun Heo 	/* create the initial worker */
547729c91e99STejun Heo 	for_each_online_cpu(cpu) {
54784ce62e9eSTejun Heo 		struct worker_pool *pool;
5479e22bee78STejun Heo 
5480f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
548124647570STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
5482051e1850SLai Jiangshan 			BUG_ON(!create_worker(pool));
5483e22bee78STejun Heo 		}
54844ce62e9eSTejun Heo 	}
5485e22bee78STejun Heo 
54868a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
548729c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
548829c91e99STejun Heo 		struct workqueue_attrs *attrs;
548929c91e99STejun Heo 
549029c91e99STejun Heo 		BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
549129c91e99STejun Heo 		attrs->nice = std_nice[i];
549229c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
54938a2b7538STejun Heo 
54948a2b7538STejun Heo 		/*
54958a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
54968a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
54978a2b7538STejun Heo 		 * Turn off NUMA so that dfl_pwq is used for all nodes.
54988a2b7538STejun Heo 		 */
54998a2b7538STejun Heo 		BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
55008a2b7538STejun Heo 		attrs->nice = std_nice[i];
55018a2b7538STejun Heo 		attrs->no_numa = true;
55028a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
550329c91e99STejun Heo 	}
550429c91e99STejun Heo 
5505d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
55061aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
5507d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
5508f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
5509f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
551024d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
551124d51addSTejun Heo 					      WQ_FREEZABLE, 0);
55120668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
55130668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
55140668106cSViresh Kumar 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
55150668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
55160668106cSViresh Kumar 					      0);
55171aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
55180668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
55190668106cSViresh Kumar 	       !system_power_efficient_wq ||
55200668106cSViresh Kumar 	       !system_freezable_power_efficient_wq);
552182607adcSTejun Heo 
552282607adcSTejun Heo 	wq_watchdog_init();
552382607adcSTejun Heo 
55246ee0578bSSuresh Siddha 	return 0;
55251da177e4SLinus Torvalds }
55266ee0578bSSuresh Siddha early_initcall(init_workqueues);
5527