xref: /linux-6.15/kernel/workqueue.c (revision 02a982a6)
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 
304ef557180SMike Galbraith /* PL: allowable cpus for unbound wqs and work items */
305ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
306ef557180SMike Galbraith 
307ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
308ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
309b05a7928SFrederic Weisbecker 
310f303fccbSTejun Heo /*
311f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
312f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
313f303fccbSTejun Heo  * to uncover usages which depend on it.
314f303fccbSTejun Heo  */
315f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
316f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
317f303fccbSTejun Heo #else
318f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
319f303fccbSTejun Heo #endif
320f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
321f303fccbSTejun Heo 
3227d19c5ceSTejun Heo /* the per-cpu worker pools */
32325528213SPeter Zijlstra static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
3247d19c5ceSTejun Heo 
32568e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
3267d19c5ceSTejun Heo 
32768e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
32829c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
32929c91e99STejun Heo 
330c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
33129c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
33229c91e99STejun Heo 
3338a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
3348a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
3358a2b7538STejun Heo 
336d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
337ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
338044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
3391aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
340044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
341d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
342044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
343f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
344044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
34524d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
3460668106cSViresh Kumar struct workqueue_struct *system_power_efficient_wq __read_mostly;
3470668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
3480668106cSViresh Kumar struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
3490668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
350d320c038STejun Heo 
3517d19c5ceSTejun Heo static int worker_thread(void *__worker);
3526ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
3537d19c5ceSTejun Heo 
35497bd2347STejun Heo #define CREATE_TRACE_POINTS
35597bd2347STejun Heo #include <trace/events/workqueue.h>
35697bd2347STejun Heo 
35768e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
358f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
359f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
36068e13a67SLai Jiangshan 			 "sched RCU or wq_pool_mutex should be held")
3615bcab335STejun Heo 
362b09f4fd3SLai Jiangshan #define assert_rcu_or_wq_mutex(wq)					\
363f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
364f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex),			\
365b09f4fd3SLai Jiangshan 			 "sched RCU or wq->mutex should be held")
36676af4d93STejun Heo 
3675b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
368f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
369f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
370f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
3715b95e1afSLai Jiangshan 			 "sched RCU, wq->mutex or wq_pool_mutex should be held")
3725b95e1afSLai Jiangshan 
373f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
374f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
375f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
3767a62c2c8STejun Heo 	     (pool)++)
3774ce62e9eSTejun Heo 
37849e3cf44STejun Heo /**
37917116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
38017116969STejun Heo  * @pool: iteration cursor
381611c92a0STejun Heo  * @pi: integer used for iteration
382fa1b54e6STejun Heo  *
38368e13a67SLai Jiangshan  * This must be called either with wq_pool_mutex held or sched RCU read
38468e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
38568e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
386fa1b54e6STejun Heo  *
387fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
388fa1b54e6STejun Heo  * ignored.
38917116969STejun Heo  */
390611c92a0STejun Heo #define for_each_pool(pool, pi)						\
391611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
39268e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
393fa1b54e6STejun Heo 		else
39417116969STejun Heo 
39517116969STejun Heo /**
396822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
397822d8405STejun Heo  * @worker: iteration cursor
398822d8405STejun Heo  * @pool: worker_pool to iterate workers of
399822d8405STejun Heo  *
40092f9c5c4SLai Jiangshan  * This must be called with @pool->attach_mutex.
401822d8405STejun Heo  *
402822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
403822d8405STejun Heo  * ignored.
404822d8405STejun Heo  */
405da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
406da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
40792f9c5c4SLai Jiangshan 		if (({ lockdep_assert_held(&pool->attach_mutex); false; })) { } \
408822d8405STejun Heo 		else
409822d8405STejun Heo 
410822d8405STejun Heo /**
41149e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
41249e3cf44STejun Heo  * @pwq: iteration cursor
41349e3cf44STejun Heo  * @wq: the target workqueue
41476af4d93STejun Heo  *
415b09f4fd3SLai Jiangshan  * This must be called either with wq->mutex held or sched RCU read locked.
416794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
417794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
41876af4d93STejun Heo  *
41976af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
42076af4d93STejun Heo  * ignored.
42149e3cf44STejun Heo  */
42249e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
42376af4d93STejun Heo 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node)		\
424b09f4fd3SLai Jiangshan 		if (({ assert_rcu_or_wq_mutex(wq); false; })) { }	\
42576af4d93STejun Heo 		else
426f3421797STejun Heo 
427dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
428dc186ad7SThomas Gleixner 
429dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr;
430dc186ad7SThomas Gleixner 
43199777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
43299777288SStanislaw Gruszka {
43399777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
43499777288SStanislaw Gruszka }
43599777288SStanislaw Gruszka 
436dc186ad7SThomas Gleixner /*
437dc186ad7SThomas Gleixner  * fixup_init is called when:
438dc186ad7SThomas Gleixner  * - an active object is initialized
439dc186ad7SThomas Gleixner  */
440*02a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
441dc186ad7SThomas Gleixner {
442dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
443dc186ad7SThomas Gleixner 
444dc186ad7SThomas Gleixner 	switch (state) {
445dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
446dc186ad7SThomas Gleixner 		cancel_work_sync(work);
447dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
448*02a982a6SDu, Changbin 		return true;
449dc186ad7SThomas Gleixner 	default:
450*02a982a6SDu, Changbin 		return false;
451dc186ad7SThomas Gleixner 	}
452dc186ad7SThomas Gleixner }
453dc186ad7SThomas Gleixner 
454dc186ad7SThomas Gleixner /*
455dc186ad7SThomas Gleixner  * fixup_activate is called when:
456dc186ad7SThomas Gleixner  * - an active object is activated
457dc186ad7SThomas Gleixner  * - an unknown object is activated (might be a statically initialized object)
458dc186ad7SThomas Gleixner  */
459*02a982a6SDu, Changbin static bool work_fixup_activate(void *addr, enum debug_obj_state state)
460dc186ad7SThomas Gleixner {
461dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
462dc186ad7SThomas Gleixner 
463dc186ad7SThomas Gleixner 	switch (state) {
464dc186ad7SThomas Gleixner 
465dc186ad7SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
466dc186ad7SThomas Gleixner 		/*
467dc186ad7SThomas Gleixner 		 * This is not really a fixup. The work struct was
468dc186ad7SThomas Gleixner 		 * statically initialized. We just make sure that it
469dc186ad7SThomas Gleixner 		 * is tracked in the object tracker.
470dc186ad7SThomas Gleixner 		 */
47122df02bbSTejun Heo 		if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
472dc186ad7SThomas Gleixner 			debug_object_init(work, &work_debug_descr);
473dc186ad7SThomas Gleixner 			debug_object_activate(work, &work_debug_descr);
474*02a982a6SDu, Changbin 			return false;
475dc186ad7SThomas Gleixner 		}
476dc186ad7SThomas Gleixner 		WARN_ON_ONCE(1);
477*02a982a6SDu, Changbin 		return false;
478dc186ad7SThomas Gleixner 
479dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
480dc186ad7SThomas Gleixner 		WARN_ON(1);
481dc186ad7SThomas Gleixner 
482dc186ad7SThomas Gleixner 	default:
483*02a982a6SDu, Changbin 		return false;
484dc186ad7SThomas Gleixner 	}
485dc186ad7SThomas Gleixner }
486dc186ad7SThomas Gleixner 
487dc186ad7SThomas Gleixner /*
488dc186ad7SThomas Gleixner  * fixup_free is called when:
489dc186ad7SThomas Gleixner  * - an active object is freed
490dc186ad7SThomas Gleixner  */
491*02a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
492dc186ad7SThomas Gleixner {
493dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
494dc186ad7SThomas Gleixner 
495dc186ad7SThomas Gleixner 	switch (state) {
496dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
497dc186ad7SThomas Gleixner 		cancel_work_sync(work);
498dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
499*02a982a6SDu, Changbin 		return true;
500dc186ad7SThomas Gleixner 	default:
501*02a982a6SDu, Changbin 		return false;
502dc186ad7SThomas Gleixner 	}
503dc186ad7SThomas Gleixner }
504dc186ad7SThomas Gleixner 
505dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr = {
506dc186ad7SThomas Gleixner 	.name		= "work_struct",
50799777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
508dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
509dc186ad7SThomas Gleixner 	.fixup_activate	= work_fixup_activate,
510dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
511dc186ad7SThomas Gleixner };
512dc186ad7SThomas Gleixner 
513dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
514dc186ad7SThomas Gleixner {
515dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
516dc186ad7SThomas Gleixner }
517dc186ad7SThomas Gleixner 
518dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
519dc186ad7SThomas Gleixner {
520dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
521dc186ad7SThomas Gleixner }
522dc186ad7SThomas Gleixner 
523dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
524dc186ad7SThomas Gleixner {
525dc186ad7SThomas Gleixner 	if (onstack)
526dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
527dc186ad7SThomas Gleixner 	else
528dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
529dc186ad7SThomas Gleixner }
530dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
531dc186ad7SThomas Gleixner 
532dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
533dc186ad7SThomas Gleixner {
534dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
535dc186ad7SThomas Gleixner }
536dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
537dc186ad7SThomas Gleixner 
538ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
539ea2e64f2SThomas Gleixner {
540ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
541ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
542ea2e64f2SThomas Gleixner }
543ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
544ea2e64f2SThomas Gleixner 
545dc186ad7SThomas Gleixner #else
546dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
547dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
548dc186ad7SThomas Gleixner #endif
549dc186ad7SThomas Gleixner 
5504e8b22bdSLi Bin /**
5514e8b22bdSLi Bin  * worker_pool_assign_id - allocate ID and assing it to @pool
5524e8b22bdSLi Bin  * @pool: the pool pointer of interest
5534e8b22bdSLi Bin  *
5544e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
5554e8b22bdSLi Bin  * successfully, -errno on failure.
5564e8b22bdSLi Bin  */
5579daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
5589daf9e67STejun Heo {
5599daf9e67STejun Heo 	int ret;
5609daf9e67STejun Heo 
56168e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5625bcab335STejun Heo 
5634e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
5644e8b22bdSLi Bin 			GFP_KERNEL);
565229641a6STejun Heo 	if (ret >= 0) {
566e68035fbSTejun Heo 		pool->id = ret;
567229641a6STejun Heo 		return 0;
568229641a6STejun Heo 	}
5699daf9e67STejun Heo 	return ret;
5709daf9e67STejun Heo }
5719daf9e67STejun Heo 
57276af4d93STejun Heo /**
573df2d5ae4STejun Heo  * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
574df2d5ae4STejun Heo  * @wq: the target workqueue
575df2d5ae4STejun Heo  * @node: the node ID
576df2d5ae4STejun Heo  *
5775b95e1afSLai Jiangshan  * This must be called with any of wq_pool_mutex, wq->mutex or sched RCU
5785b95e1afSLai Jiangshan  * read locked.
579df2d5ae4STejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
580df2d5ae4STejun Heo  * responsible for guaranteeing that the pwq stays online.
581d185af30SYacine Belkadi  *
582d185af30SYacine Belkadi  * Return: The unbound pool_workqueue for @node.
583df2d5ae4STejun Heo  */
584df2d5ae4STejun Heo static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
585df2d5ae4STejun Heo 						  int node)
586df2d5ae4STejun Heo {
5875b95e1afSLai Jiangshan 	assert_rcu_or_wq_mutex_or_pool_mutex(wq);
588d6e022f1STejun Heo 
589d6e022f1STejun Heo 	/*
590d6e022f1STejun Heo 	 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
591d6e022f1STejun Heo 	 * delayed item is pending.  The plan is to keep CPU -> NODE
592d6e022f1STejun Heo 	 * mapping valid and stable across CPU on/offlines.  Once that
593d6e022f1STejun Heo 	 * happens, this workaround can be removed.
594d6e022f1STejun Heo 	 */
595d6e022f1STejun Heo 	if (unlikely(node == NUMA_NO_NODE))
596d6e022f1STejun Heo 		return wq->dfl_pwq;
597d6e022f1STejun Heo 
598df2d5ae4STejun Heo 	return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
599df2d5ae4STejun Heo }
600df2d5ae4STejun Heo 
60173f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
60273f53c4aSTejun Heo {
60373f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
60473f53c4aSTejun Heo }
60573f53c4aSTejun Heo 
60673f53c4aSTejun Heo static int get_work_color(struct work_struct *work)
60773f53c4aSTejun Heo {
60873f53c4aSTejun Heo 	return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
60973f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
61073f53c4aSTejun Heo }
61173f53c4aSTejun Heo 
61273f53c4aSTejun Heo static int work_next_color(int color)
61373f53c4aSTejun Heo {
61473f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
615a848e3b6SOleg Nesterov }
616a848e3b6SOleg Nesterov 
6174594bf15SDavid Howells /*
618112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
619112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
6207c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
6217a22ad75STejun Heo  *
622112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
623112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
624bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
625bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
6267a22ad75STejun Heo  *
627112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6287c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
629112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
6307c3eed5cSTejun Heo  * available only while the work item is queued.
631bbb68dfaSTejun Heo  *
632bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
633bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
634bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
635bbb68dfaSTejun Heo  * try to steal the PENDING bit.
6364594bf15SDavid Howells  */
6377a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6387a22ad75STejun Heo 				 unsigned long flags)
6397a22ad75STejun Heo {
6406183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
6417a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
6427a22ad75STejun Heo }
6437a22ad75STejun Heo 
644112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6454690c4abSTejun Heo 			 unsigned long extra_flags)
646365970a1SDavid Howells {
647112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
648112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
649365970a1SDavid Howells }
650365970a1SDavid Howells 
6514468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6524468a00fSLai Jiangshan 					   int pool_id)
6534468a00fSLai Jiangshan {
6544468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6554468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6564468a00fSLai Jiangshan }
6574468a00fSLai Jiangshan 
6587c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6597c3eed5cSTejun Heo 					    int pool_id)
6604d707b9fSOleg Nesterov {
66123657bb1STejun Heo 	/*
66223657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
66323657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
66423657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
66523657bb1STejun Heo 	 * owner.
66623657bb1STejun Heo 	 */
66723657bb1STejun Heo 	smp_wmb();
6687c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
669346c09f8SRoman Pen 	/*
670346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
671346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
672346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
673346c09f8SRoman Pen 	 * reordering can lead to a missed execution on attempt to qeueue
674346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
675346c09f8SRoman Pen 	 *
676346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
677346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
678346c09f8SRoman Pen 	 *
679346c09f8SRoman Pen 	 * 1  STORE event_indicated
680346c09f8SRoman Pen 	 * 2  queue_work_on() {
681346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
682346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
683346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
684346c09f8SRoman Pen 	 * 6                                 smp_mb()
685346c09f8SRoman Pen 	 * 7                               work->current_func() {
686346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
687346c09f8SRoman Pen 	 *				   }
688346c09f8SRoman Pen 	 *
689346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
690346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
691346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
692346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
693346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
694346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
695346c09f8SRoman Pen 	 * before actual STORE.
696346c09f8SRoman Pen 	 */
697346c09f8SRoman Pen 	smp_mb();
6984d707b9fSOleg Nesterov }
6994d707b9fSOleg Nesterov 
7007a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
701365970a1SDavid Howells {
7027c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
7037c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
7047a22ad75STejun Heo }
7057a22ad75STejun Heo 
706112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
7077a22ad75STejun Heo {
708e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7097a22ad75STejun Heo 
710112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
711e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
712e120153dSTejun Heo 	else
713e120153dSTejun Heo 		return NULL;
7147a22ad75STejun Heo }
7157a22ad75STejun Heo 
7167c3eed5cSTejun Heo /**
7177c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
7187c3eed5cSTejun Heo  * @work: the work item of interest
7197c3eed5cSTejun Heo  *
72068e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
72168e13a67SLai Jiangshan  * access under sched-RCU read lock.  As such, this function should be
72268e13a67SLai Jiangshan  * called under wq_pool_mutex or with preemption disabled.
723fa1b54e6STejun Heo  *
724fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
725fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
726fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
727fa1b54e6STejun Heo  * returned pool is and stays online.
728d185af30SYacine Belkadi  *
729d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
7307c3eed5cSTejun Heo  */
7317c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
7327a22ad75STejun Heo {
733e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7347c3eed5cSTejun Heo 	int pool_id;
7357a22ad75STejun Heo 
73668e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
737fa1b54e6STejun Heo 
738112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
739112202d9STejun Heo 		return ((struct pool_workqueue *)
7407c3eed5cSTejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool;
7417a22ad75STejun Heo 
7427c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
7437c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
7447a22ad75STejun Heo 		return NULL;
7457a22ad75STejun Heo 
746fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
7477c3eed5cSTejun Heo }
7487c3eed5cSTejun Heo 
7497c3eed5cSTejun Heo /**
7507c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
7517c3eed5cSTejun Heo  * @work: the work item of interest
7527c3eed5cSTejun Heo  *
753d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
7547c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
7557c3eed5cSTejun Heo  */
7567c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
7577c3eed5cSTejun Heo {
75854d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
7597c3eed5cSTejun Heo 
760112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
761112202d9STejun Heo 		return ((struct pool_workqueue *)
76254d5b7d0SLai Jiangshan 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
76354d5b7d0SLai Jiangshan 
76454d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
7657c3eed5cSTejun Heo }
7667c3eed5cSTejun Heo 
767bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
768bbb68dfaSTejun Heo {
7697c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
770bbb68dfaSTejun Heo 
7717c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
7727c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
773bbb68dfaSTejun Heo }
774bbb68dfaSTejun Heo 
775bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
776bbb68dfaSTejun Heo {
777bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
778bbb68dfaSTejun Heo 
779112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
780bbb68dfaSTejun Heo }
781bbb68dfaSTejun Heo 
782e22bee78STejun Heo /*
7833270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
7843270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
785d565ed63STejun Heo  * they're being called with pool->lock held.
786e22bee78STejun Heo  */
787e22bee78STejun Heo 
78863d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
789649027d7STejun Heo {
790e19e397aSTejun Heo 	return !atomic_read(&pool->nr_running);
791649027d7STejun Heo }
792649027d7STejun Heo 
793e22bee78STejun Heo /*
794e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
795e22bee78STejun Heo  * running workers.
796974271c4STejun Heo  *
797974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
798706026c2STejun Heo  * function will always return %true for unbound pools as long as the
799974271c4STejun Heo  * worklist isn't empty.
800e22bee78STejun Heo  */
80163d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
802e22bee78STejun Heo {
80363d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
804e22bee78STejun Heo }
805e22bee78STejun Heo 
806e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
80763d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
808e22bee78STejun Heo {
80963d95a91STejun Heo 	return pool->nr_idle;
810e22bee78STejun Heo }
811e22bee78STejun Heo 
812e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
81363d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
814e22bee78STejun Heo {
815e19e397aSTejun Heo 	return !list_empty(&pool->worklist) &&
816e19e397aSTejun Heo 		atomic_read(&pool->nr_running) <= 1;
817e22bee78STejun Heo }
818e22bee78STejun Heo 
819e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
82063d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
821e22bee78STejun Heo {
82263d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
823e22bee78STejun Heo }
824e22bee78STejun Heo 
825e22bee78STejun Heo /* Do we have too many workers and should some go away? */
82663d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
827e22bee78STejun Heo {
82834a06bd6STejun Heo 	bool managing = mutex_is_locked(&pool->manager_arb);
82963d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
83063d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
831e22bee78STejun Heo 
832e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
833e22bee78STejun Heo }
834e22bee78STejun Heo 
835e22bee78STejun Heo /*
836e22bee78STejun Heo  * Wake up functions.
837e22bee78STejun Heo  */
838e22bee78STejun Heo 
8391037de36SLai Jiangshan /* Return the first idle worker.  Safe with preemption disabled */
8401037de36SLai Jiangshan static struct worker *first_idle_worker(struct worker_pool *pool)
8417e11629dSTejun Heo {
84263d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
8437e11629dSTejun Heo 		return NULL;
8447e11629dSTejun Heo 
84563d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
8467e11629dSTejun Heo }
8477e11629dSTejun Heo 
8487e11629dSTejun Heo /**
8497e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
85063d95a91STejun Heo  * @pool: worker pool to wake worker from
8517e11629dSTejun Heo  *
85263d95a91STejun Heo  * Wake up the first idle worker of @pool.
8537e11629dSTejun Heo  *
8547e11629dSTejun Heo  * CONTEXT:
855d565ed63STejun Heo  * spin_lock_irq(pool->lock).
8567e11629dSTejun Heo  */
85763d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
8587e11629dSTejun Heo {
8591037de36SLai Jiangshan 	struct worker *worker = first_idle_worker(pool);
8607e11629dSTejun Heo 
8617e11629dSTejun Heo 	if (likely(worker))
8627e11629dSTejun Heo 		wake_up_process(worker->task);
8637e11629dSTejun Heo }
8647e11629dSTejun Heo 
8654690c4abSTejun Heo /**
866e22bee78STejun Heo  * wq_worker_waking_up - a worker is waking up
867e22bee78STejun Heo  * @task: task waking up
868e22bee78STejun Heo  * @cpu: CPU @task is waking up to
869e22bee78STejun Heo  *
870e22bee78STejun Heo  * This function is called during try_to_wake_up() when a worker is
871e22bee78STejun Heo  * being awoken.
872e22bee78STejun Heo  *
873e22bee78STejun Heo  * CONTEXT:
874e22bee78STejun Heo  * spin_lock_irq(rq->lock)
875e22bee78STejun Heo  */
876d84ff051STejun Heo void wq_worker_waking_up(struct task_struct *task, int cpu)
877e22bee78STejun Heo {
878e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
879e22bee78STejun Heo 
88036576000SJoonsoo Kim 	if (!(worker->flags & WORKER_NOT_RUNNING)) {
881ec22ca5eSTejun Heo 		WARN_ON_ONCE(worker->pool->cpu != cpu);
882e19e397aSTejun Heo 		atomic_inc(&worker->pool->nr_running);
883e22bee78STejun Heo 	}
88436576000SJoonsoo Kim }
885e22bee78STejun Heo 
886e22bee78STejun Heo /**
887e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
888e22bee78STejun Heo  * @task: task going to sleep
889e22bee78STejun Heo  *
890e22bee78STejun Heo  * This function is called during schedule() when a busy worker is
891e22bee78STejun Heo  * going to sleep.  Worker on the same cpu can be woken up by
892e22bee78STejun Heo  * returning pointer to its task.
893e22bee78STejun Heo  *
894e22bee78STejun Heo  * CONTEXT:
895e22bee78STejun Heo  * spin_lock_irq(rq->lock)
896e22bee78STejun Heo  *
897d185af30SYacine Belkadi  * Return:
898e22bee78STejun Heo  * Worker task on @cpu to wake up, %NULL if none.
899e22bee78STejun Heo  */
9009b7f6597SAlexander Gordeev struct task_struct *wq_worker_sleeping(struct task_struct *task)
901e22bee78STejun Heo {
902e22bee78STejun Heo 	struct worker *worker = kthread_data(task), *to_wakeup = NULL;
903111c225aSTejun Heo 	struct worker_pool *pool;
904e22bee78STejun Heo 
905111c225aSTejun Heo 	/*
906111c225aSTejun Heo 	 * Rescuers, which may not have all the fields set up like normal
907111c225aSTejun Heo 	 * workers, also reach here, let's not access anything before
908111c225aSTejun Heo 	 * checking NOT_RUNNING.
909111c225aSTejun Heo 	 */
9102d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
911e22bee78STejun Heo 		return NULL;
912e22bee78STejun Heo 
913111c225aSTejun Heo 	pool = worker->pool;
914111c225aSTejun Heo 
915e22bee78STejun Heo 	/* this can only happen on the local cpu */
9169b7f6597SAlexander Gordeev 	if (WARN_ON_ONCE(pool->cpu != raw_smp_processor_id()))
9176183c009STejun Heo 		return NULL;
918e22bee78STejun Heo 
919e22bee78STejun Heo 	/*
920e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
921e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
922e22bee78STejun Heo 	 * Please read comment there.
923e22bee78STejun Heo 	 *
924628c78e7STejun Heo 	 * NOT_RUNNING is clear.  This means that we're bound to and
925628c78e7STejun Heo 	 * running on the local cpu w/ rq lock held and preemption
926628c78e7STejun Heo 	 * disabled, which in turn means that none else could be
927d565ed63STejun Heo 	 * manipulating idle_list, so dereferencing idle_list without pool
928628c78e7STejun Heo 	 * lock is safe.
929e22bee78STejun Heo 	 */
930e19e397aSTejun Heo 	if (atomic_dec_and_test(&pool->nr_running) &&
931e19e397aSTejun Heo 	    !list_empty(&pool->worklist))
9321037de36SLai Jiangshan 		to_wakeup = first_idle_worker(pool);
933e22bee78STejun Heo 	return to_wakeup ? to_wakeup->task : NULL;
934e22bee78STejun Heo }
935e22bee78STejun Heo 
936e22bee78STejun Heo /**
937e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
938cb444766STejun Heo  * @worker: self
939d302f017STejun Heo  * @flags: flags to set
940d302f017STejun Heo  *
941228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
942d302f017STejun Heo  *
943cb444766STejun Heo  * CONTEXT:
944d565ed63STejun Heo  * spin_lock_irq(pool->lock)
945d302f017STejun Heo  */
946228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
947d302f017STejun Heo {
948bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
949e22bee78STejun Heo 
950cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
951cb444766STejun Heo 
952228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
953e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
954e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
955e19e397aSTejun Heo 		atomic_dec(&pool->nr_running);
956e22bee78STejun Heo 	}
957e22bee78STejun Heo 
958d302f017STejun Heo 	worker->flags |= flags;
959d302f017STejun Heo }
960d302f017STejun Heo 
961d302f017STejun Heo /**
962e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
963cb444766STejun Heo  * @worker: self
964d302f017STejun Heo  * @flags: flags to clear
965d302f017STejun Heo  *
966e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
967d302f017STejun Heo  *
968cb444766STejun Heo  * CONTEXT:
969d565ed63STejun Heo  * spin_lock_irq(pool->lock)
970d302f017STejun Heo  */
971d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
972d302f017STejun Heo {
97363d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
974e22bee78STejun Heo 	unsigned int oflags = worker->flags;
975e22bee78STejun Heo 
976cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
977cb444766STejun Heo 
978d302f017STejun Heo 	worker->flags &= ~flags;
979e22bee78STejun Heo 
98042c025f3STejun Heo 	/*
98142c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
98242c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
98342c025f3STejun Heo 	 * of multiple flags, not a single flag.
98442c025f3STejun Heo 	 */
985e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
986e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
987e19e397aSTejun Heo 			atomic_inc(&pool->nr_running);
988d302f017STejun Heo }
989d302f017STejun Heo 
990d302f017STejun Heo /**
9918cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
992c9e7cf27STejun Heo  * @pool: pool of interest
9938cca0eeaSTejun Heo  * @work: work to find worker for
9948cca0eeaSTejun Heo  *
995c9e7cf27STejun Heo  * Find a worker which is executing @work on @pool by searching
996c9e7cf27STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
997a2c1c57bSTejun Heo  * to match, its current execution should match the address of @work and
998a2c1c57bSTejun Heo  * its work function.  This is to avoid unwanted dependency between
999a2c1c57bSTejun Heo  * unrelated work executions through a work item being recycled while still
1000a2c1c57bSTejun Heo  * being executed.
1001a2c1c57bSTejun Heo  *
1002a2c1c57bSTejun Heo  * This is a bit tricky.  A work item may be freed once its execution
1003a2c1c57bSTejun Heo  * starts and nothing prevents the freed area from being recycled for
1004a2c1c57bSTejun Heo  * another work item.  If the same work item address ends up being reused
1005a2c1c57bSTejun Heo  * before the original execution finishes, workqueue will identify the
1006a2c1c57bSTejun Heo  * recycled work item as currently executing and make it wait until the
1007a2c1c57bSTejun Heo  * current execution finishes, introducing an unwanted dependency.
1008a2c1c57bSTejun Heo  *
1009c5aa87bbSTejun Heo  * This function checks the work item address and work function to avoid
1010c5aa87bbSTejun Heo  * false positives.  Note that this isn't complete as one may construct a
1011c5aa87bbSTejun Heo  * work function which can introduce dependency onto itself through a
1012c5aa87bbSTejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
1013c5aa87bbSTejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
1014c5aa87bbSTejun Heo  * actually occurs, it should be easy to locate the culprit work function.
10158cca0eeaSTejun Heo  *
10168cca0eeaSTejun Heo  * CONTEXT:
1017d565ed63STejun Heo  * spin_lock_irq(pool->lock).
10188cca0eeaSTejun Heo  *
1019d185af30SYacine Belkadi  * Return:
1020d185af30SYacine Belkadi  * Pointer to worker which is executing @work if found, %NULL
10218cca0eeaSTejun Heo  * otherwise.
10228cca0eeaSTejun Heo  */
1023c9e7cf27STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
10248cca0eeaSTejun Heo 						 struct work_struct *work)
10258cca0eeaSTejun Heo {
102642f8570fSSasha Levin 	struct worker *worker;
102742f8570fSSasha Levin 
1028b67bfe0dSSasha Levin 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1029a2c1c57bSTejun Heo 			       (unsigned long)work)
1030a2c1c57bSTejun Heo 		if (worker->current_work == work &&
1031a2c1c57bSTejun Heo 		    worker->current_func == work->func)
103242f8570fSSasha Levin 			return worker;
103342f8570fSSasha Levin 
103442f8570fSSasha Levin 	return NULL;
10358cca0eeaSTejun Heo }
10368cca0eeaSTejun Heo 
10378cca0eeaSTejun Heo /**
1038bf4ede01STejun Heo  * move_linked_works - move linked works to a list
1039bf4ede01STejun Heo  * @work: start of series of works to be scheduled
1040bf4ede01STejun Heo  * @head: target list to append @work to
1041402dd89dSShailendra Verma  * @nextp: out parameter for nested worklist walking
1042bf4ede01STejun Heo  *
1043bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
1044bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
1045bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
1046bf4ede01STejun Heo  *
1047bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
1048bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
1049bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
1050bf4ede01STejun Heo  *
1051bf4ede01STejun Heo  * CONTEXT:
1052d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1053bf4ede01STejun Heo  */
1054bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1055bf4ede01STejun Heo 			      struct work_struct **nextp)
1056bf4ede01STejun Heo {
1057bf4ede01STejun Heo 	struct work_struct *n;
1058bf4ede01STejun Heo 
1059bf4ede01STejun Heo 	/*
1060bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
1061bf4ede01STejun Heo 	 * use NULL for list head.
1062bf4ede01STejun Heo 	 */
1063bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1064bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
1065bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1066bf4ede01STejun Heo 			break;
1067bf4ede01STejun Heo 	}
1068bf4ede01STejun Heo 
1069bf4ede01STejun Heo 	/*
1070bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
1071bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
1072bf4ede01STejun Heo 	 * needs to be updated.
1073bf4ede01STejun Heo 	 */
1074bf4ede01STejun Heo 	if (nextp)
1075bf4ede01STejun Heo 		*nextp = n;
1076bf4ede01STejun Heo }
1077bf4ede01STejun Heo 
10788864b4e5STejun Heo /**
10798864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
10808864b4e5STejun Heo  * @pwq: pool_workqueue to get
10818864b4e5STejun Heo  *
10828864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
10838864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
10848864b4e5STejun Heo  */
10858864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
10868864b4e5STejun Heo {
10878864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
10888864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
10898864b4e5STejun Heo 	pwq->refcnt++;
10908864b4e5STejun Heo }
10918864b4e5STejun Heo 
10928864b4e5STejun Heo /**
10938864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
10948864b4e5STejun Heo  * @pwq: pool_workqueue to put
10958864b4e5STejun Heo  *
10968864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
10978864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
10988864b4e5STejun Heo  */
10998864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
11008864b4e5STejun Heo {
11018864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
11028864b4e5STejun Heo 	if (likely(--pwq->refcnt))
11038864b4e5STejun Heo 		return;
11048864b4e5STejun Heo 	if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
11058864b4e5STejun Heo 		return;
11068864b4e5STejun Heo 	/*
11078864b4e5STejun Heo 	 * @pwq can't be released under pool->lock, bounce to
11088864b4e5STejun Heo 	 * pwq_unbound_release_workfn().  This never recurses on the same
11098864b4e5STejun Heo 	 * pool->lock as this path is taken only for unbound workqueues and
11108864b4e5STejun Heo 	 * the release work item is scheduled on a per-cpu workqueue.  To
11118864b4e5STejun Heo 	 * avoid lockdep warning, unbound pool->locks are given lockdep
11128864b4e5STejun Heo 	 * subclass of 1 in get_unbound_pool().
11138864b4e5STejun Heo 	 */
11148864b4e5STejun Heo 	schedule_work(&pwq->unbound_release_work);
11158864b4e5STejun Heo }
11168864b4e5STejun Heo 
1117dce90d47STejun Heo /**
1118dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1119dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1120dce90d47STejun Heo  *
1121dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1122dce90d47STejun Heo  */
1123dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1124dce90d47STejun Heo {
1125dce90d47STejun Heo 	if (pwq) {
1126dce90d47STejun Heo 		/*
1127dce90d47STejun Heo 		 * As both pwqs and pools are sched-RCU protected, the
1128dce90d47STejun Heo 		 * following lock operations are safe.
1129dce90d47STejun Heo 		 */
1130dce90d47STejun Heo 		spin_lock_irq(&pwq->pool->lock);
1131dce90d47STejun Heo 		put_pwq(pwq);
1132dce90d47STejun Heo 		spin_unlock_irq(&pwq->pool->lock);
1133dce90d47STejun Heo 	}
1134dce90d47STejun Heo }
1135dce90d47STejun Heo 
1136112202d9STejun Heo static void pwq_activate_delayed_work(struct work_struct *work)
1137bf4ede01STejun Heo {
1138112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1139bf4ede01STejun Heo 
1140bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
114182607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
114282607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1143112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
1144bf4ede01STejun Heo 	__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1145112202d9STejun Heo 	pwq->nr_active++;
1146bf4ede01STejun Heo }
1147bf4ede01STejun Heo 
1148112202d9STejun Heo static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
11493aa62497SLai Jiangshan {
1150112202d9STejun Heo 	struct work_struct *work = list_first_entry(&pwq->delayed_works,
11513aa62497SLai Jiangshan 						    struct work_struct, entry);
11523aa62497SLai Jiangshan 
1153112202d9STejun Heo 	pwq_activate_delayed_work(work);
11543aa62497SLai Jiangshan }
11553aa62497SLai Jiangshan 
1156bf4ede01STejun Heo /**
1157112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1158112202d9STejun Heo  * @pwq: pwq of interest
1159bf4ede01STejun Heo  * @color: color of work which left the queue
1160bf4ede01STejun Heo  *
1161bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1162112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1163bf4ede01STejun Heo  *
1164bf4ede01STejun Heo  * CONTEXT:
1165d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1166bf4ede01STejun Heo  */
1167112202d9STejun Heo static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1168bf4ede01STejun Heo {
11698864b4e5STejun Heo 	/* uncolored work items don't participate in flushing or nr_active */
1170bf4ede01STejun Heo 	if (color == WORK_NO_COLOR)
11718864b4e5STejun Heo 		goto out_put;
1172bf4ede01STejun Heo 
1173112202d9STejun Heo 	pwq->nr_in_flight[color]--;
1174bf4ede01STejun Heo 
1175112202d9STejun Heo 	pwq->nr_active--;
1176112202d9STejun Heo 	if (!list_empty(&pwq->delayed_works)) {
1177bf4ede01STejun Heo 		/* one down, submit a delayed one */
1178112202d9STejun Heo 		if (pwq->nr_active < pwq->max_active)
1179112202d9STejun Heo 			pwq_activate_first_delayed(pwq);
1180bf4ede01STejun Heo 	}
1181bf4ede01STejun Heo 
1182bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1183112202d9STejun Heo 	if (likely(pwq->flush_color != color))
11848864b4e5STejun Heo 		goto out_put;
1185bf4ede01STejun Heo 
1186bf4ede01STejun Heo 	/* are there still in-flight works? */
1187112202d9STejun Heo 	if (pwq->nr_in_flight[color])
11888864b4e5STejun Heo 		goto out_put;
1189bf4ede01STejun Heo 
1190112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1191112202d9STejun Heo 	pwq->flush_color = -1;
1192bf4ede01STejun Heo 
1193bf4ede01STejun Heo 	/*
1194112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1195bf4ede01STejun Heo 	 * will handle the rest.
1196bf4ede01STejun Heo 	 */
1197112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1198112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
11998864b4e5STejun Heo out_put:
12008864b4e5STejun Heo 	put_pwq(pwq);
1201bf4ede01STejun Heo }
1202bf4ede01STejun Heo 
120336e227d2STejun Heo /**
1204bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
120536e227d2STejun Heo  * @work: work item to steal
120636e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1207bbb68dfaSTejun Heo  * @flags: place to store irq state
120836e227d2STejun Heo  *
120936e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1210d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
121136e227d2STejun Heo  *
1212d185af30SYacine Belkadi  * Return:
121336e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
121436e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
121536e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1216bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1217bbb68dfaSTejun Heo  *		for arbitrarily long
121836e227d2STejun Heo  *
1219d185af30SYacine Belkadi  * Note:
1220bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1221e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1222e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1223e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1224bbb68dfaSTejun Heo  *
1225bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1226bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1227bbb68dfaSTejun Heo  *
1228e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1229bf4ede01STejun Heo  */
1230bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1231bbb68dfaSTejun Heo 			       unsigned long *flags)
1232bf4ede01STejun Heo {
1233d565ed63STejun Heo 	struct worker_pool *pool;
1234112202d9STejun Heo 	struct pool_workqueue *pwq;
1235bf4ede01STejun Heo 
1236bbb68dfaSTejun Heo 	local_irq_save(*flags);
1237bbb68dfaSTejun Heo 
123836e227d2STejun Heo 	/* try to steal the timer if it exists */
123936e227d2STejun Heo 	if (is_dwork) {
124036e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
124136e227d2STejun Heo 
1242e0aecdd8STejun Heo 		/*
1243e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1244e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1245e0aecdd8STejun Heo 		 * running on the local CPU.
1246e0aecdd8STejun Heo 		 */
124736e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
124836e227d2STejun Heo 			return 1;
124936e227d2STejun Heo 	}
125036e227d2STejun Heo 
125136e227d2STejun Heo 	/* try to claim PENDING the normal way */
1252bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1253bf4ede01STejun Heo 		return 0;
1254bf4ede01STejun Heo 
1255bf4ede01STejun Heo 	/*
1256bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1257bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1258bf4ede01STejun Heo 	 */
1259d565ed63STejun Heo 	pool = get_work_pool(work);
1260d565ed63STejun Heo 	if (!pool)
1261bbb68dfaSTejun Heo 		goto fail;
1262bf4ede01STejun Heo 
1263d565ed63STejun Heo 	spin_lock(&pool->lock);
1264bf4ede01STejun Heo 	/*
1265112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1266112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1267112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1268112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1269112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
12700b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1271bf4ede01STejun Heo 	 */
1272112202d9STejun Heo 	pwq = get_work_pwq(work);
1273112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1274bf4ede01STejun Heo 		debug_work_deactivate(work);
12753aa62497SLai Jiangshan 
12763aa62497SLai Jiangshan 		/*
127716062836STejun Heo 		 * A delayed work item cannot be grabbed directly because
127816062836STejun Heo 		 * it might have linked NO_COLOR work items which, if left
1279112202d9STejun Heo 		 * on the delayed_list, will confuse pwq->nr_active
128016062836STejun Heo 		 * management later on and cause stall.  Make sure the work
128116062836STejun Heo 		 * item is activated before grabbing.
12823aa62497SLai Jiangshan 		 */
12833aa62497SLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1284112202d9STejun Heo 			pwq_activate_delayed_work(work);
12853aa62497SLai Jiangshan 
1286bf4ede01STejun Heo 		list_del_init(&work->entry);
12879c34a704SLai Jiangshan 		pwq_dec_nr_in_flight(pwq, get_work_color(work));
128836e227d2STejun Heo 
1289112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
12904468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
12914468a00fSLai Jiangshan 
1292d565ed63STejun Heo 		spin_unlock(&pool->lock);
129336e227d2STejun Heo 		return 1;
1294bf4ede01STejun Heo 	}
1295d565ed63STejun Heo 	spin_unlock(&pool->lock);
1296bbb68dfaSTejun Heo fail:
1297bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1298bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1299bbb68dfaSTejun Heo 		return -ENOENT;
1300bbb68dfaSTejun Heo 	cpu_relax();
130136e227d2STejun Heo 	return -EAGAIN;
1302bf4ede01STejun Heo }
1303bf4ede01STejun Heo 
1304bf4ede01STejun Heo /**
1305706026c2STejun Heo  * insert_work - insert a work into a pool
1306112202d9STejun Heo  * @pwq: pwq @work belongs to
13074690c4abSTejun Heo  * @work: work to insert
13084690c4abSTejun Heo  * @head: insertion point
13094690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
13104690c4abSTejun Heo  *
1311112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1312706026c2STejun Heo  * work_struct flags.
13134690c4abSTejun Heo  *
13144690c4abSTejun Heo  * CONTEXT:
1315d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1316365970a1SDavid Howells  */
1317112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1318112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1319b89deed3SOleg Nesterov {
1320112202d9STejun Heo 	struct worker_pool *pool = pwq->pool;
1321e1d8aa9fSFrederic Weisbecker 
13224690c4abSTejun Heo 	/* we own @work, set data and link */
1323112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
13241a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
13258864b4e5STejun Heo 	get_pwq(pwq);
1326e22bee78STejun Heo 
1327e22bee78STejun Heo 	/*
1328c5aa87bbSTejun Heo 	 * Ensure either wq_worker_sleeping() sees the above
1329c5aa87bbSTejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers lying
1330c5aa87bbSTejun Heo 	 * around lazily while there are works to be processed.
1331e22bee78STejun Heo 	 */
1332e22bee78STejun Heo 	smp_mb();
1333e22bee78STejun Heo 
133463d95a91STejun Heo 	if (__need_more_worker(pool))
133563d95a91STejun Heo 		wake_up_worker(pool);
1336b89deed3SOleg Nesterov }
1337b89deed3SOleg Nesterov 
1338c8efcc25STejun Heo /*
1339c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
13408d03ecfeSTejun Heo  * same workqueue.
1341c8efcc25STejun Heo  */
1342c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1343c8efcc25STejun Heo {
1344c8efcc25STejun Heo 	struct worker *worker;
1345c8efcc25STejun Heo 
13468d03ecfeSTejun Heo 	worker = current_wq_worker();
1347c8efcc25STejun Heo 	/*
13488d03ecfeSTejun Heo 	 * Return %true iff I'm a worker execuing a work item on @wq.  If
13498d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1350c8efcc25STejun Heo 	 */
1351112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1352c8efcc25STejun Heo }
1353c8efcc25STejun Heo 
1354ef557180SMike Galbraith /*
1355ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
1356ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
1357ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
1358ef557180SMike Galbraith  */
1359ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1360ef557180SMike Galbraith {
1361f303fccbSTejun Heo 	static bool printed_dbg_warning;
1362ef557180SMike Galbraith 	int new_cpu;
1363ef557180SMike Galbraith 
1364f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
1365ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1366ef557180SMike Galbraith 			return cpu;
1367f303fccbSTejun Heo 	} else if (!printed_dbg_warning) {
1368f303fccbSTejun Heo 		pr_warn("workqueue: round-robin CPU selection forced, expect performance impact\n");
1369f303fccbSTejun Heo 		printed_dbg_warning = true;
1370f303fccbSTejun Heo 	}
1371f303fccbSTejun Heo 
1372ef557180SMike Galbraith 	if (cpumask_empty(wq_unbound_cpumask))
1373ef557180SMike Galbraith 		return cpu;
1374ef557180SMike Galbraith 
1375ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
1376ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1377ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
1378ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1379ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
1380ef557180SMike Galbraith 			return cpu;
1381ef557180SMike Galbraith 	}
1382ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
1383ef557180SMike Galbraith 
1384ef557180SMike Galbraith 	return new_cpu;
1385ef557180SMike Galbraith }
1386ef557180SMike Galbraith 
1387d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
13881da177e4SLinus Torvalds 			 struct work_struct *work)
13891da177e4SLinus Torvalds {
1390112202d9STejun Heo 	struct pool_workqueue *pwq;
1391c9178087STejun Heo 	struct worker_pool *last_pool;
13921e19ffc6STejun Heo 	struct list_head *worklist;
13938a2e8e5dSTejun Heo 	unsigned int work_flags;
1394b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
13958930cabaSTejun Heo 
13968930cabaSTejun Heo 	/*
13978930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
13988930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
13998930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
14008930cabaSTejun Heo 	 * happen with IRQ disabled.
14018930cabaSTejun Heo 	 */
14028930cabaSTejun Heo 	WARN_ON_ONCE(!irqs_disabled());
14031da177e4SLinus Torvalds 
1404dc186ad7SThomas Gleixner 	debug_work_activate(work);
14051e19ffc6STejun Heo 
14069ef28a73SLi Bin 	/* if draining, only works from the same workqueue are allowed */
1407618b01ebSTejun Heo 	if (unlikely(wq->flags & __WQ_DRAINING) &&
1408c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
1409e41e704bSTejun Heo 		return;
14109e8cd2f5STejun Heo retry:
1411df2d5ae4STejun Heo 	if (req_cpu == WORK_CPU_UNBOUND)
1412ef557180SMike Galbraith 		cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1413df2d5ae4STejun Heo 
1414df2d5ae4STejun Heo 	/* pwq which will be used unless @work is executing elsewhere */
1415df2d5ae4STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
1416c9178087STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1417df2d5ae4STejun Heo 	else
1418df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1419f3421797STejun Heo 
142018aa9effSTejun Heo 	/*
1421c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1422c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1423c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
142418aa9effSTejun Heo 	 */
1425c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1426112202d9STejun Heo 	if (last_pool && last_pool != pwq->pool) {
142718aa9effSTejun Heo 		struct worker *worker;
142818aa9effSTejun Heo 
1429d565ed63STejun Heo 		spin_lock(&last_pool->lock);
143018aa9effSTejun Heo 
1431c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
143218aa9effSTejun Heo 
1433112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1434c9178087STejun Heo 			pwq = worker->current_pwq;
14358594fadeSLai Jiangshan 		} else {
143618aa9effSTejun Heo 			/* meh... not running there, queue here */
1437d565ed63STejun Heo 			spin_unlock(&last_pool->lock);
1438112202d9STejun Heo 			spin_lock(&pwq->pool->lock);
143918aa9effSTejun Heo 		}
14408930cabaSTejun Heo 	} else {
1441112202d9STejun Heo 		spin_lock(&pwq->pool->lock);
14428930cabaSTejun Heo 	}
1443502ca9d8STejun Heo 
14449e8cd2f5STejun Heo 	/*
14459e8cd2f5STejun Heo 	 * pwq is determined and locked.  For unbound pools, we could have
14469e8cd2f5STejun Heo 	 * raced with pwq release and it could already be dead.  If its
14479e8cd2f5STejun Heo 	 * refcnt is zero, repeat pwq selection.  Note that pwqs never die
1448df2d5ae4STejun Heo 	 * without another pwq replacing it in the numa_pwq_tbl or while
1449df2d5ae4STejun Heo 	 * work items are executing on it, so the retrying is guaranteed to
14509e8cd2f5STejun Heo 	 * make forward-progress.
14519e8cd2f5STejun Heo 	 */
14529e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
14539e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
14549e8cd2f5STejun Heo 			spin_unlock(&pwq->pool->lock);
14559e8cd2f5STejun Heo 			cpu_relax();
14569e8cd2f5STejun Heo 			goto retry;
14579e8cd2f5STejun Heo 		}
14589e8cd2f5STejun Heo 		/* oops */
14599e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
14609e8cd2f5STejun Heo 			  wq->name, cpu);
14619e8cd2f5STejun Heo 	}
14629e8cd2f5STejun Heo 
1463112202d9STejun Heo 	/* pwq determined, queue */
1464112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1465502ca9d8STejun Heo 
1466f5b2552bSDan Carpenter 	if (WARN_ON(!list_empty(&work->entry))) {
1467112202d9STejun Heo 		spin_unlock(&pwq->pool->lock);
1468f5b2552bSDan Carpenter 		return;
1469f5b2552bSDan Carpenter 	}
14701e19ffc6STejun Heo 
1471112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1472112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
14731e19ffc6STejun Heo 
1474112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1475cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1476112202d9STejun Heo 		pwq->nr_active++;
1477112202d9STejun Heo 		worklist = &pwq->pool->worklist;
147882607adcSTejun Heo 		if (list_empty(worklist))
147982607adcSTejun Heo 			pwq->pool->watchdog_ts = jiffies;
14808a2e8e5dSTejun Heo 	} else {
14818a2e8e5dSTejun Heo 		work_flags |= WORK_STRUCT_DELAYED;
1482112202d9STejun Heo 		worklist = &pwq->delayed_works;
14838a2e8e5dSTejun Heo 	}
14841e19ffc6STejun Heo 
1485112202d9STejun Heo 	insert_work(pwq, work, worklist, work_flags);
14861e19ffc6STejun Heo 
1487112202d9STejun Heo 	spin_unlock(&pwq->pool->lock);
14881da177e4SLinus Torvalds }
14891da177e4SLinus Torvalds 
14900fcb78c2SRolf Eike Beer /**
1491c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1492c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1493c1a220e7SZhang Rui  * @wq: workqueue to use
1494c1a220e7SZhang Rui  * @work: work to queue
1495c1a220e7SZhang Rui  *
1496c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1497c1a220e7SZhang Rui  * can't go away.
1498d185af30SYacine Belkadi  *
1499d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
1500c1a220e7SZhang Rui  */
1501d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1502d4283e93STejun Heo 		   struct work_struct *work)
1503c1a220e7SZhang Rui {
1504d4283e93STejun Heo 	bool ret = false;
15058930cabaSTejun Heo 	unsigned long flags;
15068930cabaSTejun Heo 
15078930cabaSTejun Heo 	local_irq_save(flags);
1508c1a220e7SZhang Rui 
150922df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
15104690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1511d4283e93STejun Heo 		ret = true;
1512c1a220e7SZhang Rui 	}
15138930cabaSTejun Heo 
15148930cabaSTejun Heo 	local_irq_restore(flags);
1515c1a220e7SZhang Rui 	return ret;
1516c1a220e7SZhang Rui }
1517ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1518c1a220e7SZhang Rui 
1519d8e794dfSTejun Heo void delayed_work_timer_fn(unsigned long __data)
15201da177e4SLinus Torvalds {
152152bad64dSDavid Howells 	struct delayed_work *dwork = (struct delayed_work *)__data;
15221da177e4SLinus Torvalds 
1523e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
152460c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
15251da177e4SLinus Torvalds }
15261438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
15271da177e4SLinus Torvalds 
15287beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
152952bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
15301da177e4SLinus Torvalds {
15317beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
15327beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
15331da177e4SLinus Torvalds 
15347beb2edfSTejun Heo 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn ||
15357beb2edfSTejun Heo 		     timer->data != (unsigned long)dwork);
1536fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1537fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
15387beb2edfSTejun Heo 
15398852aac2STejun Heo 	/*
15408852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
15418852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
15428852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
15438852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
15448852aac2STejun Heo 	 */
15458852aac2STejun Heo 	if (!delay) {
15468852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
15478852aac2STejun Heo 		return;
15488852aac2STejun Heo 	}
15498852aac2STejun Heo 
15507beb2edfSTejun Heo 	timer_stats_timer_set_start_info(&dwork->timer);
15517beb2edfSTejun Heo 
155260c057bcSLai Jiangshan 	dwork->wq = wq;
15531265057fSTejun Heo 	dwork->cpu = cpu;
15547beb2edfSTejun Heo 	timer->expires = jiffies + delay;
15557beb2edfSTejun Heo 
1556041bd12eSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
15577beb2edfSTejun Heo 		add_timer_on(timer, cpu);
1558041bd12eSTejun Heo 	else
1559041bd12eSTejun Heo 		add_timer(timer);
15607beb2edfSTejun Heo }
15611da177e4SLinus Torvalds 
15620fcb78c2SRolf Eike Beer /**
15630fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
15640fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
15650fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1566af9997e4SRandy Dunlap  * @dwork: work to queue
15670fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
15680fcb78c2SRolf Eike Beer  *
1569d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
1570715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1571715f1300STejun Heo  * execution.
15720fcb78c2SRolf Eike Beer  */
1573d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
157452bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
15757a6bc1cdSVenkatesh Pallipadi {
157652bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1577d4283e93STejun Heo 	bool ret = false;
15788930cabaSTejun Heo 	unsigned long flags;
15798930cabaSTejun Heo 
15808930cabaSTejun Heo 	/* read the comment in __queue_work() */
15818930cabaSTejun Heo 	local_irq_save(flags);
15827a6bc1cdSVenkatesh Pallipadi 
158322df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
15847beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1585d4283e93STejun Heo 		ret = true;
15867a6bc1cdSVenkatesh Pallipadi 	}
15878930cabaSTejun Heo 
15888930cabaSTejun Heo 	local_irq_restore(flags);
15897a6bc1cdSVenkatesh Pallipadi 	return ret;
15907a6bc1cdSVenkatesh Pallipadi }
1591ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
15921da177e4SLinus Torvalds 
1593c8e55f36STejun Heo /**
15948376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
15958376fe22STejun Heo  * @cpu: CPU number to execute work on
15968376fe22STejun Heo  * @wq: workqueue to use
15978376fe22STejun Heo  * @dwork: work to queue
15988376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
15998376fe22STejun Heo  *
16008376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
16018376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
16028376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
16038376fe22STejun Heo  * current state.
16048376fe22STejun Heo  *
1605d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
16068376fe22STejun Heo  * pending and its timer was modified.
16078376fe22STejun Heo  *
1608e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
16098376fe22STejun Heo  * See try_to_grab_pending() for details.
16108376fe22STejun Heo  */
16118376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
16128376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
16138376fe22STejun Heo {
16148376fe22STejun Heo 	unsigned long flags;
16158376fe22STejun Heo 	int ret;
16168376fe22STejun Heo 
16178376fe22STejun Heo 	do {
16188376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
16198376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
16208376fe22STejun Heo 
16218376fe22STejun Heo 	if (likely(ret >= 0)) {
16228376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
16238376fe22STejun Heo 		local_irq_restore(flags);
16248376fe22STejun Heo 	}
16258376fe22STejun Heo 
16268376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
16278376fe22STejun Heo 	return ret;
16288376fe22STejun Heo }
16298376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
16308376fe22STejun Heo 
16318376fe22STejun Heo /**
1632c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1633c8e55f36STejun Heo  * @worker: worker which is entering idle state
1634c8e55f36STejun Heo  *
1635c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1636c8e55f36STejun Heo  * necessary.
1637c8e55f36STejun Heo  *
1638c8e55f36STejun Heo  * LOCKING:
1639d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1640c8e55f36STejun Heo  */
1641c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
16421da177e4SLinus Torvalds {
1643bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1644c8e55f36STejun Heo 
16456183c009STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
16466183c009STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
16476183c009STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
16486183c009STejun Heo 		return;
1649c8e55f36STejun Heo 
1650051e1850SLai Jiangshan 	/* can't use worker_set_flags(), also called from create_worker() */
1651cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1652bd7bdd43STejun Heo 	pool->nr_idle++;
1653e22bee78STejun Heo 	worker->last_active = jiffies;
1654c8e55f36STejun Heo 
1655c8e55f36STejun Heo 	/* idle_list is LIFO */
1656bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1657db7bccf4STejun Heo 
165863d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1659628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1660cb444766STejun Heo 
1661544ecf31STejun Heo 	/*
1662706026c2STejun Heo 	 * Sanity check nr_running.  Because wq_unbind_fn() releases
1663d565ed63STejun Heo 	 * pool->lock between setting %WORKER_UNBOUND and zapping
1664628c78e7STejun Heo 	 * nr_running, the warning may trigger spuriously.  Check iff
1665628c78e7STejun Heo 	 * unbind is not in progress.
1666544ecf31STejun Heo 	 */
166724647570STejun Heo 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1668bd7bdd43STejun Heo 		     pool->nr_workers == pool->nr_idle &&
1669e19e397aSTejun Heo 		     atomic_read(&pool->nr_running));
1670c8e55f36STejun Heo }
1671c8e55f36STejun Heo 
1672c8e55f36STejun Heo /**
1673c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1674c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1675c8e55f36STejun Heo  *
1676c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1677c8e55f36STejun Heo  *
1678c8e55f36STejun Heo  * LOCKING:
1679d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1680c8e55f36STejun Heo  */
1681c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1682c8e55f36STejun Heo {
1683bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1684c8e55f36STejun Heo 
16856183c009STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
16866183c009STejun Heo 		return;
1687d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1688bd7bdd43STejun Heo 	pool->nr_idle--;
1689c8e55f36STejun Heo 	list_del_init(&worker->entry);
1690c8e55f36STejun Heo }
1691c8e55f36STejun Heo 
1692f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
1693c34056a3STejun Heo {
1694c34056a3STejun Heo 	struct worker *worker;
1695c34056a3STejun Heo 
1696f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1697c8e55f36STejun Heo 	if (worker) {
1698c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1699affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
1700da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
1701e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1702e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1703c8e55f36STejun Heo 	}
1704c34056a3STejun Heo 	return worker;
1705c34056a3STejun Heo }
1706c34056a3STejun Heo 
1707c34056a3STejun Heo /**
17084736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
17094736cbf7SLai Jiangshan  * @worker: worker to be attached
17104736cbf7SLai Jiangshan  * @pool: the target pool
17114736cbf7SLai Jiangshan  *
17124736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
17134736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
17144736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
17154736cbf7SLai Jiangshan  */
17164736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
17174736cbf7SLai Jiangshan 				   struct worker_pool *pool)
17184736cbf7SLai Jiangshan {
17194736cbf7SLai Jiangshan 	mutex_lock(&pool->attach_mutex);
17204736cbf7SLai Jiangshan 
17214736cbf7SLai Jiangshan 	/*
17224736cbf7SLai Jiangshan 	 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
17234736cbf7SLai Jiangshan 	 * online CPUs.  It'll be re-applied when any of the CPUs come up.
17244736cbf7SLai Jiangshan 	 */
17254736cbf7SLai Jiangshan 	set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
17264736cbf7SLai Jiangshan 
17274736cbf7SLai Jiangshan 	/*
17284736cbf7SLai Jiangshan 	 * The pool->attach_mutex ensures %POOL_DISASSOCIATED remains
17294736cbf7SLai Jiangshan 	 * stable across this function.  See the comments above the
17304736cbf7SLai Jiangshan 	 * flag definition for details.
17314736cbf7SLai Jiangshan 	 */
17324736cbf7SLai Jiangshan 	if (pool->flags & POOL_DISASSOCIATED)
17334736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
17344736cbf7SLai Jiangshan 
17354736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
17364736cbf7SLai Jiangshan 
17374736cbf7SLai Jiangshan 	mutex_unlock(&pool->attach_mutex);
17384736cbf7SLai Jiangshan }
17394736cbf7SLai Jiangshan 
17404736cbf7SLai Jiangshan /**
174160f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
174260f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
174360f5a4bcSLai Jiangshan  * @pool: the pool @worker is attached to
174460f5a4bcSLai Jiangshan  *
17454736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
17464736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
17474736cbf7SLai Jiangshan  * other reference to the pool.
174860f5a4bcSLai Jiangshan  */
174960f5a4bcSLai Jiangshan static void worker_detach_from_pool(struct worker *worker,
175060f5a4bcSLai Jiangshan 				    struct worker_pool *pool)
175160f5a4bcSLai Jiangshan {
175260f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
175360f5a4bcSLai Jiangshan 
175492f9c5c4SLai Jiangshan 	mutex_lock(&pool->attach_mutex);
1755da028469SLai Jiangshan 	list_del(&worker->node);
1756da028469SLai Jiangshan 	if (list_empty(&pool->workers))
175760f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
175892f9c5c4SLai Jiangshan 	mutex_unlock(&pool->attach_mutex);
175960f5a4bcSLai Jiangshan 
1760b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
1761b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1762b62c0751SLai Jiangshan 
176360f5a4bcSLai Jiangshan 	if (detach_completion)
176460f5a4bcSLai Jiangshan 		complete(detach_completion);
176560f5a4bcSLai Jiangshan }
176660f5a4bcSLai Jiangshan 
176760f5a4bcSLai Jiangshan /**
1768c34056a3STejun Heo  * create_worker - create a new workqueue worker
176963d95a91STejun Heo  * @pool: pool the new worker will belong to
1770c34056a3STejun Heo  *
1771051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
1772c34056a3STejun Heo  *
1773c34056a3STejun Heo  * CONTEXT:
1774c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1775c34056a3STejun Heo  *
1776d185af30SYacine Belkadi  * Return:
1777c34056a3STejun Heo  * Pointer to the newly created worker.
1778c34056a3STejun Heo  */
1779bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1780c34056a3STejun Heo {
1781c34056a3STejun Heo 	struct worker *worker = NULL;
1782f3421797STejun Heo 	int id = -1;
1783e3c916a4STejun Heo 	char id_buf[16];
1784c34056a3STejun Heo 
17857cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
17867cda9aaeSLai Jiangshan 	id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL);
1787822d8405STejun Heo 	if (id < 0)
1788c34056a3STejun Heo 		goto fail;
1789c34056a3STejun Heo 
1790f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
1791c34056a3STejun Heo 	if (!worker)
1792c34056a3STejun Heo 		goto fail;
1793c34056a3STejun Heo 
1794bd7bdd43STejun Heo 	worker->pool = pool;
1795c34056a3STejun Heo 	worker->id = id;
1796c34056a3STejun Heo 
179729c91e99STejun Heo 	if (pool->cpu >= 0)
1798e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1799e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
1800f3421797STejun Heo 	else
1801e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1802e3c916a4STejun Heo 
1803f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1804e3c916a4STejun Heo 					      "kworker/%s", id_buf);
1805c34056a3STejun Heo 	if (IS_ERR(worker->task))
1806c34056a3STejun Heo 		goto fail;
1807c34056a3STejun Heo 
180891151228SOleg Nesterov 	set_user_nice(worker->task, pool->attrs->nice);
180925834c73SPeter Zijlstra 	kthread_bind_mask(worker->task, pool->attrs->cpumask);
181091151228SOleg Nesterov 
1811da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
18124736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
1813822d8405STejun Heo 
1814051e1850SLai Jiangshan 	/* start the newly created worker */
1815051e1850SLai Jiangshan 	spin_lock_irq(&pool->lock);
1816051e1850SLai Jiangshan 	worker->pool->nr_workers++;
1817051e1850SLai Jiangshan 	worker_enter_idle(worker);
1818051e1850SLai Jiangshan 	wake_up_process(worker->task);
1819051e1850SLai Jiangshan 	spin_unlock_irq(&pool->lock);
1820051e1850SLai Jiangshan 
1821c34056a3STejun Heo 	return worker;
1822822d8405STejun Heo 
1823c34056a3STejun Heo fail:
18249625ab17SLai Jiangshan 	if (id >= 0)
18257cda9aaeSLai Jiangshan 		ida_simple_remove(&pool->worker_ida, id);
1826c34056a3STejun Heo 	kfree(worker);
1827c34056a3STejun Heo 	return NULL;
1828c34056a3STejun Heo }
1829c34056a3STejun Heo 
1830c34056a3STejun Heo /**
1831c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1832c34056a3STejun Heo  * @worker: worker to be destroyed
1833c34056a3STejun Heo  *
183473eb7fe7SLai Jiangshan  * Destroy @worker and adjust @pool stats accordingly.  The worker should
183573eb7fe7SLai Jiangshan  * be idle.
1836c8e55f36STejun Heo  *
1837c8e55f36STejun Heo  * CONTEXT:
183860f5a4bcSLai Jiangshan  * spin_lock_irq(pool->lock).
1839c34056a3STejun Heo  */
1840c34056a3STejun Heo static void destroy_worker(struct worker *worker)
1841c34056a3STejun Heo {
1842bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1843c34056a3STejun Heo 
1844cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
1845cd549687STejun Heo 
1846c34056a3STejun Heo 	/* sanity check frenzy */
18476183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
184873eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
184973eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
18506183c009STejun Heo 		return;
1851c34056a3STejun Heo 
1852bd7bdd43STejun Heo 	pool->nr_workers--;
1853bd7bdd43STejun Heo 	pool->nr_idle--;
1854c8e55f36STejun Heo 
1855c8e55f36STejun Heo 	list_del_init(&worker->entry);
1856cb444766STejun Heo 	worker->flags |= WORKER_DIE;
185760f5a4bcSLai Jiangshan 	wake_up_process(worker->task);
1858c34056a3STejun Heo }
1859c34056a3STejun Heo 
186063d95a91STejun Heo static void idle_worker_timeout(unsigned long __pool)
1861e22bee78STejun Heo {
186263d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
1863e22bee78STejun Heo 
1864d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1865e22bee78STejun Heo 
18663347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
1867e22bee78STejun Heo 		struct worker *worker;
1868e22bee78STejun Heo 		unsigned long expires;
1869e22bee78STejun Heo 
1870e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
187163d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1872e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1873e22bee78STejun Heo 
18743347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
187563d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
18763347fc9fSLai Jiangshan 			break;
1877e22bee78STejun Heo 		}
18783347fc9fSLai Jiangshan 
18793347fc9fSLai Jiangshan 		destroy_worker(worker);
1880e22bee78STejun Heo 	}
1881e22bee78STejun Heo 
1882d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1883e22bee78STejun Heo }
1884e22bee78STejun Heo 
1885493a1724STejun Heo static void send_mayday(struct work_struct *work)
1886e22bee78STejun Heo {
1887112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1888112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
1889493a1724STejun Heo 
18902e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
1891e22bee78STejun Heo 
1892493008a8STejun Heo 	if (!wq->rescuer)
1893493a1724STejun Heo 		return;
1894e22bee78STejun Heo 
1895e22bee78STejun Heo 	/* mayday mayday mayday */
1896493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
189777668c8bSLai Jiangshan 		/*
189877668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
189977668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
190077668c8bSLai Jiangshan 		 * rescuer is done with it.
190177668c8bSLai Jiangshan 		 */
190277668c8bSLai Jiangshan 		get_pwq(pwq);
1903493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
1904e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
1905493a1724STejun Heo 	}
1906e22bee78STejun Heo }
1907e22bee78STejun Heo 
1908706026c2STejun Heo static void pool_mayday_timeout(unsigned long __pool)
1909e22bee78STejun Heo {
191063d95a91STejun Heo 	struct worker_pool *pool = (void *)__pool;
1911e22bee78STejun Heo 	struct work_struct *work;
1912e22bee78STejun Heo 
1913b2d82909STejun Heo 	spin_lock_irq(&pool->lock);
1914b2d82909STejun Heo 	spin_lock(&wq_mayday_lock);		/* for wq->maydays */
1915e22bee78STejun Heo 
191663d95a91STejun Heo 	if (need_to_create_worker(pool)) {
1917e22bee78STejun Heo 		/*
1918e22bee78STejun Heo 		 * We've been trying to create a new worker but
1919e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
1920e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
1921e22bee78STejun Heo 		 * rescuers.
1922e22bee78STejun Heo 		 */
192363d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
1924e22bee78STejun Heo 			send_mayday(work);
1925e22bee78STejun Heo 	}
1926e22bee78STejun Heo 
1927b2d82909STejun Heo 	spin_unlock(&wq_mayday_lock);
1928b2d82909STejun Heo 	spin_unlock_irq(&pool->lock);
1929e22bee78STejun Heo 
193063d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1931e22bee78STejun Heo }
1932e22bee78STejun Heo 
1933e22bee78STejun Heo /**
1934e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
193563d95a91STejun Heo  * @pool: pool to create a new worker for
1936e22bee78STejun Heo  *
193763d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
1938e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
1939e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
194063d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
1941e22bee78STejun Heo  * possible allocation deadlock.
1942e22bee78STejun Heo  *
1943c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
1944c5aa87bbSTejun Heo  * may_start_working() %true.
1945e22bee78STejun Heo  *
1946e22bee78STejun Heo  * LOCKING:
1947d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
1948e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
1949e22bee78STejun Heo  * manager.
1950e22bee78STejun Heo  */
195129187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
1952d565ed63STejun Heo __releases(&pool->lock)
1953d565ed63STejun Heo __acquires(&pool->lock)
1954e22bee78STejun Heo {
1955e22bee78STejun Heo restart:
1956d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
19579f9c2364STejun Heo 
1958e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
195963d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1960e22bee78STejun Heo 
1961e22bee78STejun Heo 	while (true) {
1962051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
1963e22bee78STejun Heo 			break;
1964e22bee78STejun Heo 
1965e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
19669f9c2364STejun Heo 
196763d95a91STejun Heo 		if (!need_to_create_worker(pool))
1968e22bee78STejun Heo 			break;
1969e22bee78STejun Heo 	}
1970e22bee78STejun Heo 
197163d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
1972d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1973051e1850SLai Jiangshan 	/*
1974051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
1975051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
1976051e1850SLai Jiangshan 	 * already become busy.
1977051e1850SLai Jiangshan 	 */
197863d95a91STejun Heo 	if (need_to_create_worker(pool))
1979e22bee78STejun Heo 		goto restart;
1980e22bee78STejun Heo }
1981e22bee78STejun Heo 
1982e22bee78STejun Heo /**
1983e22bee78STejun Heo  * manage_workers - manage worker pool
1984e22bee78STejun Heo  * @worker: self
1985e22bee78STejun Heo  *
1986706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
1987e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
1988706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
1989e22bee78STejun Heo  *
1990e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
1991e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
1992e22bee78STejun Heo  * and may_start_working() is true.
1993e22bee78STejun Heo  *
1994e22bee78STejun Heo  * CONTEXT:
1995d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
1996e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
1997e22bee78STejun Heo  *
1998d185af30SYacine Belkadi  * Return:
199929187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
200029187a9eSTejun Heo  * start processing works, %true if management function was performed and
200129187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
200229187a9eSTejun Heo  * no longer be true.
2003e22bee78STejun Heo  */
2004e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2005e22bee78STejun Heo {
200663d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2007e22bee78STejun Heo 
2008bc3a1afcSTejun Heo 	/*
2009bc3a1afcSTejun Heo 	 * Anyone who successfully grabs manager_arb wins the arbitration
2010bc3a1afcSTejun Heo 	 * and becomes the manager.  mutex_trylock() on pool->manager_arb
2011bc3a1afcSTejun Heo 	 * failure while holding pool->lock reliably indicates that someone
2012bc3a1afcSTejun Heo 	 * else is managing the pool and the worker which failed trylock
2013bc3a1afcSTejun Heo 	 * can proceed to executing work items.  This means that anyone
2014bc3a1afcSTejun Heo 	 * grabbing manager_arb is responsible for actually performing
2015bc3a1afcSTejun Heo 	 * manager duties.  If manager_arb is grabbed and released without
2016bc3a1afcSTejun Heo 	 * actual management, the pool may stall indefinitely.
2017bc3a1afcSTejun Heo 	 */
201834a06bd6STejun Heo 	if (!mutex_trylock(&pool->manager_arb))
201929187a9eSTejun Heo 		return false;
20202607d7a6STejun Heo 	pool->manager = worker;
2021e22bee78STejun Heo 
202229187a9eSTejun Heo 	maybe_create_worker(pool);
2023e22bee78STejun Heo 
20242607d7a6STejun Heo 	pool->manager = NULL;
202534a06bd6STejun Heo 	mutex_unlock(&pool->manager_arb);
202629187a9eSTejun Heo 	return true;
2027e22bee78STejun Heo }
2028e22bee78STejun Heo 
2029a62428c0STejun Heo /**
2030a62428c0STejun Heo  * process_one_work - process single work
2031c34056a3STejun Heo  * @worker: self
2032a62428c0STejun Heo  * @work: work to process
2033a62428c0STejun Heo  *
2034a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2035a62428c0STejun Heo  * process a single work including synchronization against and
2036a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2037a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2038a62428c0STejun Heo  * call this function to process a work.
2039a62428c0STejun Heo  *
2040a62428c0STejun Heo  * CONTEXT:
2041d565ed63STejun Heo  * spin_lock_irq(pool->lock) which is released and regrabbed.
2042a62428c0STejun Heo  */
2043c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2044d565ed63STejun Heo __releases(&pool->lock)
2045d565ed63STejun Heo __acquires(&pool->lock)
20461da177e4SLinus Torvalds {
2047112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2048bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2049112202d9STejun Heo 	bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
205073f53c4aSTejun Heo 	int work_color;
20517e11629dSTejun Heo 	struct worker *collision;
20524e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
20534e6045f1SJohannes Berg 	/*
2054a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2055a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2056a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2057a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2058a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
20594e6045f1SJohannes Berg 	 */
20604d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
20614d82a1deSPeter Zijlstra 
20624d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
20634e6045f1SJohannes Berg #endif
2064807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
206585327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2066ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
206725511a47STejun Heo 
20687e11629dSTejun Heo 	/*
20697e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
20707e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
20717e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
20727e11629dSTejun Heo 	 * currently executing one.
20737e11629dSTejun Heo 	 */
2074c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
20757e11629dSTejun Heo 	if (unlikely(collision)) {
20767e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
20777e11629dSTejun Heo 		return;
20787e11629dSTejun Heo 	}
20791da177e4SLinus Torvalds 
20808930cabaSTejun Heo 	/* claim and dequeue */
20811da177e4SLinus Torvalds 	debug_work_deactivate(work);
2082c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2083c34056a3STejun Heo 	worker->current_work = work;
2084a2c1c57bSTejun Heo 	worker->current_func = work->func;
2085112202d9STejun Heo 	worker->current_pwq = pwq;
208673f53c4aSTejun Heo 	work_color = get_work_color(work);
20877a22ad75STejun Heo 
2088a62428c0STejun Heo 	list_del_init(&work->entry);
2089a62428c0STejun Heo 
2090649027d7STejun Heo 	/*
2091228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
2092228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
2093228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
2094228f1d00SLai Jiangshan 	 * execution of the pending work items.
2095fb0e7bebSTejun Heo 	 */
2096fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2097228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2098fb0e7bebSTejun Heo 
2099974271c4STejun Heo 	/*
2100a489a03eSLai Jiangshan 	 * Wake up another worker if necessary.  The condition is always
2101a489a03eSLai Jiangshan 	 * false for normal per-cpu workers since nr_running would always
2102a489a03eSLai Jiangshan 	 * be >= 1 at this point.  This is used to chain execution of the
2103a489a03eSLai Jiangshan 	 * pending work items for WORKER_NOT_RUNNING workers such as the
2104228f1d00SLai Jiangshan 	 * UNBOUND and CPU_INTENSIVE ones.
2105974271c4STejun Heo 	 */
2106a489a03eSLai Jiangshan 	if (need_more_worker(pool))
210763d95a91STejun Heo 		wake_up_worker(pool);
2108974271c4STejun Heo 
21098930cabaSTejun Heo 	/*
21107c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2111d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
211223657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
211323657bb1STejun Heo 	 * disabled.
21148930cabaSTejun Heo 	 */
21157c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
21161da177e4SLinus Torvalds 
2117d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2118365970a1SDavid Howells 
2119112202d9STejun Heo 	lock_map_acquire_read(&pwq->wq->lockdep_map);
21203295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2121e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2122a2c1c57bSTejun Heo 	worker->current_func(work);
2123e36c886aSArjan van de Ven 	/*
2124e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2125e36c886aSArjan van de Ven 	 * point will only record its address.
2126e36c886aSArjan van de Ven 	 */
2127e36c886aSArjan van de Ven 	trace_workqueue_execute_end(work);
21283295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2129112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
21301da177e4SLinus Torvalds 
2131d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2132044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2133044c782cSValentin Ilie 		       "     last function: %pf\n",
2134a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2135a2c1c57bSTejun Heo 		       worker->current_func);
2136d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2137d5abe669SPeter Zijlstra 		dump_stack();
2138d5abe669SPeter Zijlstra 	}
2139d5abe669SPeter Zijlstra 
2140b22ce278STejun Heo 	/*
2141b22ce278STejun Heo 	 * The following prevents a kworker from hogging CPU on !PREEMPT
2142b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
2143b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
2144b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
2145789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
2146789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
2147b22ce278STejun Heo 	 */
21483e28e377SJoe Lawrence 	cond_resched_rcu_qs();
2149b22ce278STejun Heo 
2150d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2151a62428c0STejun Heo 
2152fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2153fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2154fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2155fb0e7bebSTejun Heo 
2156a62428c0STejun Heo 	/* we're done with it, release */
215742f8570fSSasha Levin 	hash_del(&worker->hentry);
2158c34056a3STejun Heo 	worker->current_work = NULL;
2159a2c1c57bSTejun Heo 	worker->current_func = NULL;
2160112202d9STejun Heo 	worker->current_pwq = NULL;
21613d1cb205STejun Heo 	worker->desc_valid = false;
2162112202d9STejun Heo 	pwq_dec_nr_in_flight(pwq, work_color);
21631da177e4SLinus Torvalds }
21641da177e4SLinus Torvalds 
2165affee4b2STejun Heo /**
2166affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2167affee4b2STejun Heo  * @worker: self
2168affee4b2STejun Heo  *
2169affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2170affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2171affee4b2STejun Heo  * fetches a work from the top and executes it.
2172affee4b2STejun Heo  *
2173affee4b2STejun Heo  * CONTEXT:
2174d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2175affee4b2STejun Heo  * multiple times.
2176affee4b2STejun Heo  */
2177affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
21781da177e4SLinus Torvalds {
2179affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2180affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2181a62428c0STejun Heo 						struct work_struct, entry);
2182c34056a3STejun Heo 		process_one_work(worker, work);
2183a62428c0STejun Heo 	}
21841da177e4SLinus Torvalds }
21851da177e4SLinus Torvalds 
21864690c4abSTejun Heo /**
21874690c4abSTejun Heo  * worker_thread - the worker thread function
2188c34056a3STejun Heo  * @__worker: self
21894690c4abSTejun Heo  *
2190c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2191c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2192c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2193c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2194c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
2195d185af30SYacine Belkadi  *
2196d185af30SYacine Belkadi  * Return: 0
21974690c4abSTejun Heo  */
2198c34056a3STejun Heo static int worker_thread(void *__worker)
21991da177e4SLinus Torvalds {
2200c34056a3STejun Heo 	struct worker *worker = __worker;
2201bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
22021da177e4SLinus Torvalds 
2203e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2204e22bee78STejun Heo 	worker->task->flags |= PF_WQ_WORKER;
2205c8e55f36STejun Heo woke_up:
2206d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2207affee4b2STejun Heo 
2208a9ab775bSTejun Heo 	/* am I supposed to die? */
2209a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2210d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
2211a9ab775bSTejun Heo 		WARN_ON_ONCE(!list_empty(&worker->entry));
2212e22bee78STejun Heo 		worker->task->flags &= ~PF_WQ_WORKER;
221360f5a4bcSLai Jiangshan 
221460f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
22157cda9aaeSLai Jiangshan 		ida_simple_remove(&pool->worker_ida, worker->id);
221660f5a4bcSLai Jiangshan 		worker_detach_from_pool(worker, pool);
221760f5a4bcSLai Jiangshan 		kfree(worker);
2218c8e55f36STejun Heo 		return 0;
2219c8e55f36STejun Heo 	}
2220c8e55f36STejun Heo 
2221c8e55f36STejun Heo 	worker_leave_idle(worker);
2222db7bccf4STejun Heo recheck:
2223e22bee78STejun Heo 	/* no more worker necessary? */
222463d95a91STejun Heo 	if (!need_more_worker(pool))
2225e22bee78STejun Heo 		goto sleep;
2226e22bee78STejun Heo 
2227e22bee78STejun Heo 	/* do we need to manage? */
222863d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2229e22bee78STejun Heo 		goto recheck;
2230e22bee78STejun Heo 
2231c8e55f36STejun Heo 	/*
2232c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2233c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2234c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2235c8e55f36STejun Heo 	 */
22366183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2237c8e55f36STejun Heo 
2238e22bee78STejun Heo 	/*
2239a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2240a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2241a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2242a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2243a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2244e22bee78STejun Heo 	 */
2245a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2246e22bee78STejun Heo 
2247e22bee78STejun Heo 	do {
2248affee4b2STejun Heo 		struct work_struct *work =
2249bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2250affee4b2STejun Heo 					 struct work_struct, entry);
2251affee4b2STejun Heo 
225282607adcSTejun Heo 		pool->watchdog_ts = jiffies;
225382607adcSTejun Heo 
2254c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2255affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2256affee4b2STejun Heo 			process_one_work(worker, work);
2257affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2258affee4b2STejun Heo 				process_scheduled_works(worker);
2259affee4b2STejun Heo 		} else {
2260c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2261affee4b2STejun Heo 			process_scheduled_works(worker);
2262affee4b2STejun Heo 		}
226363d95a91STejun Heo 	} while (keep_working(pool));
2264affee4b2STejun Heo 
2265228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
2266d313dd85STejun Heo sleep:
2267c8e55f36STejun Heo 	/*
2268d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2269d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2270d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2271d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2272d565ed63STejun Heo 	 * event.
2273c8e55f36STejun Heo 	 */
2274c8e55f36STejun Heo 	worker_enter_idle(worker);
2275c8e55f36STejun Heo 	__set_current_state(TASK_INTERRUPTIBLE);
2276d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
22771da177e4SLinus Torvalds 	schedule();
2278c8e55f36STejun Heo 	goto woke_up;
22791da177e4SLinus Torvalds }
22801da177e4SLinus Torvalds 
2281e22bee78STejun Heo /**
2282e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2283111c225aSTejun Heo  * @__rescuer: self
2284e22bee78STejun Heo  *
2285e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2286493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2287e22bee78STejun Heo  *
2288706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2289e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2290e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2291e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2292e22bee78STejun Heo  * the problem rescuer solves.
2293e22bee78STejun Heo  *
2294706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2295706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2296e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2297e22bee78STejun Heo  *
2298e22bee78STejun Heo  * This should happen rarely.
2299d185af30SYacine Belkadi  *
2300d185af30SYacine Belkadi  * Return: 0
2301e22bee78STejun Heo  */
2302111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2303e22bee78STejun Heo {
2304111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2305111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2306e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
23074d595b86SLai Jiangshan 	bool should_stop;
2308e22bee78STejun Heo 
2309e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2310111c225aSTejun Heo 
2311111c225aSTejun Heo 	/*
2312111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2313111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2314111c225aSTejun Heo 	 */
2315111c225aSTejun Heo 	rescuer->task->flags |= PF_WQ_WORKER;
2316e22bee78STejun Heo repeat:
2317e22bee78STejun Heo 	set_current_state(TASK_INTERRUPTIBLE);
23181da177e4SLinus Torvalds 
23194d595b86SLai Jiangshan 	/*
23204d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
23214d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
23224d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
23234d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
23244d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
23254d595b86SLai Jiangshan 	 * list is always empty on exit.
23264d595b86SLai Jiangshan 	 */
23274d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
23281da177e4SLinus Torvalds 
2329493a1724STejun Heo 	/* see whether any pwq is asking for help */
23302e109a28STejun Heo 	spin_lock_irq(&wq_mayday_lock);
2331493a1724STejun Heo 
2332493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2333493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2334493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2335112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2336e22bee78STejun Heo 		struct work_struct *work, *n;
233782607adcSTejun Heo 		bool first = true;
2338e22bee78STejun Heo 
2339e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2340493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2341493a1724STejun Heo 
23422e109a28STejun Heo 		spin_unlock_irq(&wq_mayday_lock);
2343e22bee78STejun Heo 
234451697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
234551697d39SLai Jiangshan 
234651697d39SLai Jiangshan 		spin_lock_irq(&pool->lock);
2347b3104104SLai Jiangshan 		rescuer->pool = pool;
2348e22bee78STejun Heo 
2349e22bee78STejun Heo 		/*
2350e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2351e22bee78STejun Heo 		 * process'em.
2352e22bee78STejun Heo 		 */
23530479c8c5STejun Heo 		WARN_ON_ONCE(!list_empty(scheduled));
235482607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
235582607adcSTejun Heo 			if (get_work_pwq(work) == pwq) {
235682607adcSTejun Heo 				if (first)
235782607adcSTejun Heo 					pool->watchdog_ts = jiffies;
2358e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
235982607adcSTejun Heo 			}
236082607adcSTejun Heo 			first = false;
236182607adcSTejun Heo 		}
2362e22bee78STejun Heo 
2363008847f6SNeilBrown 		if (!list_empty(scheduled)) {
2364e22bee78STejun Heo 			process_scheduled_works(rescuer);
23657576958aSTejun Heo 
23667576958aSTejun Heo 			/*
2367008847f6SNeilBrown 			 * The above execution of rescued work items could
2368008847f6SNeilBrown 			 * have created more to rescue through
2369008847f6SNeilBrown 			 * pwq_activate_first_delayed() or chained
2370008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
2371008847f6SNeilBrown 			 * that such back-to-back work items, which may be
2372008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
2373008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
2374008847f6SNeilBrown 			 */
2375008847f6SNeilBrown 			if (need_to_create_worker(pool)) {
2376008847f6SNeilBrown 				spin_lock(&wq_mayday_lock);
2377008847f6SNeilBrown 				get_pwq(pwq);
2378008847f6SNeilBrown 				list_move_tail(&pwq->mayday_node, &wq->maydays);
2379008847f6SNeilBrown 				spin_unlock(&wq_mayday_lock);
2380008847f6SNeilBrown 			}
2381008847f6SNeilBrown 		}
2382008847f6SNeilBrown 
2383008847f6SNeilBrown 		/*
238477668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
238513b1d625SLai Jiangshan 		 * go away while we're still attached to it.
238677668c8bSLai Jiangshan 		 */
238777668c8bSLai Jiangshan 		put_pwq(pwq);
238877668c8bSLai Jiangshan 
238977668c8bSLai Jiangshan 		/*
2390d8ca83e6SLai Jiangshan 		 * Leave this pool.  If need_more_worker() is %true, notify a
23917576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
23927576958aSTejun Heo 		 * and stalling the execution.
23937576958aSTejun Heo 		 */
2394d8ca83e6SLai Jiangshan 		if (need_more_worker(pool))
239563d95a91STejun Heo 			wake_up_worker(pool);
23967576958aSTejun Heo 
2397b3104104SLai Jiangshan 		rescuer->pool = NULL;
239813b1d625SLai Jiangshan 		spin_unlock_irq(&pool->lock);
239913b1d625SLai Jiangshan 
240013b1d625SLai Jiangshan 		worker_detach_from_pool(rescuer, pool);
240113b1d625SLai Jiangshan 
240213b1d625SLai Jiangshan 		spin_lock_irq(&wq_mayday_lock);
24031da177e4SLinus Torvalds 	}
24041da177e4SLinus Torvalds 
24052e109a28STejun Heo 	spin_unlock_irq(&wq_mayday_lock);
2406493a1724STejun Heo 
24074d595b86SLai Jiangshan 	if (should_stop) {
24084d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
24094d595b86SLai Jiangshan 		rescuer->task->flags &= ~PF_WQ_WORKER;
24104d595b86SLai Jiangshan 		return 0;
24114d595b86SLai Jiangshan 	}
24124d595b86SLai Jiangshan 
2413111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2414111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2415e22bee78STejun Heo 	schedule();
2416e22bee78STejun Heo 	goto repeat;
24171da177e4SLinus Torvalds }
24181da177e4SLinus Torvalds 
2419fca839c0STejun Heo /**
2420fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
2421fca839c0STejun Heo  * @target_wq: workqueue being flushed
2422fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
2423fca839c0STejun Heo  *
2424fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
2425fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2426fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
2427fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2428fca839c0STejun Heo  * a deadlock.
2429fca839c0STejun Heo  */
2430fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
2431fca839c0STejun Heo 				   struct work_struct *target_work)
2432fca839c0STejun Heo {
2433fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
2434fca839c0STejun Heo 	struct worker *worker;
2435fca839c0STejun Heo 
2436fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
2437fca839c0STejun Heo 		return;
2438fca839c0STejun Heo 
2439fca839c0STejun Heo 	worker = current_wq_worker();
2440fca839c0STejun Heo 
2441fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
2442fca839c0STejun Heo 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%pf",
2443fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
244423d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
244523d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2446fca839c0STejun Heo 		  "workqueue: WQ_MEM_RECLAIM %s:%pf is flushing !WQ_MEM_RECLAIM %s:%pf",
2447fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
2448fca839c0STejun Heo 		  target_wq->name, target_func);
2449fca839c0STejun Heo }
2450fca839c0STejun Heo 
2451fc2e4d70SOleg Nesterov struct wq_barrier {
2452fc2e4d70SOleg Nesterov 	struct work_struct	work;
2453fc2e4d70SOleg Nesterov 	struct completion	done;
24542607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
2455fc2e4d70SOleg Nesterov };
2456fc2e4d70SOleg Nesterov 
2457fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2458fc2e4d70SOleg Nesterov {
2459fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2460fc2e4d70SOleg Nesterov 	complete(&barr->done);
2461fc2e4d70SOleg Nesterov }
2462fc2e4d70SOleg Nesterov 
24634690c4abSTejun Heo /**
24644690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2465112202d9STejun Heo  * @pwq: pwq to insert barrier into
24664690c4abSTejun Heo  * @barr: wq_barrier to insert
2467affee4b2STejun Heo  * @target: target work to attach @barr to
2468affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
24694690c4abSTejun Heo  *
2470affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2471affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2472affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2473affee4b2STejun Heo  * cpu.
2474affee4b2STejun Heo  *
2475affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2476affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2477affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2478affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2479affee4b2STejun Heo  * after a work with LINKED flag set.
2480affee4b2STejun Heo  *
2481affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2482112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
24834690c4abSTejun Heo  *
24844690c4abSTejun Heo  * CONTEXT:
2485d565ed63STejun Heo  * spin_lock_irq(pool->lock).
24864690c4abSTejun Heo  */
2487112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2488affee4b2STejun Heo 			      struct wq_barrier *barr,
2489affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2490fc2e4d70SOleg Nesterov {
2491affee4b2STejun Heo 	struct list_head *head;
2492affee4b2STejun Heo 	unsigned int linked = 0;
2493affee4b2STejun Heo 
2494dc186ad7SThomas Gleixner 	/*
2495d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2496dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2497dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2498dc186ad7SThomas Gleixner 	 * might deadlock.
2499dc186ad7SThomas Gleixner 	 */
2500ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
250122df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2502fc2e4d70SOleg Nesterov 	init_completion(&barr->done);
25032607d7a6STejun Heo 	barr->task = current;
250483c22520SOleg Nesterov 
2505affee4b2STejun Heo 	/*
2506affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2507affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2508affee4b2STejun Heo 	 */
2509affee4b2STejun Heo 	if (worker)
2510affee4b2STejun Heo 		head = worker->scheduled.next;
2511affee4b2STejun Heo 	else {
2512affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2513affee4b2STejun Heo 
2514affee4b2STejun Heo 		head = target->entry.next;
2515affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2516affee4b2STejun Heo 		linked = *bits & WORK_STRUCT_LINKED;
2517affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2518affee4b2STejun Heo 	}
2519affee4b2STejun Heo 
2520dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2521112202d9STejun Heo 	insert_work(pwq, &barr->work, head,
2522affee4b2STejun Heo 		    work_color_to_flags(WORK_NO_COLOR) | linked);
2523fc2e4d70SOleg Nesterov }
2524fc2e4d70SOleg Nesterov 
252573f53c4aSTejun Heo /**
2526112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
252773f53c4aSTejun Heo  * @wq: workqueue being flushed
252873f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
252973f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
253073f53c4aSTejun Heo  *
2531112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
253273f53c4aSTejun Heo  *
2533112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
2534112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
2535112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
2536112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
2537112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
253873f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
253973f53c4aSTejun Heo  *
254073f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
254173f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
254273f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
254373f53c4aSTejun Heo  * is returned.
254473f53c4aSTejun Heo  *
2545112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
254673f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
254773f53c4aSTejun Heo  * advanced to @work_color.
254873f53c4aSTejun Heo  *
254973f53c4aSTejun Heo  * CONTEXT:
25503c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
255173f53c4aSTejun Heo  *
2552d185af30SYacine Belkadi  * Return:
255373f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
255473f53c4aSTejun Heo  * otherwise.
255573f53c4aSTejun Heo  */
2556112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
255773f53c4aSTejun Heo 				      int flush_color, int work_color)
25581da177e4SLinus Torvalds {
255973f53c4aSTejun Heo 	bool wait = false;
256049e3cf44STejun Heo 	struct pool_workqueue *pwq;
25611da177e4SLinus Torvalds 
256273f53c4aSTejun Heo 	if (flush_color >= 0) {
25636183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2564112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
2565dc186ad7SThomas Gleixner 	}
256614441960SOleg Nesterov 
256749e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2568112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
25691da177e4SLinus Torvalds 
2570b09f4fd3SLai Jiangshan 		spin_lock_irq(&pool->lock);
257173f53c4aSTejun Heo 
257273f53c4aSTejun Heo 		if (flush_color >= 0) {
25736183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
257473f53c4aSTejun Heo 
2575112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
2576112202d9STejun Heo 				pwq->flush_color = flush_color;
2577112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
257873f53c4aSTejun Heo 				wait = true;
25791da177e4SLinus Torvalds 			}
258073f53c4aSTejun Heo 		}
258173f53c4aSTejun Heo 
258273f53c4aSTejun Heo 		if (work_color >= 0) {
25836183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2584112202d9STejun Heo 			pwq->work_color = work_color;
258573f53c4aSTejun Heo 		}
258673f53c4aSTejun Heo 
2587b09f4fd3SLai Jiangshan 		spin_unlock_irq(&pool->lock);
25881da177e4SLinus Torvalds 	}
25891da177e4SLinus Torvalds 
2590112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
259173f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
259273f53c4aSTejun Heo 
259373f53c4aSTejun Heo 	return wait;
259483c22520SOleg Nesterov }
25951da177e4SLinus Torvalds 
25960fcb78c2SRolf Eike Beer /**
25971da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
25980fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
25991da177e4SLinus Torvalds  *
2600c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
2601c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
26021da177e4SLinus Torvalds  */
26037ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
26041da177e4SLinus Torvalds {
260573f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
260673f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
260773f53c4aSTejun Heo 		.flush_color = -1,
260873f53c4aSTejun Heo 		.done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
260973f53c4aSTejun Heo 	};
261073f53c4aSTejun Heo 	int next_color;
2611b1f4ec17SOleg Nesterov 
26123295f0efSIngo Molnar 	lock_map_acquire(&wq->lockdep_map);
26133295f0efSIngo Molnar 	lock_map_release(&wq->lockdep_map);
261473f53c4aSTejun Heo 
26153c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
261673f53c4aSTejun Heo 
261773f53c4aSTejun Heo 	/*
261873f53c4aSTejun Heo 	 * Start-to-wait phase
261973f53c4aSTejun Heo 	 */
262073f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
262173f53c4aSTejun Heo 
262273f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
262373f53c4aSTejun Heo 		/*
262473f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
262573f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
262673f53c4aSTejun Heo 		 * by one.
262773f53c4aSTejun Heo 		 */
26286183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
262973f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
263073f53c4aSTejun Heo 		wq->work_color = next_color;
263173f53c4aSTejun Heo 
263273f53c4aSTejun Heo 		if (!wq->first_flusher) {
263373f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
26346183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
263573f53c4aSTejun Heo 
263673f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
263773f53c4aSTejun Heo 
2638112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
263973f53c4aSTejun Heo 						       wq->work_color)) {
264073f53c4aSTejun Heo 				/* nothing to flush, done */
264173f53c4aSTejun Heo 				wq->flush_color = next_color;
264273f53c4aSTejun Heo 				wq->first_flusher = NULL;
264373f53c4aSTejun Heo 				goto out_unlock;
264473f53c4aSTejun Heo 			}
264573f53c4aSTejun Heo 		} else {
264673f53c4aSTejun Heo 			/* wait in queue */
26476183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
264873f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
2649112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
265073f53c4aSTejun Heo 		}
265173f53c4aSTejun Heo 	} else {
265273f53c4aSTejun Heo 		/*
265373f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
265473f53c4aSTejun Heo 		 * The next flush completion will assign us
265573f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
265673f53c4aSTejun Heo 		 */
265773f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
265873f53c4aSTejun Heo 	}
265973f53c4aSTejun Heo 
2660fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
2661fca839c0STejun Heo 
26623c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
266373f53c4aSTejun Heo 
266473f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
266573f53c4aSTejun Heo 
266673f53c4aSTejun Heo 	/*
266773f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
266873f53c4aSTejun Heo 	 *
266973f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
267073f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
267173f53c4aSTejun Heo 	 */
267273f53c4aSTejun Heo 	if (wq->first_flusher != &this_flusher)
267373f53c4aSTejun Heo 		return;
267473f53c4aSTejun Heo 
26753c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
267673f53c4aSTejun Heo 
26774ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
26784ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
26794ce48b37STejun Heo 		goto out_unlock;
26804ce48b37STejun Heo 
268173f53c4aSTejun Heo 	wq->first_flusher = NULL;
268273f53c4aSTejun Heo 
26836183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
26846183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
268573f53c4aSTejun Heo 
268673f53c4aSTejun Heo 	while (true) {
268773f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
268873f53c4aSTejun Heo 
268973f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
269073f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
269173f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
269273f53c4aSTejun Heo 				break;
269373f53c4aSTejun Heo 			list_del_init(&next->list);
269473f53c4aSTejun Heo 			complete(&next->done);
269573f53c4aSTejun Heo 		}
269673f53c4aSTejun Heo 
26976183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
269873f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
269973f53c4aSTejun Heo 
270073f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
270173f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
270273f53c4aSTejun Heo 
270373f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
270473f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
270573f53c4aSTejun Heo 			/*
270673f53c4aSTejun Heo 			 * Assign the same color to all overflowed
270773f53c4aSTejun Heo 			 * flushers, advance work_color and append to
270873f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
270973f53c4aSTejun Heo 			 * phase for these overflowed flushers.
271073f53c4aSTejun Heo 			 */
271173f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
271273f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
271373f53c4aSTejun Heo 
271473f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
271573f53c4aSTejun Heo 
271673f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
271773f53c4aSTejun Heo 					      &wq->flusher_queue);
2718112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
271973f53c4aSTejun Heo 		}
272073f53c4aSTejun Heo 
272173f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
27226183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
272373f53c4aSTejun Heo 			break;
272473f53c4aSTejun Heo 		}
272573f53c4aSTejun Heo 
272673f53c4aSTejun Heo 		/*
272773f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
2728112202d9STejun Heo 		 * the new first flusher and arm pwqs.
272973f53c4aSTejun Heo 		 */
27306183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
27316183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
273273f53c4aSTejun Heo 
273373f53c4aSTejun Heo 		list_del_init(&next->list);
273473f53c4aSTejun Heo 		wq->first_flusher = next;
273573f53c4aSTejun Heo 
2736112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
273773f53c4aSTejun Heo 			break;
273873f53c4aSTejun Heo 
273973f53c4aSTejun Heo 		/*
274073f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
274173f53c4aSTejun Heo 		 * flusher and repeat cascading.
274273f53c4aSTejun Heo 		 */
274373f53c4aSTejun Heo 		wq->first_flusher = NULL;
274473f53c4aSTejun Heo 	}
274573f53c4aSTejun Heo 
274673f53c4aSTejun Heo out_unlock:
27473c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
27481da177e4SLinus Torvalds }
27491dadafa8STim Gardner EXPORT_SYMBOL(flush_workqueue);
27501da177e4SLinus Torvalds 
27519c5a2ba7STejun Heo /**
27529c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
27539c5a2ba7STejun Heo  * @wq: workqueue to drain
27549c5a2ba7STejun Heo  *
27559c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
27569c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
27579c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
2758b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
27599c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
27609c5a2ba7STejun Heo  * takes too long.
27619c5a2ba7STejun Heo  */
27629c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
27639c5a2ba7STejun Heo {
27649c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
276549e3cf44STejun Heo 	struct pool_workqueue *pwq;
27669c5a2ba7STejun Heo 
27679c5a2ba7STejun Heo 	/*
27689c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
27699c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
2770618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
27719c5a2ba7STejun Heo 	 */
277287fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
27739c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
2774618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
277587fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
27769c5a2ba7STejun Heo reflush:
27779c5a2ba7STejun Heo 	flush_workqueue(wq);
27789c5a2ba7STejun Heo 
2779b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
278076af4d93STejun Heo 
278149e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2782fa2563e4SThomas Tuttle 		bool drained;
27839c5a2ba7STejun Heo 
2784b09f4fd3SLai Jiangshan 		spin_lock_irq(&pwq->pool->lock);
2785112202d9STejun Heo 		drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2786b09f4fd3SLai Jiangshan 		spin_unlock_irq(&pwq->pool->lock);
2787fa2563e4SThomas Tuttle 
2788fa2563e4SThomas Tuttle 		if (drained)
27899c5a2ba7STejun Heo 			continue;
27909c5a2ba7STejun Heo 
27919c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
27929c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2793c5aa87bbSTejun Heo 			pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
27949c5a2ba7STejun Heo 				wq->name, flush_cnt);
279576af4d93STejun Heo 
2796b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
27979c5a2ba7STejun Heo 		goto reflush;
27989c5a2ba7STejun Heo 	}
27999c5a2ba7STejun Heo 
28009c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
2801618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
280287fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
28039c5a2ba7STejun Heo }
28049c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
28059c5a2ba7STejun Heo 
2806606a5020STejun Heo static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2807baf59022STejun Heo {
2808baf59022STejun Heo 	struct worker *worker = NULL;
2809c9e7cf27STejun Heo 	struct worker_pool *pool;
2810112202d9STejun Heo 	struct pool_workqueue *pwq;
2811baf59022STejun Heo 
2812baf59022STejun Heo 	might_sleep();
2813baf59022STejun Heo 
2814fa1b54e6STejun Heo 	local_irq_disable();
2815fa1b54e6STejun Heo 	pool = get_work_pool(work);
2816fa1b54e6STejun Heo 	if (!pool) {
2817fa1b54e6STejun Heo 		local_irq_enable();
2818fa1b54e6STejun Heo 		return false;
2819fa1b54e6STejun Heo 	}
2820fa1b54e6STejun Heo 
2821fa1b54e6STejun Heo 	spin_lock(&pool->lock);
28220b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
2823112202d9STejun Heo 	pwq = get_work_pwq(work);
2824112202d9STejun Heo 	if (pwq) {
2825112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
2826baf59022STejun Heo 			goto already_gone;
2827606a5020STejun Heo 	} else {
2828c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
2829baf59022STejun Heo 		if (!worker)
2830baf59022STejun Heo 			goto already_gone;
2831112202d9STejun Heo 		pwq = worker->current_pwq;
2832606a5020STejun Heo 	}
2833baf59022STejun Heo 
2834fca839c0STejun Heo 	check_flush_dependency(pwq->wq, work);
2835fca839c0STejun Heo 
2836112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
2837d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2838baf59022STejun Heo 
2839e159489bSTejun Heo 	/*
2840e159489bSTejun Heo 	 * If @max_active is 1 or rescuer is in use, flushing another work
2841e159489bSTejun Heo 	 * item on the same workqueue may lead to deadlock.  Make sure the
2842e159489bSTejun Heo 	 * flusher is not running on the same workqueue by verifying write
2843e159489bSTejun Heo 	 * access.
2844e159489bSTejun Heo 	 */
2845493008a8STejun Heo 	if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)
2846112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
2847e159489bSTejun Heo 	else
2848112202d9STejun Heo 		lock_map_acquire_read(&pwq->wq->lockdep_map);
2849112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
2850e159489bSTejun Heo 
2851baf59022STejun Heo 	return true;
2852baf59022STejun Heo already_gone:
2853d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2854baf59022STejun Heo 	return false;
2855baf59022STejun Heo }
2856baf59022STejun Heo 
2857db700897SOleg Nesterov /**
2858401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
2859401a8d04STejun Heo  * @work: the work to flush
2860db700897SOleg Nesterov  *
2861606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
2862606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
2863401a8d04STejun Heo  *
2864d185af30SYacine Belkadi  * Return:
2865401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2866401a8d04STejun Heo  * %false if it was already idle.
2867db700897SOleg Nesterov  */
2868401a8d04STejun Heo bool flush_work(struct work_struct *work)
2869db700897SOleg Nesterov {
287012997d1aSBjorn Helgaas 	struct wq_barrier barr;
287112997d1aSBjorn Helgaas 
28720976dfc1SStephen Boyd 	lock_map_acquire(&work->lockdep_map);
28730976dfc1SStephen Boyd 	lock_map_release(&work->lockdep_map);
28740976dfc1SStephen Boyd 
287512997d1aSBjorn Helgaas 	if (start_flush_work(work, &barr)) {
287612997d1aSBjorn Helgaas 		wait_for_completion(&barr.done);
287712997d1aSBjorn Helgaas 		destroy_work_on_stack(&barr.work);
287812997d1aSBjorn Helgaas 		return true;
287912997d1aSBjorn Helgaas 	} else {
288012997d1aSBjorn Helgaas 		return false;
288112997d1aSBjorn Helgaas 	}
2882606a5020STejun Heo }
2883db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
2884db700897SOleg Nesterov 
28858603e1b3STejun Heo struct cwt_wait {
28868603e1b3STejun Heo 	wait_queue_t		wait;
28878603e1b3STejun Heo 	struct work_struct	*work;
28888603e1b3STejun Heo };
28898603e1b3STejun Heo 
28908603e1b3STejun Heo static int cwt_wakefn(wait_queue_t *wait, unsigned mode, int sync, void *key)
28918603e1b3STejun Heo {
28928603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
28938603e1b3STejun Heo 
28948603e1b3STejun Heo 	if (cwait->work != key)
28958603e1b3STejun Heo 		return 0;
28968603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
28978603e1b3STejun Heo }
28988603e1b3STejun Heo 
289936e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2900401a8d04STejun Heo {
29018603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
2902bbb68dfaSTejun Heo 	unsigned long flags;
29031f1f642eSOleg Nesterov 	int ret;
29041f1f642eSOleg Nesterov 
29051f1f642eSOleg Nesterov 	do {
2906bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
2907bbb68dfaSTejun Heo 		/*
29088603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
29098603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
29108603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
29118603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
29128603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
29138603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
29148603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
29158603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
29168603e1b3STejun Heo 		 * we're hogging the CPU.
29178603e1b3STejun Heo 		 *
29188603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
29198603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
29208603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
29218603e1b3STejun Heo 		 * wait and wakeup.
2922bbb68dfaSTejun Heo 		 */
29238603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
29248603e1b3STejun Heo 			struct cwt_wait cwait;
29258603e1b3STejun Heo 
29268603e1b3STejun Heo 			init_wait(&cwait.wait);
29278603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
29288603e1b3STejun Heo 			cwait.work = work;
29298603e1b3STejun Heo 
29308603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
29318603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
29328603e1b3STejun Heo 			if (work_is_canceling(work))
29338603e1b3STejun Heo 				schedule();
29348603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
29358603e1b3STejun Heo 		}
29361f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
29371f1f642eSOleg Nesterov 
2938bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
2939bbb68dfaSTejun Heo 	mark_work_canceling(work);
2940bbb68dfaSTejun Heo 	local_irq_restore(flags);
2941bbb68dfaSTejun Heo 
2942606a5020STejun Heo 	flush_work(work);
29437a22ad75STejun Heo 	clear_work_data(work);
29448603e1b3STejun Heo 
29458603e1b3STejun Heo 	/*
29468603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
29478603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
29488603e1b3STejun Heo 	 * visible there.
29498603e1b3STejun Heo 	 */
29508603e1b3STejun Heo 	smp_mb();
29518603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
29528603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
29538603e1b3STejun Heo 
29541f1f642eSOleg Nesterov 	return ret;
29551f1f642eSOleg Nesterov }
29561f1f642eSOleg Nesterov 
29576e84d644SOleg Nesterov /**
2958401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
2959401a8d04STejun Heo  * @work: the work to cancel
29606e84d644SOleg Nesterov  *
2961401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
2962401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
2963401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
2964401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
29651f1f642eSOleg Nesterov  *
2966401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
2967401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
29686e84d644SOleg Nesterov  *
2969401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
29706e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
2971401a8d04STejun Heo  *
2972d185af30SYacine Belkadi  * Return:
2973401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
29746e84d644SOleg Nesterov  */
2975401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
29766e84d644SOleg Nesterov {
297736e227d2STejun Heo 	return __cancel_work_timer(work, false);
2978b89deed3SOleg Nesterov }
297928e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
2980b89deed3SOleg Nesterov 
29816e84d644SOleg Nesterov /**
2982401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
2983401a8d04STejun Heo  * @dwork: the delayed work to flush
29846e84d644SOleg Nesterov  *
2985401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
2986401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
2987401a8d04STejun Heo  * considers the last queueing instance of @dwork.
29881f1f642eSOleg Nesterov  *
2989d185af30SYacine Belkadi  * Return:
2990401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2991401a8d04STejun Heo  * %false if it was already idle.
29926e84d644SOleg Nesterov  */
2993401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
2994401a8d04STejun Heo {
29958930cabaSTejun Heo 	local_irq_disable();
2996401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
299760c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
29988930cabaSTejun Heo 	local_irq_enable();
2999401a8d04STejun Heo 	return flush_work(&dwork->work);
3000401a8d04STejun Heo }
3001401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3002401a8d04STejun Heo 
3003401a8d04STejun Heo /**
300457b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
300557b30ae7STejun Heo  * @dwork: delayed_work to cancel
300609383498STejun Heo  *
3007d185af30SYacine Belkadi  * Kill off a pending delayed_work.
3008d185af30SYacine Belkadi  *
3009d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
3010d185af30SYacine Belkadi  * pending.
3011d185af30SYacine Belkadi  *
3012d185af30SYacine Belkadi  * Note:
3013d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
3014d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
3015d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
301609383498STejun Heo  *
301757b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
301809383498STejun Heo  */
301957b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
302009383498STejun Heo {
302157b30ae7STejun Heo 	unsigned long flags;
302257b30ae7STejun Heo 	int ret;
302357b30ae7STejun Heo 
302457b30ae7STejun Heo 	do {
302557b30ae7STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
302657b30ae7STejun Heo 	} while (unlikely(ret == -EAGAIN));
302757b30ae7STejun Heo 
302857b30ae7STejun Heo 	if (unlikely(ret < 0))
302957b30ae7STejun Heo 		return false;
303057b30ae7STejun Heo 
30317c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(&dwork->work,
30327c3eed5cSTejun Heo 					get_work_pool_id(&dwork->work));
303357b30ae7STejun Heo 	local_irq_restore(flags);
3034c0158ca6SDan Magenheimer 	return ret;
303509383498STejun Heo }
303657b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
303709383498STejun Heo 
303809383498STejun Heo /**
3039401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3040401a8d04STejun Heo  * @dwork: the delayed work cancel
3041401a8d04STejun Heo  *
3042401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
3043401a8d04STejun Heo  *
3044d185af30SYacine Belkadi  * Return:
3045401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
3046401a8d04STejun Heo  */
3047401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
30486e84d644SOleg Nesterov {
304936e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
30506e84d644SOleg Nesterov }
3051f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
30521da177e4SLinus Torvalds 
30530fcb78c2SRolf Eike Beer /**
305431ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3055b6136773SAndrew Morton  * @func: the function to call
3056b6136773SAndrew Morton  *
305731ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
305831ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3059b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
306031ddd871STejun Heo  *
3061d185af30SYacine Belkadi  * Return:
306231ddd871STejun Heo  * 0 on success, -errno on failure.
3063b6136773SAndrew Morton  */
306465f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
306515316ba8SChristoph Lameter {
306615316ba8SChristoph Lameter 	int cpu;
306738f51568SNamhyung Kim 	struct work_struct __percpu *works;
306815316ba8SChristoph Lameter 
3069b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3070b6136773SAndrew Morton 	if (!works)
307115316ba8SChristoph Lameter 		return -ENOMEM;
3072b6136773SAndrew Morton 
307395402b38SGautham R Shenoy 	get_online_cpus();
307493981800STejun Heo 
307515316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
30769bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
30779bfb1839SIngo Molnar 
30789bfb1839SIngo Molnar 		INIT_WORK(work, func);
30798de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
308015316ba8SChristoph Lameter 	}
308193981800STejun Heo 
308293981800STejun Heo 	for_each_online_cpu(cpu)
30838616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
308493981800STejun Heo 
308595402b38SGautham R Shenoy 	put_online_cpus();
3086b6136773SAndrew Morton 	free_percpu(works);
308715316ba8SChristoph Lameter 	return 0;
308815316ba8SChristoph Lameter }
308915316ba8SChristoph Lameter 
3090eef6a7d5SAlan Stern /**
30911fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
30921fa44ecaSJames Bottomley  * @fn:		the function to execute
30931fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
30941fa44ecaSJames Bottomley  *		be available when the work executes)
30951fa44ecaSJames Bottomley  *
30961fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
30971fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
30981fa44ecaSJames Bottomley  *
3099d185af30SYacine Belkadi  * Return:	0 - function was executed
31001fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
31011fa44ecaSJames Bottomley  */
310265f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
31031fa44ecaSJames Bottomley {
31041fa44ecaSJames Bottomley 	if (!in_interrupt()) {
310565f27f38SDavid Howells 		fn(&ew->work);
31061fa44ecaSJames Bottomley 		return 0;
31071fa44ecaSJames Bottomley 	}
31081fa44ecaSJames Bottomley 
310965f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
31101fa44ecaSJames Bottomley 	schedule_work(&ew->work);
31111fa44ecaSJames Bottomley 
31121fa44ecaSJames Bottomley 	return 1;
31131fa44ecaSJames Bottomley }
31141fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
31151fa44ecaSJames Bottomley 
31167a4e344cSTejun Heo /**
31177a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
31187a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
31197a4e344cSTejun Heo  *
31207a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
31217a4e344cSTejun Heo  */
31227a4e344cSTejun Heo void free_workqueue_attrs(struct workqueue_attrs *attrs)
31237a4e344cSTejun Heo {
31247a4e344cSTejun Heo 	if (attrs) {
31257a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
31267a4e344cSTejun Heo 		kfree(attrs);
31277a4e344cSTejun Heo 	}
31287a4e344cSTejun Heo }
31297a4e344cSTejun Heo 
31307a4e344cSTejun Heo /**
31317a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
31327a4e344cSTejun Heo  * @gfp_mask: allocation mask to use
31337a4e344cSTejun Heo  *
31347a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3135d185af30SYacine Belkadi  * return it.
3136d185af30SYacine Belkadi  *
3137d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
31387a4e344cSTejun Heo  */
31397a4e344cSTejun Heo struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
31407a4e344cSTejun Heo {
31417a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
31427a4e344cSTejun Heo 
31437a4e344cSTejun Heo 	attrs = kzalloc(sizeof(*attrs), gfp_mask);
31447a4e344cSTejun Heo 	if (!attrs)
31457a4e344cSTejun Heo 		goto fail;
31467a4e344cSTejun Heo 	if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
31477a4e344cSTejun Heo 		goto fail;
31487a4e344cSTejun Heo 
314913e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
31507a4e344cSTejun Heo 	return attrs;
31517a4e344cSTejun Heo fail:
31527a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
31537a4e344cSTejun Heo 	return NULL;
31547a4e344cSTejun Heo }
31557a4e344cSTejun Heo 
315629c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
315729c91e99STejun Heo 				 const struct workqueue_attrs *from)
315829c91e99STejun Heo {
315929c91e99STejun Heo 	to->nice = from->nice;
316029c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
31612865a8fbSShaohua Li 	/*
31622865a8fbSShaohua Li 	 * Unlike hash and equality test, this function doesn't ignore
31632865a8fbSShaohua Li 	 * ->no_numa as it is used for both pool and wq attrs.  Instead,
31642865a8fbSShaohua Li 	 * get_unbound_pool() explicitly clears ->no_numa after copying.
31652865a8fbSShaohua Li 	 */
31662865a8fbSShaohua Li 	to->no_numa = from->no_numa;
316729c91e99STejun Heo }
316829c91e99STejun Heo 
316929c91e99STejun Heo /* hash value of the content of @attr */
317029c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
317129c91e99STejun Heo {
317229c91e99STejun Heo 	u32 hash = 0;
317329c91e99STejun Heo 
317429c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
317513e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
317613e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
317729c91e99STejun Heo 	return hash;
317829c91e99STejun Heo }
317929c91e99STejun Heo 
318029c91e99STejun Heo /* content equality test */
318129c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
318229c91e99STejun Heo 			  const struct workqueue_attrs *b)
318329c91e99STejun Heo {
318429c91e99STejun Heo 	if (a->nice != b->nice)
318529c91e99STejun Heo 		return false;
318629c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
318729c91e99STejun Heo 		return false;
318829c91e99STejun Heo 	return true;
318929c91e99STejun Heo }
319029c91e99STejun Heo 
31917a4e344cSTejun Heo /**
31927a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
31937a4e344cSTejun Heo  * @pool: worker_pool to initialize
31947a4e344cSTejun Heo  *
3195402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3196d185af30SYacine Belkadi  *
3197d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
319829c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
319929c91e99STejun Heo  * on @pool safely to release it.
32007a4e344cSTejun Heo  */
32017a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
32024e1a1f9aSTejun Heo {
32034e1a1f9aSTejun Heo 	spin_lock_init(&pool->lock);
320429c91e99STejun Heo 	pool->id = -1;
320529c91e99STejun Heo 	pool->cpu = -1;
3206f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
32074e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
320882607adcSTejun Heo 	pool->watchdog_ts = jiffies;
32094e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
32104e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
32114e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
32124e1a1f9aSTejun Heo 
32134e1a1f9aSTejun Heo 	init_timer_deferrable(&pool->idle_timer);
32144e1a1f9aSTejun Heo 	pool->idle_timer.function = idle_worker_timeout;
32154e1a1f9aSTejun Heo 	pool->idle_timer.data = (unsigned long)pool;
32164e1a1f9aSTejun Heo 
32174e1a1f9aSTejun Heo 	setup_timer(&pool->mayday_timer, pool_mayday_timeout,
32184e1a1f9aSTejun Heo 		    (unsigned long)pool);
32194e1a1f9aSTejun Heo 
32204e1a1f9aSTejun Heo 	mutex_init(&pool->manager_arb);
322192f9c5c4SLai Jiangshan 	mutex_init(&pool->attach_mutex);
3222da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
32237a4e344cSTejun Heo 
32247cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
322529c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
322629c91e99STejun Heo 	pool->refcnt = 1;
322729c91e99STejun Heo 
322829c91e99STejun Heo 	/* shouldn't fail above this point */
32297a4e344cSTejun Heo 	pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
32307a4e344cSTejun Heo 	if (!pool->attrs)
32317a4e344cSTejun Heo 		return -ENOMEM;
32327a4e344cSTejun Heo 	return 0;
32334e1a1f9aSTejun Heo }
32344e1a1f9aSTejun Heo 
3235e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
3236e2dca7adSTejun Heo {
3237e2dca7adSTejun Heo 	struct workqueue_struct *wq =
3238e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
3239e2dca7adSTejun Heo 
3240e2dca7adSTejun Heo 	if (!(wq->flags & WQ_UNBOUND))
3241e2dca7adSTejun Heo 		free_percpu(wq->cpu_pwqs);
3242e2dca7adSTejun Heo 	else
3243e2dca7adSTejun Heo 		free_workqueue_attrs(wq->unbound_attrs);
3244e2dca7adSTejun Heo 
3245e2dca7adSTejun Heo 	kfree(wq->rescuer);
3246e2dca7adSTejun Heo 	kfree(wq);
3247e2dca7adSTejun Heo }
3248e2dca7adSTejun Heo 
324929c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
325029c91e99STejun Heo {
325129c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
325229c91e99STejun Heo 
32537cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
325429c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
325529c91e99STejun Heo 	kfree(pool);
325629c91e99STejun Heo }
325729c91e99STejun Heo 
325829c91e99STejun Heo /**
325929c91e99STejun Heo  * put_unbound_pool - put a worker_pool
326029c91e99STejun Heo  * @pool: worker_pool to put
326129c91e99STejun Heo  *
326229c91e99STejun Heo  * Put @pool.  If its refcnt reaches zero, it gets destroyed in sched-RCU
3263c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3264c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3265c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
3266a892caccSTejun Heo  *
3267a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
326829c91e99STejun Heo  */
326929c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
327029c91e99STejun Heo {
327160f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
327229c91e99STejun Heo 	struct worker *worker;
327329c91e99STejun Heo 
3274a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3275a892caccSTejun Heo 
3276a892caccSTejun Heo 	if (--pool->refcnt)
327729c91e99STejun Heo 		return;
327829c91e99STejun Heo 
327929c91e99STejun Heo 	/* sanity checks */
328061d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
3281a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
328229c91e99STejun Heo 		return;
328329c91e99STejun Heo 
328429c91e99STejun Heo 	/* release id and unhash */
328529c91e99STejun Heo 	if (pool->id >= 0)
328629c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
328729c91e99STejun Heo 	hash_del(&pool->hash_node);
328829c91e99STejun Heo 
3289c5aa87bbSTejun Heo 	/*
3290c5aa87bbSTejun Heo 	 * Become the manager and destroy all workers.  Grabbing
3291c5aa87bbSTejun Heo 	 * manager_arb prevents @pool's workers from blocking on
329292f9c5c4SLai Jiangshan 	 * attach_mutex.
3293c5aa87bbSTejun Heo 	 */
329429c91e99STejun Heo 	mutex_lock(&pool->manager_arb);
329529c91e99STejun Heo 
329660f5a4bcSLai Jiangshan 	spin_lock_irq(&pool->lock);
32971037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
329829c91e99STejun Heo 		destroy_worker(worker);
329929c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
330029c91e99STejun Heo 	spin_unlock_irq(&pool->lock);
330160f5a4bcSLai Jiangshan 
330292f9c5c4SLai Jiangshan 	mutex_lock(&pool->attach_mutex);
3303da028469SLai Jiangshan 	if (!list_empty(&pool->workers))
330460f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
330592f9c5c4SLai Jiangshan 	mutex_unlock(&pool->attach_mutex);
330660f5a4bcSLai Jiangshan 
330760f5a4bcSLai Jiangshan 	if (pool->detach_completion)
330860f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
330960f5a4bcSLai Jiangshan 
331029c91e99STejun Heo 	mutex_unlock(&pool->manager_arb);
331129c91e99STejun Heo 
331229c91e99STejun Heo 	/* shut down the timers */
331329c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
331429c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
331529c91e99STejun Heo 
331629c91e99STejun Heo 	/* sched-RCU protected to allow dereferences from get_work_pool() */
331729c91e99STejun Heo 	call_rcu_sched(&pool->rcu, rcu_free_pool);
331829c91e99STejun Heo }
331929c91e99STejun Heo 
332029c91e99STejun Heo /**
332129c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
332229c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
332329c91e99STejun Heo  *
332429c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
332529c91e99STejun Heo  * reference count and return it.  If there already is a matching
332629c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
3327d185af30SYacine Belkadi  * create a new one.
3328a892caccSTejun Heo  *
3329a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
3330d185af30SYacine Belkadi  *
3331d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
3332d185af30SYacine Belkadi  * On failure, %NULL.
333329c91e99STejun Heo  */
333429c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
333529c91e99STejun Heo {
333629c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
333729c91e99STejun Heo 	struct worker_pool *pool;
3338f3f90ad4STejun Heo 	int node;
3339e2273584SXunlei Pang 	int target_node = NUMA_NO_NODE;
334029c91e99STejun Heo 
3341a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
334229c91e99STejun Heo 
334329c91e99STejun Heo 	/* do we already have a matching pool? */
334429c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
334529c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
334629c91e99STejun Heo 			pool->refcnt++;
33473fb1823cSLai Jiangshan 			return pool;
334829c91e99STejun Heo 		}
334929c91e99STejun Heo 	}
335029c91e99STejun Heo 
3351e2273584SXunlei Pang 	/* if cpumask is contained inside a NUMA node, we belong to that node */
3352e2273584SXunlei Pang 	if (wq_numa_enabled) {
3353e2273584SXunlei Pang 		for_each_node(node) {
3354e2273584SXunlei Pang 			if (cpumask_subset(attrs->cpumask,
3355e2273584SXunlei Pang 					   wq_numa_possible_cpumask[node])) {
3356e2273584SXunlei Pang 				target_node = node;
3357e2273584SXunlei Pang 				break;
3358e2273584SXunlei Pang 			}
3359e2273584SXunlei Pang 		}
3360e2273584SXunlei Pang 	}
3361e2273584SXunlei Pang 
336229c91e99STejun Heo 	/* nope, create a new one */
3363e2273584SXunlei Pang 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
336429c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
336529c91e99STejun Heo 		goto fail;
336629c91e99STejun Heo 
33678864b4e5STejun Heo 	lockdep_set_subclass(&pool->lock, 1);	/* see put_pwq() */
336829c91e99STejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
3369e2273584SXunlei Pang 	pool->node = target_node;
337029c91e99STejun Heo 
33712865a8fbSShaohua Li 	/*
33722865a8fbSShaohua Li 	 * no_numa isn't a worker_pool attribute, always clear it.  See
33732865a8fbSShaohua Li 	 * 'struct workqueue_attrs' comments for detail.
33742865a8fbSShaohua Li 	 */
33752865a8fbSShaohua Li 	pool->attrs->no_numa = false;
33762865a8fbSShaohua Li 
337729c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
337829c91e99STejun Heo 		goto fail;
337929c91e99STejun Heo 
338029c91e99STejun Heo 	/* create and start the initial worker */
3381051e1850SLai Jiangshan 	if (!create_worker(pool))
338229c91e99STejun Heo 		goto fail;
338329c91e99STejun Heo 
338429c91e99STejun Heo 	/* install */
338529c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
33863fb1823cSLai Jiangshan 
338729c91e99STejun Heo 	return pool;
338829c91e99STejun Heo fail:
338929c91e99STejun Heo 	if (pool)
339029c91e99STejun Heo 		put_unbound_pool(pool);
339129c91e99STejun Heo 	return NULL;
339229c91e99STejun Heo }
339329c91e99STejun Heo 
33948864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
33958864b4e5STejun Heo {
33968864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
33978864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
33988864b4e5STejun Heo }
33998864b4e5STejun Heo 
34008864b4e5STejun Heo /*
34018864b4e5STejun Heo  * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
34028864b4e5STejun Heo  * and needs to be destroyed.
34038864b4e5STejun Heo  */
34048864b4e5STejun Heo static void pwq_unbound_release_workfn(struct work_struct *work)
34058864b4e5STejun Heo {
34068864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
34078864b4e5STejun Heo 						  unbound_release_work);
34088864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
34098864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
3410bc0caf09STejun Heo 	bool is_last;
34118864b4e5STejun Heo 
34128864b4e5STejun Heo 	if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
34138864b4e5STejun Heo 		return;
34148864b4e5STejun Heo 
34153c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
34168864b4e5STejun Heo 	list_del_rcu(&pwq->pwqs_node);
3417bc0caf09STejun Heo 	is_last = list_empty(&wq->pwqs);
34183c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
34198864b4e5STejun Heo 
3420a892caccSTejun Heo 	mutex_lock(&wq_pool_mutex);
34218864b4e5STejun Heo 	put_unbound_pool(pool);
3422a892caccSTejun Heo 	mutex_unlock(&wq_pool_mutex);
3423a892caccSTejun Heo 
34248864b4e5STejun Heo 	call_rcu_sched(&pwq->rcu, rcu_free_pwq);
34258864b4e5STejun Heo 
34268864b4e5STejun Heo 	/*
34278864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
3428e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
34298864b4e5STejun Heo 	 */
3430e2dca7adSTejun Heo 	if (is_last)
3431e2dca7adSTejun Heo 		call_rcu_sched(&wq->rcu, rcu_free_wq);
34326029a918STejun Heo }
34338864b4e5STejun Heo 
34340fbd95aaSTejun Heo /**
3435699ce097STejun Heo  * pwq_adjust_max_active - update a pwq's max_active to the current setting
34360fbd95aaSTejun Heo  * @pwq: target pool_workqueue
34370fbd95aaSTejun Heo  *
3438699ce097STejun Heo  * If @pwq isn't freezing, set @pwq->max_active to the associated
3439699ce097STejun Heo  * workqueue's saved_max_active and activate delayed work items
3440699ce097STejun Heo  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
34410fbd95aaSTejun Heo  */
3442699ce097STejun Heo static void pwq_adjust_max_active(struct pool_workqueue *pwq)
34430fbd95aaSTejun Heo {
3444699ce097STejun Heo 	struct workqueue_struct *wq = pwq->wq;
3445699ce097STejun Heo 	bool freezable = wq->flags & WQ_FREEZABLE;
3446699ce097STejun Heo 
3447699ce097STejun Heo 	/* for @wq->saved_max_active */
3448a357fc03SLai Jiangshan 	lockdep_assert_held(&wq->mutex);
3449699ce097STejun Heo 
3450699ce097STejun Heo 	/* fast exit for non-freezable wqs */
3451699ce097STejun Heo 	if (!freezable && pwq->max_active == wq->saved_max_active)
3452699ce097STejun Heo 		return;
3453699ce097STejun Heo 
3454a357fc03SLai Jiangshan 	spin_lock_irq(&pwq->pool->lock);
3455699ce097STejun Heo 
345674b414eaSLai Jiangshan 	/*
345774b414eaSLai Jiangshan 	 * During [un]freezing, the caller is responsible for ensuring that
345874b414eaSLai Jiangshan 	 * this function is called at least once after @workqueue_freezing
345974b414eaSLai Jiangshan 	 * is updated and visible.
346074b414eaSLai Jiangshan 	 */
346174b414eaSLai Jiangshan 	if (!freezable || !workqueue_freezing) {
3462699ce097STejun Heo 		pwq->max_active = wq->saved_max_active;
34630fbd95aaSTejun Heo 
34640fbd95aaSTejun Heo 		while (!list_empty(&pwq->delayed_works) &&
34650fbd95aaSTejun Heo 		       pwq->nr_active < pwq->max_active)
34660fbd95aaSTejun Heo 			pwq_activate_first_delayed(pwq);
3467951a078aSLai Jiangshan 
3468951a078aSLai Jiangshan 		/*
3469951a078aSLai Jiangshan 		 * Need to kick a worker after thawed or an unbound wq's
3470951a078aSLai Jiangshan 		 * max_active is bumped.  It's a slow path.  Do it always.
3471951a078aSLai Jiangshan 		 */
3472951a078aSLai Jiangshan 		wake_up_worker(pwq->pool);
3473699ce097STejun Heo 	} else {
3474699ce097STejun Heo 		pwq->max_active = 0;
3475699ce097STejun Heo 	}
3476699ce097STejun Heo 
3477a357fc03SLai Jiangshan 	spin_unlock_irq(&pwq->pool->lock);
34780fbd95aaSTejun Heo }
34790fbd95aaSTejun Heo 
3480e50aba9aSTejun Heo /* initialize newly alloced @pwq which is associated with @wq and @pool */
3481f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3482f147f29eSTejun Heo 		     struct worker_pool *pool)
3483d2c1d404STejun Heo {
3484d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3485d2c1d404STejun Heo 
3486e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
3487e50aba9aSTejun Heo 
3488d2c1d404STejun Heo 	pwq->pool = pool;
3489d2c1d404STejun Heo 	pwq->wq = wq;
3490d2c1d404STejun Heo 	pwq->flush_color = -1;
34918864b4e5STejun Heo 	pwq->refcnt = 1;
3492d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->delayed_works);
34931befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
3494d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
34958864b4e5STejun Heo 	INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3496f147f29eSTejun Heo }
3497d2c1d404STejun Heo 
3498f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
34991befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
3500f147f29eSTejun Heo {
3501f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
3502f147f29eSTejun Heo 
3503f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
350475ccf595STejun Heo 
35051befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
35061befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
35071befcf30STejun Heo 		return;
35081befcf30STejun Heo 
350929b1cb41SLai Jiangshan 	/* set the matching work_color */
351075ccf595STejun Heo 	pwq->work_color = wq->work_color;
3511983ca25eSTejun Heo 
3512983ca25eSTejun Heo 	/* sync max_active to the current setting */
3513983ca25eSTejun Heo 	pwq_adjust_max_active(pwq);
3514983ca25eSTejun Heo 
3515983ca25eSTejun Heo 	/* link in @pwq */
35169e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3517df2d5ae4STejun Heo }
35186029a918STejun Heo 
3519f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3520f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3521f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
3522f147f29eSTejun Heo {
3523f147f29eSTejun Heo 	struct worker_pool *pool;
3524f147f29eSTejun Heo 	struct pool_workqueue *pwq;
3525f147f29eSTejun Heo 
3526f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3527f147f29eSTejun Heo 
3528f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
3529f147f29eSTejun Heo 	if (!pool)
3530f147f29eSTejun Heo 		return NULL;
3531f147f29eSTejun Heo 
3532e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3533f147f29eSTejun Heo 	if (!pwq) {
3534f147f29eSTejun Heo 		put_unbound_pool(pool);
3535f147f29eSTejun Heo 		return NULL;
3536f147f29eSTejun Heo 	}
3537f147f29eSTejun Heo 
3538f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
3539f147f29eSTejun Heo 	return pwq;
3540d2c1d404STejun Heo }
3541d2c1d404STejun Heo 
35424c16bd32STejun Heo /**
354330186c6fSGong Zhaogang  * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
3544042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
35454c16bd32STejun Heo  * @node: the target NUMA node
35464c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
35474c16bd32STejun Heo  * @cpumask: outarg, the resulting cpumask
35484c16bd32STejun Heo  *
35494c16bd32STejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @node.  If
35504c16bd32STejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during
3551d185af30SYacine Belkadi  * calculation.  The result is stored in @cpumask.
35524c16bd32STejun Heo  *
35534c16bd32STejun Heo  * If NUMA affinity is not enabled, @attrs->cpumask is always used.  If
35544c16bd32STejun Heo  * enabled and @node has online CPUs requested by @attrs, the returned
35554c16bd32STejun Heo  * cpumask is the intersection of the possible CPUs of @node and
35564c16bd32STejun Heo  * @attrs->cpumask.
35574c16bd32STejun Heo  *
35584c16bd32STejun Heo  * The caller is responsible for ensuring that the cpumask of @node stays
35594c16bd32STejun Heo  * stable.
3560d185af30SYacine Belkadi  *
3561d185af30SYacine Belkadi  * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3562d185af30SYacine Belkadi  * %false if equal.
35634c16bd32STejun Heo  */
35644c16bd32STejun Heo static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
35654c16bd32STejun Heo 				 int cpu_going_down, cpumask_t *cpumask)
35664c16bd32STejun Heo {
3567d55262c4STejun Heo 	if (!wq_numa_enabled || attrs->no_numa)
35684c16bd32STejun Heo 		goto use_dfl;
35694c16bd32STejun Heo 
35704c16bd32STejun Heo 	/* does @node have any online CPUs @attrs wants? */
35714c16bd32STejun Heo 	cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
35724c16bd32STejun Heo 	if (cpu_going_down >= 0)
35734c16bd32STejun Heo 		cpumask_clear_cpu(cpu_going_down, cpumask);
35744c16bd32STejun Heo 
35754c16bd32STejun Heo 	if (cpumask_empty(cpumask))
35764c16bd32STejun Heo 		goto use_dfl;
35774c16bd32STejun Heo 
35784c16bd32STejun Heo 	/* yeap, return possible CPUs in @node that @attrs wants */
35794c16bd32STejun Heo 	cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
35804c16bd32STejun Heo 	return !cpumask_equal(cpumask, attrs->cpumask);
35814c16bd32STejun Heo 
35824c16bd32STejun Heo use_dfl:
35834c16bd32STejun Heo 	cpumask_copy(cpumask, attrs->cpumask);
35844c16bd32STejun Heo 	return false;
35854c16bd32STejun Heo }
35864c16bd32STejun Heo 
35871befcf30STejun Heo /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
35881befcf30STejun Heo static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
35891befcf30STejun Heo 						   int node,
35901befcf30STejun Heo 						   struct pool_workqueue *pwq)
35911befcf30STejun Heo {
35921befcf30STejun Heo 	struct pool_workqueue *old_pwq;
35931befcf30STejun Heo 
35945b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
35951befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
35961befcf30STejun Heo 
35971befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
35981befcf30STejun Heo 	link_pwq(pwq);
35991befcf30STejun Heo 
36001befcf30STejun Heo 	old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
36011befcf30STejun Heo 	rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
36021befcf30STejun Heo 	return old_pwq;
36031befcf30STejun Heo }
36041befcf30STejun Heo 
36052d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
36062d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
36072d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
36082d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
3609042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
36102d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
36112d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
36122d5f0764SLai Jiangshan };
36132d5f0764SLai Jiangshan 
36142d5f0764SLai Jiangshan /* free the resources after success or abort */
36152d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
36162d5f0764SLai Jiangshan {
36172d5f0764SLai Jiangshan 	if (ctx) {
36182d5f0764SLai Jiangshan 		int node;
36192d5f0764SLai Jiangshan 
36202d5f0764SLai Jiangshan 		for_each_node(node)
36212d5f0764SLai Jiangshan 			put_pwq_unlocked(ctx->pwq_tbl[node]);
36222d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
36232d5f0764SLai Jiangshan 
36242d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
36252d5f0764SLai Jiangshan 
36262d5f0764SLai Jiangshan 		kfree(ctx);
36272d5f0764SLai Jiangshan 	}
36282d5f0764SLai Jiangshan }
36292d5f0764SLai Jiangshan 
36302d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
36312d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
36322d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
36332d5f0764SLai Jiangshan 		      const struct workqueue_attrs *attrs)
36342d5f0764SLai Jiangshan {
36352d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
36362d5f0764SLai Jiangshan 	struct workqueue_attrs *new_attrs, *tmp_attrs;
36372d5f0764SLai Jiangshan 	int node;
36382d5f0764SLai Jiangshan 
36392d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
36402d5f0764SLai Jiangshan 
36412d5f0764SLai Jiangshan 	ctx = kzalloc(sizeof(*ctx) + nr_node_ids * sizeof(ctx->pwq_tbl[0]),
36422d5f0764SLai Jiangshan 		      GFP_KERNEL);
36432d5f0764SLai Jiangshan 
36442d5f0764SLai Jiangshan 	new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
36452d5f0764SLai Jiangshan 	tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
36462d5f0764SLai Jiangshan 	if (!ctx || !new_attrs || !tmp_attrs)
36472d5f0764SLai Jiangshan 		goto out_free;
36482d5f0764SLai Jiangshan 
3649042f7df1SLai Jiangshan 	/*
3650042f7df1SLai Jiangshan 	 * Calculate the attrs of the default pwq.
3651042f7df1SLai Jiangshan 	 * If the user configured cpumask doesn't overlap with the
3652042f7df1SLai Jiangshan 	 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
3653042f7df1SLai Jiangshan 	 */
36542d5f0764SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
3655b05a7928SFrederic Weisbecker 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, wq_unbound_cpumask);
3656042f7df1SLai Jiangshan 	if (unlikely(cpumask_empty(new_attrs->cpumask)))
3657042f7df1SLai Jiangshan 		cpumask_copy(new_attrs->cpumask, wq_unbound_cpumask);
36582d5f0764SLai Jiangshan 
36592d5f0764SLai Jiangshan 	/*
36602d5f0764SLai Jiangshan 	 * We may create multiple pwqs with differing cpumasks.  Make a
36612d5f0764SLai Jiangshan 	 * copy of @new_attrs which will be modified and used to obtain
36622d5f0764SLai Jiangshan 	 * pools.
36632d5f0764SLai Jiangshan 	 */
36642d5f0764SLai Jiangshan 	copy_workqueue_attrs(tmp_attrs, new_attrs);
36652d5f0764SLai Jiangshan 
36662d5f0764SLai Jiangshan 	/*
36672d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
36682d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
36692d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
36702d5f0764SLai Jiangshan 	 */
36712d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
36722d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
36732d5f0764SLai Jiangshan 		goto out_free;
36742d5f0764SLai Jiangshan 
36752d5f0764SLai Jiangshan 	for_each_node(node) {
3676042f7df1SLai Jiangshan 		if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
36772d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
36782d5f0764SLai Jiangshan 			if (!ctx->pwq_tbl[node])
36792d5f0764SLai Jiangshan 				goto out_free;
36802d5f0764SLai Jiangshan 		} else {
36812d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
36822d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = ctx->dfl_pwq;
36832d5f0764SLai Jiangshan 		}
36842d5f0764SLai Jiangshan 	}
36852d5f0764SLai Jiangshan 
3686042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
3687042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
3688042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
36892d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
3690042f7df1SLai Jiangshan 
36912d5f0764SLai Jiangshan 	ctx->wq = wq;
36922d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
36932d5f0764SLai Jiangshan 	return ctx;
36942d5f0764SLai Jiangshan 
36952d5f0764SLai Jiangshan out_free:
36962d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
36972d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
36982d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
36992d5f0764SLai Jiangshan 	return NULL;
37002d5f0764SLai Jiangshan }
37012d5f0764SLai Jiangshan 
37022d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
37032d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
37042d5f0764SLai Jiangshan {
37052d5f0764SLai Jiangshan 	int node;
37062d5f0764SLai Jiangshan 
37072d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
37082d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
37092d5f0764SLai Jiangshan 
37102d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
37112d5f0764SLai Jiangshan 
37122d5f0764SLai Jiangshan 	/* save the previous pwq and install the new one */
37132d5f0764SLai Jiangshan 	for_each_node(node)
37142d5f0764SLai Jiangshan 		ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
37152d5f0764SLai Jiangshan 							  ctx->pwq_tbl[node]);
37162d5f0764SLai Jiangshan 
37172d5f0764SLai Jiangshan 	/* @dfl_pwq might not have been used, ensure it's linked */
37182d5f0764SLai Jiangshan 	link_pwq(ctx->dfl_pwq);
37192d5f0764SLai Jiangshan 	swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
37202d5f0764SLai Jiangshan 
37212d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
37222d5f0764SLai Jiangshan }
37232d5f0764SLai Jiangshan 
3724a0111cf6SLai Jiangshan static void apply_wqattrs_lock(void)
3725a0111cf6SLai Jiangshan {
3726a0111cf6SLai Jiangshan 	/* CPUs should stay stable across pwq creations and installations */
3727a0111cf6SLai Jiangshan 	get_online_cpus();
3728a0111cf6SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
3729a0111cf6SLai Jiangshan }
3730a0111cf6SLai Jiangshan 
3731a0111cf6SLai Jiangshan static void apply_wqattrs_unlock(void)
3732a0111cf6SLai Jiangshan {
3733a0111cf6SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
3734a0111cf6SLai Jiangshan 	put_online_cpus();
3735a0111cf6SLai Jiangshan }
3736a0111cf6SLai Jiangshan 
3737a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
3738a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
3739a0111cf6SLai Jiangshan {
3740a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
3741a0111cf6SLai Jiangshan 
3742a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
3743a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
3744a0111cf6SLai Jiangshan 		return -EINVAL;
3745a0111cf6SLai Jiangshan 
3746a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
3747a0111cf6SLai Jiangshan 	if (WARN_ON((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs)))
3748a0111cf6SLai Jiangshan 		return -EINVAL;
3749a0111cf6SLai Jiangshan 
3750a0111cf6SLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs);
37516201171eSwanghaibin 	if (!ctx)
37526201171eSwanghaibin 		return -ENOMEM;
3753a0111cf6SLai Jiangshan 
3754a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
3755a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
3756a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
3757a0111cf6SLai Jiangshan 
37586201171eSwanghaibin 	return 0;
3759a0111cf6SLai Jiangshan }
3760a0111cf6SLai Jiangshan 
37619e8cd2f5STejun Heo /**
37629e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
37639e8cd2f5STejun Heo  * @wq: the target workqueue
37649e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
37659e8cd2f5STejun Heo  *
37664c16bd32STejun Heo  * Apply @attrs to an unbound workqueue @wq.  Unless disabled, on NUMA
37674c16bd32STejun Heo  * machines, this function maps a separate pwq to each NUMA node with
37684c16bd32STejun Heo  * possibles CPUs in @attrs->cpumask so that work items are affine to the
37694c16bd32STejun Heo  * NUMA node it was issued on.  Older pwqs are released as in-flight work
37704c16bd32STejun Heo  * items finish.  Note that a work item which repeatedly requeues itself
37714c16bd32STejun Heo  * back-to-back will stay on its current pwq.
37729e8cd2f5STejun Heo  *
3773d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
3774d185af30SYacine Belkadi  *
3775d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
37769e8cd2f5STejun Heo  */
37779e8cd2f5STejun Heo int apply_workqueue_attrs(struct workqueue_struct *wq,
37789e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
37799e8cd2f5STejun Heo {
3780a0111cf6SLai Jiangshan 	int ret;
37819e8cd2f5STejun Heo 
3782a0111cf6SLai Jiangshan 	apply_wqattrs_lock();
3783a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
3784a0111cf6SLai Jiangshan 	apply_wqattrs_unlock();
37852d5f0764SLai Jiangshan 
37862d5f0764SLai Jiangshan 	return ret;
37879e8cd2f5STejun Heo }
37889e8cd2f5STejun Heo 
37894c16bd32STejun Heo /**
37904c16bd32STejun Heo  * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
37914c16bd32STejun Heo  * @wq: the target workqueue
37924c16bd32STejun Heo  * @cpu: the CPU coming up or going down
37934c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
37944c16bd32STejun Heo  *
37954c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
37964c16bd32STejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update NUMA affinity of
37974c16bd32STejun Heo  * @wq accordingly.
37984c16bd32STejun Heo  *
37994c16bd32STejun Heo  * If NUMA affinity can't be adjusted due to memory allocation failure, it
38004c16bd32STejun Heo  * falls back to @wq->dfl_pwq which may not be optimal but is always
38014c16bd32STejun Heo  * correct.
38024c16bd32STejun Heo  *
38034c16bd32STejun Heo  * Note that when the last allowed CPU of a NUMA node goes offline for a
38044c16bd32STejun Heo  * workqueue with a cpumask spanning multiple nodes, the workers which were
38054c16bd32STejun Heo  * already executing the work items for the workqueue will lose their CPU
38064c16bd32STejun Heo  * affinity and may execute on any CPU.  This is similar to how per-cpu
38074c16bd32STejun Heo  * workqueues behave on CPU_DOWN.  If a workqueue user wants strict
38084c16bd32STejun Heo  * affinity, it's the user's responsibility to flush the work item from
38094c16bd32STejun Heo  * CPU_DOWN_PREPARE.
38104c16bd32STejun Heo  */
38114c16bd32STejun Heo static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
38124c16bd32STejun Heo 				   bool online)
38134c16bd32STejun Heo {
38144c16bd32STejun Heo 	int node = cpu_to_node(cpu);
38154c16bd32STejun Heo 	int cpu_off = online ? -1 : cpu;
38164c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
38174c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
38184c16bd32STejun Heo 	cpumask_t *cpumask;
38194c16bd32STejun Heo 
38204c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
38214c16bd32STejun Heo 
3822f7142ed4SLai Jiangshan 	if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
3823f7142ed4SLai Jiangshan 	    wq->unbound_attrs->no_numa)
38244c16bd32STejun Heo 		return;
38254c16bd32STejun Heo 
38264c16bd32STejun Heo 	/*
38274c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
38284c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
38294c16bd32STejun Heo 	 * CPU hotplug exclusion.
38304c16bd32STejun Heo 	 */
38314c16bd32STejun Heo 	target_attrs = wq_update_unbound_numa_attrs_buf;
38324c16bd32STejun Heo 	cpumask = target_attrs->cpumask;
38334c16bd32STejun Heo 
38344c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
38354c16bd32STejun Heo 	pwq = unbound_pwq_by_node(wq, node);
38364c16bd32STejun Heo 
38374c16bd32STejun Heo 	/*
38384c16bd32STejun Heo 	 * Let's determine what needs to be done.  If the target cpumask is
3839042f7df1SLai Jiangshan 	 * different from the default pwq's, we need to compare it to @pwq's
3840042f7df1SLai Jiangshan 	 * and create a new one if they don't match.  If the target cpumask
3841042f7df1SLai Jiangshan 	 * equals the default pwq's, the default pwq should be used.
38424c16bd32STejun Heo 	 */
3843042f7df1SLai Jiangshan 	if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
38444c16bd32STejun Heo 		if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
3845f7142ed4SLai Jiangshan 			return;
38464c16bd32STejun Heo 	} else {
38474c16bd32STejun Heo 		goto use_dfl_pwq;
38484c16bd32STejun Heo 	}
38494c16bd32STejun Heo 
38504c16bd32STejun Heo 	/* create a new pwq */
38514c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
38524c16bd32STejun Heo 	if (!pwq) {
38532d916033SFabian Frederick 		pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
38544c16bd32STejun Heo 			wq->name);
385577f300b1SDaeseok Youn 		goto use_dfl_pwq;
38564c16bd32STejun Heo 	}
38574c16bd32STejun Heo 
3858f7142ed4SLai Jiangshan 	/* Install the new pwq. */
38594c16bd32STejun Heo 	mutex_lock(&wq->mutex);
38604c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, pwq);
38614c16bd32STejun Heo 	goto out_unlock;
38624c16bd32STejun Heo 
38634c16bd32STejun Heo use_dfl_pwq:
3864f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
38654c16bd32STejun Heo 	spin_lock_irq(&wq->dfl_pwq->pool->lock);
38664c16bd32STejun Heo 	get_pwq(wq->dfl_pwq);
38674c16bd32STejun Heo 	spin_unlock_irq(&wq->dfl_pwq->pool->lock);
38684c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
38694c16bd32STejun Heo out_unlock:
38704c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
38714c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
38724c16bd32STejun Heo }
38734c16bd32STejun Heo 
387430cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
38751da177e4SLinus Torvalds {
387649e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
38778a2b7538STejun Heo 	int cpu, ret;
3878e1d8aa9fSFrederic Weisbecker 
387930cdf249STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
3880420c0ddbSTejun Heo 		wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
3881420c0ddbSTejun Heo 		if (!wq->cpu_pwqs)
388230cdf249STejun Heo 			return -ENOMEM;
388330cdf249STejun Heo 
388430cdf249STejun Heo 		for_each_possible_cpu(cpu) {
38857fb98ea7STejun Heo 			struct pool_workqueue *pwq =
38867fb98ea7STejun Heo 				per_cpu_ptr(wq->cpu_pwqs, cpu);
38877a62c2c8STejun Heo 			struct worker_pool *cpu_pools =
3888f02ae73aSTejun Heo 				per_cpu(cpu_worker_pools, cpu);
388930cdf249STejun Heo 
3890f147f29eSTejun Heo 			init_pwq(pwq, wq, &cpu_pools[highpri]);
3891f147f29eSTejun Heo 
3892f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
38931befcf30STejun Heo 			link_pwq(pwq);
3894f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
389530cdf249STejun Heo 		}
389630cdf249STejun Heo 		return 0;
38978a2b7538STejun Heo 	} else if (wq->flags & __WQ_ORDERED) {
38988a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
38998a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
39008a2b7538STejun Heo 		WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
39018a2b7538STejun Heo 			      wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
39028a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
39038a2b7538STejun Heo 		return ret;
39049e8cd2f5STejun Heo 	} else {
39059e8cd2f5STejun Heo 		return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
39069e8cd2f5STejun Heo 	}
39070f900049STejun Heo }
39080f900049STejun Heo 
3909f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
3910f3421797STejun Heo 			       const char *name)
3911b71ab8c2STejun Heo {
3912f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3913f3421797STejun Heo 
3914f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
3915044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3916f3421797STejun Heo 			max_active, name, 1, lim);
3917b71ab8c2STejun Heo 
3918f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
3919b71ab8c2STejun Heo }
3920b71ab8c2STejun Heo 
3921b196be89STejun Heo struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
392297e37d7bSTejun Heo 					       unsigned int flags,
39231e19ffc6STejun Heo 					       int max_active,
3924eb13ba87SJohannes Berg 					       struct lock_class_key *key,
3925b196be89STejun Heo 					       const char *lock_name, ...)
39263af24433SOleg Nesterov {
3927df2d5ae4STejun Heo 	size_t tbl_size = 0;
3928ecf6881fSTejun Heo 	va_list args;
39293af24433SOleg Nesterov 	struct workqueue_struct *wq;
393049e3cf44STejun Heo 	struct pool_workqueue *pwq;
3931b196be89STejun Heo 
3932cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
3933cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
3934cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
3935cee22a15SViresh Kumar 
3936ecf6881fSTejun Heo 	/* allocate wq and format name */
3937df2d5ae4STejun Heo 	if (flags & WQ_UNBOUND)
3938ddcb57e2SLai Jiangshan 		tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
3939df2d5ae4STejun Heo 
3940df2d5ae4STejun Heo 	wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
3941b196be89STejun Heo 	if (!wq)
3942d2c1d404STejun Heo 		return NULL;
3943b196be89STejun Heo 
39446029a918STejun Heo 	if (flags & WQ_UNBOUND) {
39456029a918STejun Heo 		wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
39466029a918STejun Heo 		if (!wq->unbound_attrs)
39476029a918STejun Heo 			goto err_free_wq;
39486029a918STejun Heo 	}
39496029a918STejun Heo 
3950ecf6881fSTejun Heo 	va_start(args, lock_name);
3951ecf6881fSTejun Heo 	vsnprintf(wq->name, sizeof(wq->name), fmt, args);
3952b196be89STejun Heo 	va_end(args);
39533af24433SOleg Nesterov 
3954d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
3955b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
39563af24433SOleg Nesterov 
3957b196be89STejun Heo 	/* init wq */
395897e37d7bSTejun Heo 	wq->flags = flags;
3959a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
39603c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
3961112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
396230cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
396373f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
396473f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
3965493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
39663af24433SOleg Nesterov 
3967eb13ba87SJohannes Berg 	lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3968cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
39693af24433SOleg Nesterov 
397030cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
3971d2c1d404STejun Heo 		goto err_free_wq;
39721537663fSTejun Heo 
3973493008a8STejun Heo 	/*
3974493008a8STejun Heo 	 * Workqueues which may be used during memory reclaim should
3975493008a8STejun Heo 	 * have a rescuer to guarantee forward progress.
3976493008a8STejun Heo 	 */
3977493008a8STejun Heo 	if (flags & WQ_MEM_RECLAIM) {
3978e22bee78STejun Heo 		struct worker *rescuer;
3979e22bee78STejun Heo 
3980f7537df5SLai Jiangshan 		rescuer = alloc_worker(NUMA_NO_NODE);
3981e22bee78STejun Heo 		if (!rescuer)
3982d2c1d404STejun Heo 			goto err_destroy;
3983e22bee78STejun Heo 
3984111c225aSTejun Heo 		rescuer->rescue_wq = wq;
3985111c225aSTejun Heo 		rescuer->task = kthread_create(rescuer_thread, rescuer, "%s",
3986b196be89STejun Heo 					       wq->name);
3987d2c1d404STejun Heo 		if (IS_ERR(rescuer->task)) {
3988d2c1d404STejun Heo 			kfree(rescuer);
3989d2c1d404STejun Heo 			goto err_destroy;
3990d2c1d404STejun Heo 		}
3991e22bee78STejun Heo 
3992d2c1d404STejun Heo 		wq->rescuer = rescuer;
399325834c73SPeter Zijlstra 		kthread_bind_mask(rescuer->task, cpu_possible_mask);
3994e22bee78STejun Heo 		wake_up_process(rescuer->task);
39953af24433SOleg Nesterov 	}
39961537663fSTejun Heo 
3997226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
3998226223abSTejun Heo 		goto err_destroy;
3999226223abSTejun Heo 
40003af24433SOleg Nesterov 	/*
400168e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
400268e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
400368e13a67SLai Jiangshan 	 * list.
40043af24433SOleg Nesterov 	 */
400568e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4006a0a1a5fdSTejun Heo 
4007a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
400849e3cf44STejun Heo 	for_each_pwq(pwq, wq)
4009699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4010a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4011a0a1a5fdSTejun Heo 
4012e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
4013a0a1a5fdSTejun Heo 
401468e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
40153af24433SOleg Nesterov 
40163af24433SOleg Nesterov 	return wq;
4017d2c1d404STejun Heo 
4018d2c1d404STejun Heo err_free_wq:
40196029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
40204690c4abSTejun Heo 	kfree(wq);
4021d2c1d404STejun Heo 	return NULL;
4022d2c1d404STejun Heo err_destroy:
4023d2c1d404STejun Heo 	destroy_workqueue(wq);
40244690c4abSTejun Heo 	return NULL;
40251da177e4SLinus Torvalds }
4026d320c038STejun Heo EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
40271da177e4SLinus Torvalds 
40283af24433SOleg Nesterov /**
40293af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
40303af24433SOleg Nesterov  * @wq: target workqueue
40313af24433SOleg Nesterov  *
40323af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
40333af24433SOleg Nesterov  */
40343af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
40353af24433SOleg Nesterov {
403649e3cf44STejun Heo 	struct pool_workqueue *pwq;
40374c16bd32STejun Heo 	int node;
40383af24433SOleg Nesterov 
40399c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
40409c5a2ba7STejun Heo 	drain_workqueue(wq);
4041c8efcc25STejun Heo 
40426183c009STejun Heo 	/* sanity checks */
4043b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
404449e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
40456183c009STejun Heo 		int i;
40466183c009STejun Heo 
404776af4d93STejun Heo 		for (i = 0; i < WORK_NR_COLORS; i++) {
404876af4d93STejun Heo 			if (WARN_ON(pwq->nr_in_flight[i])) {
4049b09f4fd3SLai Jiangshan 				mutex_unlock(&wq->mutex);
40506183c009STejun Heo 				return;
405176af4d93STejun Heo 			}
405276af4d93STejun Heo 		}
405376af4d93STejun Heo 
40545c529597SLai Jiangshan 		if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
40558864b4e5STejun Heo 		    WARN_ON(pwq->nr_active) ||
405676af4d93STejun Heo 		    WARN_ON(!list_empty(&pwq->delayed_works))) {
4057b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
40586183c009STejun Heo 			return;
40596183c009STejun Heo 		}
406076af4d93STejun Heo 	}
4061b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
40626183c009STejun Heo 
4063a0a1a5fdSTejun Heo 	/*
4064a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
4065a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
4066a0a1a5fdSTejun Heo 	 */
406768e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4068e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
406968e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
40703af24433SOleg Nesterov 
4071226223abSTejun Heo 	workqueue_sysfs_unregister(wq);
4072226223abSTejun Heo 
4073e2dca7adSTejun Heo 	if (wq->rescuer)
4074e22bee78STejun Heo 		kthread_stop(wq->rescuer->task);
4075e22bee78STejun Heo 
40768864b4e5STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
407729c91e99STejun Heo 		/*
40788864b4e5STejun Heo 		 * The base ref is never dropped on per-cpu pwqs.  Directly
4079e2dca7adSTejun Heo 		 * schedule RCU free.
408029c91e99STejun Heo 		 */
4081e2dca7adSTejun Heo 		call_rcu_sched(&wq->rcu, rcu_free_wq);
40828864b4e5STejun Heo 	} else {
40838864b4e5STejun Heo 		/*
40848864b4e5STejun Heo 		 * We're the sole accessor of @wq at this point.  Directly
40854c16bd32STejun Heo 		 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
40864c16bd32STejun Heo 		 * @wq will be freed when the last pwq is released.
40878864b4e5STejun Heo 		 */
40884c16bd32STejun Heo 		for_each_node(node) {
40894c16bd32STejun Heo 			pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
40904c16bd32STejun Heo 			RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
40914c16bd32STejun Heo 			put_pwq_unlocked(pwq);
40924c16bd32STejun Heo 		}
40934c16bd32STejun Heo 
40944c16bd32STejun Heo 		/*
40954c16bd32STejun Heo 		 * Put dfl_pwq.  @wq may be freed any time after dfl_pwq is
40964c16bd32STejun Heo 		 * put.  Don't access it afterwards.
40974c16bd32STejun Heo 		 */
40984c16bd32STejun Heo 		pwq = wq->dfl_pwq;
40994c16bd32STejun Heo 		wq->dfl_pwq = NULL;
4100dce90d47STejun Heo 		put_pwq_unlocked(pwq);
410129c91e99STejun Heo 	}
41023af24433SOleg Nesterov }
41033af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
41043af24433SOleg Nesterov 
4105dcd989cbSTejun Heo /**
4106dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
4107dcd989cbSTejun Heo  * @wq: target workqueue
4108dcd989cbSTejun Heo  * @max_active: new max_active value.
4109dcd989cbSTejun Heo  *
4110dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
4111dcd989cbSTejun Heo  *
4112dcd989cbSTejun Heo  * CONTEXT:
4113dcd989cbSTejun Heo  * Don't call from IRQ context.
4114dcd989cbSTejun Heo  */
4115dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4116dcd989cbSTejun Heo {
411749e3cf44STejun Heo 	struct pool_workqueue *pwq;
4118dcd989cbSTejun Heo 
41198719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
41208719dceaSTejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED))
41218719dceaSTejun Heo 		return;
41228719dceaSTejun Heo 
4123f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4124dcd989cbSTejun Heo 
4125a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4126dcd989cbSTejun Heo 
4127dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4128dcd989cbSTejun Heo 
4129699ce097STejun Heo 	for_each_pwq(pwq, wq)
4130699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4131dcd989cbSTejun Heo 
4132a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4133dcd989cbSTejun Heo }
4134dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4135dcd989cbSTejun Heo 
4136dcd989cbSTejun Heo /**
4137e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4138e6267616STejun Heo  *
4139e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4140e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4141d185af30SYacine Belkadi  *
4142d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
4143e6267616STejun Heo  */
4144e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4145e6267616STejun Heo {
4146e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4147e6267616STejun Heo 
41486a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
4149e6267616STejun Heo }
4150e6267616STejun Heo 
4151e6267616STejun Heo /**
4152dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4153dcd989cbSTejun Heo  * @cpu: CPU in question
4154dcd989cbSTejun Heo  * @wq: target workqueue
4155dcd989cbSTejun Heo  *
4156dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4157dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4158dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4159dcd989cbSTejun Heo  *
4160d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4161d3251859STejun Heo  * Note that both per-cpu and unbound workqueues may be associated with
4162d3251859STejun Heo  * multiple pool_workqueues which have separate congested states.  A
4163d3251859STejun Heo  * workqueue being congested on one CPU doesn't mean the workqueue is also
4164d3251859STejun Heo  * contested on other CPUs / NUMA nodes.
4165d3251859STejun Heo  *
4166d185af30SYacine Belkadi  * Return:
4167dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4168dcd989cbSTejun Heo  */
4169d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4170dcd989cbSTejun Heo {
41717fb98ea7STejun Heo 	struct pool_workqueue *pwq;
417276af4d93STejun Heo 	bool ret;
417376af4d93STejun Heo 
417488109453SLai Jiangshan 	rcu_read_lock_sched();
41757fb98ea7STejun Heo 
4176d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
4177d3251859STejun Heo 		cpu = smp_processor_id();
4178d3251859STejun Heo 
41797fb98ea7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
41807fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
41817fb98ea7STejun Heo 	else
4182df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4183dcd989cbSTejun Heo 
418476af4d93STejun Heo 	ret = !list_empty(&pwq->delayed_works);
418588109453SLai Jiangshan 	rcu_read_unlock_sched();
418676af4d93STejun Heo 
418776af4d93STejun Heo 	return ret;
4188dcd989cbSTejun Heo }
4189dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4190dcd989cbSTejun Heo 
4191dcd989cbSTejun Heo /**
4192dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4193dcd989cbSTejun Heo  * @work: the work to be tested
4194dcd989cbSTejun Heo  *
4195dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4196dcd989cbSTejun Heo  * synchronization around this function and the test result is
4197dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4198dcd989cbSTejun Heo  *
4199d185af30SYacine Belkadi  * Return:
4200dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
4201dcd989cbSTejun Heo  */
4202dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4203dcd989cbSTejun Heo {
4204fa1b54e6STejun Heo 	struct worker_pool *pool;
4205dcd989cbSTejun Heo 	unsigned long flags;
4206dcd989cbSTejun Heo 	unsigned int ret = 0;
4207dcd989cbSTejun Heo 
4208dcd989cbSTejun Heo 	if (work_pending(work))
4209dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
4210038366c5SLai Jiangshan 
4211fa1b54e6STejun Heo 	local_irq_save(flags);
4212fa1b54e6STejun Heo 	pool = get_work_pool(work);
4213038366c5SLai Jiangshan 	if (pool) {
4214fa1b54e6STejun Heo 		spin_lock(&pool->lock);
4215c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
4216dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
4217fa1b54e6STejun Heo 		spin_unlock(&pool->lock);
4218038366c5SLai Jiangshan 	}
4219fa1b54e6STejun Heo 	local_irq_restore(flags);
4220dcd989cbSTejun Heo 
4221dcd989cbSTejun Heo 	return ret;
4222dcd989cbSTejun Heo }
4223dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
4224dcd989cbSTejun Heo 
42253d1cb205STejun Heo /**
42263d1cb205STejun Heo  * set_worker_desc - set description for the current work item
42273d1cb205STejun Heo  * @fmt: printf-style format string
42283d1cb205STejun Heo  * @...: arguments for the format string
42293d1cb205STejun Heo  *
42303d1cb205STejun Heo  * This function can be called by a running work function to describe what
42313d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
42323d1cb205STejun Heo  * information will be printed out together to help debugging.  The
42333d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
42343d1cb205STejun Heo  */
42353d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
42363d1cb205STejun Heo {
42373d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
42383d1cb205STejun Heo 	va_list args;
42393d1cb205STejun Heo 
42403d1cb205STejun Heo 	if (worker) {
42413d1cb205STejun Heo 		va_start(args, fmt);
42423d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
42433d1cb205STejun Heo 		va_end(args);
42443d1cb205STejun Heo 		worker->desc_valid = true;
42453d1cb205STejun Heo 	}
42463d1cb205STejun Heo }
42473d1cb205STejun Heo 
42483d1cb205STejun Heo /**
42493d1cb205STejun Heo  * print_worker_info - print out worker information and description
42503d1cb205STejun Heo  * @log_lvl: the log level to use when printing
42513d1cb205STejun Heo  * @task: target task
42523d1cb205STejun Heo  *
42533d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
42543d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
42553d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
42563d1cb205STejun Heo  *
42573d1cb205STejun Heo  * This function can be safely called on any task as long as the
42583d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
42593d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
42603d1cb205STejun Heo  */
42613d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
42623d1cb205STejun Heo {
42633d1cb205STejun Heo 	work_func_t *fn = NULL;
42643d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
42653d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
42663d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
42673d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
42683d1cb205STejun Heo 	bool desc_valid = false;
42693d1cb205STejun Heo 	struct worker *worker;
42703d1cb205STejun Heo 
42713d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
42723d1cb205STejun Heo 		return;
42733d1cb205STejun Heo 
42743d1cb205STejun Heo 	/*
42753d1cb205STejun Heo 	 * This function is called without any synchronization and @task
42763d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
42773d1cb205STejun Heo 	 */
42783d1cb205STejun Heo 	worker = probe_kthread_data(task);
42793d1cb205STejun Heo 
42803d1cb205STejun Heo 	/*
42813d1cb205STejun Heo 	 * Carefully copy the associated workqueue's workfn and name.  Keep
42823d1cb205STejun Heo 	 * the original last '\0' in case the original contains garbage.
42833d1cb205STejun Heo 	 */
42843d1cb205STejun Heo 	probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
42853d1cb205STejun Heo 	probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
42863d1cb205STejun Heo 	probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
42873d1cb205STejun Heo 	probe_kernel_read(name, wq->name, sizeof(name) - 1);
42883d1cb205STejun Heo 
42893d1cb205STejun Heo 	/* copy worker description */
42903d1cb205STejun Heo 	probe_kernel_read(&desc_valid, &worker->desc_valid, sizeof(desc_valid));
42913d1cb205STejun Heo 	if (desc_valid)
42923d1cb205STejun Heo 		probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
42933d1cb205STejun Heo 
42943d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
42953d1cb205STejun Heo 		printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
42963d1cb205STejun Heo 		if (desc[0])
42973d1cb205STejun Heo 			pr_cont(" (%s)", desc);
42983d1cb205STejun Heo 		pr_cont("\n");
42993d1cb205STejun Heo 	}
43003d1cb205STejun Heo }
43013d1cb205STejun Heo 
43023494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
43033494fc30STejun Heo {
43043494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
43053494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
43063494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
43073494fc30STejun Heo 	pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
43083494fc30STejun Heo }
43093494fc30STejun Heo 
43103494fc30STejun Heo static void pr_cont_work(bool comma, struct work_struct *work)
43113494fc30STejun Heo {
43123494fc30STejun Heo 	if (work->func == wq_barrier_func) {
43133494fc30STejun Heo 		struct wq_barrier *barr;
43143494fc30STejun Heo 
43153494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
43163494fc30STejun Heo 
43173494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
43183494fc30STejun Heo 			task_pid_nr(barr->task));
43193494fc30STejun Heo 	} else {
43203494fc30STejun Heo 		pr_cont("%s %pf", comma ? "," : "", work->func);
43213494fc30STejun Heo 	}
43223494fc30STejun Heo }
43233494fc30STejun Heo 
43243494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
43253494fc30STejun Heo {
43263494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
43273494fc30STejun Heo 	struct work_struct *work;
43283494fc30STejun Heo 	struct worker *worker;
43293494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
43303494fc30STejun Heo 	int bkt;
43313494fc30STejun Heo 
43323494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
43333494fc30STejun Heo 	pr_cont_pool_info(pool);
43343494fc30STejun Heo 
43353494fc30STejun Heo 	pr_cont(" active=%d/%d%s\n", pwq->nr_active, pwq->max_active,
43363494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
43373494fc30STejun Heo 
43383494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
43393494fc30STejun Heo 		if (worker->current_pwq == pwq) {
43403494fc30STejun Heo 			has_in_flight = true;
43413494fc30STejun Heo 			break;
43423494fc30STejun Heo 		}
43433494fc30STejun Heo 	}
43443494fc30STejun Heo 	if (has_in_flight) {
43453494fc30STejun Heo 		bool comma = false;
43463494fc30STejun Heo 
43473494fc30STejun Heo 		pr_info("    in-flight:");
43483494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
43493494fc30STejun Heo 			if (worker->current_pwq != pwq)
43503494fc30STejun Heo 				continue;
43513494fc30STejun Heo 
43523494fc30STejun Heo 			pr_cont("%s %d%s:%pf", comma ? "," : "",
43533494fc30STejun Heo 				task_pid_nr(worker->task),
43543494fc30STejun Heo 				worker == pwq->wq->rescuer ? "(RESCUER)" : "",
43553494fc30STejun Heo 				worker->current_func);
43563494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
43573494fc30STejun Heo 				pr_cont_work(false, work);
43583494fc30STejun Heo 			comma = true;
43593494fc30STejun Heo 		}
43603494fc30STejun Heo 		pr_cont("\n");
43613494fc30STejun Heo 	}
43623494fc30STejun Heo 
43633494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
43643494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
43653494fc30STejun Heo 			has_pending = true;
43663494fc30STejun Heo 			break;
43673494fc30STejun Heo 		}
43683494fc30STejun Heo 	}
43693494fc30STejun Heo 	if (has_pending) {
43703494fc30STejun Heo 		bool comma = false;
43713494fc30STejun Heo 
43723494fc30STejun Heo 		pr_info("    pending:");
43733494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
43743494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
43753494fc30STejun Heo 				continue;
43763494fc30STejun Heo 
43773494fc30STejun Heo 			pr_cont_work(comma, work);
43783494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
43793494fc30STejun Heo 		}
43803494fc30STejun Heo 		pr_cont("\n");
43813494fc30STejun Heo 	}
43823494fc30STejun Heo 
43833494fc30STejun Heo 	if (!list_empty(&pwq->delayed_works)) {
43843494fc30STejun Heo 		bool comma = false;
43853494fc30STejun Heo 
43863494fc30STejun Heo 		pr_info("    delayed:");
43873494fc30STejun Heo 		list_for_each_entry(work, &pwq->delayed_works, entry) {
43883494fc30STejun Heo 			pr_cont_work(comma, work);
43893494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
43903494fc30STejun Heo 		}
43913494fc30STejun Heo 		pr_cont("\n");
43923494fc30STejun Heo 	}
43933494fc30STejun Heo }
43943494fc30STejun Heo 
43953494fc30STejun Heo /**
43963494fc30STejun Heo  * show_workqueue_state - dump workqueue state
43973494fc30STejun Heo  *
43983494fc30STejun Heo  * Called from a sysrq handler and prints out all busy workqueues and
43993494fc30STejun Heo  * pools.
44003494fc30STejun Heo  */
44013494fc30STejun Heo void show_workqueue_state(void)
44023494fc30STejun Heo {
44033494fc30STejun Heo 	struct workqueue_struct *wq;
44043494fc30STejun Heo 	struct worker_pool *pool;
44053494fc30STejun Heo 	unsigned long flags;
44063494fc30STejun Heo 	int pi;
44073494fc30STejun Heo 
44083494fc30STejun Heo 	rcu_read_lock_sched();
44093494fc30STejun Heo 
44103494fc30STejun Heo 	pr_info("Showing busy workqueues and worker pools:\n");
44113494fc30STejun Heo 
44123494fc30STejun Heo 	list_for_each_entry_rcu(wq, &workqueues, list) {
44133494fc30STejun Heo 		struct pool_workqueue *pwq;
44143494fc30STejun Heo 		bool idle = true;
44153494fc30STejun Heo 
44163494fc30STejun Heo 		for_each_pwq(pwq, wq) {
44173494fc30STejun Heo 			if (pwq->nr_active || !list_empty(&pwq->delayed_works)) {
44183494fc30STejun Heo 				idle = false;
44193494fc30STejun Heo 				break;
44203494fc30STejun Heo 			}
44213494fc30STejun Heo 		}
44223494fc30STejun Heo 		if (idle)
44233494fc30STejun Heo 			continue;
44243494fc30STejun Heo 
44253494fc30STejun Heo 		pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
44263494fc30STejun Heo 
44273494fc30STejun Heo 		for_each_pwq(pwq, wq) {
44283494fc30STejun Heo 			spin_lock_irqsave(&pwq->pool->lock, flags);
44293494fc30STejun Heo 			if (pwq->nr_active || !list_empty(&pwq->delayed_works))
44303494fc30STejun Heo 				show_pwq(pwq);
44313494fc30STejun Heo 			spin_unlock_irqrestore(&pwq->pool->lock, flags);
44323494fc30STejun Heo 		}
44333494fc30STejun Heo 	}
44343494fc30STejun Heo 
44353494fc30STejun Heo 	for_each_pool(pool, pi) {
44363494fc30STejun Heo 		struct worker *worker;
44373494fc30STejun Heo 		bool first = true;
44383494fc30STejun Heo 
44393494fc30STejun Heo 		spin_lock_irqsave(&pool->lock, flags);
44403494fc30STejun Heo 		if (pool->nr_workers == pool->nr_idle)
44413494fc30STejun Heo 			goto next_pool;
44423494fc30STejun Heo 
44433494fc30STejun Heo 		pr_info("pool %d:", pool->id);
44443494fc30STejun Heo 		pr_cont_pool_info(pool);
444582607adcSTejun Heo 		pr_cont(" hung=%us workers=%d",
444682607adcSTejun Heo 			jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000,
444782607adcSTejun Heo 			pool->nr_workers);
44483494fc30STejun Heo 		if (pool->manager)
44493494fc30STejun Heo 			pr_cont(" manager: %d",
44503494fc30STejun Heo 				task_pid_nr(pool->manager->task));
44513494fc30STejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry) {
44523494fc30STejun Heo 			pr_cont(" %s%d", first ? "idle: " : "",
44533494fc30STejun Heo 				task_pid_nr(worker->task));
44543494fc30STejun Heo 			first = false;
44553494fc30STejun Heo 		}
44563494fc30STejun Heo 		pr_cont("\n");
44573494fc30STejun Heo 	next_pool:
44583494fc30STejun Heo 		spin_unlock_irqrestore(&pool->lock, flags);
44593494fc30STejun Heo 	}
44603494fc30STejun Heo 
44613494fc30STejun Heo 	rcu_read_unlock_sched();
44623494fc30STejun Heo }
44633494fc30STejun Heo 
4464db7bccf4STejun Heo /*
4465db7bccf4STejun Heo  * CPU hotplug.
4466db7bccf4STejun Heo  *
4467e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
4468112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
4469706026c2STejun Heo  * pool which make migrating pending and scheduled works very
4470e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
447194cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
4472e22bee78STejun Heo  * blocked draining impractical.
4473e22bee78STejun Heo  *
447424647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
4475628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
4476628c78e7STejun Heo  * cpu comes back online.
4477db7bccf4STejun Heo  */
4478db7bccf4STejun Heo 
4479706026c2STejun Heo static void wq_unbind_fn(struct work_struct *work)
4480db7bccf4STejun Heo {
448138db41d9STejun Heo 	int cpu = smp_processor_id();
44824ce62e9eSTejun Heo 	struct worker_pool *pool;
4483db7bccf4STejun Heo 	struct worker *worker;
4484db7bccf4STejun Heo 
4485f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
448692f9c5c4SLai Jiangshan 		mutex_lock(&pool->attach_mutex);
448794cf58bbSTejun Heo 		spin_lock_irq(&pool->lock);
4488e22bee78STejun Heo 
4489f2d5a0eeSTejun Heo 		/*
449092f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
449194cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
449294cf58bbSTejun Heo 		 * except for the ones which are still executing works from
449394cf58bbSTejun Heo 		 * before the last CPU down must be on the cpu.  After
449494cf58bbSTejun Heo 		 * this, they may become diasporas.
4495f2d5a0eeSTejun Heo 		 */
4496da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
4497403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
4498db7bccf4STejun Heo 
449924647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
4500f2d5a0eeSTejun Heo 
450194cf58bbSTejun Heo 		spin_unlock_irq(&pool->lock);
450292f9c5c4SLai Jiangshan 		mutex_unlock(&pool->attach_mutex);
4503e22bee78STejun Heo 
4504e22bee78STejun Heo 		/*
4505eb283428SLai Jiangshan 		 * Call schedule() so that we cross rq->lock and thus can
4506eb283428SLai Jiangshan 		 * guarantee sched callbacks see the %WORKER_UNBOUND flag.
4507eb283428SLai Jiangshan 		 * This is necessary as scheduler callbacks may be invoked
4508eb283428SLai Jiangshan 		 * from other cpus.
4509628c78e7STejun Heo 		 */
4510628c78e7STejun Heo 		schedule();
4511628c78e7STejun Heo 
4512628c78e7STejun Heo 		/*
4513eb283428SLai Jiangshan 		 * Sched callbacks are disabled now.  Zap nr_running.
4514eb283428SLai Jiangshan 		 * After this, nr_running stays zero and need_more_worker()
4515eb283428SLai Jiangshan 		 * and keep_working() are always true as long as the
4516eb283428SLai Jiangshan 		 * worklist is not empty.  This pool now behaves as an
4517eb283428SLai Jiangshan 		 * unbound (in terms of concurrency management) pool which
4518eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
4519e22bee78STejun Heo 		 */
4520e19e397aSTejun Heo 		atomic_set(&pool->nr_running, 0);
4521eb283428SLai Jiangshan 
4522eb283428SLai Jiangshan 		/*
4523eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
4524eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
4525eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
4526eb283428SLai Jiangshan 		 */
4527eb283428SLai Jiangshan 		spin_lock_irq(&pool->lock);
4528eb283428SLai Jiangshan 		wake_up_worker(pool);
4529eb283428SLai Jiangshan 		spin_unlock_irq(&pool->lock);
4530eb283428SLai Jiangshan 	}
4531db7bccf4STejun Heo }
4532db7bccf4STejun Heo 
4533bd7c089eSTejun Heo /**
4534bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
4535bd7c089eSTejun Heo  * @pool: pool of interest
4536bd7c089eSTejun Heo  *
4537a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
4538bd7c089eSTejun Heo  */
4539bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
4540bd7c089eSTejun Heo {
4541a9ab775bSTejun Heo 	struct worker *worker;
4542bd7c089eSTejun Heo 
454392f9c5c4SLai Jiangshan 	lockdep_assert_held(&pool->attach_mutex);
4544bd7c089eSTejun Heo 
4545bd7c089eSTejun Heo 	/*
4546a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
4547a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
4548402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
4549a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
4550a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
4551bd7c089eSTejun Heo 	 */
4552da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
4553a9ab775bSTejun Heo 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4554a9ab775bSTejun Heo 						  pool->attrs->cpumask) < 0);
4555a9ab775bSTejun Heo 
4556a9ab775bSTejun Heo 	spin_lock_irq(&pool->lock);
4557f7c17d26SWanpeng Li 
4558f7c17d26SWanpeng Li 	/*
4559f7c17d26SWanpeng Li 	 * XXX: CPU hotplug notifiers are weird and can call DOWN_FAILED
4560f7c17d26SWanpeng Li 	 * w/o preceding DOWN_PREPARE.  Work around it.  CPU hotplug is
4561f7c17d26SWanpeng Li 	 * being reworked and this can go away in time.
4562f7c17d26SWanpeng Li 	 */
4563f7c17d26SWanpeng Li 	if (!(pool->flags & POOL_DISASSOCIATED)) {
4564f7c17d26SWanpeng Li 		spin_unlock_irq(&pool->lock);
4565f7c17d26SWanpeng Li 		return;
4566f7c17d26SWanpeng Li 	}
4567f7c17d26SWanpeng Li 
45683de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
4569a9ab775bSTejun Heo 
4570da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
4571a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
4572a9ab775bSTejun Heo 
4573a9ab775bSTejun Heo 		/*
4574a9ab775bSTejun Heo 		 * A bound idle worker should actually be on the runqueue
4575a9ab775bSTejun Heo 		 * of the associated CPU for local wake-ups targeting it to
4576a9ab775bSTejun Heo 		 * work.  Kick all idle workers so that they migrate to the
4577a9ab775bSTejun Heo 		 * associated CPU.  Doing this in the same loop as
4578a9ab775bSTejun Heo 		 * replacing UNBOUND with REBOUND is safe as no worker will
4579a9ab775bSTejun Heo 		 * be bound before @pool->lock is released.
4580a9ab775bSTejun Heo 		 */
4581a9ab775bSTejun Heo 		if (worker_flags & WORKER_IDLE)
4582bd7c089eSTejun Heo 			wake_up_process(worker->task);
4583bd7c089eSTejun Heo 
4584bd7c089eSTejun Heo 		/*
4585a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
4586a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
4587a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4588a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
4589a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
4590a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
4591a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
4592a9ab775bSTejun Heo 		 *
4593a9ab775bSTejun Heo 		 * ACCESS_ONCE() is necessary because @worker->flags may be
4594a9ab775bSTejun Heo 		 * tested without holding any lock in
4595a9ab775bSTejun Heo 		 * wq_worker_waking_up().  Without it, NOT_RUNNING test may
4596a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
4597a9ab775bSTejun Heo 		 * management operations.
4598bd7c089eSTejun Heo 		 */
4599a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4600a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
4601a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
4602a9ab775bSTejun Heo 		ACCESS_ONCE(worker->flags) = worker_flags;
4603bd7c089eSTejun Heo 	}
4604a9ab775bSTejun Heo 
4605a9ab775bSTejun Heo 	spin_unlock_irq(&pool->lock);
4606bd7c089eSTejun Heo }
4607bd7c089eSTejun Heo 
46087dbc725eSTejun Heo /**
46097dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
46107dbc725eSTejun Heo  * @pool: unbound pool of interest
46117dbc725eSTejun Heo  * @cpu: the CPU which is coming up
46127dbc725eSTejun Heo  *
46137dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
46147dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
46157dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
46167dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
46177dbc725eSTejun Heo  */
46187dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
46197dbc725eSTejun Heo {
46207dbc725eSTejun Heo 	static cpumask_t cpumask;
46217dbc725eSTejun Heo 	struct worker *worker;
46227dbc725eSTejun Heo 
462392f9c5c4SLai Jiangshan 	lockdep_assert_held(&pool->attach_mutex);
46247dbc725eSTejun Heo 
46257dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
46267dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
46277dbc725eSTejun Heo 		return;
46287dbc725eSTejun Heo 
46297dbc725eSTejun Heo 	/* is @cpu the only online CPU? */
46307dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
46317dbc725eSTejun Heo 	if (cpumask_weight(&cpumask) != 1)
46327dbc725eSTejun Heo 		return;
46337dbc725eSTejun Heo 
46347dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
4635da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
46367dbc725eSTejun Heo 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
46377dbc725eSTejun Heo 						  pool->attrs->cpumask) < 0);
46387dbc725eSTejun Heo }
46397dbc725eSTejun Heo 
46408db25e78STejun Heo /*
46418db25e78STejun Heo  * Workqueues should be brought up before normal priority CPU notifiers.
46428db25e78STejun Heo  * This will be registered high priority CPU notifier.
46438db25e78STejun Heo  */
46440db0628dSPaul Gortmaker static int workqueue_cpu_up_callback(struct notifier_block *nfb,
46451da177e4SLinus Torvalds 					       unsigned long action,
46461da177e4SLinus Torvalds 					       void *hcpu)
46471da177e4SLinus Torvalds {
4648d84ff051STejun Heo 	int cpu = (unsigned long)hcpu;
46494ce62e9eSTejun Heo 	struct worker_pool *pool;
46504c16bd32STejun Heo 	struct workqueue_struct *wq;
46517dbc725eSTejun Heo 	int pi;
46521da177e4SLinus Torvalds 
46538db25e78STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
46543af24433SOleg Nesterov 	case CPU_UP_PREPARE:
4655f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
46563ce63377STejun Heo 			if (pool->nr_workers)
46573ce63377STejun Heo 				continue;
4658051e1850SLai Jiangshan 			if (!create_worker(pool))
46593ce63377STejun Heo 				return NOTIFY_BAD;
46603af24433SOleg Nesterov 		}
46611da177e4SLinus Torvalds 		break;
46621da177e4SLinus Torvalds 
466365758202STejun Heo 	case CPU_DOWN_FAILED:
466465758202STejun Heo 	case CPU_ONLINE:
466568e13a67SLai Jiangshan 		mutex_lock(&wq_pool_mutex);
46667dbc725eSTejun Heo 
46677dbc725eSTejun Heo 		for_each_pool(pool, pi) {
466892f9c5c4SLai Jiangshan 			mutex_lock(&pool->attach_mutex);
466994cf58bbSTejun Heo 
4670f05b558dSLai Jiangshan 			if (pool->cpu == cpu)
467194cf58bbSTejun Heo 				rebind_workers(pool);
4672f05b558dSLai Jiangshan 			else if (pool->cpu < 0)
46737dbc725eSTejun Heo 				restore_unbound_workers_cpumask(pool, cpu);
467494cf58bbSTejun Heo 
467592f9c5c4SLai Jiangshan 			mutex_unlock(&pool->attach_mutex);
467694cf58bbSTejun Heo 		}
46777dbc725eSTejun Heo 
46784c16bd32STejun Heo 		/* update NUMA affinity of unbound workqueues */
46794c16bd32STejun Heo 		list_for_each_entry(wq, &workqueues, list)
46804c16bd32STejun Heo 			wq_update_unbound_numa(wq, cpu, true);
46814c16bd32STejun Heo 
468268e13a67SLai Jiangshan 		mutex_unlock(&wq_pool_mutex);
46838db25e78STejun Heo 		break;
468465758202STejun Heo 	}
468565758202STejun Heo 	return NOTIFY_OK;
468665758202STejun Heo }
468765758202STejun Heo 
468865758202STejun Heo /*
468965758202STejun Heo  * Workqueues should be brought down after normal priority CPU notifiers.
469065758202STejun Heo  * This will be registered as low priority CPU notifier.
469165758202STejun Heo  */
46920db0628dSPaul Gortmaker static int workqueue_cpu_down_callback(struct notifier_block *nfb,
469365758202STejun Heo 						 unsigned long action,
469465758202STejun Heo 						 void *hcpu)
469565758202STejun Heo {
4696d84ff051STejun Heo 	int cpu = (unsigned long)hcpu;
46978db25e78STejun Heo 	struct work_struct unbind_work;
46984c16bd32STejun Heo 	struct workqueue_struct *wq;
46998db25e78STejun Heo 
470065758202STejun Heo 	switch (action & ~CPU_TASKS_FROZEN) {
470165758202STejun Heo 	case CPU_DOWN_PREPARE:
47024c16bd32STejun Heo 		/* unbinding per-cpu workers should happen on the local CPU */
4703706026c2STejun Heo 		INIT_WORK_ONSTACK(&unbind_work, wq_unbind_fn);
47047635d2fdSJoonsoo Kim 		queue_work_on(cpu, system_highpri_wq, &unbind_work);
47054c16bd32STejun Heo 
47064c16bd32STejun Heo 		/* update NUMA affinity of unbound workqueues */
47074c16bd32STejun Heo 		mutex_lock(&wq_pool_mutex);
47084c16bd32STejun Heo 		list_for_each_entry(wq, &workqueues, list)
47094c16bd32STejun Heo 			wq_update_unbound_numa(wq, cpu, false);
47104c16bd32STejun Heo 		mutex_unlock(&wq_pool_mutex);
47114c16bd32STejun Heo 
47124c16bd32STejun Heo 		/* wait for per-cpu unbinding to finish */
47138db25e78STejun Heo 		flush_work(&unbind_work);
4714440a1136SChuansheng Liu 		destroy_work_on_stack(&unbind_work);
47158db25e78STejun Heo 		break;
471665758202STejun Heo 	}
471765758202STejun Heo 	return NOTIFY_OK;
471865758202STejun Heo }
471965758202STejun Heo 
47202d3854a3SRusty Russell #ifdef CONFIG_SMP
47218ccad40dSRusty Russell 
47222d3854a3SRusty Russell struct work_for_cpu {
4723ed48ece2STejun Heo 	struct work_struct work;
47242d3854a3SRusty Russell 	long (*fn)(void *);
47252d3854a3SRusty Russell 	void *arg;
47262d3854a3SRusty Russell 	long ret;
47272d3854a3SRusty Russell };
47282d3854a3SRusty Russell 
4729ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
47302d3854a3SRusty Russell {
4731ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4732ed48ece2STejun Heo 
47332d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
47342d3854a3SRusty Russell }
47352d3854a3SRusty Russell 
47362d3854a3SRusty Russell /**
473722aceb31SAnna-Maria Gleixner  * work_on_cpu - run a function in thread context on a particular cpu
47382d3854a3SRusty Russell  * @cpu: the cpu to run on
47392d3854a3SRusty Russell  * @fn: the function to run
47402d3854a3SRusty Russell  * @arg: the function arg
47412d3854a3SRusty Russell  *
474231ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
47436b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
4744d185af30SYacine Belkadi  *
4745d185af30SYacine Belkadi  * Return: The value @fn returns.
47462d3854a3SRusty Russell  */
4747d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
47482d3854a3SRusty Russell {
4749ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
47502d3854a3SRusty Russell 
4751ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4752ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
475312997d1aSBjorn Helgaas 	flush_work(&wfc.work);
4754440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
47552d3854a3SRusty Russell 	return wfc.ret;
47562d3854a3SRusty Russell }
47572d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
47582d3854a3SRusty Russell #endif /* CONFIG_SMP */
47592d3854a3SRusty Russell 
4760a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
4761e7577c50SRusty Russell 
4762a0a1a5fdSTejun Heo /**
4763a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
4764a0a1a5fdSTejun Heo  *
476558a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
4766c5aa87bbSTejun Heo  * workqueues will queue new works to their delayed_works list instead of
4767706026c2STejun Heo  * pool->worklist.
4768a0a1a5fdSTejun Heo  *
4769a0a1a5fdSTejun Heo  * CONTEXT:
4770a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4771a0a1a5fdSTejun Heo  */
4772a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
4773a0a1a5fdSTejun Heo {
477424b8a847STejun Heo 	struct workqueue_struct *wq;
477524b8a847STejun Heo 	struct pool_workqueue *pwq;
4776a0a1a5fdSTejun Heo 
477768e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4778a0a1a5fdSTejun Heo 
47796183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
4780a0a1a5fdSTejun Heo 	workqueue_freezing = true;
4781a0a1a5fdSTejun Heo 
478224b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
4783a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
4784699ce097STejun Heo 		for_each_pwq(pwq, wq)
4785699ce097STejun Heo 			pwq_adjust_max_active(pwq);
4786a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
4787a1056305STejun Heo 	}
47885bcab335STejun Heo 
478968e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4790a0a1a5fdSTejun Heo }
4791a0a1a5fdSTejun Heo 
4792a0a1a5fdSTejun Heo /**
479358a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
4794a0a1a5fdSTejun Heo  *
4795a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
4796a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
4797a0a1a5fdSTejun Heo  *
4798a0a1a5fdSTejun Heo  * CONTEXT:
479968e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
4800a0a1a5fdSTejun Heo  *
4801d185af30SYacine Belkadi  * Return:
480258a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
480358a69cb4STejun Heo  * is complete.
4804a0a1a5fdSTejun Heo  */
4805a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
4806a0a1a5fdSTejun Heo {
4807a0a1a5fdSTejun Heo 	bool busy = false;
480824b8a847STejun Heo 	struct workqueue_struct *wq;
480924b8a847STejun Heo 	struct pool_workqueue *pwq;
4810a0a1a5fdSTejun Heo 
481168e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4812a0a1a5fdSTejun Heo 
48136183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
4814a0a1a5fdSTejun Heo 
481524b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
481624b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
481724b8a847STejun Heo 			continue;
4818a0a1a5fdSTejun Heo 		/*
4819a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
4820a0a1a5fdSTejun Heo 		 * to peek without lock.
4821a0a1a5fdSTejun Heo 		 */
482288109453SLai Jiangshan 		rcu_read_lock_sched();
482324b8a847STejun Heo 		for_each_pwq(pwq, wq) {
48246183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
4825112202d9STejun Heo 			if (pwq->nr_active) {
4826a0a1a5fdSTejun Heo 				busy = true;
482788109453SLai Jiangshan 				rcu_read_unlock_sched();
4828a0a1a5fdSTejun Heo 				goto out_unlock;
4829a0a1a5fdSTejun Heo 			}
4830a0a1a5fdSTejun Heo 		}
483188109453SLai Jiangshan 		rcu_read_unlock_sched();
4832a0a1a5fdSTejun Heo 	}
4833a0a1a5fdSTejun Heo out_unlock:
483468e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4835a0a1a5fdSTejun Heo 	return busy;
4836a0a1a5fdSTejun Heo }
4837a0a1a5fdSTejun Heo 
4838a0a1a5fdSTejun Heo /**
4839a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
4840a0a1a5fdSTejun Heo  *
4841a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
4842706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
4843a0a1a5fdSTejun Heo  *
4844a0a1a5fdSTejun Heo  * CONTEXT:
4845a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4846a0a1a5fdSTejun Heo  */
4847a0a1a5fdSTejun Heo void thaw_workqueues(void)
4848a0a1a5fdSTejun Heo {
484924b8a847STejun Heo 	struct workqueue_struct *wq;
485024b8a847STejun Heo 	struct pool_workqueue *pwq;
4851a0a1a5fdSTejun Heo 
485268e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4853a0a1a5fdSTejun Heo 
4854a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
4855a0a1a5fdSTejun Heo 		goto out_unlock;
4856a0a1a5fdSTejun Heo 
485774b414eaSLai Jiangshan 	workqueue_freezing = false;
485824b8a847STejun Heo 
485924b8a847STejun Heo 	/* restore max_active and repopulate worklist */
486024b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
4861a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
4862699ce097STejun Heo 		for_each_pwq(pwq, wq)
4863699ce097STejun Heo 			pwq_adjust_max_active(pwq);
4864a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
486524b8a847STejun Heo 	}
486624b8a847STejun Heo 
4867a0a1a5fdSTejun Heo out_unlock:
486868e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4869a0a1a5fdSTejun Heo }
4870a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
4871a0a1a5fdSTejun Heo 
4872042f7df1SLai Jiangshan static int workqueue_apply_unbound_cpumask(void)
4873042f7df1SLai Jiangshan {
4874042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
4875042f7df1SLai Jiangshan 	int ret = 0;
4876042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
4877042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
4878042f7df1SLai Jiangshan 
4879042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
4880042f7df1SLai Jiangshan 
4881042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
4882042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
4883042f7df1SLai Jiangshan 			continue;
4884042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
4885042f7df1SLai Jiangshan 		if (wq->flags & __WQ_ORDERED)
4886042f7df1SLai Jiangshan 			continue;
4887042f7df1SLai Jiangshan 
4888042f7df1SLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs);
4889042f7df1SLai Jiangshan 		if (!ctx) {
4890042f7df1SLai Jiangshan 			ret = -ENOMEM;
4891042f7df1SLai Jiangshan 			break;
4892042f7df1SLai Jiangshan 		}
4893042f7df1SLai Jiangshan 
4894042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
4895042f7df1SLai Jiangshan 	}
4896042f7df1SLai Jiangshan 
4897042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
4898042f7df1SLai Jiangshan 		if (!ret)
4899042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
4900042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
4901042f7df1SLai Jiangshan 	}
4902042f7df1SLai Jiangshan 
4903042f7df1SLai Jiangshan 	return ret;
4904042f7df1SLai Jiangshan }
4905042f7df1SLai Jiangshan 
4906042f7df1SLai Jiangshan /**
4907042f7df1SLai Jiangshan  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
4908042f7df1SLai Jiangshan  *  @cpumask: the cpumask to set
4909042f7df1SLai Jiangshan  *
4910042f7df1SLai Jiangshan  *  The low-level workqueues cpumask is a global cpumask that limits
4911042f7df1SLai Jiangshan  *  the affinity of all unbound workqueues.  This function check the @cpumask
4912042f7df1SLai Jiangshan  *  and apply it to all unbound workqueues and updates all pwqs of them.
4913042f7df1SLai Jiangshan  *
4914042f7df1SLai Jiangshan  *  Retun:	0	- Success
4915042f7df1SLai Jiangshan  *  		-EINVAL	- Invalid @cpumask
4916042f7df1SLai Jiangshan  *  		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
4917042f7df1SLai Jiangshan  */
4918042f7df1SLai Jiangshan int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
4919042f7df1SLai Jiangshan {
4920042f7df1SLai Jiangshan 	int ret = -EINVAL;
4921042f7df1SLai Jiangshan 	cpumask_var_t saved_cpumask;
4922042f7df1SLai Jiangshan 
4923042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&saved_cpumask, GFP_KERNEL))
4924042f7df1SLai Jiangshan 		return -ENOMEM;
4925042f7df1SLai Jiangshan 
4926042f7df1SLai Jiangshan 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
4927042f7df1SLai Jiangshan 	if (!cpumask_empty(cpumask)) {
4928a0111cf6SLai Jiangshan 		apply_wqattrs_lock();
4929042f7df1SLai Jiangshan 
4930042f7df1SLai Jiangshan 		/* save the old wq_unbound_cpumask. */
4931042f7df1SLai Jiangshan 		cpumask_copy(saved_cpumask, wq_unbound_cpumask);
4932042f7df1SLai Jiangshan 
4933042f7df1SLai Jiangshan 		/* update wq_unbound_cpumask at first and apply it to wqs. */
4934042f7df1SLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, cpumask);
4935042f7df1SLai Jiangshan 		ret = workqueue_apply_unbound_cpumask();
4936042f7df1SLai Jiangshan 
4937042f7df1SLai Jiangshan 		/* restore the wq_unbound_cpumask when failed. */
4938042f7df1SLai Jiangshan 		if (ret < 0)
4939042f7df1SLai Jiangshan 			cpumask_copy(wq_unbound_cpumask, saved_cpumask);
4940042f7df1SLai Jiangshan 
4941a0111cf6SLai Jiangshan 		apply_wqattrs_unlock();
4942042f7df1SLai Jiangshan 	}
4943042f7df1SLai Jiangshan 
4944042f7df1SLai Jiangshan 	free_cpumask_var(saved_cpumask);
4945042f7df1SLai Jiangshan 	return ret;
4946042f7df1SLai Jiangshan }
4947042f7df1SLai Jiangshan 
49486ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
49496ba94429SFrederic Weisbecker /*
49506ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
49516ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
49526ba94429SFrederic Weisbecker  * following attributes.
49536ba94429SFrederic Weisbecker  *
49546ba94429SFrederic Weisbecker  *  per_cpu	RO bool	: whether the workqueue is per-cpu or unbound
49556ba94429SFrederic Weisbecker  *  max_active	RW int	: maximum number of in-flight work items
49566ba94429SFrederic Weisbecker  *
49576ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
49586ba94429SFrederic Weisbecker  *
49596ba94429SFrederic Weisbecker  *  id		RO int	: the associated pool ID
49606ba94429SFrederic Weisbecker  *  nice	RW int	: nice value of the workers
49616ba94429SFrederic Weisbecker  *  cpumask	RW mask	: bitmask of allowed CPUs for the workers
49626ba94429SFrederic Weisbecker  */
49636ba94429SFrederic Weisbecker struct wq_device {
49646ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
49656ba94429SFrederic Weisbecker 	struct device			dev;
49666ba94429SFrederic Weisbecker };
49676ba94429SFrederic Weisbecker 
49686ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
49696ba94429SFrederic Weisbecker {
49706ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
49716ba94429SFrederic Weisbecker 
49726ba94429SFrederic Weisbecker 	return wq_dev->wq;
49736ba94429SFrederic Weisbecker }
49746ba94429SFrederic Weisbecker 
49756ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
49766ba94429SFrederic Weisbecker 			    char *buf)
49776ba94429SFrederic Weisbecker {
49786ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
49796ba94429SFrederic Weisbecker 
49806ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
49816ba94429SFrederic Weisbecker }
49826ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
49836ba94429SFrederic Weisbecker 
49846ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
49856ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
49866ba94429SFrederic Weisbecker {
49876ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
49886ba94429SFrederic Weisbecker 
49896ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
49906ba94429SFrederic Weisbecker }
49916ba94429SFrederic Weisbecker 
49926ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
49936ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
49946ba94429SFrederic Weisbecker 				size_t count)
49956ba94429SFrederic Weisbecker {
49966ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
49976ba94429SFrederic Weisbecker 	int val;
49986ba94429SFrederic Weisbecker 
49996ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
50006ba94429SFrederic Weisbecker 		return -EINVAL;
50016ba94429SFrederic Weisbecker 
50026ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
50036ba94429SFrederic Weisbecker 	return count;
50046ba94429SFrederic Weisbecker }
50056ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
50066ba94429SFrederic Weisbecker 
50076ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
50086ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
50096ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
50106ba94429SFrederic Weisbecker 	NULL,
50116ba94429SFrederic Weisbecker };
50126ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
50136ba94429SFrederic Weisbecker 
50146ba94429SFrederic Weisbecker static ssize_t wq_pool_ids_show(struct device *dev,
50156ba94429SFrederic Weisbecker 				struct device_attribute *attr, char *buf)
50166ba94429SFrederic Weisbecker {
50176ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
50186ba94429SFrederic Weisbecker 	const char *delim = "";
50196ba94429SFrederic Weisbecker 	int node, written = 0;
50206ba94429SFrederic Weisbecker 
50216ba94429SFrederic Weisbecker 	rcu_read_lock_sched();
50226ba94429SFrederic Weisbecker 	for_each_node(node) {
50236ba94429SFrederic Weisbecker 		written += scnprintf(buf + written, PAGE_SIZE - written,
50246ba94429SFrederic Weisbecker 				     "%s%d:%d", delim, node,
50256ba94429SFrederic Weisbecker 				     unbound_pwq_by_node(wq, node)->pool->id);
50266ba94429SFrederic Weisbecker 		delim = " ";
50276ba94429SFrederic Weisbecker 	}
50286ba94429SFrederic Weisbecker 	written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
50296ba94429SFrederic Weisbecker 	rcu_read_unlock_sched();
50306ba94429SFrederic Weisbecker 
50316ba94429SFrederic Weisbecker 	return written;
50326ba94429SFrederic Weisbecker }
50336ba94429SFrederic Weisbecker 
50346ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
50356ba94429SFrederic Weisbecker 			    char *buf)
50366ba94429SFrederic Weisbecker {
50376ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
50386ba94429SFrederic Weisbecker 	int written;
50396ba94429SFrederic Weisbecker 
50406ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
50416ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
50426ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
50436ba94429SFrederic Weisbecker 
50446ba94429SFrederic Weisbecker 	return written;
50456ba94429SFrederic Weisbecker }
50466ba94429SFrederic Weisbecker 
50476ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
50486ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
50496ba94429SFrederic Weisbecker {
50506ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
50516ba94429SFrederic Weisbecker 
5052899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5053899a94feSLai Jiangshan 
50546ba94429SFrederic Weisbecker 	attrs = alloc_workqueue_attrs(GFP_KERNEL);
50556ba94429SFrederic Weisbecker 	if (!attrs)
50566ba94429SFrederic Weisbecker 		return NULL;
50576ba94429SFrederic Weisbecker 
50586ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
50596ba94429SFrederic Weisbecker 	return attrs;
50606ba94429SFrederic Weisbecker }
50616ba94429SFrederic Weisbecker 
50626ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
50636ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
50646ba94429SFrederic Weisbecker {
50656ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
50666ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5067d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5068d4d3e257SLai Jiangshan 
5069d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
50706ba94429SFrederic Weisbecker 
50716ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
50726ba94429SFrederic Weisbecker 	if (!attrs)
5073d4d3e257SLai Jiangshan 		goto out_unlock;
50746ba94429SFrederic Weisbecker 
50756ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
50766ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5077d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
50786ba94429SFrederic Weisbecker 	else
50796ba94429SFrederic Weisbecker 		ret = -EINVAL;
50806ba94429SFrederic Weisbecker 
5081d4d3e257SLai Jiangshan out_unlock:
5082d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
50836ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
50846ba94429SFrederic Weisbecker 	return ret ?: count;
50856ba94429SFrederic Weisbecker }
50866ba94429SFrederic Weisbecker 
50876ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
50886ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
50896ba94429SFrederic Weisbecker {
50906ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
50916ba94429SFrederic Weisbecker 	int written;
50926ba94429SFrederic Weisbecker 
50936ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
50946ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
50956ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
50966ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
50976ba94429SFrederic Weisbecker 	return written;
50986ba94429SFrederic Weisbecker }
50996ba94429SFrederic Weisbecker 
51006ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
51016ba94429SFrederic Weisbecker 				struct device_attribute *attr,
51026ba94429SFrederic Weisbecker 				const char *buf, size_t count)
51036ba94429SFrederic Weisbecker {
51046ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
51056ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5106d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5107d4d3e257SLai Jiangshan 
5108d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
51096ba94429SFrederic Weisbecker 
51106ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
51116ba94429SFrederic Weisbecker 	if (!attrs)
5112d4d3e257SLai Jiangshan 		goto out_unlock;
51136ba94429SFrederic Weisbecker 
51146ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
51156ba94429SFrederic Weisbecker 	if (!ret)
5116d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
51176ba94429SFrederic Weisbecker 
5118d4d3e257SLai Jiangshan out_unlock:
5119d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
51206ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
51216ba94429SFrederic Weisbecker 	return ret ?: count;
51226ba94429SFrederic Weisbecker }
51236ba94429SFrederic Weisbecker 
51246ba94429SFrederic Weisbecker static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
51256ba94429SFrederic Weisbecker 			    char *buf)
51266ba94429SFrederic Weisbecker {
51276ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
51286ba94429SFrederic Weisbecker 	int written;
51296ba94429SFrederic Weisbecker 
51306ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
51316ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n",
51326ba94429SFrederic Weisbecker 			    !wq->unbound_attrs->no_numa);
51336ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
51346ba94429SFrederic Weisbecker 
51356ba94429SFrederic Weisbecker 	return written;
51366ba94429SFrederic Weisbecker }
51376ba94429SFrederic Weisbecker 
51386ba94429SFrederic Weisbecker static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
51396ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
51406ba94429SFrederic Weisbecker {
51416ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
51426ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5143d4d3e257SLai Jiangshan 	int v, ret = -ENOMEM;
5144d4d3e257SLai Jiangshan 
5145d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
51466ba94429SFrederic Weisbecker 
51476ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
51486ba94429SFrederic Weisbecker 	if (!attrs)
5149d4d3e257SLai Jiangshan 		goto out_unlock;
51506ba94429SFrederic Weisbecker 
51516ba94429SFrederic Weisbecker 	ret = -EINVAL;
51526ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &v) == 1) {
51536ba94429SFrederic Weisbecker 		attrs->no_numa = !v;
5154d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
51556ba94429SFrederic Weisbecker 	}
51566ba94429SFrederic Weisbecker 
5157d4d3e257SLai Jiangshan out_unlock:
5158d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
51596ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
51606ba94429SFrederic Weisbecker 	return ret ?: count;
51616ba94429SFrederic Weisbecker }
51626ba94429SFrederic Weisbecker 
51636ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
51646ba94429SFrederic Weisbecker 	__ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
51656ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
51666ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
51676ba94429SFrederic Weisbecker 	__ATTR(numa, 0644, wq_numa_show, wq_numa_store),
51686ba94429SFrederic Weisbecker 	__ATTR_NULL,
51696ba94429SFrederic Weisbecker };
51706ba94429SFrederic Weisbecker 
51716ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
51726ba94429SFrederic Weisbecker 	.name				= "workqueue",
51736ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
51746ba94429SFrederic Weisbecker };
51756ba94429SFrederic Weisbecker 
5176b05a7928SFrederic Weisbecker static ssize_t wq_unbound_cpumask_show(struct device *dev,
5177b05a7928SFrederic Weisbecker 		struct device_attribute *attr, char *buf)
5178b05a7928SFrederic Weisbecker {
5179b05a7928SFrederic Weisbecker 	int written;
5180b05a7928SFrederic Weisbecker 
5181042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5182b05a7928SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5183b05a7928SFrederic Weisbecker 			    cpumask_pr_args(wq_unbound_cpumask));
5184042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5185b05a7928SFrederic Weisbecker 
5186b05a7928SFrederic Weisbecker 	return written;
5187b05a7928SFrederic Weisbecker }
5188b05a7928SFrederic Weisbecker 
5189042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
5190042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
5191042f7df1SLai Jiangshan {
5192042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
5193042f7df1SLai Jiangshan 	int ret;
5194042f7df1SLai Jiangshan 
5195042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5196042f7df1SLai Jiangshan 		return -ENOMEM;
5197042f7df1SLai Jiangshan 
5198042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
5199042f7df1SLai Jiangshan 	if (!ret)
5200042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
5201042f7df1SLai Jiangshan 
5202042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
5203042f7df1SLai Jiangshan 	return ret ? ret : count;
5204042f7df1SLai Jiangshan }
5205042f7df1SLai Jiangshan 
5206b05a7928SFrederic Weisbecker static struct device_attribute wq_sysfs_cpumask_attr =
5207042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5208042f7df1SLai Jiangshan 	       wq_unbound_cpumask_store);
5209b05a7928SFrederic Weisbecker 
52106ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
52116ba94429SFrederic Weisbecker {
5212b05a7928SFrederic Weisbecker 	int err;
5213b05a7928SFrederic Weisbecker 
5214b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
5215b05a7928SFrederic Weisbecker 	if (err)
5216b05a7928SFrederic Weisbecker 		return err;
5217b05a7928SFrederic Weisbecker 
5218b05a7928SFrederic Weisbecker 	return device_create_file(wq_subsys.dev_root, &wq_sysfs_cpumask_attr);
52196ba94429SFrederic Weisbecker }
52206ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
52216ba94429SFrederic Weisbecker 
52226ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
52236ba94429SFrederic Weisbecker {
52246ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
52256ba94429SFrederic Weisbecker 
52266ba94429SFrederic Weisbecker 	kfree(wq_dev);
52276ba94429SFrederic Weisbecker }
52286ba94429SFrederic Weisbecker 
52296ba94429SFrederic Weisbecker /**
52306ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
52316ba94429SFrederic Weisbecker  * @wq: the workqueue to register
52326ba94429SFrederic Weisbecker  *
52336ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
52346ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
52356ba94429SFrederic Weisbecker  * which is the preferred method.
52366ba94429SFrederic Weisbecker  *
52376ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
52386ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
52396ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
52406ba94429SFrederic Weisbecker  * attributes.
52416ba94429SFrederic Weisbecker  *
52426ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
52436ba94429SFrederic Weisbecker  */
52446ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
52456ba94429SFrederic Weisbecker {
52466ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
52476ba94429SFrederic Weisbecker 	int ret;
52486ba94429SFrederic Weisbecker 
52496ba94429SFrederic Weisbecker 	/*
5250402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
52516ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
52526ba94429SFrederic Weisbecker 	 * workqueues.
52536ba94429SFrederic Weisbecker 	 */
52546ba94429SFrederic Weisbecker 	if (WARN_ON(wq->flags & __WQ_ORDERED))
52556ba94429SFrederic Weisbecker 		return -EINVAL;
52566ba94429SFrederic Weisbecker 
52576ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
52586ba94429SFrederic Weisbecker 	if (!wq_dev)
52596ba94429SFrederic Weisbecker 		return -ENOMEM;
52606ba94429SFrederic Weisbecker 
52616ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
52626ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
52636ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
526423217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
52656ba94429SFrederic Weisbecker 
52666ba94429SFrederic Weisbecker 	/*
52676ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
52686ba94429SFrederic Weisbecker 	 * everything is ready.
52696ba94429SFrederic Weisbecker 	 */
52706ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
52716ba94429SFrederic Weisbecker 
52726ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
52736ba94429SFrederic Weisbecker 	if (ret) {
52746ba94429SFrederic Weisbecker 		kfree(wq_dev);
52756ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
52766ba94429SFrederic Weisbecker 		return ret;
52776ba94429SFrederic Weisbecker 	}
52786ba94429SFrederic Weisbecker 
52796ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
52806ba94429SFrederic Weisbecker 		struct device_attribute *attr;
52816ba94429SFrederic Weisbecker 
52826ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
52836ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
52846ba94429SFrederic Weisbecker 			if (ret) {
52856ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
52866ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
52876ba94429SFrederic Weisbecker 				return ret;
52886ba94429SFrederic Weisbecker 			}
52896ba94429SFrederic Weisbecker 		}
52906ba94429SFrederic Weisbecker 	}
52916ba94429SFrederic Weisbecker 
52926ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
52936ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
52946ba94429SFrederic Weisbecker 	return 0;
52956ba94429SFrederic Weisbecker }
52966ba94429SFrederic Weisbecker 
52976ba94429SFrederic Weisbecker /**
52986ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
52996ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
53006ba94429SFrederic Weisbecker  *
53016ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
53026ba94429SFrederic Weisbecker  */
53036ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
53046ba94429SFrederic Weisbecker {
53056ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
53066ba94429SFrederic Weisbecker 
53076ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
53086ba94429SFrederic Weisbecker 		return;
53096ba94429SFrederic Weisbecker 
53106ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
53116ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
53126ba94429SFrederic Weisbecker }
53136ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
53146ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
53156ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
53166ba94429SFrederic Weisbecker 
531782607adcSTejun Heo /*
531882607adcSTejun Heo  * Workqueue watchdog.
531982607adcSTejun Heo  *
532082607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
532182607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
532282607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
532382607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
532482607adcSTejun Heo  * largely opaque.
532582607adcSTejun Heo  *
532682607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
532782607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
532882607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
532982607adcSTejun Heo  *
533082607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
533182607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
533282607adcSTejun Heo  * corresponding sysfs parameter file.
533382607adcSTejun Heo  */
533482607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
533582607adcSTejun Heo 
533682607adcSTejun Heo static void wq_watchdog_timer_fn(unsigned long data);
533782607adcSTejun Heo 
533882607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
533982607adcSTejun Heo static struct timer_list wq_watchdog_timer =
534082607adcSTejun Heo 	TIMER_DEFERRED_INITIALIZER(wq_watchdog_timer_fn, 0, 0);
534182607adcSTejun Heo 
534282607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
534382607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
534482607adcSTejun Heo 
534582607adcSTejun Heo static void wq_watchdog_reset_touched(void)
534682607adcSTejun Heo {
534782607adcSTejun Heo 	int cpu;
534882607adcSTejun Heo 
534982607adcSTejun Heo 	wq_watchdog_touched = jiffies;
535082607adcSTejun Heo 	for_each_possible_cpu(cpu)
535182607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
535282607adcSTejun Heo }
535382607adcSTejun Heo 
535482607adcSTejun Heo static void wq_watchdog_timer_fn(unsigned long data)
535582607adcSTejun Heo {
535682607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
535782607adcSTejun Heo 	bool lockup_detected = false;
535882607adcSTejun Heo 	struct worker_pool *pool;
535982607adcSTejun Heo 	int pi;
536082607adcSTejun Heo 
536182607adcSTejun Heo 	if (!thresh)
536282607adcSTejun Heo 		return;
536382607adcSTejun Heo 
536482607adcSTejun Heo 	rcu_read_lock();
536582607adcSTejun Heo 
536682607adcSTejun Heo 	for_each_pool(pool, pi) {
536782607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
536882607adcSTejun Heo 
536982607adcSTejun Heo 		if (list_empty(&pool->worklist))
537082607adcSTejun Heo 			continue;
537182607adcSTejun Heo 
537282607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
537382607adcSTejun Heo 		pool_ts = READ_ONCE(pool->watchdog_ts);
537482607adcSTejun Heo 		touched = READ_ONCE(wq_watchdog_touched);
537582607adcSTejun Heo 
537682607adcSTejun Heo 		if (time_after(pool_ts, touched))
537782607adcSTejun Heo 			ts = pool_ts;
537882607adcSTejun Heo 		else
537982607adcSTejun Heo 			ts = touched;
538082607adcSTejun Heo 
538182607adcSTejun Heo 		if (pool->cpu >= 0) {
538282607adcSTejun Heo 			unsigned long cpu_touched =
538382607adcSTejun Heo 				READ_ONCE(per_cpu(wq_watchdog_touched_cpu,
538482607adcSTejun Heo 						  pool->cpu));
538582607adcSTejun Heo 			if (time_after(cpu_touched, ts))
538682607adcSTejun Heo 				ts = cpu_touched;
538782607adcSTejun Heo 		}
538882607adcSTejun Heo 
538982607adcSTejun Heo 		/* did we stall? */
539082607adcSTejun Heo 		if (time_after(jiffies, ts + thresh)) {
539182607adcSTejun Heo 			lockup_detected = true;
539282607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
539382607adcSTejun Heo 			pr_cont_pool_info(pool);
539482607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
539582607adcSTejun Heo 				jiffies_to_msecs(jiffies - pool_ts) / 1000);
539682607adcSTejun Heo 		}
539782607adcSTejun Heo 	}
539882607adcSTejun Heo 
539982607adcSTejun Heo 	rcu_read_unlock();
540082607adcSTejun Heo 
540182607adcSTejun Heo 	if (lockup_detected)
540282607adcSTejun Heo 		show_workqueue_state();
540382607adcSTejun Heo 
540482607adcSTejun Heo 	wq_watchdog_reset_touched();
540582607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
540682607adcSTejun Heo }
540782607adcSTejun Heo 
540882607adcSTejun Heo void wq_watchdog_touch(int cpu)
540982607adcSTejun Heo {
541082607adcSTejun Heo 	if (cpu >= 0)
541182607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
541282607adcSTejun Heo 	else
541382607adcSTejun Heo 		wq_watchdog_touched = jiffies;
541482607adcSTejun Heo }
541582607adcSTejun Heo 
541682607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
541782607adcSTejun Heo {
541882607adcSTejun Heo 	wq_watchdog_thresh = 0;
541982607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
542082607adcSTejun Heo 
542182607adcSTejun Heo 	if (thresh) {
542282607adcSTejun Heo 		wq_watchdog_thresh = thresh;
542382607adcSTejun Heo 		wq_watchdog_reset_touched();
542482607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
542582607adcSTejun Heo 	}
542682607adcSTejun Heo }
542782607adcSTejun Heo 
542882607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
542982607adcSTejun Heo 					const struct kernel_param *kp)
543082607adcSTejun Heo {
543182607adcSTejun Heo 	unsigned long thresh;
543282607adcSTejun Heo 	int ret;
543382607adcSTejun Heo 
543482607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
543582607adcSTejun Heo 	if (ret)
543682607adcSTejun Heo 		return ret;
543782607adcSTejun Heo 
543882607adcSTejun Heo 	if (system_wq)
543982607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
544082607adcSTejun Heo 	else
544182607adcSTejun Heo 		wq_watchdog_thresh = thresh;
544282607adcSTejun Heo 
544382607adcSTejun Heo 	return 0;
544482607adcSTejun Heo }
544582607adcSTejun Heo 
544682607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
544782607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
544882607adcSTejun Heo 	.get	= param_get_ulong,
544982607adcSTejun Heo };
545082607adcSTejun Heo 
545182607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
545282607adcSTejun Heo 		0644);
545382607adcSTejun Heo 
545482607adcSTejun Heo static void wq_watchdog_init(void)
545582607adcSTejun Heo {
545682607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
545782607adcSTejun Heo }
545882607adcSTejun Heo 
545982607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
546082607adcSTejun Heo 
546182607adcSTejun Heo static inline void wq_watchdog_init(void) { }
546282607adcSTejun Heo 
546382607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
546482607adcSTejun Heo 
5465bce90380STejun Heo static void __init wq_numa_init(void)
5466bce90380STejun Heo {
5467bce90380STejun Heo 	cpumask_var_t *tbl;
5468bce90380STejun Heo 	int node, cpu;
5469bce90380STejun Heo 
5470bce90380STejun Heo 	if (num_possible_nodes() <= 1)
5471bce90380STejun Heo 		return;
5472bce90380STejun Heo 
5473d55262c4STejun Heo 	if (wq_disable_numa) {
5474d55262c4STejun Heo 		pr_info("workqueue: NUMA affinity support disabled\n");
5475d55262c4STejun Heo 		return;
5476d55262c4STejun Heo 	}
5477d55262c4STejun Heo 
54784c16bd32STejun Heo 	wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
54794c16bd32STejun Heo 	BUG_ON(!wq_update_unbound_numa_attrs_buf);
54804c16bd32STejun Heo 
5481bce90380STejun Heo 	/*
5482bce90380STejun Heo 	 * We want masks of possible CPUs of each node which isn't readily
5483bce90380STejun Heo 	 * available.  Build one from cpu_to_node() which should have been
5484bce90380STejun Heo 	 * fully initialized by now.
5485bce90380STejun Heo 	 */
5486ddcb57e2SLai Jiangshan 	tbl = kzalloc(nr_node_ids * sizeof(tbl[0]), GFP_KERNEL);
5487bce90380STejun Heo 	BUG_ON(!tbl);
5488bce90380STejun Heo 
5489bce90380STejun Heo 	for_each_node(node)
54905a6024f1SYasuaki Ishimatsu 		BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
54911be0c25dSTejun Heo 				node_online(node) ? node : NUMA_NO_NODE));
5492bce90380STejun Heo 
5493bce90380STejun Heo 	for_each_possible_cpu(cpu) {
5494bce90380STejun Heo 		node = cpu_to_node(cpu);
5495bce90380STejun Heo 		if (WARN_ON(node == NUMA_NO_NODE)) {
5496bce90380STejun Heo 			pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
5497bce90380STejun Heo 			/* happens iff arch is bonkers, let's just proceed */
5498bce90380STejun Heo 			return;
5499bce90380STejun Heo 		}
5500bce90380STejun Heo 		cpumask_set_cpu(cpu, tbl[node]);
5501bce90380STejun Heo 	}
5502bce90380STejun Heo 
5503bce90380STejun Heo 	wq_numa_possible_cpumask = tbl;
5504bce90380STejun Heo 	wq_numa_enabled = true;
5505bce90380STejun Heo }
5506bce90380STejun Heo 
55076ee0578bSSuresh Siddha static int __init init_workqueues(void)
55081da177e4SLinus Torvalds {
55097a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
55107a4e344cSTejun Heo 	int i, cpu;
5511c34056a3STejun Heo 
5512e904e6c2STejun Heo 	WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
5513e904e6c2STejun Heo 
5514b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
5515b05a7928SFrederic Weisbecker 	cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
5516b05a7928SFrederic Weisbecker 
5517e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
5518e904e6c2STejun Heo 
551965758202STejun Heo 	cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
5520a5b4e57dSLai Jiangshan 	hotcpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
55218b03ae3cSTejun Heo 
5522bce90380STejun Heo 	wq_numa_init();
5523bce90380STejun Heo 
5524706026c2STejun Heo 	/* initialize CPU pools */
552529c91e99STejun Heo 	for_each_possible_cpu(cpu) {
55264ce62e9eSTejun Heo 		struct worker_pool *pool;
55278b03ae3cSTejun Heo 
55287a4e344cSTejun Heo 		i = 0;
5529f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
55307a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
5531ec22ca5eSTejun Heo 			pool->cpu = cpu;
55327a4e344cSTejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
55337a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
5534f3f90ad4STejun Heo 			pool->node = cpu_to_node(cpu);
55357a4e344cSTejun Heo 
55369daf9e67STejun Heo 			/* alloc pool ID */
553768e13a67SLai Jiangshan 			mutex_lock(&wq_pool_mutex);
55389daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
553968e13a67SLai Jiangshan 			mutex_unlock(&wq_pool_mutex);
55404ce62e9eSTejun Heo 		}
55418b03ae3cSTejun Heo 	}
55428b03ae3cSTejun Heo 
5543e22bee78STejun Heo 	/* create the initial worker */
554429c91e99STejun Heo 	for_each_online_cpu(cpu) {
55454ce62e9eSTejun Heo 		struct worker_pool *pool;
5546e22bee78STejun Heo 
5547f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
554824647570STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
5549051e1850SLai Jiangshan 			BUG_ON(!create_worker(pool));
5550e22bee78STejun Heo 		}
55514ce62e9eSTejun Heo 	}
5552e22bee78STejun Heo 
55538a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
555429c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
555529c91e99STejun Heo 		struct workqueue_attrs *attrs;
555629c91e99STejun Heo 
555729c91e99STejun Heo 		BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
555829c91e99STejun Heo 		attrs->nice = std_nice[i];
555929c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
55608a2b7538STejun Heo 
55618a2b7538STejun Heo 		/*
55628a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
55638a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
55648a2b7538STejun Heo 		 * Turn off NUMA so that dfl_pwq is used for all nodes.
55658a2b7538STejun Heo 		 */
55668a2b7538STejun Heo 		BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
55678a2b7538STejun Heo 		attrs->nice = std_nice[i];
55688a2b7538STejun Heo 		attrs->no_numa = true;
55698a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
557029c91e99STejun Heo 	}
557129c91e99STejun Heo 
5572d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
55731aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
5574d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
5575f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
5576f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
557724d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
557824d51addSTejun Heo 					      WQ_FREEZABLE, 0);
55790668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
55800668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
55810668106cSViresh Kumar 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
55820668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
55830668106cSViresh Kumar 					      0);
55841aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
55850668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
55860668106cSViresh Kumar 	       !system_power_efficient_wq ||
55870668106cSViresh Kumar 	       !system_freezable_power_efficient_wq);
558882607adcSTejun Heo 
558982607adcSTejun Heo 	wq_watchdog_init();
559082607adcSTejun Heo 
55916ee0578bSSuresh Siddha 	return 0;
55921da177e4SLinus Torvalds }
55936ee0578bSSuresh Siddha early_initcall(init_workqueues);
5594