xref: /linux-6.15/kernel/workqueue.c (revision 8194fe94)
11da177e4SLinus Torvalds /*
2c54fce6eSTejun Heo  * kernel/workqueue.c - generic async execution with shared worker pool
31da177e4SLinus Torvalds  *
4c54fce6eSTejun Heo  * Copyright (C) 2002		Ingo Molnar
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  *   Derived from the taskqueue/keventd code by:
71da177e4SLinus Torvalds  *     David Woodhouse <[email protected]>
8e1f8e874SFrancois Cami  *     Andrew Morton
91da177e4SLinus Torvalds  *     Kai Petzke <[email protected]>
101da177e4SLinus Torvalds  *     Theodore Ts'o <[email protected]>
1189ada679SChristoph Lameter  *
12cde53535SChristoph Lameter  * Made to use alloc_percpu by Christoph Lameter.
13c54fce6eSTejun Heo  *
14c54fce6eSTejun Heo  * Copyright (C) 2010		SUSE Linux Products GmbH
15c54fce6eSTejun Heo  * Copyright (C) 2010		Tejun Heo <[email protected]>
16c54fce6eSTejun Heo  *
17c54fce6eSTejun Heo  * This is the generic async execution mechanism.  Work items as are
18c54fce6eSTejun Heo  * executed in process context.  The worker pool is shared and
19b11895c4SLibin  * automatically managed.  There are two worker pools for each CPU (one for
20b11895c4SLibin  * normal work items and the other for high priority ones) and some extra
21b11895c4SLibin  * pools for workqueues which are not bound to any specific CPU - the
22b11895c4SLibin  * number of these backing pools is dynamic.
23c54fce6eSTejun Heo  *
249a261491SBenjamin Peterson  * Please read Documentation/core-api/workqueue.rst for details.
251da177e4SLinus Torvalds  */
261da177e4SLinus Torvalds 
279984de1aSPaul Gortmaker #include <linux/export.h>
281da177e4SLinus Torvalds #include <linux/kernel.h>
291da177e4SLinus Torvalds #include <linux/sched.h>
301da177e4SLinus Torvalds #include <linux/init.h>
311da177e4SLinus Torvalds #include <linux/signal.h>
321da177e4SLinus Torvalds #include <linux/completion.h>
331da177e4SLinus Torvalds #include <linux/workqueue.h>
341da177e4SLinus Torvalds #include <linux/slab.h>
351da177e4SLinus Torvalds #include <linux/cpu.h>
361da177e4SLinus Torvalds #include <linux/notifier.h>
371da177e4SLinus Torvalds #include <linux/kthread.h>
381fa44ecaSJames Bottomley #include <linux/hardirq.h>
3946934023SChristoph Lameter #include <linux/mempolicy.h>
40341a5958SRafael J. Wysocki #include <linux/freezer.h>
41d5abe669SPeter Zijlstra #include <linux/debug_locks.h>
424e6045f1SJohannes Berg #include <linux/lockdep.h>
43c34056a3STejun Heo #include <linux/idr.h>
4429c91e99STejun Heo #include <linux/jhash.h>
4542f8570fSSasha Levin #include <linux/hashtable.h>
4676af4d93STejun Heo #include <linux/rculist.h>
47bce90380STejun Heo #include <linux/nodemask.h>
484c16bd32STejun Heo #include <linux/moduleparam.h>
493d1cb205STejun Heo #include <linux/uaccess.h>
50c98a9805STal Shorer #include <linux/sched/isolation.h>
5162635ea8SSergey Senozhatsky #include <linux/nmi.h>
52e22bee78STejun Heo 
53ea138446STejun Heo #include "workqueue_internal.h"
541da177e4SLinus Torvalds 
55c8e55f36STejun Heo enum {
56bc2ae0f5STejun Heo 	/*
5724647570STejun Heo 	 * worker_pool flags
58bc2ae0f5STejun Heo 	 *
5924647570STejun Heo 	 * A bound pool is either associated or disassociated with its CPU.
60bc2ae0f5STejun Heo 	 * While associated (!DISASSOCIATED), all workers are bound to the
61bc2ae0f5STejun Heo 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
62bc2ae0f5STejun Heo 	 * is in effect.
63bc2ae0f5STejun Heo 	 *
64bc2ae0f5STejun Heo 	 * While DISASSOCIATED, the cpu may be offline and all workers have
65bc2ae0f5STejun Heo 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
6624647570STejun Heo 	 * be executing on any CPU.  The pool behaves as an unbound one.
67bc2ae0f5STejun Heo 	 *
68bc3a1afcSTejun Heo 	 * Note that DISASSOCIATED should be flipped only while holding
691258fae7STejun Heo 	 * wq_pool_attach_mutex to avoid changing binding state while
704736cbf7SLai Jiangshan 	 * worker_attach_to_pool() is in progress.
71bc2ae0f5STejun Heo 	 */
72692b4825STejun Heo 	POOL_MANAGER_ACTIVE	= 1 << 0,	/* being managed */
7324647570STejun Heo 	POOL_DISASSOCIATED	= 1 << 2,	/* cpu can't serve workers */
74db7bccf4STejun Heo 
75c8e55f36STejun Heo 	/* worker flags */
76c8e55f36STejun Heo 	WORKER_DIE		= 1 << 1,	/* die die die */
77c8e55f36STejun Heo 	WORKER_IDLE		= 1 << 2,	/* is idle */
78e22bee78STejun Heo 	WORKER_PREP		= 1 << 3,	/* preparing to run works */
79fb0e7bebSTejun Heo 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
80f3421797STejun Heo 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
81a9ab775bSTejun Heo 	WORKER_REBOUND		= 1 << 8,	/* worker was rebound */
82e22bee78STejun Heo 
83a9ab775bSTejun Heo 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_CPU_INTENSIVE |
84a9ab775bSTejun Heo 				  WORKER_UNBOUND | WORKER_REBOUND,
85db7bccf4STejun Heo 
86e34cdddbSTejun Heo 	NR_STD_WORKER_POOLS	= 2,		/* # standard pools per cpu */
874ce62e9eSTejun Heo 
8829c91e99STejun Heo 	UNBOUND_POOL_HASH_ORDER	= 6,		/* hashed by pool->attrs */
89c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
90db7bccf4STejun Heo 
91e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
92e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
93e22bee78STejun Heo 
943233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
953233cdbdSTejun Heo 						/* call for help after 10ms
963233cdbdSTejun Heo 						   (min two ticks) */
97e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
98e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
991da177e4SLinus Torvalds 
1001da177e4SLinus Torvalds 	/*
101e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
1028698a745SDongsheng Yang 	 * all cpus.  Give MIN_NICE.
103e22bee78STejun Heo 	 */
1048698a745SDongsheng Yang 	RESCUER_NICE_LEVEL	= MIN_NICE,
1058698a745SDongsheng Yang 	HIGHPRI_NICE_LEVEL	= MIN_NICE,
106ecf6881fSTejun Heo 
107ecf6881fSTejun Heo 	WQ_NAME_LEN		= 24,
108c8e55f36STejun Heo };
109c8e55f36STejun Heo 
1101da177e4SLinus Torvalds /*
1114690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1124690c4abSTejun Heo  *
113e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
114e41e704bSTejun Heo  *    everyone else.
1154690c4abSTejun Heo  *
116e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
117e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
118e22bee78STejun Heo  *
119d565ed63STejun Heo  * L: pool->lock protected.  Access with pool->lock held.
1204690c4abSTejun Heo  *
121d565ed63STejun Heo  * X: During normal operation, modification requires pool->lock and should
122d565ed63STejun Heo  *    be done only from local cpu.  Either disabling preemption on local
123d565ed63STejun Heo  *    cpu or grabbing pool->lock is enough for read access.  If
124d565ed63STejun Heo  *    POOL_DISASSOCIATED is set, it's identical to L.
125e22bee78STejun Heo  *
1261258fae7STejun Heo  * A: wq_pool_attach_mutex protected.
127822d8405STejun Heo  *
12868e13a67SLai Jiangshan  * PL: wq_pool_mutex protected.
12976af4d93STejun Heo  *
13068e13a67SLai Jiangshan  * PR: wq_pool_mutex protected for writes.  Sched-RCU protected for reads.
1315bcab335STejun Heo  *
1325b95e1afSLai Jiangshan  * PW: wq_pool_mutex and wq->mutex protected for writes.  Either for reads.
1335b95e1afSLai Jiangshan  *
1345b95e1afSLai Jiangshan  * PWR: wq_pool_mutex and wq->mutex protected for writes.  Either or
1355b95e1afSLai Jiangshan  *      sched-RCU for reads.
1365b95e1afSLai Jiangshan  *
1373c25a55dSLai Jiangshan  * WQ: wq->mutex protected.
1383c25a55dSLai Jiangshan  *
139b5927605SLai Jiangshan  * WR: wq->mutex protected for writes.  Sched-RCU protected for reads.
1402e109a28STejun Heo  *
1412e109a28STejun Heo  * MD: wq_mayday_lock protected.
1424690c4abSTejun Heo  */
1434690c4abSTejun Heo 
1442eaebdb3STejun Heo /* struct worker is defined in workqueue_internal.h */
145c34056a3STejun Heo 
146bd7bdd43STejun Heo struct worker_pool {
147d565ed63STejun Heo 	spinlock_t		lock;		/* the pool lock */
148d84ff051STejun Heo 	int			cpu;		/* I: the associated cpu */
149f3f90ad4STejun Heo 	int			node;		/* I: the associated node ID */
1509daf9e67STejun Heo 	int			id;		/* I: pool ID */
15111ebea50STejun Heo 	unsigned int		flags;		/* X: flags */
152bd7bdd43STejun Heo 
15382607adcSTejun Heo 	unsigned long		watchdog_ts;	/* L: watchdog timestamp */
15482607adcSTejun Heo 
155bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
156ea1abd61SLai Jiangshan 
1575826cc8fSLai Jiangshan 	int			nr_workers;	/* L: total number of workers */
1585826cc8fSLai Jiangshan 	int			nr_idle;	/* L: currently idle workers */
159bd7bdd43STejun Heo 
160bd7bdd43STejun Heo 	struct list_head	idle_list;	/* X: list of idle workers */
161bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
162bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	/* L: SOS timer for workers */
163bd7bdd43STejun Heo 
164c5aa87bbSTejun Heo 	/* a workers is either on busy_hash or idle_list, or the manager */
165c9e7cf27STejun Heo 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
166c9e7cf27STejun Heo 						/* L: hash of busy workers */
167c9e7cf27STejun Heo 
1682607d7a6STejun Heo 	struct worker		*manager;	/* L: purely informational */
16992f9c5c4SLai Jiangshan 	struct list_head	workers;	/* A: attached workers */
17060f5a4bcSLai Jiangshan 	struct completion	*detach_completion; /* all workers detached */
171e19e397aSTejun Heo 
1727cda9aaeSLai Jiangshan 	struct ida		worker_ida;	/* worker IDs for task name */
173e19e397aSTejun Heo 
1747a4e344cSTejun Heo 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
17568e13a67SLai Jiangshan 	struct hlist_node	hash_node;	/* PL: unbound_pool_hash node */
17668e13a67SLai Jiangshan 	int			refcnt;		/* PL: refcnt for unbound pools */
1777a4e344cSTejun Heo 
178e19e397aSTejun Heo 	/*
179e19e397aSTejun Heo 	 * The current concurrency level.  As it's likely to be accessed
180e19e397aSTejun Heo 	 * from other CPUs during try_to_wake_up(), put it in a separate
181e19e397aSTejun Heo 	 * cacheline.
182e19e397aSTejun Heo 	 */
183e19e397aSTejun Heo 	atomic_t		nr_running ____cacheline_aligned_in_smp;
18429c91e99STejun Heo 
18529c91e99STejun Heo 	/*
18629c91e99STejun Heo 	 * Destruction of pool is sched-RCU protected to allow dereferences
18729c91e99STejun Heo 	 * from get_work_pool().
18829c91e99STejun Heo 	 */
18929c91e99STejun Heo 	struct rcu_head		rcu;
1908b03ae3cSTejun Heo } ____cacheline_aligned_in_smp;
1918b03ae3cSTejun Heo 
1928b03ae3cSTejun Heo /*
193112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
194112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
195112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
196112202d9STejun Heo  * number of flag bits.
1971da177e4SLinus Torvalds  */
198112202d9STejun Heo struct pool_workqueue {
199bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
2004690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
20173f53c4aSTejun Heo 	int			work_color;	/* L: current color */
20273f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
2038864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
20473f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
20573f53c4aSTejun Heo 						/* L: nr of in_flight works */
2061e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
207a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
2081e19ffc6STejun Heo 	struct list_head	delayed_works;	/* L: delayed works */
2093c25a55dSLai Jiangshan 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
2102e109a28STejun Heo 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
2118864b4e5STejun Heo 
2128864b4e5STejun Heo 	/*
2138864b4e5STejun Heo 	 * Release of unbound pwq is punted to system_wq.  See put_pwq()
2148864b4e5STejun Heo 	 * and pwq_unbound_release_workfn() for details.  pool_workqueue
2158864b4e5STejun Heo 	 * itself is also sched-RCU protected so that the first pwq can be
216b09f4fd3SLai Jiangshan 	 * determined without grabbing wq->mutex.
2178864b4e5STejun Heo 	 */
2188864b4e5STejun Heo 	struct work_struct	unbound_release_work;
2198864b4e5STejun Heo 	struct rcu_head		rcu;
220e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2211da177e4SLinus Torvalds 
2221da177e4SLinus Torvalds /*
22373f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
22473f53c4aSTejun Heo  */
22573f53c4aSTejun Heo struct wq_flusher {
2263c25a55dSLai Jiangshan 	struct list_head	list;		/* WQ: list of flushers */
2273c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: flush color waiting for */
22873f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
22973f53c4aSTejun Heo };
2301da177e4SLinus Torvalds 
231226223abSTejun Heo struct wq_device;
232226223abSTejun Heo 
23373f53c4aSTejun Heo /*
234c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
235c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
2361da177e4SLinus Torvalds  */
2371da177e4SLinus Torvalds struct workqueue_struct {
2383c25a55dSLai Jiangshan 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
239e2dca7adSTejun Heo 	struct list_head	list;		/* PR: list of all workqueues */
24073f53c4aSTejun Heo 
2413c25a55dSLai Jiangshan 	struct mutex		mutex;		/* protects this wq */
2423c25a55dSLai Jiangshan 	int			work_color;	/* WQ: current work color */
2433c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: current flush color */
244112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
2453c25a55dSLai Jiangshan 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
2463c25a55dSLai Jiangshan 	struct list_head	flusher_queue;	/* WQ: flush waiters */
2473c25a55dSLai Jiangshan 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
24873f53c4aSTejun Heo 
2492e109a28STejun Heo 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
250e22bee78STejun Heo 	struct worker		*rescuer;	/* I: rescue worker */
251e22bee78STejun Heo 
25287fc741eSLai Jiangshan 	int			nr_drainers;	/* WQ: drain in progress */
253a357fc03SLai Jiangshan 	int			saved_max_active; /* WQ: saved pwq max_active */
254226223abSTejun Heo 
2555b95e1afSLai Jiangshan 	struct workqueue_attrs	*unbound_attrs;	/* PW: only for unbound wqs */
2565b95e1afSLai Jiangshan 	struct pool_workqueue	*dfl_pwq;	/* PW: only for unbound wqs */
2576029a918STejun Heo 
258226223abSTejun Heo #ifdef CONFIG_SYSFS
259226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
260226223abSTejun Heo #endif
2614e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
262669de8bdSBart Van Assche 	char			*lock_name;
263669de8bdSBart Van Assche 	struct lock_class_key	key;
2644e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
2654e6045f1SJohannes Berg #endif
266ecf6881fSTejun Heo 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
2672728fd2fSTejun Heo 
268e2dca7adSTejun Heo 	/*
269e2dca7adSTejun Heo 	 * Destruction of workqueue_struct is sched-RCU protected to allow
270e2dca7adSTejun Heo 	 * walking the workqueues list without grabbing wq_pool_mutex.
271e2dca7adSTejun Heo 	 * This is used to dump all workqueues from sysrq.
272e2dca7adSTejun Heo 	 */
273e2dca7adSTejun Heo 	struct rcu_head		rcu;
274e2dca7adSTejun Heo 
2752728fd2fSTejun Heo 	/* hot fields used during command issue, aligned to cacheline */
2762728fd2fSTejun Heo 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
2772728fd2fSTejun Heo 	struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
2785b95e1afSLai Jiangshan 	struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
2791da177e4SLinus Torvalds };
2801da177e4SLinus Torvalds 
281e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
282e904e6c2STejun Heo 
283bce90380STejun Heo static cpumask_var_t *wq_numa_possible_cpumask;
284bce90380STejun Heo 					/* possible CPUs of each node */
285bce90380STejun Heo 
286d55262c4STejun Heo static bool wq_disable_numa;
287d55262c4STejun Heo module_param_named(disable_numa, wq_disable_numa, bool, 0444);
288d55262c4STejun Heo 
289cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
290552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
291cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
292cee22a15SViresh Kumar 
293863b710bSTejun Heo static bool wq_online;			/* can kworkers be created yet? */
2943347fa09STejun Heo 
295bce90380STejun Heo static bool wq_numa_enabled;		/* unbound NUMA affinity enabled */
296bce90380STejun Heo 
2974c16bd32STejun Heo /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
2984c16bd32STejun Heo static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
2994c16bd32STejun Heo 
30068e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
3011258fae7STejun Heo static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
3022e109a28STejun Heo static DEFINE_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
303692b4825STejun Heo static DECLARE_WAIT_QUEUE_HEAD(wq_manager_wait); /* wait for manager to go away */
3045bcab335STejun Heo 
305e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
30668e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
3077d19c5ceSTejun Heo 
308ef557180SMike Galbraith /* PL: allowable cpus for unbound wqs and work items */
309ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
310ef557180SMike Galbraith 
311ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
312ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
313b05a7928SFrederic Weisbecker 
314f303fccbSTejun Heo /*
315f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
316f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
317f303fccbSTejun Heo  * to uncover usages which depend on it.
318f303fccbSTejun Heo  */
319f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
320f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
321f303fccbSTejun Heo #else
322f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
323f303fccbSTejun Heo #endif
324f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
325f303fccbSTejun Heo 
3267d19c5ceSTejun Heo /* the per-cpu worker pools */
32725528213SPeter Zijlstra static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
3287d19c5ceSTejun Heo 
32968e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
3307d19c5ceSTejun Heo 
33168e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
33229c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
33329c91e99STejun Heo 
334c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
33529c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
33629c91e99STejun Heo 
3378a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
3388a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
3398a2b7538STejun Heo 
340d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
341ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
342044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
3431aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
344044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
345d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
346044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
347f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
348044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
34924d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
3500668106cSViresh Kumar struct workqueue_struct *system_power_efficient_wq __read_mostly;
3510668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
3520668106cSViresh Kumar struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
3530668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
354d320c038STejun Heo 
3557d19c5ceSTejun Heo static int worker_thread(void *__worker);
3566ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
3577d19c5ceSTejun Heo 
35897bd2347STejun Heo #define CREATE_TRACE_POINTS
35997bd2347STejun Heo #include <trace/events/workqueue.h>
36097bd2347STejun Heo 
36168e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
362f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
363f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
36468e13a67SLai Jiangshan 			 "sched RCU or wq_pool_mutex should be held")
3655bcab335STejun Heo 
366b09f4fd3SLai Jiangshan #define assert_rcu_or_wq_mutex(wq)					\
367f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
368f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex),			\
369b09f4fd3SLai Jiangshan 			 "sched RCU or wq->mutex should be held")
37076af4d93STejun Heo 
3715b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
372f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
373f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
374f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
3755b95e1afSLai Jiangshan 			 "sched RCU, wq->mutex or wq_pool_mutex should be held")
3765b95e1afSLai Jiangshan 
377f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
378f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
379f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
3807a62c2c8STejun Heo 	     (pool)++)
3814ce62e9eSTejun Heo 
38249e3cf44STejun Heo /**
38317116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
38417116969STejun Heo  * @pool: iteration cursor
385611c92a0STejun Heo  * @pi: integer used for iteration
386fa1b54e6STejun Heo  *
38768e13a67SLai Jiangshan  * This must be called either with wq_pool_mutex held or sched RCU read
38868e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
38968e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
390fa1b54e6STejun Heo  *
391fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
392fa1b54e6STejun Heo  * ignored.
39317116969STejun Heo  */
394611c92a0STejun Heo #define for_each_pool(pool, pi)						\
395611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
39668e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
397fa1b54e6STejun Heo 		else
39817116969STejun Heo 
39917116969STejun Heo /**
400822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
401822d8405STejun Heo  * @worker: iteration cursor
402822d8405STejun Heo  * @pool: worker_pool to iterate workers of
403822d8405STejun Heo  *
4041258fae7STejun Heo  * This must be called with wq_pool_attach_mutex.
405822d8405STejun Heo  *
406822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
407822d8405STejun Heo  * ignored.
408822d8405STejun Heo  */
409da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
410da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
4111258fae7STejun Heo 		if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
412822d8405STejun Heo 		else
413822d8405STejun Heo 
414822d8405STejun Heo /**
41549e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
41649e3cf44STejun Heo  * @pwq: iteration cursor
41749e3cf44STejun Heo  * @wq: the target workqueue
41876af4d93STejun Heo  *
419b09f4fd3SLai Jiangshan  * This must be called either with wq->mutex held or sched RCU read locked.
420794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
421794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
42276af4d93STejun Heo  *
42376af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
42476af4d93STejun Heo  * ignored.
42549e3cf44STejun Heo  */
42649e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
42776af4d93STejun Heo 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node)		\
428b09f4fd3SLai Jiangshan 		if (({ assert_rcu_or_wq_mutex(wq); false; })) { }	\
42976af4d93STejun Heo 		else
430f3421797STejun Heo 
431dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
432dc186ad7SThomas Gleixner 
433dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr;
434dc186ad7SThomas Gleixner 
43599777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
43699777288SStanislaw Gruszka {
43799777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
43899777288SStanislaw Gruszka }
43999777288SStanislaw Gruszka 
440b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
441b9fdac7fSDu, Changbin {
442b9fdac7fSDu, Changbin 	struct work_struct *work = addr;
443b9fdac7fSDu, Changbin 
444b9fdac7fSDu, Changbin 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
445b9fdac7fSDu, Changbin }
446b9fdac7fSDu, Changbin 
447dc186ad7SThomas Gleixner /*
448dc186ad7SThomas Gleixner  * fixup_init is called when:
449dc186ad7SThomas Gleixner  * - an active object is initialized
450dc186ad7SThomas Gleixner  */
45102a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
452dc186ad7SThomas Gleixner {
453dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
454dc186ad7SThomas Gleixner 
455dc186ad7SThomas Gleixner 	switch (state) {
456dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
457dc186ad7SThomas Gleixner 		cancel_work_sync(work);
458dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
45902a982a6SDu, Changbin 		return true;
460dc186ad7SThomas Gleixner 	default:
46102a982a6SDu, Changbin 		return false;
462dc186ad7SThomas Gleixner 	}
463dc186ad7SThomas Gleixner }
464dc186ad7SThomas Gleixner 
465dc186ad7SThomas Gleixner /*
466dc186ad7SThomas Gleixner  * fixup_free is called when:
467dc186ad7SThomas Gleixner  * - an active object is freed
468dc186ad7SThomas Gleixner  */
46902a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
470dc186ad7SThomas Gleixner {
471dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
472dc186ad7SThomas Gleixner 
473dc186ad7SThomas Gleixner 	switch (state) {
474dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
475dc186ad7SThomas Gleixner 		cancel_work_sync(work);
476dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
47702a982a6SDu, Changbin 		return true;
478dc186ad7SThomas Gleixner 	default:
47902a982a6SDu, Changbin 		return false;
480dc186ad7SThomas Gleixner 	}
481dc186ad7SThomas Gleixner }
482dc186ad7SThomas Gleixner 
483dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr = {
484dc186ad7SThomas Gleixner 	.name		= "work_struct",
48599777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
486b9fdac7fSDu, Changbin 	.is_static_object = work_is_static_object,
487dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
488dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
489dc186ad7SThomas Gleixner };
490dc186ad7SThomas Gleixner 
491dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
492dc186ad7SThomas Gleixner {
493dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
494dc186ad7SThomas Gleixner }
495dc186ad7SThomas Gleixner 
496dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
497dc186ad7SThomas Gleixner {
498dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
499dc186ad7SThomas Gleixner }
500dc186ad7SThomas Gleixner 
501dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
502dc186ad7SThomas Gleixner {
503dc186ad7SThomas Gleixner 	if (onstack)
504dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
505dc186ad7SThomas Gleixner 	else
506dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
507dc186ad7SThomas Gleixner }
508dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
509dc186ad7SThomas Gleixner 
510dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
511dc186ad7SThomas Gleixner {
512dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
513dc186ad7SThomas Gleixner }
514dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
515dc186ad7SThomas Gleixner 
516ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
517ea2e64f2SThomas Gleixner {
518ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
519ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
520ea2e64f2SThomas Gleixner }
521ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
522ea2e64f2SThomas Gleixner 
523dc186ad7SThomas Gleixner #else
524dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
525dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
526dc186ad7SThomas Gleixner #endif
527dc186ad7SThomas Gleixner 
5284e8b22bdSLi Bin /**
5294e8b22bdSLi Bin  * worker_pool_assign_id - allocate ID and assing it to @pool
5304e8b22bdSLi Bin  * @pool: the pool pointer of interest
5314e8b22bdSLi Bin  *
5324e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
5334e8b22bdSLi Bin  * successfully, -errno on failure.
5344e8b22bdSLi Bin  */
5359daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
5369daf9e67STejun Heo {
5379daf9e67STejun Heo 	int ret;
5389daf9e67STejun Heo 
53968e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5405bcab335STejun Heo 
5414e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
5424e8b22bdSLi Bin 			GFP_KERNEL);
543229641a6STejun Heo 	if (ret >= 0) {
544e68035fbSTejun Heo 		pool->id = ret;
545229641a6STejun Heo 		return 0;
546229641a6STejun Heo 	}
5479daf9e67STejun Heo 	return ret;
5489daf9e67STejun Heo }
5499daf9e67STejun Heo 
55076af4d93STejun Heo /**
551df2d5ae4STejun Heo  * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
552df2d5ae4STejun Heo  * @wq: the target workqueue
553df2d5ae4STejun Heo  * @node: the node ID
554df2d5ae4STejun Heo  *
5555b95e1afSLai Jiangshan  * This must be called with any of wq_pool_mutex, wq->mutex or sched RCU
5565b95e1afSLai Jiangshan  * read locked.
557df2d5ae4STejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
558df2d5ae4STejun Heo  * responsible for guaranteeing that the pwq stays online.
559d185af30SYacine Belkadi  *
560d185af30SYacine Belkadi  * Return: The unbound pool_workqueue for @node.
561df2d5ae4STejun Heo  */
562df2d5ae4STejun Heo static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
563df2d5ae4STejun Heo 						  int node)
564df2d5ae4STejun Heo {
5655b95e1afSLai Jiangshan 	assert_rcu_or_wq_mutex_or_pool_mutex(wq);
566d6e022f1STejun Heo 
567d6e022f1STejun Heo 	/*
568d6e022f1STejun Heo 	 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
569d6e022f1STejun Heo 	 * delayed item is pending.  The plan is to keep CPU -> NODE
570d6e022f1STejun Heo 	 * mapping valid and stable across CPU on/offlines.  Once that
571d6e022f1STejun Heo 	 * happens, this workaround can be removed.
572d6e022f1STejun Heo 	 */
573d6e022f1STejun Heo 	if (unlikely(node == NUMA_NO_NODE))
574d6e022f1STejun Heo 		return wq->dfl_pwq;
575d6e022f1STejun Heo 
576df2d5ae4STejun Heo 	return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
577df2d5ae4STejun Heo }
578df2d5ae4STejun Heo 
57973f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
58073f53c4aSTejun Heo {
58173f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
58273f53c4aSTejun Heo }
58373f53c4aSTejun Heo 
58473f53c4aSTejun Heo static int get_work_color(struct work_struct *work)
58573f53c4aSTejun Heo {
58673f53c4aSTejun Heo 	return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
58773f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
58873f53c4aSTejun Heo }
58973f53c4aSTejun Heo 
59073f53c4aSTejun Heo static int work_next_color(int color)
59173f53c4aSTejun Heo {
59273f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
593a848e3b6SOleg Nesterov }
594a848e3b6SOleg Nesterov 
5954594bf15SDavid Howells /*
596112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
597112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
5987c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
5997a22ad75STejun Heo  *
600112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
601112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
602bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
603bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
6047a22ad75STejun Heo  *
605112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6067c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
607112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
6087c3eed5cSTejun Heo  * available only while the work item is queued.
609bbb68dfaSTejun Heo  *
610bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
611bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
612bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
613bbb68dfaSTejun Heo  * try to steal the PENDING bit.
6144594bf15SDavid Howells  */
6157a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6167a22ad75STejun Heo 				 unsigned long flags)
6177a22ad75STejun Heo {
6186183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
6197a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
6207a22ad75STejun Heo }
6217a22ad75STejun Heo 
622112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6234690c4abSTejun Heo 			 unsigned long extra_flags)
624365970a1SDavid Howells {
625112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
626112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
627365970a1SDavid Howells }
628365970a1SDavid Howells 
6294468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6304468a00fSLai Jiangshan 					   int pool_id)
6314468a00fSLai Jiangshan {
6324468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6334468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6344468a00fSLai Jiangshan }
6354468a00fSLai Jiangshan 
6367c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6377c3eed5cSTejun Heo 					    int pool_id)
6384d707b9fSOleg Nesterov {
63923657bb1STejun Heo 	/*
64023657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
64123657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
64223657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
64323657bb1STejun Heo 	 * owner.
64423657bb1STejun Heo 	 */
64523657bb1STejun Heo 	smp_wmb();
6467c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
647346c09f8SRoman Pen 	/*
648346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
649346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
650346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
6518bdc6201SLiu Song 	 * reordering can lead to a missed execution on attempt to queue
652346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
653346c09f8SRoman Pen 	 *
654346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
655346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
656346c09f8SRoman Pen 	 *
657346c09f8SRoman Pen 	 * 1  STORE event_indicated
658346c09f8SRoman Pen 	 * 2  queue_work_on() {
659346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
660346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
661346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
662346c09f8SRoman Pen 	 * 6                                 smp_mb()
663346c09f8SRoman Pen 	 * 7                               work->current_func() {
664346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
665346c09f8SRoman Pen 	 *				   }
666346c09f8SRoman Pen 	 *
667346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
668346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
669346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
670346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
671346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
672346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
673346c09f8SRoman Pen 	 * before actual STORE.
674346c09f8SRoman Pen 	 */
675346c09f8SRoman Pen 	smp_mb();
6764d707b9fSOleg Nesterov }
6774d707b9fSOleg Nesterov 
6787a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
679365970a1SDavid Howells {
6807c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
6817c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
6827a22ad75STejun Heo }
6837a22ad75STejun Heo 
684112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
6857a22ad75STejun Heo {
686e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
6877a22ad75STejun Heo 
688112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
689e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
690e120153dSTejun Heo 	else
691e120153dSTejun Heo 		return NULL;
6927a22ad75STejun Heo }
6937a22ad75STejun Heo 
6947c3eed5cSTejun Heo /**
6957c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
6967c3eed5cSTejun Heo  * @work: the work item of interest
6977c3eed5cSTejun Heo  *
69868e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
69968e13a67SLai Jiangshan  * access under sched-RCU read lock.  As such, this function should be
70068e13a67SLai Jiangshan  * called under wq_pool_mutex or with preemption disabled.
701fa1b54e6STejun Heo  *
702fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
703fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
704fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
705fa1b54e6STejun Heo  * returned pool is and stays online.
706d185af30SYacine Belkadi  *
707d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
7087c3eed5cSTejun Heo  */
7097c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
7107a22ad75STejun Heo {
711e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7127c3eed5cSTejun Heo 	int pool_id;
7137a22ad75STejun Heo 
71468e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
715fa1b54e6STejun Heo 
716112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
717112202d9STejun Heo 		return ((struct pool_workqueue *)
7187c3eed5cSTejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool;
7197a22ad75STejun Heo 
7207c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
7217c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
7227a22ad75STejun Heo 		return NULL;
7237a22ad75STejun Heo 
724fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
7257c3eed5cSTejun Heo }
7267c3eed5cSTejun Heo 
7277c3eed5cSTejun Heo /**
7287c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
7297c3eed5cSTejun Heo  * @work: the work item of interest
7307c3eed5cSTejun Heo  *
731d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
7327c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
7337c3eed5cSTejun Heo  */
7347c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
7357c3eed5cSTejun Heo {
73654d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
7377c3eed5cSTejun Heo 
738112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
739112202d9STejun Heo 		return ((struct pool_workqueue *)
74054d5b7d0SLai Jiangshan 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
74154d5b7d0SLai Jiangshan 
74254d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
7437c3eed5cSTejun Heo }
7447c3eed5cSTejun Heo 
745bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
746bbb68dfaSTejun Heo {
7477c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
748bbb68dfaSTejun Heo 
7497c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
7507c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
751bbb68dfaSTejun Heo }
752bbb68dfaSTejun Heo 
753bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
754bbb68dfaSTejun Heo {
755bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
756bbb68dfaSTejun Heo 
757112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
758bbb68dfaSTejun Heo }
759bbb68dfaSTejun Heo 
760e22bee78STejun Heo /*
7613270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
7623270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
763d565ed63STejun Heo  * they're being called with pool->lock held.
764e22bee78STejun Heo  */
765e22bee78STejun Heo 
76663d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
767649027d7STejun Heo {
768e19e397aSTejun Heo 	return !atomic_read(&pool->nr_running);
769649027d7STejun Heo }
770649027d7STejun Heo 
771e22bee78STejun Heo /*
772e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
773e22bee78STejun Heo  * running workers.
774974271c4STejun Heo  *
775974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
776706026c2STejun Heo  * function will always return %true for unbound pools as long as the
777974271c4STejun Heo  * worklist isn't empty.
778e22bee78STejun Heo  */
77963d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
780e22bee78STejun Heo {
78163d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
782e22bee78STejun Heo }
783e22bee78STejun Heo 
784e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
78563d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
786e22bee78STejun Heo {
78763d95a91STejun Heo 	return pool->nr_idle;
788e22bee78STejun Heo }
789e22bee78STejun Heo 
790e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
79163d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
792e22bee78STejun Heo {
793e19e397aSTejun Heo 	return !list_empty(&pool->worklist) &&
794e19e397aSTejun Heo 		atomic_read(&pool->nr_running) <= 1;
795e22bee78STejun Heo }
796e22bee78STejun Heo 
797e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
79863d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
799e22bee78STejun Heo {
80063d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
801e22bee78STejun Heo }
802e22bee78STejun Heo 
803e22bee78STejun Heo /* Do we have too many workers and should some go away? */
80463d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
805e22bee78STejun Heo {
806692b4825STejun Heo 	bool managing = pool->flags & POOL_MANAGER_ACTIVE;
80763d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
80863d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
809e22bee78STejun Heo 
810e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
811e22bee78STejun Heo }
812e22bee78STejun Heo 
813e22bee78STejun Heo /*
814e22bee78STejun Heo  * Wake up functions.
815e22bee78STejun Heo  */
816e22bee78STejun Heo 
8171037de36SLai Jiangshan /* Return the first idle worker.  Safe with preemption disabled */
8181037de36SLai Jiangshan static struct worker *first_idle_worker(struct worker_pool *pool)
8197e11629dSTejun Heo {
82063d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
8217e11629dSTejun Heo 		return NULL;
8227e11629dSTejun Heo 
82363d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
8247e11629dSTejun Heo }
8257e11629dSTejun Heo 
8267e11629dSTejun Heo /**
8277e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
82863d95a91STejun Heo  * @pool: worker pool to wake worker from
8297e11629dSTejun Heo  *
83063d95a91STejun Heo  * Wake up the first idle worker of @pool.
8317e11629dSTejun Heo  *
8327e11629dSTejun Heo  * CONTEXT:
833d565ed63STejun Heo  * spin_lock_irq(pool->lock).
8347e11629dSTejun Heo  */
83563d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
8367e11629dSTejun Heo {
8371037de36SLai Jiangshan 	struct worker *worker = first_idle_worker(pool);
8387e11629dSTejun Heo 
8397e11629dSTejun Heo 	if (likely(worker))
8407e11629dSTejun Heo 		wake_up_process(worker->task);
8417e11629dSTejun Heo }
8427e11629dSTejun Heo 
8434690c4abSTejun Heo /**
844e22bee78STejun Heo  * wq_worker_waking_up - a worker is waking up
845e22bee78STejun Heo  * @task: task waking up
846e22bee78STejun Heo  * @cpu: CPU @task is waking up to
847e22bee78STejun Heo  *
848e22bee78STejun Heo  * This function is called during try_to_wake_up() when a worker is
849e22bee78STejun Heo  * being awoken.
850e22bee78STejun Heo  *
851e22bee78STejun Heo  * CONTEXT:
852e22bee78STejun Heo  * spin_lock_irq(rq->lock)
853e22bee78STejun Heo  */
854d84ff051STejun Heo void wq_worker_waking_up(struct task_struct *task, int cpu)
855e22bee78STejun Heo {
856e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
857e22bee78STejun Heo 
85836576000SJoonsoo Kim 	if (!(worker->flags & WORKER_NOT_RUNNING)) {
859ec22ca5eSTejun Heo 		WARN_ON_ONCE(worker->pool->cpu != cpu);
860e19e397aSTejun Heo 		atomic_inc(&worker->pool->nr_running);
861e22bee78STejun Heo 	}
86236576000SJoonsoo Kim }
863e22bee78STejun Heo 
864e22bee78STejun Heo /**
865e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
866e22bee78STejun Heo  * @task: task going to sleep
867e22bee78STejun Heo  *
868e22bee78STejun Heo  * This function is called during schedule() when a busy worker is
869e22bee78STejun Heo  * going to sleep.  Worker on the same cpu can be woken up by
870e22bee78STejun Heo  * returning pointer to its task.
871e22bee78STejun Heo  *
872e22bee78STejun Heo  * CONTEXT:
873e22bee78STejun Heo  * spin_lock_irq(rq->lock)
874e22bee78STejun Heo  *
875d185af30SYacine Belkadi  * Return:
876e22bee78STejun Heo  * Worker task on @cpu to wake up, %NULL if none.
877e22bee78STejun Heo  */
8789b7f6597SAlexander Gordeev struct task_struct *wq_worker_sleeping(struct task_struct *task)
879e22bee78STejun Heo {
880e22bee78STejun Heo 	struct worker *worker = kthread_data(task), *to_wakeup = NULL;
881111c225aSTejun Heo 	struct worker_pool *pool;
882e22bee78STejun Heo 
883111c225aSTejun Heo 	/*
884111c225aSTejun Heo 	 * Rescuers, which may not have all the fields set up like normal
885111c225aSTejun Heo 	 * workers, also reach here, let's not access anything before
886111c225aSTejun Heo 	 * checking NOT_RUNNING.
887111c225aSTejun Heo 	 */
8882d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
889e22bee78STejun Heo 		return NULL;
890e22bee78STejun Heo 
891111c225aSTejun Heo 	pool = worker->pool;
892111c225aSTejun Heo 
893e22bee78STejun Heo 	/* this can only happen on the local cpu */
8949b7f6597SAlexander Gordeev 	if (WARN_ON_ONCE(pool->cpu != raw_smp_processor_id()))
8956183c009STejun Heo 		return NULL;
896e22bee78STejun Heo 
897e22bee78STejun Heo 	/*
898e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
899e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
900e22bee78STejun Heo 	 * Please read comment there.
901e22bee78STejun Heo 	 *
902628c78e7STejun Heo 	 * NOT_RUNNING is clear.  This means that we're bound to and
903628c78e7STejun Heo 	 * running on the local cpu w/ rq lock held and preemption
904628c78e7STejun Heo 	 * disabled, which in turn means that none else could be
905d565ed63STejun Heo 	 * manipulating idle_list, so dereferencing idle_list without pool
906628c78e7STejun Heo 	 * lock is safe.
907e22bee78STejun Heo 	 */
908e19e397aSTejun Heo 	if (atomic_dec_and_test(&pool->nr_running) &&
909e19e397aSTejun Heo 	    !list_empty(&pool->worklist))
9101037de36SLai Jiangshan 		to_wakeup = first_idle_worker(pool);
911e22bee78STejun Heo 	return to_wakeup ? to_wakeup->task : NULL;
912e22bee78STejun Heo }
913e22bee78STejun Heo 
914e22bee78STejun Heo /**
9151b69ac6bSJohannes Weiner  * wq_worker_last_func - retrieve worker's last work function
916*8194fe94SBart Van Assche  * @task: Task to retrieve last work function of.
9171b69ac6bSJohannes Weiner  *
9181b69ac6bSJohannes Weiner  * Determine the last function a worker executed. This is called from
9191b69ac6bSJohannes Weiner  * the scheduler to get a worker's last known identity.
9201b69ac6bSJohannes Weiner  *
9211b69ac6bSJohannes Weiner  * CONTEXT:
9221b69ac6bSJohannes Weiner  * spin_lock_irq(rq->lock)
9231b69ac6bSJohannes Weiner  *
9244b047002SJohannes Weiner  * This function is called during schedule() when a kworker is going
9254b047002SJohannes Weiner  * to sleep. It's used by psi to identify aggregation workers during
9264b047002SJohannes Weiner  * dequeuing, to allow periodic aggregation to shut-off when that
9274b047002SJohannes Weiner  * worker is the last task in the system or cgroup to go to sleep.
9284b047002SJohannes Weiner  *
9294b047002SJohannes Weiner  * As this function doesn't involve any workqueue-related locking, it
9304b047002SJohannes Weiner  * only returns stable values when called from inside the scheduler's
9314b047002SJohannes Weiner  * queuing and dequeuing paths, when @task, which must be a kworker,
9324b047002SJohannes Weiner  * is guaranteed to not be processing any works.
9334b047002SJohannes Weiner  *
9341b69ac6bSJohannes Weiner  * Return:
9351b69ac6bSJohannes Weiner  * The last work function %current executed as a worker, NULL if it
9361b69ac6bSJohannes Weiner  * hasn't executed any work yet.
9371b69ac6bSJohannes Weiner  */
9381b69ac6bSJohannes Weiner work_func_t wq_worker_last_func(struct task_struct *task)
9391b69ac6bSJohannes Weiner {
9401b69ac6bSJohannes Weiner 	struct worker *worker = kthread_data(task);
9411b69ac6bSJohannes Weiner 
9421b69ac6bSJohannes Weiner 	return worker->last_func;
9431b69ac6bSJohannes Weiner }
9441b69ac6bSJohannes Weiner 
9451b69ac6bSJohannes Weiner /**
946e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
947cb444766STejun Heo  * @worker: self
948d302f017STejun Heo  * @flags: flags to set
949d302f017STejun Heo  *
950228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
951d302f017STejun Heo  *
952cb444766STejun Heo  * CONTEXT:
953d565ed63STejun Heo  * spin_lock_irq(pool->lock)
954d302f017STejun Heo  */
955228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
956d302f017STejun Heo {
957bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
958e22bee78STejun Heo 
959cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
960cb444766STejun Heo 
961228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
962e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
963e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
964e19e397aSTejun Heo 		atomic_dec(&pool->nr_running);
965e22bee78STejun Heo 	}
966e22bee78STejun Heo 
967d302f017STejun Heo 	worker->flags |= flags;
968d302f017STejun Heo }
969d302f017STejun Heo 
970d302f017STejun Heo /**
971e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
972cb444766STejun Heo  * @worker: self
973d302f017STejun Heo  * @flags: flags to clear
974d302f017STejun Heo  *
975e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
976d302f017STejun Heo  *
977cb444766STejun Heo  * CONTEXT:
978d565ed63STejun Heo  * spin_lock_irq(pool->lock)
979d302f017STejun Heo  */
980d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
981d302f017STejun Heo {
98263d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
983e22bee78STejun Heo 	unsigned int oflags = worker->flags;
984e22bee78STejun Heo 
985cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
986cb444766STejun Heo 
987d302f017STejun Heo 	worker->flags &= ~flags;
988e22bee78STejun Heo 
98942c025f3STejun Heo 	/*
99042c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
99142c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
99242c025f3STejun Heo 	 * of multiple flags, not a single flag.
99342c025f3STejun Heo 	 */
994e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
995e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
996e19e397aSTejun Heo 			atomic_inc(&pool->nr_running);
997d302f017STejun Heo }
998d302f017STejun Heo 
999d302f017STejun Heo /**
10008cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
1001c9e7cf27STejun Heo  * @pool: pool of interest
10028cca0eeaSTejun Heo  * @work: work to find worker for
10038cca0eeaSTejun Heo  *
1004c9e7cf27STejun Heo  * Find a worker which is executing @work on @pool by searching
1005c9e7cf27STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
1006a2c1c57bSTejun Heo  * to match, its current execution should match the address of @work and
1007a2c1c57bSTejun Heo  * its work function.  This is to avoid unwanted dependency between
1008a2c1c57bSTejun Heo  * unrelated work executions through a work item being recycled while still
1009a2c1c57bSTejun Heo  * being executed.
1010a2c1c57bSTejun Heo  *
1011a2c1c57bSTejun Heo  * This is a bit tricky.  A work item may be freed once its execution
1012a2c1c57bSTejun Heo  * starts and nothing prevents the freed area from being recycled for
1013a2c1c57bSTejun Heo  * another work item.  If the same work item address ends up being reused
1014a2c1c57bSTejun Heo  * before the original execution finishes, workqueue will identify the
1015a2c1c57bSTejun Heo  * recycled work item as currently executing and make it wait until the
1016a2c1c57bSTejun Heo  * current execution finishes, introducing an unwanted dependency.
1017a2c1c57bSTejun Heo  *
1018c5aa87bbSTejun Heo  * This function checks the work item address and work function to avoid
1019c5aa87bbSTejun Heo  * false positives.  Note that this isn't complete as one may construct a
1020c5aa87bbSTejun Heo  * work function which can introduce dependency onto itself through a
1021c5aa87bbSTejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
1022c5aa87bbSTejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
1023c5aa87bbSTejun Heo  * actually occurs, it should be easy to locate the culprit work function.
10248cca0eeaSTejun Heo  *
10258cca0eeaSTejun Heo  * CONTEXT:
1026d565ed63STejun Heo  * spin_lock_irq(pool->lock).
10278cca0eeaSTejun Heo  *
1028d185af30SYacine Belkadi  * Return:
1029d185af30SYacine Belkadi  * Pointer to worker which is executing @work if found, %NULL
10308cca0eeaSTejun Heo  * otherwise.
10318cca0eeaSTejun Heo  */
1032c9e7cf27STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
10338cca0eeaSTejun Heo 						 struct work_struct *work)
10348cca0eeaSTejun Heo {
103542f8570fSSasha Levin 	struct worker *worker;
103642f8570fSSasha Levin 
1037b67bfe0dSSasha Levin 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1038a2c1c57bSTejun Heo 			       (unsigned long)work)
1039a2c1c57bSTejun Heo 		if (worker->current_work == work &&
1040a2c1c57bSTejun Heo 		    worker->current_func == work->func)
104142f8570fSSasha Levin 			return worker;
104242f8570fSSasha Levin 
104342f8570fSSasha Levin 	return NULL;
10448cca0eeaSTejun Heo }
10458cca0eeaSTejun Heo 
10468cca0eeaSTejun Heo /**
1047bf4ede01STejun Heo  * move_linked_works - move linked works to a list
1048bf4ede01STejun Heo  * @work: start of series of works to be scheduled
1049bf4ede01STejun Heo  * @head: target list to append @work to
1050402dd89dSShailendra Verma  * @nextp: out parameter for nested worklist walking
1051bf4ede01STejun Heo  *
1052bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
1053bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
1054bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
1055bf4ede01STejun Heo  *
1056bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
1057bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
1058bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
1059bf4ede01STejun Heo  *
1060bf4ede01STejun Heo  * CONTEXT:
1061d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1062bf4ede01STejun Heo  */
1063bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1064bf4ede01STejun Heo 			      struct work_struct **nextp)
1065bf4ede01STejun Heo {
1066bf4ede01STejun Heo 	struct work_struct *n;
1067bf4ede01STejun Heo 
1068bf4ede01STejun Heo 	/*
1069bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
1070bf4ede01STejun Heo 	 * use NULL for list head.
1071bf4ede01STejun Heo 	 */
1072bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1073bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
1074bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1075bf4ede01STejun Heo 			break;
1076bf4ede01STejun Heo 	}
1077bf4ede01STejun Heo 
1078bf4ede01STejun Heo 	/*
1079bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
1080bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
1081bf4ede01STejun Heo 	 * needs to be updated.
1082bf4ede01STejun Heo 	 */
1083bf4ede01STejun Heo 	if (nextp)
1084bf4ede01STejun Heo 		*nextp = n;
1085bf4ede01STejun Heo }
1086bf4ede01STejun Heo 
10878864b4e5STejun Heo /**
10888864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
10898864b4e5STejun Heo  * @pwq: pool_workqueue to get
10908864b4e5STejun Heo  *
10918864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
10928864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
10938864b4e5STejun Heo  */
10948864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
10958864b4e5STejun Heo {
10968864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
10978864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
10988864b4e5STejun Heo 	pwq->refcnt++;
10998864b4e5STejun Heo }
11008864b4e5STejun Heo 
11018864b4e5STejun Heo /**
11028864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
11038864b4e5STejun Heo  * @pwq: pool_workqueue to put
11048864b4e5STejun Heo  *
11058864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
11068864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
11078864b4e5STejun Heo  */
11088864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
11098864b4e5STejun Heo {
11108864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
11118864b4e5STejun Heo 	if (likely(--pwq->refcnt))
11128864b4e5STejun Heo 		return;
11138864b4e5STejun Heo 	if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
11148864b4e5STejun Heo 		return;
11158864b4e5STejun Heo 	/*
11168864b4e5STejun Heo 	 * @pwq can't be released under pool->lock, bounce to
11178864b4e5STejun Heo 	 * pwq_unbound_release_workfn().  This never recurses on the same
11188864b4e5STejun Heo 	 * pool->lock as this path is taken only for unbound workqueues and
11198864b4e5STejun Heo 	 * the release work item is scheduled on a per-cpu workqueue.  To
11208864b4e5STejun Heo 	 * avoid lockdep warning, unbound pool->locks are given lockdep
11218864b4e5STejun Heo 	 * subclass of 1 in get_unbound_pool().
11228864b4e5STejun Heo 	 */
11238864b4e5STejun Heo 	schedule_work(&pwq->unbound_release_work);
11248864b4e5STejun Heo }
11258864b4e5STejun Heo 
1126dce90d47STejun Heo /**
1127dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1128dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1129dce90d47STejun Heo  *
1130dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1131dce90d47STejun Heo  */
1132dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1133dce90d47STejun Heo {
1134dce90d47STejun Heo 	if (pwq) {
1135dce90d47STejun Heo 		/*
1136dce90d47STejun Heo 		 * As both pwqs and pools are sched-RCU protected, the
1137dce90d47STejun Heo 		 * following lock operations are safe.
1138dce90d47STejun Heo 		 */
1139dce90d47STejun Heo 		spin_lock_irq(&pwq->pool->lock);
1140dce90d47STejun Heo 		put_pwq(pwq);
1141dce90d47STejun Heo 		spin_unlock_irq(&pwq->pool->lock);
1142dce90d47STejun Heo 	}
1143dce90d47STejun Heo }
1144dce90d47STejun Heo 
1145112202d9STejun Heo static void pwq_activate_delayed_work(struct work_struct *work)
1146bf4ede01STejun Heo {
1147112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1148bf4ede01STejun Heo 
1149bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
115082607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
115182607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1152112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
1153bf4ede01STejun Heo 	__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1154112202d9STejun Heo 	pwq->nr_active++;
1155bf4ede01STejun Heo }
1156bf4ede01STejun Heo 
1157112202d9STejun Heo static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
11583aa62497SLai Jiangshan {
1159112202d9STejun Heo 	struct work_struct *work = list_first_entry(&pwq->delayed_works,
11603aa62497SLai Jiangshan 						    struct work_struct, entry);
11613aa62497SLai Jiangshan 
1162112202d9STejun Heo 	pwq_activate_delayed_work(work);
11633aa62497SLai Jiangshan }
11643aa62497SLai Jiangshan 
1165bf4ede01STejun Heo /**
1166112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1167112202d9STejun Heo  * @pwq: pwq of interest
1168bf4ede01STejun Heo  * @color: color of work which left the queue
1169bf4ede01STejun Heo  *
1170bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1171112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1172bf4ede01STejun Heo  *
1173bf4ede01STejun Heo  * CONTEXT:
1174d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1175bf4ede01STejun Heo  */
1176112202d9STejun Heo static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1177bf4ede01STejun Heo {
11788864b4e5STejun Heo 	/* uncolored work items don't participate in flushing or nr_active */
1179bf4ede01STejun Heo 	if (color == WORK_NO_COLOR)
11808864b4e5STejun Heo 		goto out_put;
1181bf4ede01STejun Heo 
1182112202d9STejun Heo 	pwq->nr_in_flight[color]--;
1183bf4ede01STejun Heo 
1184112202d9STejun Heo 	pwq->nr_active--;
1185112202d9STejun Heo 	if (!list_empty(&pwq->delayed_works)) {
1186bf4ede01STejun Heo 		/* one down, submit a delayed one */
1187112202d9STejun Heo 		if (pwq->nr_active < pwq->max_active)
1188112202d9STejun Heo 			pwq_activate_first_delayed(pwq);
1189bf4ede01STejun Heo 	}
1190bf4ede01STejun Heo 
1191bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1192112202d9STejun Heo 	if (likely(pwq->flush_color != color))
11938864b4e5STejun Heo 		goto out_put;
1194bf4ede01STejun Heo 
1195bf4ede01STejun Heo 	/* are there still in-flight works? */
1196112202d9STejun Heo 	if (pwq->nr_in_flight[color])
11978864b4e5STejun Heo 		goto out_put;
1198bf4ede01STejun Heo 
1199112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1200112202d9STejun Heo 	pwq->flush_color = -1;
1201bf4ede01STejun Heo 
1202bf4ede01STejun Heo 	/*
1203112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1204bf4ede01STejun Heo 	 * will handle the rest.
1205bf4ede01STejun Heo 	 */
1206112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1207112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
12088864b4e5STejun Heo out_put:
12098864b4e5STejun Heo 	put_pwq(pwq);
1210bf4ede01STejun Heo }
1211bf4ede01STejun Heo 
121236e227d2STejun Heo /**
1213bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
121436e227d2STejun Heo  * @work: work item to steal
121536e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1216bbb68dfaSTejun Heo  * @flags: place to store irq state
121736e227d2STejun Heo  *
121836e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1219d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
122036e227d2STejun Heo  *
1221d185af30SYacine Belkadi  * Return:
122236e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
122336e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
122436e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1225bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1226bbb68dfaSTejun Heo  *		for arbitrarily long
122736e227d2STejun Heo  *
1228d185af30SYacine Belkadi  * Note:
1229bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1230e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1231e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1232e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1233bbb68dfaSTejun Heo  *
1234bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1235bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1236bbb68dfaSTejun Heo  *
1237e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1238bf4ede01STejun Heo  */
1239bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1240bbb68dfaSTejun Heo 			       unsigned long *flags)
1241bf4ede01STejun Heo {
1242d565ed63STejun Heo 	struct worker_pool *pool;
1243112202d9STejun Heo 	struct pool_workqueue *pwq;
1244bf4ede01STejun Heo 
1245bbb68dfaSTejun Heo 	local_irq_save(*flags);
1246bbb68dfaSTejun Heo 
124736e227d2STejun Heo 	/* try to steal the timer if it exists */
124836e227d2STejun Heo 	if (is_dwork) {
124936e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
125036e227d2STejun Heo 
1251e0aecdd8STejun Heo 		/*
1252e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1253e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1254e0aecdd8STejun Heo 		 * running on the local CPU.
1255e0aecdd8STejun Heo 		 */
125636e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
125736e227d2STejun Heo 			return 1;
125836e227d2STejun Heo 	}
125936e227d2STejun Heo 
126036e227d2STejun Heo 	/* try to claim PENDING the normal way */
1261bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1262bf4ede01STejun Heo 		return 0;
1263bf4ede01STejun Heo 
1264bf4ede01STejun Heo 	/*
1265bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1266bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1267bf4ede01STejun Heo 	 */
1268d565ed63STejun Heo 	pool = get_work_pool(work);
1269d565ed63STejun Heo 	if (!pool)
1270bbb68dfaSTejun Heo 		goto fail;
1271bf4ede01STejun Heo 
1272d565ed63STejun Heo 	spin_lock(&pool->lock);
1273bf4ede01STejun Heo 	/*
1274112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1275112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1276112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1277112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1278112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
12790b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1280bf4ede01STejun Heo 	 */
1281112202d9STejun Heo 	pwq = get_work_pwq(work);
1282112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1283bf4ede01STejun Heo 		debug_work_deactivate(work);
12843aa62497SLai Jiangshan 
12853aa62497SLai Jiangshan 		/*
128616062836STejun Heo 		 * A delayed work item cannot be grabbed directly because
128716062836STejun Heo 		 * it might have linked NO_COLOR work items which, if left
1288112202d9STejun Heo 		 * on the delayed_list, will confuse pwq->nr_active
128916062836STejun Heo 		 * management later on and cause stall.  Make sure the work
129016062836STejun Heo 		 * item is activated before grabbing.
12913aa62497SLai Jiangshan 		 */
12923aa62497SLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1293112202d9STejun Heo 			pwq_activate_delayed_work(work);
12943aa62497SLai Jiangshan 
1295bf4ede01STejun Heo 		list_del_init(&work->entry);
12969c34a704SLai Jiangshan 		pwq_dec_nr_in_flight(pwq, get_work_color(work));
129736e227d2STejun Heo 
1298112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
12994468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
13004468a00fSLai Jiangshan 
1301d565ed63STejun Heo 		spin_unlock(&pool->lock);
130236e227d2STejun Heo 		return 1;
1303bf4ede01STejun Heo 	}
1304d565ed63STejun Heo 	spin_unlock(&pool->lock);
1305bbb68dfaSTejun Heo fail:
1306bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1307bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1308bbb68dfaSTejun Heo 		return -ENOENT;
1309bbb68dfaSTejun Heo 	cpu_relax();
131036e227d2STejun Heo 	return -EAGAIN;
1311bf4ede01STejun Heo }
1312bf4ede01STejun Heo 
1313bf4ede01STejun Heo /**
1314706026c2STejun Heo  * insert_work - insert a work into a pool
1315112202d9STejun Heo  * @pwq: pwq @work belongs to
13164690c4abSTejun Heo  * @work: work to insert
13174690c4abSTejun Heo  * @head: insertion point
13184690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
13194690c4abSTejun Heo  *
1320112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1321706026c2STejun Heo  * work_struct flags.
13224690c4abSTejun Heo  *
13234690c4abSTejun Heo  * CONTEXT:
1324d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1325365970a1SDavid Howells  */
1326112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1327112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1328b89deed3SOleg Nesterov {
1329112202d9STejun Heo 	struct worker_pool *pool = pwq->pool;
1330e1d8aa9fSFrederic Weisbecker 
13314690c4abSTejun Heo 	/* we own @work, set data and link */
1332112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
13331a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
13348864b4e5STejun Heo 	get_pwq(pwq);
1335e22bee78STejun Heo 
1336e22bee78STejun Heo 	/*
1337c5aa87bbSTejun Heo 	 * Ensure either wq_worker_sleeping() sees the above
1338c5aa87bbSTejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers lying
1339c5aa87bbSTejun Heo 	 * around lazily while there are works to be processed.
1340e22bee78STejun Heo 	 */
1341e22bee78STejun Heo 	smp_mb();
1342e22bee78STejun Heo 
134363d95a91STejun Heo 	if (__need_more_worker(pool))
134463d95a91STejun Heo 		wake_up_worker(pool);
1345b89deed3SOleg Nesterov }
1346b89deed3SOleg Nesterov 
1347c8efcc25STejun Heo /*
1348c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
13498d03ecfeSTejun Heo  * same workqueue.
1350c8efcc25STejun Heo  */
1351c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1352c8efcc25STejun Heo {
1353c8efcc25STejun Heo 	struct worker *worker;
1354c8efcc25STejun Heo 
13558d03ecfeSTejun Heo 	worker = current_wq_worker();
1356c8efcc25STejun Heo 	/*
1357bf393fd4SBart Van Assche 	 * Return %true iff I'm a worker executing a work item on @wq.  If
13588d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1359c8efcc25STejun Heo 	 */
1360112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1361c8efcc25STejun Heo }
1362c8efcc25STejun Heo 
1363ef557180SMike Galbraith /*
1364ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
1365ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
1366ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
1367ef557180SMike Galbraith  */
1368ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1369ef557180SMike Galbraith {
1370f303fccbSTejun Heo 	static bool printed_dbg_warning;
1371ef557180SMike Galbraith 	int new_cpu;
1372ef557180SMike Galbraith 
1373f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
1374ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1375ef557180SMike Galbraith 			return cpu;
1376f303fccbSTejun Heo 	} else if (!printed_dbg_warning) {
1377f303fccbSTejun Heo 		pr_warn("workqueue: round-robin CPU selection forced, expect performance impact\n");
1378f303fccbSTejun Heo 		printed_dbg_warning = true;
1379f303fccbSTejun Heo 	}
1380f303fccbSTejun Heo 
1381ef557180SMike Galbraith 	if (cpumask_empty(wq_unbound_cpumask))
1382ef557180SMike Galbraith 		return cpu;
1383ef557180SMike Galbraith 
1384ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
1385ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1386ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
1387ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1388ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
1389ef557180SMike Galbraith 			return cpu;
1390ef557180SMike Galbraith 	}
1391ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
1392ef557180SMike Galbraith 
1393ef557180SMike Galbraith 	return new_cpu;
1394ef557180SMike Galbraith }
1395ef557180SMike Galbraith 
1396d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
13971da177e4SLinus Torvalds 			 struct work_struct *work)
13981da177e4SLinus Torvalds {
1399112202d9STejun Heo 	struct pool_workqueue *pwq;
1400c9178087STejun Heo 	struct worker_pool *last_pool;
14011e19ffc6STejun Heo 	struct list_head *worklist;
14028a2e8e5dSTejun Heo 	unsigned int work_flags;
1403b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
14048930cabaSTejun Heo 
14058930cabaSTejun Heo 	/*
14068930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
14078930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
14088930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
14098930cabaSTejun Heo 	 * happen with IRQ disabled.
14108930cabaSTejun Heo 	 */
14118e8eb730SFrederic Weisbecker 	lockdep_assert_irqs_disabled();
14121da177e4SLinus Torvalds 
1413dc186ad7SThomas Gleixner 	debug_work_activate(work);
14141e19ffc6STejun Heo 
14159ef28a73SLi Bin 	/* if draining, only works from the same workqueue are allowed */
1416618b01ebSTejun Heo 	if (unlikely(wq->flags & __WQ_DRAINING) &&
1417c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
1418e41e704bSTejun Heo 		return;
14199e8cd2f5STejun Heo retry:
1420df2d5ae4STejun Heo 	if (req_cpu == WORK_CPU_UNBOUND)
1421ef557180SMike Galbraith 		cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1422df2d5ae4STejun Heo 
1423df2d5ae4STejun Heo 	/* pwq which will be used unless @work is executing elsewhere */
1424df2d5ae4STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
1425c9178087STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1426df2d5ae4STejun Heo 	else
1427df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1428f3421797STejun Heo 
142918aa9effSTejun Heo 	/*
1430c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1431c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1432c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
143318aa9effSTejun Heo 	 */
1434c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1435112202d9STejun Heo 	if (last_pool && last_pool != pwq->pool) {
143618aa9effSTejun Heo 		struct worker *worker;
143718aa9effSTejun Heo 
1438d565ed63STejun Heo 		spin_lock(&last_pool->lock);
143918aa9effSTejun Heo 
1440c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
144118aa9effSTejun Heo 
1442112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1443c9178087STejun Heo 			pwq = worker->current_pwq;
14448594fadeSLai Jiangshan 		} else {
144518aa9effSTejun Heo 			/* meh... not running there, queue here */
1446d565ed63STejun Heo 			spin_unlock(&last_pool->lock);
1447112202d9STejun Heo 			spin_lock(&pwq->pool->lock);
144818aa9effSTejun Heo 		}
14498930cabaSTejun Heo 	} else {
1450112202d9STejun Heo 		spin_lock(&pwq->pool->lock);
14518930cabaSTejun Heo 	}
1452502ca9d8STejun Heo 
14539e8cd2f5STejun Heo 	/*
14549e8cd2f5STejun Heo 	 * pwq is determined and locked.  For unbound pools, we could have
14559e8cd2f5STejun Heo 	 * raced with pwq release and it could already be dead.  If its
14569e8cd2f5STejun Heo 	 * refcnt is zero, repeat pwq selection.  Note that pwqs never die
1457df2d5ae4STejun Heo 	 * without another pwq replacing it in the numa_pwq_tbl or while
1458df2d5ae4STejun Heo 	 * work items are executing on it, so the retrying is guaranteed to
14599e8cd2f5STejun Heo 	 * make forward-progress.
14609e8cd2f5STejun Heo 	 */
14619e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
14629e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
14639e8cd2f5STejun Heo 			spin_unlock(&pwq->pool->lock);
14649e8cd2f5STejun Heo 			cpu_relax();
14659e8cd2f5STejun Heo 			goto retry;
14669e8cd2f5STejun Heo 		}
14679e8cd2f5STejun Heo 		/* oops */
14689e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
14699e8cd2f5STejun Heo 			  wq->name, cpu);
14709e8cd2f5STejun Heo 	}
14719e8cd2f5STejun Heo 
1472112202d9STejun Heo 	/* pwq determined, queue */
1473112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1474502ca9d8STejun Heo 
1475f5b2552bSDan Carpenter 	if (WARN_ON(!list_empty(&work->entry))) {
1476112202d9STejun Heo 		spin_unlock(&pwq->pool->lock);
1477f5b2552bSDan Carpenter 		return;
1478f5b2552bSDan Carpenter 	}
14791e19ffc6STejun Heo 
1480112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1481112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
14821e19ffc6STejun Heo 
1483112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1484cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1485112202d9STejun Heo 		pwq->nr_active++;
1486112202d9STejun Heo 		worklist = &pwq->pool->worklist;
148782607adcSTejun Heo 		if (list_empty(worklist))
148882607adcSTejun Heo 			pwq->pool->watchdog_ts = jiffies;
14898a2e8e5dSTejun Heo 	} else {
14908a2e8e5dSTejun Heo 		work_flags |= WORK_STRUCT_DELAYED;
1491112202d9STejun Heo 		worklist = &pwq->delayed_works;
14928a2e8e5dSTejun Heo 	}
14931e19ffc6STejun Heo 
1494112202d9STejun Heo 	insert_work(pwq, work, worklist, work_flags);
14951e19ffc6STejun Heo 
1496112202d9STejun Heo 	spin_unlock(&pwq->pool->lock);
14971da177e4SLinus Torvalds }
14981da177e4SLinus Torvalds 
14990fcb78c2SRolf Eike Beer /**
1500c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1501c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1502c1a220e7SZhang Rui  * @wq: workqueue to use
1503c1a220e7SZhang Rui  * @work: work to queue
1504c1a220e7SZhang Rui  *
1505c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1506c1a220e7SZhang Rui  * can't go away.
1507d185af30SYacine Belkadi  *
1508d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
1509c1a220e7SZhang Rui  */
1510d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1511d4283e93STejun Heo 		   struct work_struct *work)
1512c1a220e7SZhang Rui {
1513d4283e93STejun Heo 	bool ret = false;
15148930cabaSTejun Heo 	unsigned long flags;
15158930cabaSTejun Heo 
15168930cabaSTejun Heo 	local_irq_save(flags);
1517c1a220e7SZhang Rui 
151822df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
15194690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1520d4283e93STejun Heo 		ret = true;
1521c1a220e7SZhang Rui 	}
15228930cabaSTejun Heo 
15238930cabaSTejun Heo 	local_irq_restore(flags);
1524c1a220e7SZhang Rui 	return ret;
1525c1a220e7SZhang Rui }
1526ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1527c1a220e7SZhang Rui 
15288204e0c1SAlexander Duyck /**
15298204e0c1SAlexander Duyck  * workqueue_select_cpu_near - Select a CPU based on NUMA node
15308204e0c1SAlexander Duyck  * @node: NUMA node ID that we want to select a CPU from
15318204e0c1SAlexander Duyck  *
15328204e0c1SAlexander Duyck  * This function will attempt to find a "random" cpu available on a given
15338204e0c1SAlexander Duyck  * node. If there are no CPUs available on the given node it will return
15348204e0c1SAlexander Duyck  * WORK_CPU_UNBOUND indicating that we should just schedule to any
15358204e0c1SAlexander Duyck  * available CPU if we need to schedule this work.
15368204e0c1SAlexander Duyck  */
15378204e0c1SAlexander Duyck static int workqueue_select_cpu_near(int node)
15388204e0c1SAlexander Duyck {
15398204e0c1SAlexander Duyck 	int cpu;
15408204e0c1SAlexander Duyck 
15418204e0c1SAlexander Duyck 	/* No point in doing this if NUMA isn't enabled for workqueues */
15428204e0c1SAlexander Duyck 	if (!wq_numa_enabled)
15438204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
15448204e0c1SAlexander Duyck 
15458204e0c1SAlexander Duyck 	/* Delay binding to CPU if node is not valid or online */
15468204e0c1SAlexander Duyck 	if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
15478204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
15488204e0c1SAlexander Duyck 
15498204e0c1SAlexander Duyck 	/* Use local node/cpu if we are already there */
15508204e0c1SAlexander Duyck 	cpu = raw_smp_processor_id();
15518204e0c1SAlexander Duyck 	if (node == cpu_to_node(cpu))
15528204e0c1SAlexander Duyck 		return cpu;
15538204e0c1SAlexander Duyck 
15548204e0c1SAlexander Duyck 	/* Use "random" otherwise know as "first" online CPU of node */
15558204e0c1SAlexander Duyck 	cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
15568204e0c1SAlexander Duyck 
15578204e0c1SAlexander Duyck 	/* If CPU is valid return that, otherwise just defer */
15588204e0c1SAlexander Duyck 	return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
15598204e0c1SAlexander Duyck }
15608204e0c1SAlexander Duyck 
15618204e0c1SAlexander Duyck /**
15628204e0c1SAlexander Duyck  * queue_work_node - queue work on a "random" cpu for a given NUMA node
15638204e0c1SAlexander Duyck  * @node: NUMA node that we are targeting the work for
15648204e0c1SAlexander Duyck  * @wq: workqueue to use
15658204e0c1SAlexander Duyck  * @work: work to queue
15668204e0c1SAlexander Duyck  *
15678204e0c1SAlexander Duyck  * We queue the work to a "random" CPU within a given NUMA node. The basic
15688204e0c1SAlexander Duyck  * idea here is to provide a way to somehow associate work with a given
15698204e0c1SAlexander Duyck  * NUMA node.
15708204e0c1SAlexander Duyck  *
15718204e0c1SAlexander Duyck  * This function will only make a best effort attempt at getting this onto
15728204e0c1SAlexander Duyck  * the right NUMA node. If no node is requested or the requested node is
15738204e0c1SAlexander Duyck  * offline then we just fall back to standard queue_work behavior.
15748204e0c1SAlexander Duyck  *
15758204e0c1SAlexander Duyck  * Currently the "random" CPU ends up being the first available CPU in the
15768204e0c1SAlexander Duyck  * intersection of cpu_online_mask and the cpumask of the node, unless we
15778204e0c1SAlexander Duyck  * are running on the node. In that case we just use the current CPU.
15788204e0c1SAlexander Duyck  *
15798204e0c1SAlexander Duyck  * Return: %false if @work was already on a queue, %true otherwise.
15808204e0c1SAlexander Duyck  */
15818204e0c1SAlexander Duyck bool queue_work_node(int node, struct workqueue_struct *wq,
15828204e0c1SAlexander Duyck 		     struct work_struct *work)
15838204e0c1SAlexander Duyck {
15848204e0c1SAlexander Duyck 	unsigned long flags;
15858204e0c1SAlexander Duyck 	bool ret = false;
15868204e0c1SAlexander Duyck 
15878204e0c1SAlexander Duyck 	/*
15888204e0c1SAlexander Duyck 	 * This current implementation is specific to unbound workqueues.
15898204e0c1SAlexander Duyck 	 * Specifically we only return the first available CPU for a given
15908204e0c1SAlexander Duyck 	 * node instead of cycling through individual CPUs within the node.
15918204e0c1SAlexander Duyck 	 *
15928204e0c1SAlexander Duyck 	 * If this is used with a per-cpu workqueue then the logic in
15938204e0c1SAlexander Duyck 	 * workqueue_select_cpu_near would need to be updated to allow for
15948204e0c1SAlexander Duyck 	 * some round robin type logic.
15958204e0c1SAlexander Duyck 	 */
15968204e0c1SAlexander Duyck 	WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
15978204e0c1SAlexander Duyck 
15988204e0c1SAlexander Duyck 	local_irq_save(flags);
15998204e0c1SAlexander Duyck 
16008204e0c1SAlexander Duyck 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
16018204e0c1SAlexander Duyck 		int cpu = workqueue_select_cpu_near(node);
16028204e0c1SAlexander Duyck 
16038204e0c1SAlexander Duyck 		__queue_work(cpu, wq, work);
16048204e0c1SAlexander Duyck 		ret = true;
16058204e0c1SAlexander Duyck 	}
16068204e0c1SAlexander Duyck 
16078204e0c1SAlexander Duyck 	local_irq_restore(flags);
16088204e0c1SAlexander Duyck 	return ret;
16098204e0c1SAlexander Duyck }
16108204e0c1SAlexander Duyck EXPORT_SYMBOL_GPL(queue_work_node);
16118204e0c1SAlexander Duyck 
16128c20feb6SKees Cook void delayed_work_timer_fn(struct timer_list *t)
16131da177e4SLinus Torvalds {
16148c20feb6SKees Cook 	struct delayed_work *dwork = from_timer(dwork, t, timer);
16151da177e4SLinus Torvalds 
1616e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
161760c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
16181da177e4SLinus Torvalds }
16191438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
16201da177e4SLinus Torvalds 
16217beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
162252bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
16231da177e4SLinus Torvalds {
16247beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
16257beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
16261da177e4SLinus Torvalds 
1627637fdbaeSTejun Heo 	WARN_ON_ONCE(!wq);
1628841b86f3SKees Cook 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
1629fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1630fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
16317beb2edfSTejun Heo 
16328852aac2STejun Heo 	/*
16338852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
16348852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
16358852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
16368852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
16378852aac2STejun Heo 	 */
16388852aac2STejun Heo 	if (!delay) {
16398852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
16408852aac2STejun Heo 		return;
16418852aac2STejun Heo 	}
16428852aac2STejun Heo 
164360c057bcSLai Jiangshan 	dwork->wq = wq;
16441265057fSTejun Heo 	dwork->cpu = cpu;
16457beb2edfSTejun Heo 	timer->expires = jiffies + delay;
16467beb2edfSTejun Heo 
1647041bd12eSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
16487beb2edfSTejun Heo 		add_timer_on(timer, cpu);
1649041bd12eSTejun Heo 	else
1650041bd12eSTejun Heo 		add_timer(timer);
16517beb2edfSTejun Heo }
16521da177e4SLinus Torvalds 
16530fcb78c2SRolf Eike Beer /**
16540fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
16550fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
16560fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1657af9997e4SRandy Dunlap  * @dwork: work to queue
16580fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
16590fcb78c2SRolf Eike Beer  *
1660d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
1661715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1662715f1300STejun Heo  * execution.
16630fcb78c2SRolf Eike Beer  */
1664d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
166552bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
16667a6bc1cdSVenkatesh Pallipadi {
166752bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1668d4283e93STejun Heo 	bool ret = false;
16698930cabaSTejun Heo 	unsigned long flags;
16708930cabaSTejun Heo 
16718930cabaSTejun Heo 	/* read the comment in __queue_work() */
16728930cabaSTejun Heo 	local_irq_save(flags);
16737a6bc1cdSVenkatesh Pallipadi 
167422df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
16757beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1676d4283e93STejun Heo 		ret = true;
16777a6bc1cdSVenkatesh Pallipadi 	}
16788930cabaSTejun Heo 
16798930cabaSTejun Heo 	local_irq_restore(flags);
16807a6bc1cdSVenkatesh Pallipadi 	return ret;
16817a6bc1cdSVenkatesh Pallipadi }
1682ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
16831da177e4SLinus Torvalds 
1684c8e55f36STejun Heo /**
16858376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
16868376fe22STejun Heo  * @cpu: CPU number to execute work on
16878376fe22STejun Heo  * @wq: workqueue to use
16888376fe22STejun Heo  * @dwork: work to queue
16898376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
16908376fe22STejun Heo  *
16918376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
16928376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
16938376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
16948376fe22STejun Heo  * current state.
16958376fe22STejun Heo  *
1696d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
16978376fe22STejun Heo  * pending and its timer was modified.
16988376fe22STejun Heo  *
1699e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
17008376fe22STejun Heo  * See try_to_grab_pending() for details.
17018376fe22STejun Heo  */
17028376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
17038376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
17048376fe22STejun Heo {
17058376fe22STejun Heo 	unsigned long flags;
17068376fe22STejun Heo 	int ret;
17078376fe22STejun Heo 
17088376fe22STejun Heo 	do {
17098376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
17108376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
17118376fe22STejun Heo 
17128376fe22STejun Heo 	if (likely(ret >= 0)) {
17138376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
17148376fe22STejun Heo 		local_irq_restore(flags);
17158376fe22STejun Heo 	}
17168376fe22STejun Heo 
17178376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
17188376fe22STejun Heo 	return ret;
17198376fe22STejun Heo }
17208376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
17218376fe22STejun Heo 
172205f0fe6bSTejun Heo static void rcu_work_rcufn(struct rcu_head *rcu)
172305f0fe6bSTejun Heo {
172405f0fe6bSTejun Heo 	struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
172505f0fe6bSTejun Heo 
172605f0fe6bSTejun Heo 	/* read the comment in __queue_work() */
172705f0fe6bSTejun Heo 	local_irq_disable();
172805f0fe6bSTejun Heo 	__queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
172905f0fe6bSTejun Heo 	local_irq_enable();
173005f0fe6bSTejun Heo }
173105f0fe6bSTejun Heo 
173205f0fe6bSTejun Heo /**
173305f0fe6bSTejun Heo  * queue_rcu_work - queue work after a RCU grace period
173405f0fe6bSTejun Heo  * @wq: workqueue to use
173505f0fe6bSTejun Heo  * @rwork: work to queue
173605f0fe6bSTejun Heo  *
173705f0fe6bSTejun Heo  * Return: %false if @rwork was already pending, %true otherwise.  Note
173805f0fe6bSTejun Heo  * that a full RCU grace period is guaranteed only after a %true return.
1739bf393fd4SBart Van Assche  * While @rwork is guaranteed to be executed after a %false return, the
174005f0fe6bSTejun Heo  * execution may happen before a full RCU grace period has passed.
174105f0fe6bSTejun Heo  */
174205f0fe6bSTejun Heo bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
174305f0fe6bSTejun Heo {
174405f0fe6bSTejun Heo 	struct work_struct *work = &rwork->work;
174505f0fe6bSTejun Heo 
174605f0fe6bSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
174705f0fe6bSTejun Heo 		rwork->wq = wq;
174805f0fe6bSTejun Heo 		call_rcu(&rwork->rcu, rcu_work_rcufn);
174905f0fe6bSTejun Heo 		return true;
175005f0fe6bSTejun Heo 	}
175105f0fe6bSTejun Heo 
175205f0fe6bSTejun Heo 	return false;
175305f0fe6bSTejun Heo }
175405f0fe6bSTejun Heo EXPORT_SYMBOL(queue_rcu_work);
175505f0fe6bSTejun Heo 
17568376fe22STejun Heo /**
1757c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1758c8e55f36STejun Heo  * @worker: worker which is entering idle state
1759c8e55f36STejun Heo  *
1760c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1761c8e55f36STejun Heo  * necessary.
1762c8e55f36STejun Heo  *
1763c8e55f36STejun Heo  * LOCKING:
1764d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1765c8e55f36STejun Heo  */
1766c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
17671da177e4SLinus Torvalds {
1768bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1769c8e55f36STejun Heo 
17706183c009STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
17716183c009STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
17726183c009STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
17736183c009STejun Heo 		return;
1774c8e55f36STejun Heo 
1775051e1850SLai Jiangshan 	/* can't use worker_set_flags(), also called from create_worker() */
1776cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1777bd7bdd43STejun Heo 	pool->nr_idle++;
1778e22bee78STejun Heo 	worker->last_active = jiffies;
1779c8e55f36STejun Heo 
1780c8e55f36STejun Heo 	/* idle_list is LIFO */
1781bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1782db7bccf4STejun Heo 
178363d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1784628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1785cb444766STejun Heo 
1786544ecf31STejun Heo 	/*
1787e8b3f8dbSLai Jiangshan 	 * Sanity check nr_running.  Because unbind_workers() releases
1788d565ed63STejun Heo 	 * pool->lock between setting %WORKER_UNBOUND and zapping
1789628c78e7STejun Heo 	 * nr_running, the warning may trigger spuriously.  Check iff
1790628c78e7STejun Heo 	 * unbind is not in progress.
1791544ecf31STejun Heo 	 */
179224647570STejun Heo 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1793bd7bdd43STejun Heo 		     pool->nr_workers == pool->nr_idle &&
1794e19e397aSTejun Heo 		     atomic_read(&pool->nr_running));
1795c8e55f36STejun Heo }
1796c8e55f36STejun Heo 
1797c8e55f36STejun Heo /**
1798c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1799c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1800c8e55f36STejun Heo  *
1801c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1802c8e55f36STejun Heo  *
1803c8e55f36STejun Heo  * LOCKING:
1804d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1805c8e55f36STejun Heo  */
1806c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1807c8e55f36STejun Heo {
1808bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1809c8e55f36STejun Heo 
18106183c009STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
18116183c009STejun Heo 		return;
1812d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1813bd7bdd43STejun Heo 	pool->nr_idle--;
1814c8e55f36STejun Heo 	list_del_init(&worker->entry);
1815c8e55f36STejun Heo }
1816c8e55f36STejun Heo 
1817f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
1818c34056a3STejun Heo {
1819c34056a3STejun Heo 	struct worker *worker;
1820c34056a3STejun Heo 
1821f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1822c8e55f36STejun Heo 	if (worker) {
1823c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1824affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
1825da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
1826e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1827e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1828c8e55f36STejun Heo 	}
1829c34056a3STejun Heo 	return worker;
1830c34056a3STejun Heo }
1831c34056a3STejun Heo 
1832c34056a3STejun Heo /**
18334736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
18344736cbf7SLai Jiangshan  * @worker: worker to be attached
18354736cbf7SLai Jiangshan  * @pool: the target pool
18364736cbf7SLai Jiangshan  *
18374736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
18384736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
18394736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
18404736cbf7SLai Jiangshan  */
18414736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
18424736cbf7SLai Jiangshan 				   struct worker_pool *pool)
18434736cbf7SLai Jiangshan {
18441258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
18454736cbf7SLai Jiangshan 
18464736cbf7SLai Jiangshan 	/*
18474736cbf7SLai Jiangshan 	 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
18484736cbf7SLai Jiangshan 	 * online CPUs.  It'll be re-applied when any of the CPUs come up.
18494736cbf7SLai Jiangshan 	 */
18504736cbf7SLai Jiangshan 	set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
18514736cbf7SLai Jiangshan 
18524736cbf7SLai Jiangshan 	/*
18531258fae7STejun Heo 	 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
18541258fae7STejun Heo 	 * stable across this function.  See the comments above the flag
18551258fae7STejun Heo 	 * definition for details.
18564736cbf7SLai Jiangshan 	 */
18574736cbf7SLai Jiangshan 	if (pool->flags & POOL_DISASSOCIATED)
18584736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
18594736cbf7SLai Jiangshan 
18604736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
1861a2d812a2STejun Heo 	worker->pool = pool;
18624736cbf7SLai Jiangshan 
18631258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
18644736cbf7SLai Jiangshan }
18654736cbf7SLai Jiangshan 
18664736cbf7SLai Jiangshan /**
186760f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
186860f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
186960f5a4bcSLai Jiangshan  *
18704736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
18714736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
18724736cbf7SLai Jiangshan  * other reference to the pool.
187360f5a4bcSLai Jiangshan  */
1874a2d812a2STejun Heo static void worker_detach_from_pool(struct worker *worker)
187560f5a4bcSLai Jiangshan {
1876a2d812a2STejun Heo 	struct worker_pool *pool = worker->pool;
187760f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
187860f5a4bcSLai Jiangshan 
18791258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
1880a2d812a2STejun Heo 
1881da028469SLai Jiangshan 	list_del(&worker->node);
1882a2d812a2STejun Heo 	worker->pool = NULL;
1883a2d812a2STejun Heo 
1884da028469SLai Jiangshan 	if (list_empty(&pool->workers))
188560f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
18861258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
188760f5a4bcSLai Jiangshan 
1888b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
1889b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1890b62c0751SLai Jiangshan 
189160f5a4bcSLai Jiangshan 	if (detach_completion)
189260f5a4bcSLai Jiangshan 		complete(detach_completion);
189360f5a4bcSLai Jiangshan }
189460f5a4bcSLai Jiangshan 
189560f5a4bcSLai Jiangshan /**
1896c34056a3STejun Heo  * create_worker - create a new workqueue worker
189763d95a91STejun Heo  * @pool: pool the new worker will belong to
1898c34056a3STejun Heo  *
1899051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
1900c34056a3STejun Heo  *
1901c34056a3STejun Heo  * CONTEXT:
1902c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1903c34056a3STejun Heo  *
1904d185af30SYacine Belkadi  * Return:
1905c34056a3STejun Heo  * Pointer to the newly created worker.
1906c34056a3STejun Heo  */
1907bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1908c34056a3STejun Heo {
1909c34056a3STejun Heo 	struct worker *worker = NULL;
1910f3421797STejun Heo 	int id = -1;
1911e3c916a4STejun Heo 	char id_buf[16];
1912c34056a3STejun Heo 
19137cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
19147cda9aaeSLai Jiangshan 	id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL);
1915822d8405STejun Heo 	if (id < 0)
1916c34056a3STejun Heo 		goto fail;
1917c34056a3STejun Heo 
1918f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
1919c34056a3STejun Heo 	if (!worker)
1920c34056a3STejun Heo 		goto fail;
1921c34056a3STejun Heo 
1922c34056a3STejun Heo 	worker->id = id;
1923c34056a3STejun Heo 
192429c91e99STejun Heo 	if (pool->cpu >= 0)
1925e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1926e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
1927f3421797STejun Heo 	else
1928e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1929e3c916a4STejun Heo 
1930f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1931e3c916a4STejun Heo 					      "kworker/%s", id_buf);
1932c34056a3STejun Heo 	if (IS_ERR(worker->task))
1933c34056a3STejun Heo 		goto fail;
1934c34056a3STejun Heo 
193591151228SOleg Nesterov 	set_user_nice(worker->task, pool->attrs->nice);
193625834c73SPeter Zijlstra 	kthread_bind_mask(worker->task, pool->attrs->cpumask);
193791151228SOleg Nesterov 
1938da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
19394736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
1940822d8405STejun Heo 
1941051e1850SLai Jiangshan 	/* start the newly created worker */
1942051e1850SLai Jiangshan 	spin_lock_irq(&pool->lock);
1943051e1850SLai Jiangshan 	worker->pool->nr_workers++;
1944051e1850SLai Jiangshan 	worker_enter_idle(worker);
1945051e1850SLai Jiangshan 	wake_up_process(worker->task);
1946051e1850SLai Jiangshan 	spin_unlock_irq(&pool->lock);
1947051e1850SLai Jiangshan 
1948c34056a3STejun Heo 	return worker;
1949822d8405STejun Heo 
1950c34056a3STejun Heo fail:
19519625ab17SLai Jiangshan 	if (id >= 0)
19527cda9aaeSLai Jiangshan 		ida_simple_remove(&pool->worker_ida, id);
1953c34056a3STejun Heo 	kfree(worker);
1954c34056a3STejun Heo 	return NULL;
1955c34056a3STejun Heo }
1956c34056a3STejun Heo 
1957c34056a3STejun Heo /**
1958c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1959c34056a3STejun Heo  * @worker: worker to be destroyed
1960c34056a3STejun Heo  *
196173eb7fe7SLai Jiangshan  * Destroy @worker and adjust @pool stats accordingly.  The worker should
196273eb7fe7SLai Jiangshan  * be idle.
1963c8e55f36STejun Heo  *
1964c8e55f36STejun Heo  * CONTEXT:
196560f5a4bcSLai Jiangshan  * spin_lock_irq(pool->lock).
1966c34056a3STejun Heo  */
1967c34056a3STejun Heo static void destroy_worker(struct worker *worker)
1968c34056a3STejun Heo {
1969bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1970c34056a3STejun Heo 
1971cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
1972cd549687STejun Heo 
1973c34056a3STejun Heo 	/* sanity check frenzy */
19746183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
197573eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
197673eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
19776183c009STejun Heo 		return;
1978c34056a3STejun Heo 
1979bd7bdd43STejun Heo 	pool->nr_workers--;
1980bd7bdd43STejun Heo 	pool->nr_idle--;
1981c8e55f36STejun Heo 
1982c8e55f36STejun Heo 	list_del_init(&worker->entry);
1983cb444766STejun Heo 	worker->flags |= WORKER_DIE;
198460f5a4bcSLai Jiangshan 	wake_up_process(worker->task);
1985c34056a3STejun Heo }
1986c34056a3STejun Heo 
198732a6c723SKees Cook static void idle_worker_timeout(struct timer_list *t)
1988e22bee78STejun Heo {
198932a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, idle_timer);
1990e22bee78STejun Heo 
1991d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1992e22bee78STejun Heo 
19933347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
1994e22bee78STejun Heo 		struct worker *worker;
1995e22bee78STejun Heo 		unsigned long expires;
1996e22bee78STejun Heo 
1997e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
199863d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1999e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2000e22bee78STejun Heo 
20013347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
200263d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
20033347fc9fSLai Jiangshan 			break;
2004e22bee78STejun Heo 		}
20053347fc9fSLai Jiangshan 
20063347fc9fSLai Jiangshan 		destroy_worker(worker);
2007e22bee78STejun Heo 	}
2008e22bee78STejun Heo 
2009d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2010e22bee78STejun Heo }
2011e22bee78STejun Heo 
2012493a1724STejun Heo static void send_mayday(struct work_struct *work)
2013e22bee78STejun Heo {
2014112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2015112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
2016493a1724STejun Heo 
20172e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
2018e22bee78STejun Heo 
2019493008a8STejun Heo 	if (!wq->rescuer)
2020493a1724STejun Heo 		return;
2021e22bee78STejun Heo 
2022e22bee78STejun Heo 	/* mayday mayday mayday */
2023493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
202477668c8bSLai Jiangshan 		/*
202577668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
202677668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
202777668c8bSLai Jiangshan 		 * rescuer is done with it.
202877668c8bSLai Jiangshan 		 */
202977668c8bSLai Jiangshan 		get_pwq(pwq);
2030493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
2031e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
2032493a1724STejun Heo 	}
2033e22bee78STejun Heo }
2034e22bee78STejun Heo 
203532a6c723SKees Cook static void pool_mayday_timeout(struct timer_list *t)
2036e22bee78STejun Heo {
203732a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2038e22bee78STejun Heo 	struct work_struct *work;
2039e22bee78STejun Heo 
2040b2d82909STejun Heo 	spin_lock_irq(&pool->lock);
2041b2d82909STejun Heo 	spin_lock(&wq_mayday_lock);		/* for wq->maydays */
2042e22bee78STejun Heo 
204363d95a91STejun Heo 	if (need_to_create_worker(pool)) {
2044e22bee78STejun Heo 		/*
2045e22bee78STejun Heo 		 * We've been trying to create a new worker but
2046e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
2047e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
2048e22bee78STejun Heo 		 * rescuers.
2049e22bee78STejun Heo 		 */
205063d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
2051e22bee78STejun Heo 			send_mayday(work);
2052e22bee78STejun Heo 	}
2053e22bee78STejun Heo 
2054b2d82909STejun Heo 	spin_unlock(&wq_mayday_lock);
2055b2d82909STejun Heo 	spin_unlock_irq(&pool->lock);
2056e22bee78STejun Heo 
205763d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2058e22bee78STejun Heo }
2059e22bee78STejun Heo 
2060e22bee78STejun Heo /**
2061e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
206263d95a91STejun Heo  * @pool: pool to create a new worker for
2063e22bee78STejun Heo  *
206463d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
2065e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
2066e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
206763d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
2068e22bee78STejun Heo  * possible allocation deadlock.
2069e22bee78STejun Heo  *
2070c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
2071c5aa87bbSTejun Heo  * may_start_working() %true.
2072e22bee78STejun Heo  *
2073e22bee78STejun Heo  * LOCKING:
2074d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2075e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
2076e22bee78STejun Heo  * manager.
2077e22bee78STejun Heo  */
207829187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
2079d565ed63STejun Heo __releases(&pool->lock)
2080d565ed63STejun Heo __acquires(&pool->lock)
2081e22bee78STejun Heo {
2082e22bee78STejun Heo restart:
2083d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
20849f9c2364STejun Heo 
2085e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
208663d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2087e22bee78STejun Heo 
2088e22bee78STejun Heo 	while (true) {
2089051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
2090e22bee78STejun Heo 			break;
2091e22bee78STejun Heo 
2092e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
20939f9c2364STejun Heo 
209463d95a91STejun Heo 		if (!need_to_create_worker(pool))
2095e22bee78STejun Heo 			break;
2096e22bee78STejun Heo 	}
2097e22bee78STejun Heo 
209863d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
2099d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2100051e1850SLai Jiangshan 	/*
2101051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
2102051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
2103051e1850SLai Jiangshan 	 * already become busy.
2104051e1850SLai Jiangshan 	 */
210563d95a91STejun Heo 	if (need_to_create_worker(pool))
2106e22bee78STejun Heo 		goto restart;
2107e22bee78STejun Heo }
2108e22bee78STejun Heo 
2109e22bee78STejun Heo /**
2110e22bee78STejun Heo  * manage_workers - manage worker pool
2111e22bee78STejun Heo  * @worker: self
2112e22bee78STejun Heo  *
2113706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
2114e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2115706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2116e22bee78STejun Heo  *
2117e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2118e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2119e22bee78STejun Heo  * and may_start_working() is true.
2120e22bee78STejun Heo  *
2121e22bee78STejun Heo  * CONTEXT:
2122d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2123e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2124e22bee78STejun Heo  *
2125d185af30SYacine Belkadi  * Return:
212629187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
212729187a9eSTejun Heo  * start processing works, %true if management function was performed and
212829187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
212929187a9eSTejun Heo  * no longer be true.
2130e22bee78STejun Heo  */
2131e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2132e22bee78STejun Heo {
213363d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2134e22bee78STejun Heo 
2135692b4825STejun Heo 	if (pool->flags & POOL_MANAGER_ACTIVE)
213629187a9eSTejun Heo 		return false;
2137692b4825STejun Heo 
2138692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
21392607d7a6STejun Heo 	pool->manager = worker;
2140e22bee78STejun Heo 
214129187a9eSTejun Heo 	maybe_create_worker(pool);
2142e22bee78STejun Heo 
21432607d7a6STejun Heo 	pool->manager = NULL;
2144692b4825STejun Heo 	pool->flags &= ~POOL_MANAGER_ACTIVE;
2145692b4825STejun Heo 	wake_up(&wq_manager_wait);
214629187a9eSTejun Heo 	return true;
2147e22bee78STejun Heo }
2148e22bee78STejun Heo 
2149a62428c0STejun Heo /**
2150a62428c0STejun Heo  * process_one_work - process single work
2151c34056a3STejun Heo  * @worker: self
2152a62428c0STejun Heo  * @work: work to process
2153a62428c0STejun Heo  *
2154a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2155a62428c0STejun Heo  * process a single work including synchronization against and
2156a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2157a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2158a62428c0STejun Heo  * call this function to process a work.
2159a62428c0STejun Heo  *
2160a62428c0STejun Heo  * CONTEXT:
2161d565ed63STejun Heo  * spin_lock_irq(pool->lock) which is released and regrabbed.
2162a62428c0STejun Heo  */
2163c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2164d565ed63STejun Heo __releases(&pool->lock)
2165d565ed63STejun Heo __acquires(&pool->lock)
21661da177e4SLinus Torvalds {
2167112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2168bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2169112202d9STejun Heo 	bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
217073f53c4aSTejun Heo 	int work_color;
21717e11629dSTejun Heo 	struct worker *collision;
21724e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
21734e6045f1SJohannes Berg 	/*
2174a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2175a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2176a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2177a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2178a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
21794e6045f1SJohannes Berg 	 */
21804d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
21814d82a1deSPeter Zijlstra 
21824d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
21834e6045f1SJohannes Berg #endif
2184807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
218585327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2186ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
218725511a47STejun Heo 
21887e11629dSTejun Heo 	/*
21897e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
21907e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
21917e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
21927e11629dSTejun Heo 	 * currently executing one.
21937e11629dSTejun Heo 	 */
2194c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
21957e11629dSTejun Heo 	if (unlikely(collision)) {
21967e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
21977e11629dSTejun Heo 		return;
21987e11629dSTejun Heo 	}
21991da177e4SLinus Torvalds 
22008930cabaSTejun Heo 	/* claim and dequeue */
22011da177e4SLinus Torvalds 	debug_work_deactivate(work);
2202c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2203c34056a3STejun Heo 	worker->current_work = work;
2204a2c1c57bSTejun Heo 	worker->current_func = work->func;
2205112202d9STejun Heo 	worker->current_pwq = pwq;
220673f53c4aSTejun Heo 	work_color = get_work_color(work);
22077a22ad75STejun Heo 
22088bf89593STejun Heo 	/*
22098bf89593STejun Heo 	 * Record wq name for cmdline and debug reporting, may get
22108bf89593STejun Heo 	 * overridden through set_worker_desc().
22118bf89593STejun Heo 	 */
22128bf89593STejun Heo 	strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
22138bf89593STejun Heo 
2214a62428c0STejun Heo 	list_del_init(&work->entry);
2215a62428c0STejun Heo 
2216649027d7STejun Heo 	/*
2217228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
2218228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
2219228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
2220228f1d00SLai Jiangshan 	 * execution of the pending work items.
2221fb0e7bebSTejun Heo 	 */
2222fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2223228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2224fb0e7bebSTejun Heo 
2225974271c4STejun Heo 	/*
2226a489a03eSLai Jiangshan 	 * Wake up another worker if necessary.  The condition is always
2227a489a03eSLai Jiangshan 	 * false for normal per-cpu workers since nr_running would always
2228a489a03eSLai Jiangshan 	 * be >= 1 at this point.  This is used to chain execution of the
2229a489a03eSLai Jiangshan 	 * pending work items for WORKER_NOT_RUNNING workers such as the
2230228f1d00SLai Jiangshan 	 * UNBOUND and CPU_INTENSIVE ones.
2231974271c4STejun Heo 	 */
2232a489a03eSLai Jiangshan 	if (need_more_worker(pool))
223363d95a91STejun Heo 		wake_up_worker(pool);
2234974271c4STejun Heo 
22358930cabaSTejun Heo 	/*
22367c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2237d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
223823657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
223923657bb1STejun Heo 	 * disabled.
22408930cabaSTejun Heo 	 */
22417c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
22421da177e4SLinus Torvalds 
2243d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2244365970a1SDavid Howells 
2245a1d14934SPeter Zijlstra 	lock_map_acquire(&pwq->wq->lockdep_map);
22463295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2247e6f3faa7SPeter Zijlstra 	/*
2248f52be570SPeter Zijlstra 	 * Strictly speaking we should mark the invariant state without holding
2249f52be570SPeter Zijlstra 	 * any locks, that is, before these two lock_map_acquire()'s.
2250e6f3faa7SPeter Zijlstra 	 *
2251e6f3faa7SPeter Zijlstra 	 * However, that would result in:
2252e6f3faa7SPeter Zijlstra 	 *
2253e6f3faa7SPeter Zijlstra 	 *   A(W1)
2254e6f3faa7SPeter Zijlstra 	 *   WFC(C)
2255e6f3faa7SPeter Zijlstra 	 *		A(W1)
2256e6f3faa7SPeter Zijlstra 	 *		C(C)
2257e6f3faa7SPeter Zijlstra 	 *
2258e6f3faa7SPeter Zijlstra 	 * Which would create W1->C->W1 dependencies, even though there is no
2259e6f3faa7SPeter Zijlstra 	 * actual deadlock possible. There are two solutions, using a
2260e6f3faa7SPeter Zijlstra 	 * read-recursive acquire on the work(queue) 'locks', but this will then
2261f52be570SPeter Zijlstra 	 * hit the lockdep limitation on recursive locks, or simply discard
2262e6f3faa7SPeter Zijlstra 	 * these locks.
2263e6f3faa7SPeter Zijlstra 	 *
2264e6f3faa7SPeter Zijlstra 	 * AFAICT there is no possible deadlock scenario between the
2265e6f3faa7SPeter Zijlstra 	 * flush_work() and complete() primitives (except for single-threaded
2266e6f3faa7SPeter Zijlstra 	 * workqueues), so hiding them isn't a problem.
2267e6f3faa7SPeter Zijlstra 	 */
2268f52be570SPeter Zijlstra 	lockdep_invariant_state(true);
2269e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2270a2c1c57bSTejun Heo 	worker->current_func(work);
2271e36c886aSArjan van de Ven 	/*
2272e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2273e36c886aSArjan van de Ven 	 * point will only record its address.
2274e36c886aSArjan van de Ven 	 */
2275e36c886aSArjan van de Ven 	trace_workqueue_execute_end(work);
22763295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2277112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
22781da177e4SLinus Torvalds 
2279d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2280044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2281044c782cSValentin Ilie 		       "     last function: %pf\n",
2282a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2283a2c1c57bSTejun Heo 		       worker->current_func);
2284d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2285d5abe669SPeter Zijlstra 		dump_stack();
2286d5abe669SPeter Zijlstra 	}
2287d5abe669SPeter Zijlstra 
2288b22ce278STejun Heo 	/*
2289b22ce278STejun Heo 	 * The following prevents a kworker from hogging CPU on !PREEMPT
2290b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
2291b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
2292b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
2293789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
2294789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
2295b22ce278STejun Heo 	 */
2296a7e6425eSPaul E. McKenney 	cond_resched();
2297b22ce278STejun Heo 
2298d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2299a62428c0STejun Heo 
2300fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2301fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2302fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2303fb0e7bebSTejun Heo 
23041b69ac6bSJohannes Weiner 	/* tag the worker for identification in schedule() */
23051b69ac6bSJohannes Weiner 	worker->last_func = worker->current_func;
23061b69ac6bSJohannes Weiner 
2307a62428c0STejun Heo 	/* we're done with it, release */
230842f8570fSSasha Levin 	hash_del(&worker->hentry);
2309c34056a3STejun Heo 	worker->current_work = NULL;
2310a2c1c57bSTejun Heo 	worker->current_func = NULL;
2311112202d9STejun Heo 	worker->current_pwq = NULL;
2312112202d9STejun Heo 	pwq_dec_nr_in_flight(pwq, work_color);
23131da177e4SLinus Torvalds }
23141da177e4SLinus Torvalds 
2315affee4b2STejun Heo /**
2316affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2317affee4b2STejun Heo  * @worker: self
2318affee4b2STejun Heo  *
2319affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2320affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2321affee4b2STejun Heo  * fetches a work from the top and executes it.
2322affee4b2STejun Heo  *
2323affee4b2STejun Heo  * CONTEXT:
2324d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2325affee4b2STejun Heo  * multiple times.
2326affee4b2STejun Heo  */
2327affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
23281da177e4SLinus Torvalds {
2329affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2330affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2331a62428c0STejun Heo 						struct work_struct, entry);
2332c34056a3STejun Heo 		process_one_work(worker, work);
2333a62428c0STejun Heo 	}
23341da177e4SLinus Torvalds }
23351da177e4SLinus Torvalds 
2336197f6accSTejun Heo static void set_pf_worker(bool val)
2337197f6accSTejun Heo {
2338197f6accSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2339197f6accSTejun Heo 	if (val)
2340197f6accSTejun Heo 		current->flags |= PF_WQ_WORKER;
2341197f6accSTejun Heo 	else
2342197f6accSTejun Heo 		current->flags &= ~PF_WQ_WORKER;
2343197f6accSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
2344197f6accSTejun Heo }
2345197f6accSTejun Heo 
23464690c4abSTejun Heo /**
23474690c4abSTejun Heo  * worker_thread - the worker thread function
2348c34056a3STejun Heo  * @__worker: self
23494690c4abSTejun Heo  *
2350c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2351c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2352c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2353c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2354c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
2355d185af30SYacine Belkadi  *
2356d185af30SYacine Belkadi  * Return: 0
23574690c4abSTejun Heo  */
2358c34056a3STejun Heo static int worker_thread(void *__worker)
23591da177e4SLinus Torvalds {
2360c34056a3STejun Heo 	struct worker *worker = __worker;
2361bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
23621da177e4SLinus Torvalds 
2363e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2364197f6accSTejun Heo 	set_pf_worker(true);
2365c8e55f36STejun Heo woke_up:
2366d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2367affee4b2STejun Heo 
2368a9ab775bSTejun Heo 	/* am I supposed to die? */
2369a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2370d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
2371a9ab775bSTejun Heo 		WARN_ON_ONCE(!list_empty(&worker->entry));
2372197f6accSTejun Heo 		set_pf_worker(false);
237360f5a4bcSLai Jiangshan 
237460f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
23757cda9aaeSLai Jiangshan 		ida_simple_remove(&pool->worker_ida, worker->id);
2376a2d812a2STejun Heo 		worker_detach_from_pool(worker);
237760f5a4bcSLai Jiangshan 		kfree(worker);
2378c8e55f36STejun Heo 		return 0;
2379c8e55f36STejun Heo 	}
2380c8e55f36STejun Heo 
2381c8e55f36STejun Heo 	worker_leave_idle(worker);
2382db7bccf4STejun Heo recheck:
2383e22bee78STejun Heo 	/* no more worker necessary? */
238463d95a91STejun Heo 	if (!need_more_worker(pool))
2385e22bee78STejun Heo 		goto sleep;
2386e22bee78STejun Heo 
2387e22bee78STejun Heo 	/* do we need to manage? */
238863d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2389e22bee78STejun Heo 		goto recheck;
2390e22bee78STejun Heo 
2391c8e55f36STejun Heo 	/*
2392c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2393c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2394c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2395c8e55f36STejun Heo 	 */
23966183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2397c8e55f36STejun Heo 
2398e22bee78STejun Heo 	/*
2399a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2400a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2401a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2402a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2403a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2404e22bee78STejun Heo 	 */
2405a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2406e22bee78STejun Heo 
2407e22bee78STejun Heo 	do {
2408affee4b2STejun Heo 		struct work_struct *work =
2409bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2410affee4b2STejun Heo 					 struct work_struct, entry);
2411affee4b2STejun Heo 
241282607adcSTejun Heo 		pool->watchdog_ts = jiffies;
241382607adcSTejun Heo 
2414c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2415affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2416affee4b2STejun Heo 			process_one_work(worker, work);
2417affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2418affee4b2STejun Heo 				process_scheduled_works(worker);
2419affee4b2STejun Heo 		} else {
2420c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2421affee4b2STejun Heo 			process_scheduled_works(worker);
2422affee4b2STejun Heo 		}
242363d95a91STejun Heo 	} while (keep_working(pool));
2424affee4b2STejun Heo 
2425228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
2426d313dd85STejun Heo sleep:
2427c8e55f36STejun Heo 	/*
2428d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2429d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2430d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2431d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2432d565ed63STejun Heo 	 * event.
2433c8e55f36STejun Heo 	 */
2434c8e55f36STejun Heo 	worker_enter_idle(worker);
2435c5a94a61SPeter Zijlstra 	__set_current_state(TASK_IDLE);
2436d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
24371da177e4SLinus Torvalds 	schedule();
2438c8e55f36STejun Heo 	goto woke_up;
24391da177e4SLinus Torvalds }
24401da177e4SLinus Torvalds 
2441e22bee78STejun Heo /**
2442e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2443111c225aSTejun Heo  * @__rescuer: self
2444e22bee78STejun Heo  *
2445e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2446493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2447e22bee78STejun Heo  *
2448706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2449e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2450e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2451e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2452e22bee78STejun Heo  * the problem rescuer solves.
2453e22bee78STejun Heo  *
2454706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2455706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2456e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2457e22bee78STejun Heo  *
2458e22bee78STejun Heo  * This should happen rarely.
2459d185af30SYacine Belkadi  *
2460d185af30SYacine Belkadi  * Return: 0
2461e22bee78STejun Heo  */
2462111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2463e22bee78STejun Heo {
2464111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2465111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2466e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
24674d595b86SLai Jiangshan 	bool should_stop;
2468e22bee78STejun Heo 
2469e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2470111c225aSTejun Heo 
2471111c225aSTejun Heo 	/*
2472111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2473111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2474111c225aSTejun Heo 	 */
2475197f6accSTejun Heo 	set_pf_worker(true);
2476e22bee78STejun Heo repeat:
2477c5a94a61SPeter Zijlstra 	set_current_state(TASK_IDLE);
24781da177e4SLinus Torvalds 
24794d595b86SLai Jiangshan 	/*
24804d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
24814d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
24824d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
24834d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
24844d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
24854d595b86SLai Jiangshan 	 * list is always empty on exit.
24864d595b86SLai Jiangshan 	 */
24874d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
24881da177e4SLinus Torvalds 
2489493a1724STejun Heo 	/* see whether any pwq is asking for help */
24902e109a28STejun Heo 	spin_lock_irq(&wq_mayday_lock);
2491493a1724STejun Heo 
2492493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2493493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2494493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2495112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2496e22bee78STejun Heo 		struct work_struct *work, *n;
249782607adcSTejun Heo 		bool first = true;
2498e22bee78STejun Heo 
2499e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2500493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2501493a1724STejun Heo 
25022e109a28STejun Heo 		spin_unlock_irq(&wq_mayday_lock);
2503e22bee78STejun Heo 
250451697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
250551697d39SLai Jiangshan 
250651697d39SLai Jiangshan 		spin_lock_irq(&pool->lock);
2507e22bee78STejun Heo 
2508e22bee78STejun Heo 		/*
2509e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2510e22bee78STejun Heo 		 * process'em.
2511e22bee78STejun Heo 		 */
25120479c8c5STejun Heo 		WARN_ON_ONCE(!list_empty(scheduled));
251382607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
251482607adcSTejun Heo 			if (get_work_pwq(work) == pwq) {
251582607adcSTejun Heo 				if (first)
251682607adcSTejun Heo 					pool->watchdog_ts = jiffies;
2517e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
251882607adcSTejun Heo 			}
251982607adcSTejun Heo 			first = false;
252082607adcSTejun Heo 		}
2521e22bee78STejun Heo 
2522008847f6SNeilBrown 		if (!list_empty(scheduled)) {
2523e22bee78STejun Heo 			process_scheduled_works(rescuer);
25247576958aSTejun Heo 
25257576958aSTejun Heo 			/*
2526008847f6SNeilBrown 			 * The above execution of rescued work items could
2527008847f6SNeilBrown 			 * have created more to rescue through
2528008847f6SNeilBrown 			 * pwq_activate_first_delayed() or chained
2529008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
2530008847f6SNeilBrown 			 * that such back-to-back work items, which may be
2531008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
2532008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
2533008847f6SNeilBrown 			 */
2534008847f6SNeilBrown 			if (need_to_create_worker(pool)) {
2535008847f6SNeilBrown 				spin_lock(&wq_mayday_lock);
2536008847f6SNeilBrown 				get_pwq(pwq);
2537008847f6SNeilBrown 				list_move_tail(&pwq->mayday_node, &wq->maydays);
2538008847f6SNeilBrown 				spin_unlock(&wq_mayday_lock);
2539008847f6SNeilBrown 			}
2540008847f6SNeilBrown 		}
2541008847f6SNeilBrown 
2542008847f6SNeilBrown 		/*
254377668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
254413b1d625SLai Jiangshan 		 * go away while we're still attached to it.
254577668c8bSLai Jiangshan 		 */
254677668c8bSLai Jiangshan 		put_pwq(pwq);
254777668c8bSLai Jiangshan 
254877668c8bSLai Jiangshan 		/*
2549d8ca83e6SLai Jiangshan 		 * Leave this pool.  If need_more_worker() is %true, notify a
25507576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
25517576958aSTejun Heo 		 * and stalling the execution.
25527576958aSTejun Heo 		 */
2553d8ca83e6SLai Jiangshan 		if (need_more_worker(pool))
255463d95a91STejun Heo 			wake_up_worker(pool);
25557576958aSTejun Heo 
255613b1d625SLai Jiangshan 		spin_unlock_irq(&pool->lock);
255713b1d625SLai Jiangshan 
2558a2d812a2STejun Heo 		worker_detach_from_pool(rescuer);
255913b1d625SLai Jiangshan 
256013b1d625SLai Jiangshan 		spin_lock_irq(&wq_mayday_lock);
25611da177e4SLinus Torvalds 	}
25621da177e4SLinus Torvalds 
25632e109a28STejun Heo 	spin_unlock_irq(&wq_mayday_lock);
2564493a1724STejun Heo 
25654d595b86SLai Jiangshan 	if (should_stop) {
25664d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
2567197f6accSTejun Heo 		set_pf_worker(false);
25684d595b86SLai Jiangshan 		return 0;
25694d595b86SLai Jiangshan 	}
25704d595b86SLai Jiangshan 
2571111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2572111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2573e22bee78STejun Heo 	schedule();
2574e22bee78STejun Heo 	goto repeat;
25751da177e4SLinus Torvalds }
25761da177e4SLinus Torvalds 
2577fca839c0STejun Heo /**
2578fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
2579fca839c0STejun Heo  * @target_wq: workqueue being flushed
2580fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
2581fca839c0STejun Heo  *
2582fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
2583fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2584fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
2585fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2586fca839c0STejun Heo  * a deadlock.
2587fca839c0STejun Heo  */
2588fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
2589fca839c0STejun Heo 				   struct work_struct *target_work)
2590fca839c0STejun Heo {
2591fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
2592fca839c0STejun Heo 	struct worker *worker;
2593fca839c0STejun Heo 
2594fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
2595fca839c0STejun Heo 		return;
2596fca839c0STejun Heo 
2597fca839c0STejun Heo 	worker = current_wq_worker();
2598fca839c0STejun Heo 
2599fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
2600fca839c0STejun Heo 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%pf",
2601fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
260223d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
260323d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2604fca839c0STejun Heo 		  "workqueue: WQ_MEM_RECLAIM %s:%pf is flushing !WQ_MEM_RECLAIM %s:%pf",
2605fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
2606fca839c0STejun Heo 		  target_wq->name, target_func);
2607fca839c0STejun Heo }
2608fca839c0STejun Heo 
2609fc2e4d70SOleg Nesterov struct wq_barrier {
2610fc2e4d70SOleg Nesterov 	struct work_struct	work;
2611fc2e4d70SOleg Nesterov 	struct completion	done;
26122607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
2613fc2e4d70SOleg Nesterov };
2614fc2e4d70SOleg Nesterov 
2615fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2616fc2e4d70SOleg Nesterov {
2617fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2618fc2e4d70SOleg Nesterov 	complete(&barr->done);
2619fc2e4d70SOleg Nesterov }
2620fc2e4d70SOleg Nesterov 
26214690c4abSTejun Heo /**
26224690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2623112202d9STejun Heo  * @pwq: pwq to insert barrier into
26244690c4abSTejun Heo  * @barr: wq_barrier to insert
2625affee4b2STejun Heo  * @target: target work to attach @barr to
2626affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
26274690c4abSTejun Heo  *
2628affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2629affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2630affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2631affee4b2STejun Heo  * cpu.
2632affee4b2STejun Heo  *
2633affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2634affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2635affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2636affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2637affee4b2STejun Heo  * after a work with LINKED flag set.
2638affee4b2STejun Heo  *
2639affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2640112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
26414690c4abSTejun Heo  *
26424690c4abSTejun Heo  * CONTEXT:
2643d565ed63STejun Heo  * spin_lock_irq(pool->lock).
26444690c4abSTejun Heo  */
2645112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2646affee4b2STejun Heo 			      struct wq_barrier *barr,
2647affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2648fc2e4d70SOleg Nesterov {
2649affee4b2STejun Heo 	struct list_head *head;
2650affee4b2STejun Heo 	unsigned int linked = 0;
2651affee4b2STejun Heo 
2652dc186ad7SThomas Gleixner 	/*
2653d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2654dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2655dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2656dc186ad7SThomas Gleixner 	 * might deadlock.
2657dc186ad7SThomas Gleixner 	 */
2658ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
265922df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
266052fa5bc5SBoqun Feng 
2661fd1a5b04SByungchul Park 	init_completion_map(&barr->done, &target->lockdep_map);
2662fd1a5b04SByungchul Park 
26632607d7a6STejun Heo 	barr->task = current;
266483c22520SOleg Nesterov 
2665affee4b2STejun Heo 	/*
2666affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2667affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2668affee4b2STejun Heo 	 */
2669affee4b2STejun Heo 	if (worker)
2670affee4b2STejun Heo 		head = worker->scheduled.next;
2671affee4b2STejun Heo 	else {
2672affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2673affee4b2STejun Heo 
2674affee4b2STejun Heo 		head = target->entry.next;
2675affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2676affee4b2STejun Heo 		linked = *bits & WORK_STRUCT_LINKED;
2677affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2678affee4b2STejun Heo 	}
2679affee4b2STejun Heo 
2680dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2681112202d9STejun Heo 	insert_work(pwq, &barr->work, head,
2682affee4b2STejun Heo 		    work_color_to_flags(WORK_NO_COLOR) | linked);
2683fc2e4d70SOleg Nesterov }
2684fc2e4d70SOleg Nesterov 
268573f53c4aSTejun Heo /**
2686112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
268773f53c4aSTejun Heo  * @wq: workqueue being flushed
268873f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
268973f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
269073f53c4aSTejun Heo  *
2691112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
269273f53c4aSTejun Heo  *
2693112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
2694112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
2695112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
2696112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
2697112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
269873f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
269973f53c4aSTejun Heo  *
270073f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
270173f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
270273f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
270373f53c4aSTejun Heo  * is returned.
270473f53c4aSTejun Heo  *
2705112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
270673f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
270773f53c4aSTejun Heo  * advanced to @work_color.
270873f53c4aSTejun Heo  *
270973f53c4aSTejun Heo  * CONTEXT:
27103c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
271173f53c4aSTejun Heo  *
2712d185af30SYacine Belkadi  * Return:
271373f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
271473f53c4aSTejun Heo  * otherwise.
271573f53c4aSTejun Heo  */
2716112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
271773f53c4aSTejun Heo 				      int flush_color, int work_color)
27181da177e4SLinus Torvalds {
271973f53c4aSTejun Heo 	bool wait = false;
272049e3cf44STejun Heo 	struct pool_workqueue *pwq;
27211da177e4SLinus Torvalds 
272273f53c4aSTejun Heo 	if (flush_color >= 0) {
27236183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2724112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
2725dc186ad7SThomas Gleixner 	}
272614441960SOleg Nesterov 
272749e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2728112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
27291da177e4SLinus Torvalds 
2730b09f4fd3SLai Jiangshan 		spin_lock_irq(&pool->lock);
273173f53c4aSTejun Heo 
273273f53c4aSTejun Heo 		if (flush_color >= 0) {
27336183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
273473f53c4aSTejun Heo 
2735112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
2736112202d9STejun Heo 				pwq->flush_color = flush_color;
2737112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
273873f53c4aSTejun Heo 				wait = true;
27391da177e4SLinus Torvalds 			}
274073f53c4aSTejun Heo 		}
274173f53c4aSTejun Heo 
274273f53c4aSTejun Heo 		if (work_color >= 0) {
27436183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2744112202d9STejun Heo 			pwq->work_color = work_color;
274573f53c4aSTejun Heo 		}
274673f53c4aSTejun Heo 
2747b09f4fd3SLai Jiangshan 		spin_unlock_irq(&pool->lock);
27481da177e4SLinus Torvalds 	}
27491da177e4SLinus Torvalds 
2750112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
275173f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
275273f53c4aSTejun Heo 
275373f53c4aSTejun Heo 	return wait;
275483c22520SOleg Nesterov }
27551da177e4SLinus Torvalds 
27560fcb78c2SRolf Eike Beer /**
27571da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
27580fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
27591da177e4SLinus Torvalds  *
2760c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
2761c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
27621da177e4SLinus Torvalds  */
27637ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
27641da177e4SLinus Torvalds {
276573f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
276673f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
276773f53c4aSTejun Heo 		.flush_color = -1,
2768fd1a5b04SByungchul Park 		.done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
276973f53c4aSTejun Heo 	};
277073f53c4aSTejun Heo 	int next_color;
2771b1f4ec17SOleg Nesterov 
27723347fa09STejun Heo 	if (WARN_ON(!wq_online))
27733347fa09STejun Heo 		return;
27743347fa09STejun Heo 
277587915adcSJohannes Berg 	lock_map_acquire(&wq->lockdep_map);
277687915adcSJohannes Berg 	lock_map_release(&wq->lockdep_map);
277787915adcSJohannes Berg 
27783c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
277973f53c4aSTejun Heo 
278073f53c4aSTejun Heo 	/*
278173f53c4aSTejun Heo 	 * Start-to-wait phase
278273f53c4aSTejun Heo 	 */
278373f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
278473f53c4aSTejun Heo 
278573f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
278673f53c4aSTejun Heo 		/*
278773f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
278873f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
278973f53c4aSTejun Heo 		 * by one.
279073f53c4aSTejun Heo 		 */
27916183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
279273f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
279373f53c4aSTejun Heo 		wq->work_color = next_color;
279473f53c4aSTejun Heo 
279573f53c4aSTejun Heo 		if (!wq->first_flusher) {
279673f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
27976183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
279873f53c4aSTejun Heo 
279973f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
280073f53c4aSTejun Heo 
2801112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
280273f53c4aSTejun Heo 						       wq->work_color)) {
280373f53c4aSTejun Heo 				/* nothing to flush, done */
280473f53c4aSTejun Heo 				wq->flush_color = next_color;
280573f53c4aSTejun Heo 				wq->first_flusher = NULL;
280673f53c4aSTejun Heo 				goto out_unlock;
280773f53c4aSTejun Heo 			}
280873f53c4aSTejun Heo 		} else {
280973f53c4aSTejun Heo 			/* wait in queue */
28106183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
281173f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
2812112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
281373f53c4aSTejun Heo 		}
281473f53c4aSTejun Heo 	} else {
281573f53c4aSTejun Heo 		/*
281673f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
281773f53c4aSTejun Heo 		 * The next flush completion will assign us
281873f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
281973f53c4aSTejun Heo 		 */
282073f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
282173f53c4aSTejun Heo 	}
282273f53c4aSTejun Heo 
2823fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
2824fca839c0STejun Heo 
28253c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
282673f53c4aSTejun Heo 
282773f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
282873f53c4aSTejun Heo 
282973f53c4aSTejun Heo 	/*
283073f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
283173f53c4aSTejun Heo 	 *
283273f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
283373f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
283473f53c4aSTejun Heo 	 */
283573f53c4aSTejun Heo 	if (wq->first_flusher != &this_flusher)
283673f53c4aSTejun Heo 		return;
283773f53c4aSTejun Heo 
28383c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
283973f53c4aSTejun Heo 
28404ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
28414ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
28424ce48b37STejun Heo 		goto out_unlock;
28434ce48b37STejun Heo 
284473f53c4aSTejun Heo 	wq->first_flusher = NULL;
284573f53c4aSTejun Heo 
28466183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
28476183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
284873f53c4aSTejun Heo 
284973f53c4aSTejun Heo 	while (true) {
285073f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
285173f53c4aSTejun Heo 
285273f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
285373f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
285473f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
285573f53c4aSTejun Heo 				break;
285673f53c4aSTejun Heo 			list_del_init(&next->list);
285773f53c4aSTejun Heo 			complete(&next->done);
285873f53c4aSTejun Heo 		}
285973f53c4aSTejun Heo 
28606183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
286173f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
286273f53c4aSTejun Heo 
286373f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
286473f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
286573f53c4aSTejun Heo 
286673f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
286773f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
286873f53c4aSTejun Heo 			/*
286973f53c4aSTejun Heo 			 * Assign the same color to all overflowed
287073f53c4aSTejun Heo 			 * flushers, advance work_color and append to
287173f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
287273f53c4aSTejun Heo 			 * phase for these overflowed flushers.
287373f53c4aSTejun Heo 			 */
287473f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
287573f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
287673f53c4aSTejun Heo 
287773f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
287873f53c4aSTejun Heo 
287973f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
288073f53c4aSTejun Heo 					      &wq->flusher_queue);
2881112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
288273f53c4aSTejun Heo 		}
288373f53c4aSTejun Heo 
288473f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
28856183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
288673f53c4aSTejun Heo 			break;
288773f53c4aSTejun Heo 		}
288873f53c4aSTejun Heo 
288973f53c4aSTejun Heo 		/*
289073f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
2891112202d9STejun Heo 		 * the new first flusher and arm pwqs.
289273f53c4aSTejun Heo 		 */
28936183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
28946183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
289573f53c4aSTejun Heo 
289673f53c4aSTejun Heo 		list_del_init(&next->list);
289773f53c4aSTejun Heo 		wq->first_flusher = next;
289873f53c4aSTejun Heo 
2899112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
290073f53c4aSTejun Heo 			break;
290173f53c4aSTejun Heo 
290273f53c4aSTejun Heo 		/*
290373f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
290473f53c4aSTejun Heo 		 * flusher and repeat cascading.
290573f53c4aSTejun Heo 		 */
290673f53c4aSTejun Heo 		wq->first_flusher = NULL;
290773f53c4aSTejun Heo 	}
290873f53c4aSTejun Heo 
290973f53c4aSTejun Heo out_unlock:
29103c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
29111da177e4SLinus Torvalds }
29121dadafa8STim Gardner EXPORT_SYMBOL(flush_workqueue);
29131da177e4SLinus Torvalds 
29149c5a2ba7STejun Heo /**
29159c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
29169c5a2ba7STejun Heo  * @wq: workqueue to drain
29179c5a2ba7STejun Heo  *
29189c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
29199c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
29209c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
2921b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
29229c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
29239c5a2ba7STejun Heo  * takes too long.
29249c5a2ba7STejun Heo  */
29259c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
29269c5a2ba7STejun Heo {
29279c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
292849e3cf44STejun Heo 	struct pool_workqueue *pwq;
29299c5a2ba7STejun Heo 
29309c5a2ba7STejun Heo 	/*
29319c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
29329c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
2933618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
29349c5a2ba7STejun Heo 	 */
293587fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
29369c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
2937618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
293887fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
29399c5a2ba7STejun Heo reflush:
29409c5a2ba7STejun Heo 	flush_workqueue(wq);
29419c5a2ba7STejun Heo 
2942b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
294376af4d93STejun Heo 
294449e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2945fa2563e4SThomas Tuttle 		bool drained;
29469c5a2ba7STejun Heo 
2947b09f4fd3SLai Jiangshan 		spin_lock_irq(&pwq->pool->lock);
2948112202d9STejun Heo 		drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2949b09f4fd3SLai Jiangshan 		spin_unlock_irq(&pwq->pool->lock);
2950fa2563e4SThomas Tuttle 
2951fa2563e4SThomas Tuttle 		if (drained)
29529c5a2ba7STejun Heo 			continue;
29539c5a2ba7STejun Heo 
29549c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
29559c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2956c5aa87bbSTejun Heo 			pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
29579c5a2ba7STejun Heo 				wq->name, flush_cnt);
295876af4d93STejun Heo 
2959b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
29609c5a2ba7STejun Heo 		goto reflush;
29619c5a2ba7STejun Heo 	}
29629c5a2ba7STejun Heo 
29639c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
2964618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
296587fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
29669c5a2ba7STejun Heo }
29679c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
29689c5a2ba7STejun Heo 
2969d6e89786SJohannes Berg static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
2970d6e89786SJohannes Berg 			     bool from_cancel)
2971baf59022STejun Heo {
2972baf59022STejun Heo 	struct worker *worker = NULL;
2973c9e7cf27STejun Heo 	struct worker_pool *pool;
2974112202d9STejun Heo 	struct pool_workqueue *pwq;
2975baf59022STejun Heo 
2976baf59022STejun Heo 	might_sleep();
2977baf59022STejun Heo 
2978fa1b54e6STejun Heo 	local_irq_disable();
2979fa1b54e6STejun Heo 	pool = get_work_pool(work);
2980fa1b54e6STejun Heo 	if (!pool) {
2981fa1b54e6STejun Heo 		local_irq_enable();
2982fa1b54e6STejun Heo 		return false;
2983fa1b54e6STejun Heo 	}
2984fa1b54e6STejun Heo 
2985fa1b54e6STejun Heo 	spin_lock(&pool->lock);
29860b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
2987112202d9STejun Heo 	pwq = get_work_pwq(work);
2988112202d9STejun Heo 	if (pwq) {
2989112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
2990baf59022STejun Heo 			goto already_gone;
2991606a5020STejun Heo 	} else {
2992c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
2993baf59022STejun Heo 		if (!worker)
2994baf59022STejun Heo 			goto already_gone;
2995112202d9STejun Heo 		pwq = worker->current_pwq;
2996606a5020STejun Heo 	}
2997baf59022STejun Heo 
2998fca839c0STejun Heo 	check_flush_dependency(pwq->wq, work);
2999fca839c0STejun Heo 
3000112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
3001d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
3002baf59022STejun Heo 
3003e159489bSTejun Heo 	/*
3004a1d14934SPeter Zijlstra 	 * Force a lock recursion deadlock when using flush_work() inside a
3005a1d14934SPeter Zijlstra 	 * single-threaded or rescuer equipped workqueue.
3006a1d14934SPeter Zijlstra 	 *
3007a1d14934SPeter Zijlstra 	 * For single threaded workqueues the deadlock happens when the work
3008a1d14934SPeter Zijlstra 	 * is after the work issuing the flush_work(). For rescuer equipped
3009a1d14934SPeter Zijlstra 	 * workqueues the deadlock happens when the rescuer stalls, blocking
3010a1d14934SPeter Zijlstra 	 * forward progress.
3011e159489bSTejun Heo 	 */
3012d6e89786SJohannes Berg 	if (!from_cancel &&
3013d6e89786SJohannes Berg 	    (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
3014112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
3015112202d9STejun Heo 		lock_map_release(&pwq->wq->lockdep_map);
3016a1d14934SPeter Zijlstra 	}
3017e159489bSTejun Heo 
3018baf59022STejun Heo 	return true;
3019baf59022STejun Heo already_gone:
3020d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
3021baf59022STejun Heo 	return false;
3022baf59022STejun Heo }
3023baf59022STejun Heo 
3024d6e89786SJohannes Berg static bool __flush_work(struct work_struct *work, bool from_cancel)
3025d6e89786SJohannes Berg {
3026d6e89786SJohannes Berg 	struct wq_barrier barr;
3027d6e89786SJohannes Berg 
3028d6e89786SJohannes Berg 	if (WARN_ON(!wq_online))
3029d6e89786SJohannes Berg 		return false;
3030d6e89786SJohannes Berg 
30314d43d395STetsuo Handa 	if (WARN_ON(!work->func))
30324d43d395STetsuo Handa 		return false;
30334d43d395STetsuo Handa 
303487915adcSJohannes Berg 	if (!from_cancel) {
303587915adcSJohannes Berg 		lock_map_acquire(&work->lockdep_map);
303687915adcSJohannes Berg 		lock_map_release(&work->lockdep_map);
303787915adcSJohannes Berg 	}
303887915adcSJohannes Berg 
3039d6e89786SJohannes Berg 	if (start_flush_work(work, &barr, from_cancel)) {
3040d6e89786SJohannes Berg 		wait_for_completion(&barr.done);
3041d6e89786SJohannes Berg 		destroy_work_on_stack(&barr.work);
3042d6e89786SJohannes Berg 		return true;
3043d6e89786SJohannes Berg 	} else {
3044d6e89786SJohannes Berg 		return false;
3045d6e89786SJohannes Berg 	}
3046d6e89786SJohannes Berg }
3047d6e89786SJohannes Berg 
3048db700897SOleg Nesterov /**
3049401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
3050401a8d04STejun Heo  * @work: the work to flush
3051db700897SOleg Nesterov  *
3052606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
3053606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
3054401a8d04STejun Heo  *
3055d185af30SYacine Belkadi  * Return:
3056401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3057401a8d04STejun Heo  * %false if it was already idle.
3058db700897SOleg Nesterov  */
3059401a8d04STejun Heo bool flush_work(struct work_struct *work)
3060db700897SOleg Nesterov {
3061d6e89786SJohannes Berg 	return __flush_work(work, false);
3062606a5020STejun Heo }
3063db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
3064db700897SOleg Nesterov 
30658603e1b3STejun Heo struct cwt_wait {
3066ac6424b9SIngo Molnar 	wait_queue_entry_t		wait;
30678603e1b3STejun Heo 	struct work_struct	*work;
30688603e1b3STejun Heo };
30698603e1b3STejun Heo 
3070ac6424b9SIngo Molnar static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
30718603e1b3STejun Heo {
30728603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
30738603e1b3STejun Heo 
30748603e1b3STejun Heo 	if (cwait->work != key)
30758603e1b3STejun Heo 		return 0;
30768603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
30778603e1b3STejun Heo }
30788603e1b3STejun Heo 
307936e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3080401a8d04STejun Heo {
30818603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3082bbb68dfaSTejun Heo 	unsigned long flags;
30831f1f642eSOleg Nesterov 	int ret;
30841f1f642eSOleg Nesterov 
30851f1f642eSOleg Nesterov 	do {
3086bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
3087bbb68dfaSTejun Heo 		/*
30888603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
30898603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
30908603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
30918603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
30928603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
30938603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
30948603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
30958603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
30968603e1b3STejun Heo 		 * we're hogging the CPU.
30978603e1b3STejun Heo 		 *
30988603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
30998603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
31008603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
31018603e1b3STejun Heo 		 * wait and wakeup.
3102bbb68dfaSTejun Heo 		 */
31038603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
31048603e1b3STejun Heo 			struct cwt_wait cwait;
31058603e1b3STejun Heo 
31068603e1b3STejun Heo 			init_wait(&cwait.wait);
31078603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
31088603e1b3STejun Heo 			cwait.work = work;
31098603e1b3STejun Heo 
31108603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
31118603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
31128603e1b3STejun Heo 			if (work_is_canceling(work))
31138603e1b3STejun Heo 				schedule();
31148603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
31158603e1b3STejun Heo 		}
31161f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
31171f1f642eSOleg Nesterov 
3118bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
3119bbb68dfaSTejun Heo 	mark_work_canceling(work);
3120bbb68dfaSTejun Heo 	local_irq_restore(flags);
3121bbb68dfaSTejun Heo 
31223347fa09STejun Heo 	/*
31233347fa09STejun Heo 	 * This allows canceling during early boot.  We know that @work
31243347fa09STejun Heo 	 * isn't executing.
31253347fa09STejun Heo 	 */
31263347fa09STejun Heo 	if (wq_online)
3127d6e89786SJohannes Berg 		__flush_work(work, true);
31283347fa09STejun Heo 
31297a22ad75STejun Heo 	clear_work_data(work);
31308603e1b3STejun Heo 
31318603e1b3STejun Heo 	/*
31328603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
31338603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
31348603e1b3STejun Heo 	 * visible there.
31358603e1b3STejun Heo 	 */
31368603e1b3STejun Heo 	smp_mb();
31378603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
31388603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
31398603e1b3STejun Heo 
31401f1f642eSOleg Nesterov 	return ret;
31411f1f642eSOleg Nesterov }
31421f1f642eSOleg Nesterov 
31436e84d644SOleg Nesterov /**
3144401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
3145401a8d04STejun Heo  * @work: the work to cancel
31466e84d644SOleg Nesterov  *
3147401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
3148401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
3149401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
3150401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
31511f1f642eSOleg Nesterov  *
3152401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
3153401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
31546e84d644SOleg Nesterov  *
3155401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
31566e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
3157401a8d04STejun Heo  *
3158d185af30SYacine Belkadi  * Return:
3159401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
31606e84d644SOleg Nesterov  */
3161401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
31626e84d644SOleg Nesterov {
316336e227d2STejun Heo 	return __cancel_work_timer(work, false);
3164b89deed3SOleg Nesterov }
316528e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
3166b89deed3SOleg Nesterov 
31676e84d644SOleg Nesterov /**
3168401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
3169401a8d04STejun Heo  * @dwork: the delayed work to flush
31706e84d644SOleg Nesterov  *
3171401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
3172401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
3173401a8d04STejun Heo  * considers the last queueing instance of @dwork.
31741f1f642eSOleg Nesterov  *
3175d185af30SYacine Belkadi  * Return:
3176401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3177401a8d04STejun Heo  * %false if it was already idle.
31786e84d644SOleg Nesterov  */
3179401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
3180401a8d04STejun Heo {
31818930cabaSTejun Heo 	local_irq_disable();
3182401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
318360c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
31848930cabaSTejun Heo 	local_irq_enable();
3185401a8d04STejun Heo 	return flush_work(&dwork->work);
3186401a8d04STejun Heo }
3187401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3188401a8d04STejun Heo 
318905f0fe6bSTejun Heo /**
319005f0fe6bSTejun Heo  * flush_rcu_work - wait for a rwork to finish executing the last queueing
319105f0fe6bSTejun Heo  * @rwork: the rcu work to flush
319205f0fe6bSTejun Heo  *
319305f0fe6bSTejun Heo  * Return:
319405f0fe6bSTejun Heo  * %true if flush_rcu_work() waited for the work to finish execution,
319505f0fe6bSTejun Heo  * %false if it was already idle.
319605f0fe6bSTejun Heo  */
319705f0fe6bSTejun Heo bool flush_rcu_work(struct rcu_work *rwork)
319805f0fe6bSTejun Heo {
319905f0fe6bSTejun Heo 	if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
320005f0fe6bSTejun Heo 		rcu_barrier();
320105f0fe6bSTejun Heo 		flush_work(&rwork->work);
320205f0fe6bSTejun Heo 		return true;
320305f0fe6bSTejun Heo 	} else {
320405f0fe6bSTejun Heo 		return flush_work(&rwork->work);
320505f0fe6bSTejun Heo 	}
320605f0fe6bSTejun Heo }
320705f0fe6bSTejun Heo EXPORT_SYMBOL(flush_rcu_work);
320805f0fe6bSTejun Heo 
3209f72b8792SJens Axboe static bool __cancel_work(struct work_struct *work, bool is_dwork)
3210f72b8792SJens Axboe {
3211f72b8792SJens Axboe 	unsigned long flags;
3212f72b8792SJens Axboe 	int ret;
3213f72b8792SJens Axboe 
3214f72b8792SJens Axboe 	do {
3215f72b8792SJens Axboe 		ret = try_to_grab_pending(work, is_dwork, &flags);
3216f72b8792SJens Axboe 	} while (unlikely(ret == -EAGAIN));
3217f72b8792SJens Axboe 
3218f72b8792SJens Axboe 	if (unlikely(ret < 0))
3219f72b8792SJens Axboe 		return false;
3220f72b8792SJens Axboe 
3221f72b8792SJens Axboe 	set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3222f72b8792SJens Axboe 	local_irq_restore(flags);
3223f72b8792SJens Axboe 	return ret;
3224f72b8792SJens Axboe }
3225f72b8792SJens Axboe 
3226401a8d04STejun Heo /**
322757b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
322857b30ae7STejun Heo  * @dwork: delayed_work to cancel
322909383498STejun Heo  *
3230d185af30SYacine Belkadi  * Kill off a pending delayed_work.
3231d185af30SYacine Belkadi  *
3232d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
3233d185af30SYacine Belkadi  * pending.
3234d185af30SYacine Belkadi  *
3235d185af30SYacine Belkadi  * Note:
3236d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
3237d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
3238d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
323909383498STejun Heo  *
324057b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
324109383498STejun Heo  */
324257b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
324309383498STejun Heo {
3244f72b8792SJens Axboe 	return __cancel_work(&dwork->work, true);
324509383498STejun Heo }
324657b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
324709383498STejun Heo 
324809383498STejun Heo /**
3249401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3250401a8d04STejun Heo  * @dwork: the delayed work cancel
3251401a8d04STejun Heo  *
3252401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
3253401a8d04STejun Heo  *
3254d185af30SYacine Belkadi  * Return:
3255401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
3256401a8d04STejun Heo  */
3257401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
32586e84d644SOleg Nesterov {
325936e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
32606e84d644SOleg Nesterov }
3261f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
32621da177e4SLinus Torvalds 
32630fcb78c2SRolf Eike Beer /**
326431ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3265b6136773SAndrew Morton  * @func: the function to call
3266b6136773SAndrew Morton  *
326731ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
326831ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3269b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
327031ddd871STejun Heo  *
3271d185af30SYacine Belkadi  * Return:
327231ddd871STejun Heo  * 0 on success, -errno on failure.
3273b6136773SAndrew Morton  */
327465f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
327515316ba8SChristoph Lameter {
327615316ba8SChristoph Lameter 	int cpu;
327738f51568SNamhyung Kim 	struct work_struct __percpu *works;
327815316ba8SChristoph Lameter 
3279b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3280b6136773SAndrew Morton 	if (!works)
328115316ba8SChristoph Lameter 		return -ENOMEM;
3282b6136773SAndrew Morton 
328395402b38SGautham R Shenoy 	get_online_cpus();
328493981800STejun Heo 
328515316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
32869bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
32879bfb1839SIngo Molnar 
32889bfb1839SIngo Molnar 		INIT_WORK(work, func);
32898de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
329015316ba8SChristoph Lameter 	}
329193981800STejun Heo 
329293981800STejun Heo 	for_each_online_cpu(cpu)
32938616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
329493981800STejun Heo 
329595402b38SGautham R Shenoy 	put_online_cpus();
3296b6136773SAndrew Morton 	free_percpu(works);
329715316ba8SChristoph Lameter 	return 0;
329815316ba8SChristoph Lameter }
329915316ba8SChristoph Lameter 
3300eef6a7d5SAlan Stern /**
33011fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
33021fa44ecaSJames Bottomley  * @fn:		the function to execute
33031fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
33041fa44ecaSJames Bottomley  *		be available when the work executes)
33051fa44ecaSJames Bottomley  *
33061fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
33071fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
33081fa44ecaSJames Bottomley  *
3309d185af30SYacine Belkadi  * Return:	0 - function was executed
33101fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
33111fa44ecaSJames Bottomley  */
331265f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
33131fa44ecaSJames Bottomley {
33141fa44ecaSJames Bottomley 	if (!in_interrupt()) {
331565f27f38SDavid Howells 		fn(&ew->work);
33161fa44ecaSJames Bottomley 		return 0;
33171fa44ecaSJames Bottomley 	}
33181fa44ecaSJames Bottomley 
331965f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
33201fa44ecaSJames Bottomley 	schedule_work(&ew->work);
33211fa44ecaSJames Bottomley 
33221fa44ecaSJames Bottomley 	return 1;
33231fa44ecaSJames Bottomley }
33241fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
33251fa44ecaSJames Bottomley 
33267a4e344cSTejun Heo /**
33277a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
33287a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
33297a4e344cSTejun Heo  *
33307a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
33317a4e344cSTejun Heo  */
33327a4e344cSTejun Heo void free_workqueue_attrs(struct workqueue_attrs *attrs)
33337a4e344cSTejun Heo {
33347a4e344cSTejun Heo 	if (attrs) {
33357a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
33367a4e344cSTejun Heo 		kfree(attrs);
33377a4e344cSTejun Heo 	}
33387a4e344cSTejun Heo }
33397a4e344cSTejun Heo 
33407a4e344cSTejun Heo /**
33417a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
33427a4e344cSTejun Heo  * @gfp_mask: allocation mask to use
33437a4e344cSTejun Heo  *
33447a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3345d185af30SYacine Belkadi  * return it.
3346d185af30SYacine Belkadi  *
3347d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
33487a4e344cSTejun Heo  */
33497a4e344cSTejun Heo struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
33507a4e344cSTejun Heo {
33517a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
33527a4e344cSTejun Heo 
33537a4e344cSTejun Heo 	attrs = kzalloc(sizeof(*attrs), gfp_mask);
33547a4e344cSTejun Heo 	if (!attrs)
33557a4e344cSTejun Heo 		goto fail;
33567a4e344cSTejun Heo 	if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
33577a4e344cSTejun Heo 		goto fail;
33587a4e344cSTejun Heo 
335913e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
33607a4e344cSTejun Heo 	return attrs;
33617a4e344cSTejun Heo fail:
33627a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
33637a4e344cSTejun Heo 	return NULL;
33647a4e344cSTejun Heo }
33657a4e344cSTejun Heo 
336629c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
336729c91e99STejun Heo 				 const struct workqueue_attrs *from)
336829c91e99STejun Heo {
336929c91e99STejun Heo 	to->nice = from->nice;
337029c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
33712865a8fbSShaohua Li 	/*
33722865a8fbSShaohua Li 	 * Unlike hash and equality test, this function doesn't ignore
33732865a8fbSShaohua Li 	 * ->no_numa as it is used for both pool and wq attrs.  Instead,
33742865a8fbSShaohua Li 	 * get_unbound_pool() explicitly clears ->no_numa after copying.
33752865a8fbSShaohua Li 	 */
33762865a8fbSShaohua Li 	to->no_numa = from->no_numa;
337729c91e99STejun Heo }
337829c91e99STejun Heo 
337929c91e99STejun Heo /* hash value of the content of @attr */
338029c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
338129c91e99STejun Heo {
338229c91e99STejun Heo 	u32 hash = 0;
338329c91e99STejun Heo 
338429c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
338513e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
338613e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
338729c91e99STejun Heo 	return hash;
338829c91e99STejun Heo }
338929c91e99STejun Heo 
339029c91e99STejun Heo /* content equality test */
339129c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
339229c91e99STejun Heo 			  const struct workqueue_attrs *b)
339329c91e99STejun Heo {
339429c91e99STejun Heo 	if (a->nice != b->nice)
339529c91e99STejun Heo 		return false;
339629c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
339729c91e99STejun Heo 		return false;
339829c91e99STejun Heo 	return true;
339929c91e99STejun Heo }
340029c91e99STejun Heo 
34017a4e344cSTejun Heo /**
34027a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
34037a4e344cSTejun Heo  * @pool: worker_pool to initialize
34047a4e344cSTejun Heo  *
3405402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3406d185af30SYacine Belkadi  *
3407d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
340829c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
340929c91e99STejun Heo  * on @pool safely to release it.
34107a4e344cSTejun Heo  */
34117a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
34124e1a1f9aSTejun Heo {
34134e1a1f9aSTejun Heo 	spin_lock_init(&pool->lock);
341429c91e99STejun Heo 	pool->id = -1;
341529c91e99STejun Heo 	pool->cpu = -1;
3416f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
34174e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
341882607adcSTejun Heo 	pool->watchdog_ts = jiffies;
34194e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
34204e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
34214e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
34224e1a1f9aSTejun Heo 
342332a6c723SKees Cook 	timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
34244e1a1f9aSTejun Heo 
342532a6c723SKees Cook 	timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
34264e1a1f9aSTejun Heo 
3427da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
34287a4e344cSTejun Heo 
34297cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
343029c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
343129c91e99STejun Heo 	pool->refcnt = 1;
343229c91e99STejun Heo 
343329c91e99STejun Heo 	/* shouldn't fail above this point */
34347a4e344cSTejun Heo 	pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
34357a4e344cSTejun Heo 	if (!pool->attrs)
34367a4e344cSTejun Heo 		return -ENOMEM;
34377a4e344cSTejun Heo 	return 0;
34384e1a1f9aSTejun Heo }
34394e1a1f9aSTejun Heo 
3440669de8bdSBart Van Assche #ifdef CONFIG_LOCKDEP
3441669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3442669de8bdSBart Van Assche {
3443669de8bdSBart Van Assche 	char *lock_name;
3444669de8bdSBart Van Assche 
3445669de8bdSBart Van Assche 	lockdep_register_key(&wq->key);
3446669de8bdSBart Van Assche 	lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3447669de8bdSBart Van Assche 	if (!lock_name)
3448669de8bdSBart Van Assche 		lock_name = wq->name;
344969a106c0SQian Cai 
345069a106c0SQian Cai 	wq->lock_name = lock_name;
3451669de8bdSBart Van Assche 	lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3452669de8bdSBart Van Assche }
3453669de8bdSBart Van Assche 
3454669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3455669de8bdSBart Van Assche {
3456669de8bdSBart Van Assche 	lockdep_unregister_key(&wq->key);
3457669de8bdSBart Van Assche }
3458669de8bdSBart Van Assche 
3459669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3460669de8bdSBart Van Assche {
3461669de8bdSBart Van Assche 	if (wq->lock_name != wq->name)
3462669de8bdSBart Van Assche 		kfree(wq->lock_name);
3463669de8bdSBart Van Assche }
3464669de8bdSBart Van Assche #else
3465669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3466669de8bdSBart Van Assche {
3467669de8bdSBart Van Assche }
3468669de8bdSBart Van Assche 
3469669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3470669de8bdSBart Van Assche {
3471669de8bdSBart Van Assche }
3472669de8bdSBart Van Assche 
3473669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3474669de8bdSBart Van Assche {
3475669de8bdSBart Van Assche }
3476669de8bdSBart Van Assche #endif
3477669de8bdSBart Van Assche 
3478e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
3479e2dca7adSTejun Heo {
3480e2dca7adSTejun Heo 	struct workqueue_struct *wq =
3481e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
3482e2dca7adSTejun Heo 
3483669de8bdSBart Van Assche 	wq_free_lockdep(wq);
3484669de8bdSBart Van Assche 
3485e2dca7adSTejun Heo 	if (!(wq->flags & WQ_UNBOUND))
3486e2dca7adSTejun Heo 		free_percpu(wq->cpu_pwqs);
3487e2dca7adSTejun Heo 	else
3488e2dca7adSTejun Heo 		free_workqueue_attrs(wq->unbound_attrs);
3489e2dca7adSTejun Heo 
3490e2dca7adSTejun Heo 	kfree(wq->rescuer);
3491e2dca7adSTejun Heo 	kfree(wq);
3492e2dca7adSTejun Heo }
3493e2dca7adSTejun Heo 
349429c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
349529c91e99STejun Heo {
349629c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
349729c91e99STejun Heo 
34987cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
349929c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
350029c91e99STejun Heo 	kfree(pool);
350129c91e99STejun Heo }
350229c91e99STejun Heo 
350329c91e99STejun Heo /**
350429c91e99STejun Heo  * put_unbound_pool - put a worker_pool
350529c91e99STejun Heo  * @pool: worker_pool to put
350629c91e99STejun Heo  *
350729c91e99STejun Heo  * Put @pool.  If its refcnt reaches zero, it gets destroyed in sched-RCU
3508c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3509c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3510c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
3511a892caccSTejun Heo  *
3512a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
351329c91e99STejun Heo  */
351429c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
351529c91e99STejun Heo {
351660f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
351729c91e99STejun Heo 	struct worker *worker;
351829c91e99STejun Heo 
3519a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3520a892caccSTejun Heo 
3521a892caccSTejun Heo 	if (--pool->refcnt)
352229c91e99STejun Heo 		return;
352329c91e99STejun Heo 
352429c91e99STejun Heo 	/* sanity checks */
352561d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
3526a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
352729c91e99STejun Heo 		return;
352829c91e99STejun Heo 
352929c91e99STejun Heo 	/* release id and unhash */
353029c91e99STejun Heo 	if (pool->id >= 0)
353129c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
353229c91e99STejun Heo 	hash_del(&pool->hash_node);
353329c91e99STejun Heo 
3534c5aa87bbSTejun Heo 	/*
3535692b4825STejun Heo 	 * Become the manager and destroy all workers.  This prevents
3536692b4825STejun Heo 	 * @pool's workers from blocking on attach_mutex.  We're the last
3537692b4825STejun Heo 	 * manager and @pool gets freed with the flag set.
3538c5aa87bbSTejun Heo 	 */
353960f5a4bcSLai Jiangshan 	spin_lock_irq(&pool->lock);
3540692b4825STejun Heo 	wait_event_lock_irq(wq_manager_wait,
3541692b4825STejun Heo 			    !(pool->flags & POOL_MANAGER_ACTIVE), pool->lock);
3542692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
3543692b4825STejun Heo 
35441037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
354529c91e99STejun Heo 		destroy_worker(worker);
354629c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
354729c91e99STejun Heo 	spin_unlock_irq(&pool->lock);
354860f5a4bcSLai Jiangshan 
35491258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
3550da028469SLai Jiangshan 	if (!list_empty(&pool->workers))
355160f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
35521258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
355360f5a4bcSLai Jiangshan 
355460f5a4bcSLai Jiangshan 	if (pool->detach_completion)
355560f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
355660f5a4bcSLai Jiangshan 
355729c91e99STejun Heo 	/* shut down the timers */
355829c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
355929c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
356029c91e99STejun Heo 
356129c91e99STejun Heo 	/* sched-RCU protected to allow dereferences from get_work_pool() */
356225b00775SPaul E. McKenney 	call_rcu(&pool->rcu, rcu_free_pool);
356329c91e99STejun Heo }
356429c91e99STejun Heo 
356529c91e99STejun Heo /**
356629c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
356729c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
356829c91e99STejun Heo  *
356929c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
357029c91e99STejun Heo  * reference count and return it.  If there already is a matching
357129c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
3572d185af30SYacine Belkadi  * create a new one.
3573a892caccSTejun Heo  *
3574a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
3575d185af30SYacine Belkadi  *
3576d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
3577d185af30SYacine Belkadi  * On failure, %NULL.
357829c91e99STejun Heo  */
357929c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
358029c91e99STejun Heo {
358129c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
358229c91e99STejun Heo 	struct worker_pool *pool;
3583f3f90ad4STejun Heo 	int node;
3584e2273584SXunlei Pang 	int target_node = NUMA_NO_NODE;
358529c91e99STejun Heo 
3586a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
358729c91e99STejun Heo 
358829c91e99STejun Heo 	/* do we already have a matching pool? */
358929c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
359029c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
359129c91e99STejun Heo 			pool->refcnt++;
35923fb1823cSLai Jiangshan 			return pool;
359329c91e99STejun Heo 		}
359429c91e99STejun Heo 	}
359529c91e99STejun Heo 
3596e2273584SXunlei Pang 	/* if cpumask is contained inside a NUMA node, we belong to that node */
3597e2273584SXunlei Pang 	if (wq_numa_enabled) {
3598e2273584SXunlei Pang 		for_each_node(node) {
3599e2273584SXunlei Pang 			if (cpumask_subset(attrs->cpumask,
3600e2273584SXunlei Pang 					   wq_numa_possible_cpumask[node])) {
3601e2273584SXunlei Pang 				target_node = node;
3602e2273584SXunlei Pang 				break;
3603e2273584SXunlei Pang 			}
3604e2273584SXunlei Pang 		}
3605e2273584SXunlei Pang 	}
3606e2273584SXunlei Pang 
360729c91e99STejun Heo 	/* nope, create a new one */
3608e2273584SXunlei Pang 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
360929c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
361029c91e99STejun Heo 		goto fail;
361129c91e99STejun Heo 
36128864b4e5STejun Heo 	lockdep_set_subclass(&pool->lock, 1);	/* see put_pwq() */
361329c91e99STejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
3614e2273584SXunlei Pang 	pool->node = target_node;
361529c91e99STejun Heo 
36162865a8fbSShaohua Li 	/*
36172865a8fbSShaohua Li 	 * no_numa isn't a worker_pool attribute, always clear it.  See
36182865a8fbSShaohua Li 	 * 'struct workqueue_attrs' comments for detail.
36192865a8fbSShaohua Li 	 */
36202865a8fbSShaohua Li 	pool->attrs->no_numa = false;
36212865a8fbSShaohua Li 
362229c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
362329c91e99STejun Heo 		goto fail;
362429c91e99STejun Heo 
362529c91e99STejun Heo 	/* create and start the initial worker */
36263347fa09STejun Heo 	if (wq_online && !create_worker(pool))
362729c91e99STejun Heo 		goto fail;
362829c91e99STejun Heo 
362929c91e99STejun Heo 	/* install */
363029c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
36313fb1823cSLai Jiangshan 
363229c91e99STejun Heo 	return pool;
363329c91e99STejun Heo fail:
363429c91e99STejun Heo 	if (pool)
363529c91e99STejun Heo 		put_unbound_pool(pool);
363629c91e99STejun Heo 	return NULL;
363729c91e99STejun Heo }
363829c91e99STejun Heo 
36398864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
36408864b4e5STejun Heo {
36418864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
36428864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
36438864b4e5STejun Heo }
36448864b4e5STejun Heo 
36458864b4e5STejun Heo /*
36468864b4e5STejun Heo  * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
36478864b4e5STejun Heo  * and needs to be destroyed.
36488864b4e5STejun Heo  */
36498864b4e5STejun Heo static void pwq_unbound_release_workfn(struct work_struct *work)
36508864b4e5STejun Heo {
36518864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
36528864b4e5STejun Heo 						  unbound_release_work);
36538864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
36548864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
3655bc0caf09STejun Heo 	bool is_last;
36568864b4e5STejun Heo 
36578864b4e5STejun Heo 	if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
36588864b4e5STejun Heo 		return;
36598864b4e5STejun Heo 
36603c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
36618864b4e5STejun Heo 	list_del_rcu(&pwq->pwqs_node);
3662bc0caf09STejun Heo 	is_last = list_empty(&wq->pwqs);
36633c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
36648864b4e5STejun Heo 
3665a892caccSTejun Heo 	mutex_lock(&wq_pool_mutex);
36668864b4e5STejun Heo 	put_unbound_pool(pool);
3667a892caccSTejun Heo 	mutex_unlock(&wq_pool_mutex);
3668a892caccSTejun Heo 
366925b00775SPaul E. McKenney 	call_rcu(&pwq->rcu, rcu_free_pwq);
36708864b4e5STejun Heo 
36718864b4e5STejun Heo 	/*
36728864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
3673e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
36748864b4e5STejun Heo 	 */
3675669de8bdSBart Van Assche 	if (is_last) {
3676669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
367725b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
36786029a918STejun Heo 	}
3679669de8bdSBart Van Assche }
36808864b4e5STejun Heo 
36810fbd95aaSTejun Heo /**
3682699ce097STejun Heo  * pwq_adjust_max_active - update a pwq's max_active to the current setting
36830fbd95aaSTejun Heo  * @pwq: target pool_workqueue
36840fbd95aaSTejun Heo  *
3685699ce097STejun Heo  * If @pwq isn't freezing, set @pwq->max_active to the associated
3686699ce097STejun Heo  * workqueue's saved_max_active and activate delayed work items
3687699ce097STejun Heo  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
36880fbd95aaSTejun Heo  */
3689699ce097STejun Heo static void pwq_adjust_max_active(struct pool_workqueue *pwq)
36900fbd95aaSTejun Heo {
3691699ce097STejun Heo 	struct workqueue_struct *wq = pwq->wq;
3692699ce097STejun Heo 	bool freezable = wq->flags & WQ_FREEZABLE;
36933347fa09STejun Heo 	unsigned long flags;
3694699ce097STejun Heo 
3695699ce097STejun Heo 	/* for @wq->saved_max_active */
3696a357fc03SLai Jiangshan 	lockdep_assert_held(&wq->mutex);
3697699ce097STejun Heo 
3698699ce097STejun Heo 	/* fast exit for non-freezable wqs */
3699699ce097STejun Heo 	if (!freezable && pwq->max_active == wq->saved_max_active)
3700699ce097STejun Heo 		return;
3701699ce097STejun Heo 
37023347fa09STejun Heo 	/* this function can be called during early boot w/ irq disabled */
37033347fa09STejun Heo 	spin_lock_irqsave(&pwq->pool->lock, flags);
3704699ce097STejun Heo 
370574b414eaSLai Jiangshan 	/*
370674b414eaSLai Jiangshan 	 * During [un]freezing, the caller is responsible for ensuring that
370774b414eaSLai Jiangshan 	 * this function is called at least once after @workqueue_freezing
370874b414eaSLai Jiangshan 	 * is updated and visible.
370974b414eaSLai Jiangshan 	 */
371074b414eaSLai Jiangshan 	if (!freezable || !workqueue_freezing) {
3711699ce097STejun Heo 		pwq->max_active = wq->saved_max_active;
37120fbd95aaSTejun Heo 
37130fbd95aaSTejun Heo 		while (!list_empty(&pwq->delayed_works) &&
37140fbd95aaSTejun Heo 		       pwq->nr_active < pwq->max_active)
37150fbd95aaSTejun Heo 			pwq_activate_first_delayed(pwq);
3716951a078aSLai Jiangshan 
3717951a078aSLai Jiangshan 		/*
3718951a078aSLai Jiangshan 		 * Need to kick a worker after thawed or an unbound wq's
3719951a078aSLai Jiangshan 		 * max_active is bumped.  It's a slow path.  Do it always.
3720951a078aSLai Jiangshan 		 */
3721951a078aSLai Jiangshan 		wake_up_worker(pwq->pool);
3722699ce097STejun Heo 	} else {
3723699ce097STejun Heo 		pwq->max_active = 0;
3724699ce097STejun Heo 	}
3725699ce097STejun Heo 
37263347fa09STejun Heo 	spin_unlock_irqrestore(&pwq->pool->lock, flags);
37270fbd95aaSTejun Heo }
37280fbd95aaSTejun Heo 
3729e50aba9aSTejun Heo /* initialize newly alloced @pwq which is associated with @wq and @pool */
3730f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3731f147f29eSTejun Heo 		     struct worker_pool *pool)
3732d2c1d404STejun Heo {
3733d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3734d2c1d404STejun Heo 
3735e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
3736e50aba9aSTejun Heo 
3737d2c1d404STejun Heo 	pwq->pool = pool;
3738d2c1d404STejun Heo 	pwq->wq = wq;
3739d2c1d404STejun Heo 	pwq->flush_color = -1;
37408864b4e5STejun Heo 	pwq->refcnt = 1;
3741d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->delayed_works);
37421befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
3743d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
37448864b4e5STejun Heo 	INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3745f147f29eSTejun Heo }
3746d2c1d404STejun Heo 
3747f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
37481befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
3749f147f29eSTejun Heo {
3750f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
3751f147f29eSTejun Heo 
3752f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
375375ccf595STejun Heo 
37541befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
37551befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
37561befcf30STejun Heo 		return;
37571befcf30STejun Heo 
375829b1cb41SLai Jiangshan 	/* set the matching work_color */
375975ccf595STejun Heo 	pwq->work_color = wq->work_color;
3760983ca25eSTejun Heo 
3761983ca25eSTejun Heo 	/* sync max_active to the current setting */
3762983ca25eSTejun Heo 	pwq_adjust_max_active(pwq);
3763983ca25eSTejun Heo 
3764983ca25eSTejun Heo 	/* link in @pwq */
37659e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3766df2d5ae4STejun Heo }
37676029a918STejun Heo 
3768f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3769f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3770f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
3771f147f29eSTejun Heo {
3772f147f29eSTejun Heo 	struct worker_pool *pool;
3773f147f29eSTejun Heo 	struct pool_workqueue *pwq;
3774f147f29eSTejun Heo 
3775f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3776f147f29eSTejun Heo 
3777f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
3778f147f29eSTejun Heo 	if (!pool)
3779f147f29eSTejun Heo 		return NULL;
3780f147f29eSTejun Heo 
3781e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3782f147f29eSTejun Heo 	if (!pwq) {
3783f147f29eSTejun Heo 		put_unbound_pool(pool);
3784f147f29eSTejun Heo 		return NULL;
3785f147f29eSTejun Heo 	}
3786f147f29eSTejun Heo 
3787f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
3788f147f29eSTejun Heo 	return pwq;
3789d2c1d404STejun Heo }
3790d2c1d404STejun Heo 
37914c16bd32STejun Heo /**
379230186c6fSGong Zhaogang  * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
3793042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
37944c16bd32STejun Heo  * @node: the target NUMA node
37954c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
37964c16bd32STejun Heo  * @cpumask: outarg, the resulting cpumask
37974c16bd32STejun Heo  *
37984c16bd32STejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @node.  If
37994c16bd32STejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during
3800d185af30SYacine Belkadi  * calculation.  The result is stored in @cpumask.
38014c16bd32STejun Heo  *
38024c16bd32STejun Heo  * If NUMA affinity is not enabled, @attrs->cpumask is always used.  If
38034c16bd32STejun Heo  * enabled and @node has online CPUs requested by @attrs, the returned
38044c16bd32STejun Heo  * cpumask is the intersection of the possible CPUs of @node and
38054c16bd32STejun Heo  * @attrs->cpumask.
38064c16bd32STejun Heo  *
38074c16bd32STejun Heo  * The caller is responsible for ensuring that the cpumask of @node stays
38084c16bd32STejun Heo  * stable.
3809d185af30SYacine Belkadi  *
3810d185af30SYacine Belkadi  * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3811d185af30SYacine Belkadi  * %false if equal.
38124c16bd32STejun Heo  */
38134c16bd32STejun Heo static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
38144c16bd32STejun Heo 				 int cpu_going_down, cpumask_t *cpumask)
38154c16bd32STejun Heo {
3816d55262c4STejun Heo 	if (!wq_numa_enabled || attrs->no_numa)
38174c16bd32STejun Heo 		goto use_dfl;
38184c16bd32STejun Heo 
38194c16bd32STejun Heo 	/* does @node have any online CPUs @attrs wants? */
38204c16bd32STejun Heo 	cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
38214c16bd32STejun Heo 	if (cpu_going_down >= 0)
38224c16bd32STejun Heo 		cpumask_clear_cpu(cpu_going_down, cpumask);
38234c16bd32STejun Heo 
38244c16bd32STejun Heo 	if (cpumask_empty(cpumask))
38254c16bd32STejun Heo 		goto use_dfl;
38264c16bd32STejun Heo 
38274c16bd32STejun Heo 	/* yeap, return possible CPUs in @node that @attrs wants */
38284c16bd32STejun Heo 	cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
38291ad0f0a7SMichael Bringmann 
38301ad0f0a7SMichael Bringmann 	if (cpumask_empty(cpumask)) {
38311ad0f0a7SMichael Bringmann 		pr_warn_once("WARNING: workqueue cpumask: online intersect > "
38321ad0f0a7SMichael Bringmann 				"possible intersect\n");
38331ad0f0a7SMichael Bringmann 		return false;
38341ad0f0a7SMichael Bringmann 	}
38351ad0f0a7SMichael Bringmann 
38364c16bd32STejun Heo 	return !cpumask_equal(cpumask, attrs->cpumask);
38374c16bd32STejun Heo 
38384c16bd32STejun Heo use_dfl:
38394c16bd32STejun Heo 	cpumask_copy(cpumask, attrs->cpumask);
38404c16bd32STejun Heo 	return false;
38414c16bd32STejun Heo }
38424c16bd32STejun Heo 
38431befcf30STejun Heo /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
38441befcf30STejun Heo static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
38451befcf30STejun Heo 						   int node,
38461befcf30STejun Heo 						   struct pool_workqueue *pwq)
38471befcf30STejun Heo {
38481befcf30STejun Heo 	struct pool_workqueue *old_pwq;
38491befcf30STejun Heo 
38505b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
38511befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
38521befcf30STejun Heo 
38531befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
38541befcf30STejun Heo 	link_pwq(pwq);
38551befcf30STejun Heo 
38561befcf30STejun Heo 	old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
38571befcf30STejun Heo 	rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
38581befcf30STejun Heo 	return old_pwq;
38591befcf30STejun Heo }
38601befcf30STejun Heo 
38612d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
38622d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
38632d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
38642d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
3865042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
38662d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
38672d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
38682d5f0764SLai Jiangshan };
38692d5f0764SLai Jiangshan 
38702d5f0764SLai Jiangshan /* free the resources after success or abort */
38712d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
38722d5f0764SLai Jiangshan {
38732d5f0764SLai Jiangshan 	if (ctx) {
38742d5f0764SLai Jiangshan 		int node;
38752d5f0764SLai Jiangshan 
38762d5f0764SLai Jiangshan 		for_each_node(node)
38772d5f0764SLai Jiangshan 			put_pwq_unlocked(ctx->pwq_tbl[node]);
38782d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
38792d5f0764SLai Jiangshan 
38802d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
38812d5f0764SLai Jiangshan 
38822d5f0764SLai Jiangshan 		kfree(ctx);
38832d5f0764SLai Jiangshan 	}
38842d5f0764SLai Jiangshan }
38852d5f0764SLai Jiangshan 
38862d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
38872d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
38882d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
38892d5f0764SLai Jiangshan 		      const struct workqueue_attrs *attrs)
38902d5f0764SLai Jiangshan {
38912d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
38922d5f0764SLai Jiangshan 	struct workqueue_attrs *new_attrs, *tmp_attrs;
38932d5f0764SLai Jiangshan 	int node;
38942d5f0764SLai Jiangshan 
38952d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
38962d5f0764SLai Jiangshan 
3897acafe7e3SKees Cook 	ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_node_ids), GFP_KERNEL);
38982d5f0764SLai Jiangshan 
38992d5f0764SLai Jiangshan 	new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
39002d5f0764SLai Jiangshan 	tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
39012d5f0764SLai Jiangshan 	if (!ctx || !new_attrs || !tmp_attrs)
39022d5f0764SLai Jiangshan 		goto out_free;
39032d5f0764SLai Jiangshan 
3904042f7df1SLai Jiangshan 	/*
3905042f7df1SLai Jiangshan 	 * Calculate the attrs of the default pwq.
3906042f7df1SLai Jiangshan 	 * If the user configured cpumask doesn't overlap with the
3907042f7df1SLai Jiangshan 	 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
3908042f7df1SLai Jiangshan 	 */
39092d5f0764SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
3910b05a7928SFrederic Weisbecker 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, wq_unbound_cpumask);
3911042f7df1SLai Jiangshan 	if (unlikely(cpumask_empty(new_attrs->cpumask)))
3912042f7df1SLai Jiangshan 		cpumask_copy(new_attrs->cpumask, wq_unbound_cpumask);
39132d5f0764SLai Jiangshan 
39142d5f0764SLai Jiangshan 	/*
39152d5f0764SLai Jiangshan 	 * We may create multiple pwqs with differing cpumasks.  Make a
39162d5f0764SLai Jiangshan 	 * copy of @new_attrs which will be modified and used to obtain
39172d5f0764SLai Jiangshan 	 * pools.
39182d5f0764SLai Jiangshan 	 */
39192d5f0764SLai Jiangshan 	copy_workqueue_attrs(tmp_attrs, new_attrs);
39202d5f0764SLai Jiangshan 
39212d5f0764SLai Jiangshan 	/*
39222d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
39232d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
39242d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
39252d5f0764SLai Jiangshan 	 */
39262d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
39272d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
39282d5f0764SLai Jiangshan 		goto out_free;
39292d5f0764SLai Jiangshan 
39302d5f0764SLai Jiangshan 	for_each_node(node) {
3931042f7df1SLai Jiangshan 		if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
39322d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
39332d5f0764SLai Jiangshan 			if (!ctx->pwq_tbl[node])
39342d5f0764SLai Jiangshan 				goto out_free;
39352d5f0764SLai Jiangshan 		} else {
39362d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
39372d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = ctx->dfl_pwq;
39382d5f0764SLai Jiangshan 		}
39392d5f0764SLai Jiangshan 	}
39402d5f0764SLai Jiangshan 
3941042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
3942042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
3943042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
39442d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
3945042f7df1SLai Jiangshan 
39462d5f0764SLai Jiangshan 	ctx->wq = wq;
39472d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
39482d5f0764SLai Jiangshan 	return ctx;
39492d5f0764SLai Jiangshan 
39502d5f0764SLai Jiangshan out_free:
39512d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
39522d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
39532d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
39542d5f0764SLai Jiangshan 	return NULL;
39552d5f0764SLai Jiangshan }
39562d5f0764SLai Jiangshan 
39572d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
39582d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
39592d5f0764SLai Jiangshan {
39602d5f0764SLai Jiangshan 	int node;
39612d5f0764SLai Jiangshan 
39622d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
39632d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
39642d5f0764SLai Jiangshan 
39652d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
39662d5f0764SLai Jiangshan 
39672d5f0764SLai Jiangshan 	/* save the previous pwq and install the new one */
39682d5f0764SLai Jiangshan 	for_each_node(node)
39692d5f0764SLai Jiangshan 		ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
39702d5f0764SLai Jiangshan 							  ctx->pwq_tbl[node]);
39712d5f0764SLai Jiangshan 
39722d5f0764SLai Jiangshan 	/* @dfl_pwq might not have been used, ensure it's linked */
39732d5f0764SLai Jiangshan 	link_pwq(ctx->dfl_pwq);
39742d5f0764SLai Jiangshan 	swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
39752d5f0764SLai Jiangshan 
39762d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
39772d5f0764SLai Jiangshan }
39782d5f0764SLai Jiangshan 
3979a0111cf6SLai Jiangshan static void apply_wqattrs_lock(void)
3980a0111cf6SLai Jiangshan {
3981a0111cf6SLai Jiangshan 	/* CPUs should stay stable across pwq creations and installations */
3982a0111cf6SLai Jiangshan 	get_online_cpus();
3983a0111cf6SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
3984a0111cf6SLai Jiangshan }
3985a0111cf6SLai Jiangshan 
3986a0111cf6SLai Jiangshan static void apply_wqattrs_unlock(void)
3987a0111cf6SLai Jiangshan {
3988a0111cf6SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
3989a0111cf6SLai Jiangshan 	put_online_cpus();
3990a0111cf6SLai Jiangshan }
3991a0111cf6SLai Jiangshan 
3992a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
3993a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
3994a0111cf6SLai Jiangshan {
3995a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
3996a0111cf6SLai Jiangshan 
3997a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
3998a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
3999a0111cf6SLai Jiangshan 		return -EINVAL;
4000a0111cf6SLai Jiangshan 
4001a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
40020a94efb5STejun Heo 	if (!list_empty(&wq->pwqs)) {
40030a94efb5STejun Heo 		if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4004a0111cf6SLai Jiangshan 			return -EINVAL;
4005a0111cf6SLai Jiangshan 
40060a94efb5STejun Heo 		wq->flags &= ~__WQ_ORDERED;
40070a94efb5STejun Heo 	}
40080a94efb5STejun Heo 
4009a0111cf6SLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs);
40106201171eSwanghaibin 	if (!ctx)
40116201171eSwanghaibin 		return -ENOMEM;
4012a0111cf6SLai Jiangshan 
4013a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
4014a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
4015a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
4016a0111cf6SLai Jiangshan 
40176201171eSwanghaibin 	return 0;
4018a0111cf6SLai Jiangshan }
4019a0111cf6SLai Jiangshan 
40209e8cd2f5STejun Heo /**
40219e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
40229e8cd2f5STejun Heo  * @wq: the target workqueue
40239e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
40249e8cd2f5STejun Heo  *
40254c16bd32STejun Heo  * Apply @attrs to an unbound workqueue @wq.  Unless disabled, on NUMA
40264c16bd32STejun Heo  * machines, this function maps a separate pwq to each NUMA node with
40274c16bd32STejun Heo  * possibles CPUs in @attrs->cpumask so that work items are affine to the
40284c16bd32STejun Heo  * NUMA node it was issued on.  Older pwqs are released as in-flight work
40294c16bd32STejun Heo  * items finish.  Note that a work item which repeatedly requeues itself
40304c16bd32STejun Heo  * back-to-back will stay on its current pwq.
40319e8cd2f5STejun Heo  *
4032d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
4033d185af30SYacine Belkadi  *
4034d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
40359e8cd2f5STejun Heo  */
40369e8cd2f5STejun Heo int apply_workqueue_attrs(struct workqueue_struct *wq,
40379e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
40389e8cd2f5STejun Heo {
4039a0111cf6SLai Jiangshan 	int ret;
40409e8cd2f5STejun Heo 
4041a0111cf6SLai Jiangshan 	apply_wqattrs_lock();
4042a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
4043a0111cf6SLai Jiangshan 	apply_wqattrs_unlock();
40442d5f0764SLai Jiangshan 
40452d5f0764SLai Jiangshan 	return ret;
40469e8cd2f5STejun Heo }
40476106c0f8SNeilBrown EXPORT_SYMBOL_GPL(apply_workqueue_attrs);
40489e8cd2f5STejun Heo 
40494c16bd32STejun Heo /**
40504c16bd32STejun Heo  * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
40514c16bd32STejun Heo  * @wq: the target workqueue
40524c16bd32STejun Heo  * @cpu: the CPU coming up or going down
40534c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
40544c16bd32STejun Heo  *
40554c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
40564c16bd32STejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update NUMA affinity of
40574c16bd32STejun Heo  * @wq accordingly.
40584c16bd32STejun Heo  *
40594c16bd32STejun Heo  * If NUMA affinity can't be adjusted due to memory allocation failure, it
40604c16bd32STejun Heo  * falls back to @wq->dfl_pwq which may not be optimal but is always
40614c16bd32STejun Heo  * correct.
40624c16bd32STejun Heo  *
40634c16bd32STejun Heo  * Note that when the last allowed CPU of a NUMA node goes offline for a
40644c16bd32STejun Heo  * workqueue with a cpumask spanning multiple nodes, the workers which were
40654c16bd32STejun Heo  * already executing the work items for the workqueue will lose their CPU
40664c16bd32STejun Heo  * affinity and may execute on any CPU.  This is similar to how per-cpu
40674c16bd32STejun Heo  * workqueues behave on CPU_DOWN.  If a workqueue user wants strict
40684c16bd32STejun Heo  * affinity, it's the user's responsibility to flush the work item from
40694c16bd32STejun Heo  * CPU_DOWN_PREPARE.
40704c16bd32STejun Heo  */
40714c16bd32STejun Heo static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
40724c16bd32STejun Heo 				   bool online)
40734c16bd32STejun Heo {
40744c16bd32STejun Heo 	int node = cpu_to_node(cpu);
40754c16bd32STejun Heo 	int cpu_off = online ? -1 : cpu;
40764c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
40774c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
40784c16bd32STejun Heo 	cpumask_t *cpumask;
40794c16bd32STejun Heo 
40804c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
40814c16bd32STejun Heo 
4082f7142ed4SLai Jiangshan 	if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
4083f7142ed4SLai Jiangshan 	    wq->unbound_attrs->no_numa)
40844c16bd32STejun Heo 		return;
40854c16bd32STejun Heo 
40864c16bd32STejun Heo 	/*
40874c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
40884c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
40894c16bd32STejun Heo 	 * CPU hotplug exclusion.
40904c16bd32STejun Heo 	 */
40914c16bd32STejun Heo 	target_attrs = wq_update_unbound_numa_attrs_buf;
40924c16bd32STejun Heo 	cpumask = target_attrs->cpumask;
40934c16bd32STejun Heo 
40944c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
40954c16bd32STejun Heo 	pwq = unbound_pwq_by_node(wq, node);
40964c16bd32STejun Heo 
40974c16bd32STejun Heo 	/*
40984c16bd32STejun Heo 	 * Let's determine what needs to be done.  If the target cpumask is
4099042f7df1SLai Jiangshan 	 * different from the default pwq's, we need to compare it to @pwq's
4100042f7df1SLai Jiangshan 	 * and create a new one if they don't match.  If the target cpumask
4101042f7df1SLai Jiangshan 	 * equals the default pwq's, the default pwq should be used.
41024c16bd32STejun Heo 	 */
4103042f7df1SLai Jiangshan 	if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
41044c16bd32STejun Heo 		if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
4105f7142ed4SLai Jiangshan 			return;
41064c16bd32STejun Heo 	} else {
41074c16bd32STejun Heo 		goto use_dfl_pwq;
41084c16bd32STejun Heo 	}
41094c16bd32STejun Heo 
41104c16bd32STejun Heo 	/* create a new pwq */
41114c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
41124c16bd32STejun Heo 	if (!pwq) {
41132d916033SFabian Frederick 		pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
41144c16bd32STejun Heo 			wq->name);
411577f300b1SDaeseok Youn 		goto use_dfl_pwq;
41164c16bd32STejun Heo 	}
41174c16bd32STejun Heo 
4118f7142ed4SLai Jiangshan 	/* Install the new pwq. */
41194c16bd32STejun Heo 	mutex_lock(&wq->mutex);
41204c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, pwq);
41214c16bd32STejun Heo 	goto out_unlock;
41224c16bd32STejun Heo 
41234c16bd32STejun Heo use_dfl_pwq:
4124f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
41254c16bd32STejun Heo 	spin_lock_irq(&wq->dfl_pwq->pool->lock);
41264c16bd32STejun Heo 	get_pwq(wq->dfl_pwq);
41274c16bd32STejun Heo 	spin_unlock_irq(&wq->dfl_pwq->pool->lock);
41284c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
41294c16bd32STejun Heo out_unlock:
41304c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
41314c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
41324c16bd32STejun Heo }
41334c16bd32STejun Heo 
413430cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
41351da177e4SLinus Torvalds {
413649e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
41378a2b7538STejun Heo 	int cpu, ret;
4138e1d8aa9fSFrederic Weisbecker 
413930cdf249STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
4140420c0ddbSTejun Heo 		wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
4141420c0ddbSTejun Heo 		if (!wq->cpu_pwqs)
414230cdf249STejun Heo 			return -ENOMEM;
414330cdf249STejun Heo 
414430cdf249STejun Heo 		for_each_possible_cpu(cpu) {
41457fb98ea7STejun Heo 			struct pool_workqueue *pwq =
41467fb98ea7STejun Heo 				per_cpu_ptr(wq->cpu_pwqs, cpu);
41477a62c2c8STejun Heo 			struct worker_pool *cpu_pools =
4148f02ae73aSTejun Heo 				per_cpu(cpu_worker_pools, cpu);
414930cdf249STejun Heo 
4150f147f29eSTejun Heo 			init_pwq(pwq, wq, &cpu_pools[highpri]);
4151f147f29eSTejun Heo 
4152f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
41531befcf30STejun Heo 			link_pwq(pwq);
4154f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
415530cdf249STejun Heo 		}
415630cdf249STejun Heo 		return 0;
41578a2b7538STejun Heo 	} else if (wq->flags & __WQ_ORDERED) {
41588a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
41598a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
41608a2b7538STejun Heo 		WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
41618a2b7538STejun Heo 			      wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
41628a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
41638a2b7538STejun Heo 		return ret;
41649e8cd2f5STejun Heo 	} else {
41659e8cd2f5STejun Heo 		return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
41669e8cd2f5STejun Heo 	}
41670f900049STejun Heo }
41680f900049STejun Heo 
4169f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
4170f3421797STejun Heo 			       const char *name)
4171b71ab8c2STejun Heo {
4172f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
4173f3421797STejun Heo 
4174f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
4175044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4176f3421797STejun Heo 			max_active, name, 1, lim);
4177b71ab8c2STejun Heo 
4178f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
4179b71ab8c2STejun Heo }
4180b71ab8c2STejun Heo 
4181983c7515STejun Heo /*
4182983c7515STejun Heo  * Workqueues which may be used during memory reclaim should have a rescuer
4183983c7515STejun Heo  * to guarantee forward progress.
4184983c7515STejun Heo  */
4185983c7515STejun Heo static int init_rescuer(struct workqueue_struct *wq)
4186983c7515STejun Heo {
4187983c7515STejun Heo 	struct worker *rescuer;
4188983c7515STejun Heo 	int ret;
4189983c7515STejun Heo 
4190983c7515STejun Heo 	if (!(wq->flags & WQ_MEM_RECLAIM))
4191983c7515STejun Heo 		return 0;
4192983c7515STejun Heo 
4193983c7515STejun Heo 	rescuer = alloc_worker(NUMA_NO_NODE);
4194983c7515STejun Heo 	if (!rescuer)
4195983c7515STejun Heo 		return -ENOMEM;
4196983c7515STejun Heo 
4197983c7515STejun Heo 	rescuer->rescue_wq = wq;
4198983c7515STejun Heo 	rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name);
4199983c7515STejun Heo 	ret = PTR_ERR_OR_ZERO(rescuer->task);
4200983c7515STejun Heo 	if (ret) {
4201983c7515STejun Heo 		kfree(rescuer);
4202983c7515STejun Heo 		return ret;
4203983c7515STejun Heo 	}
4204983c7515STejun Heo 
4205983c7515STejun Heo 	wq->rescuer = rescuer;
4206983c7515STejun Heo 	kthread_bind_mask(rescuer->task, cpu_possible_mask);
4207983c7515STejun Heo 	wake_up_process(rescuer->task);
4208983c7515STejun Heo 
4209983c7515STejun Heo 	return 0;
4210983c7515STejun Heo }
4211983c7515STejun Heo 
4212a2775bbcSMathieu Malaterre __printf(1, 4)
4213669de8bdSBart Van Assche struct workqueue_struct *alloc_workqueue(const char *fmt,
421497e37d7bSTejun Heo 					 unsigned int flags,
4215669de8bdSBart Van Assche 					 int max_active, ...)
42163af24433SOleg Nesterov {
4217df2d5ae4STejun Heo 	size_t tbl_size = 0;
4218ecf6881fSTejun Heo 	va_list args;
42193af24433SOleg Nesterov 	struct workqueue_struct *wq;
422049e3cf44STejun Heo 	struct pool_workqueue *pwq;
4221b196be89STejun Heo 
42225c0338c6STejun Heo 	/*
42235c0338c6STejun Heo 	 * Unbound && max_active == 1 used to imply ordered, which is no
42245c0338c6STejun Heo 	 * longer the case on NUMA machines due to per-node pools.  While
42255c0338c6STejun Heo 	 * alloc_ordered_workqueue() is the right way to create an ordered
42265c0338c6STejun Heo 	 * workqueue, keep the previous behavior to avoid subtle breakages
42275c0338c6STejun Heo 	 * on NUMA.
42285c0338c6STejun Heo 	 */
42295c0338c6STejun Heo 	if ((flags & WQ_UNBOUND) && max_active == 1)
42305c0338c6STejun Heo 		flags |= __WQ_ORDERED;
42315c0338c6STejun Heo 
4232cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
4233cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4234cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
4235cee22a15SViresh Kumar 
4236ecf6881fSTejun Heo 	/* allocate wq and format name */
4237df2d5ae4STejun Heo 	if (flags & WQ_UNBOUND)
4238ddcb57e2SLai Jiangshan 		tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
4239df2d5ae4STejun Heo 
4240df2d5ae4STejun Heo 	wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
4241b196be89STejun Heo 	if (!wq)
4242d2c1d404STejun Heo 		return NULL;
4243b196be89STejun Heo 
42446029a918STejun Heo 	if (flags & WQ_UNBOUND) {
42456029a918STejun Heo 		wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
42466029a918STejun Heo 		if (!wq->unbound_attrs)
42476029a918STejun Heo 			goto err_free_wq;
42486029a918STejun Heo 	}
42496029a918STejun Heo 
4250669de8bdSBart Van Assche 	va_start(args, max_active);
4251ecf6881fSTejun Heo 	vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4252b196be89STejun Heo 	va_end(args);
42533af24433SOleg Nesterov 
4254d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
4255b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
42563af24433SOleg Nesterov 
4257b196be89STejun Heo 	/* init wq */
425897e37d7bSTejun Heo 	wq->flags = flags;
4259a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
42603c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
4261112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
426230cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
426373f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
426473f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
4265493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
42663af24433SOleg Nesterov 
4267669de8bdSBart Van Assche 	wq_init_lockdep(wq);
4268cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
42693af24433SOleg Nesterov 
427030cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
4271d2c1d404STejun Heo 		goto err_free_wq;
42721537663fSTejun Heo 
427340c17f75STejun Heo 	if (wq_online && init_rescuer(wq) < 0)
4274d2c1d404STejun Heo 		goto err_destroy;
4275e22bee78STejun Heo 
4276226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4277226223abSTejun Heo 		goto err_destroy;
4278226223abSTejun Heo 
42796af8bf3dSOleg Nesterov 	/*
428068e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
428168e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
428268e13a67SLai Jiangshan 	 * list.
42836af8bf3dSOleg Nesterov 	 */
428468e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4285a0a1a5fdSTejun Heo 
4286a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
428749e3cf44STejun Heo 	for_each_pwq(pwq, wq)
4288699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4289a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4290a0a1a5fdSTejun Heo 
4291e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
4292a0a1a5fdSTejun Heo 
429368e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
42943af24433SOleg Nesterov 
42953af24433SOleg Nesterov 	return wq;
4296d2c1d404STejun Heo 
4297d2c1d404STejun Heo err_free_wq:
4298009bb421SBart Van Assche 	wq_unregister_lockdep(wq);
4299009bb421SBart Van Assche 	wq_free_lockdep(wq);
43006029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
43014690c4abSTejun Heo 	kfree(wq);
4302d2c1d404STejun Heo 	return NULL;
4303d2c1d404STejun Heo err_destroy:
4304d2c1d404STejun Heo 	destroy_workqueue(wq);
43054690c4abSTejun Heo 	return NULL;
43061da177e4SLinus Torvalds }
4307669de8bdSBart Van Assche EXPORT_SYMBOL_GPL(alloc_workqueue);
43081da177e4SLinus Torvalds 
43093af24433SOleg Nesterov /**
43103af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
43113af24433SOleg Nesterov  * @wq: target workqueue
43123af24433SOleg Nesterov  *
43133af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
43143af24433SOleg Nesterov  */
43153af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
43163af24433SOleg Nesterov {
431749e3cf44STejun Heo 	struct pool_workqueue *pwq;
43184c16bd32STejun Heo 	int node;
43193af24433SOleg Nesterov 
43209c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
43219c5a2ba7STejun Heo 	drain_workqueue(wq);
4322c8efcc25STejun Heo 
43236183c009STejun Heo 	/* sanity checks */
4324b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
432549e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
43266183c009STejun Heo 		int i;
43276183c009STejun Heo 
432876af4d93STejun Heo 		for (i = 0; i < WORK_NR_COLORS; i++) {
432976af4d93STejun Heo 			if (WARN_ON(pwq->nr_in_flight[i])) {
4330b09f4fd3SLai Jiangshan 				mutex_unlock(&wq->mutex);
4331fa07fb6aSTejun Heo 				show_workqueue_state();
43326183c009STejun Heo 				return;
433376af4d93STejun Heo 			}
433476af4d93STejun Heo 		}
433576af4d93STejun Heo 
43365c529597SLai Jiangshan 		if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
43378864b4e5STejun Heo 		    WARN_ON(pwq->nr_active) ||
433876af4d93STejun Heo 		    WARN_ON(!list_empty(&pwq->delayed_works))) {
4339b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
4340fa07fb6aSTejun Heo 			show_workqueue_state();
43416183c009STejun Heo 			return;
43426183c009STejun Heo 		}
434376af4d93STejun Heo 	}
4344b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
43456183c009STejun Heo 
4346a0a1a5fdSTejun Heo 	/*
4347a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
4348a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
4349a0a1a5fdSTejun Heo 	 */
435068e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4351e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
435268e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
43533af24433SOleg Nesterov 
4354226223abSTejun Heo 	workqueue_sysfs_unregister(wq);
4355226223abSTejun Heo 
4356e2dca7adSTejun Heo 	if (wq->rescuer)
4357e22bee78STejun Heo 		kthread_stop(wq->rescuer->task);
4358e22bee78STejun Heo 
43598864b4e5STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
4360669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
436129c91e99STejun Heo 		/*
43628864b4e5STejun Heo 		 * The base ref is never dropped on per-cpu pwqs.  Directly
4363e2dca7adSTejun Heo 		 * schedule RCU free.
436429c91e99STejun Heo 		 */
436525b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
43668864b4e5STejun Heo 	} else {
43678864b4e5STejun Heo 		/*
43688864b4e5STejun Heo 		 * We're the sole accessor of @wq at this point.  Directly
43694c16bd32STejun Heo 		 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
43704c16bd32STejun Heo 		 * @wq will be freed when the last pwq is released.
43718864b4e5STejun Heo 		 */
43724c16bd32STejun Heo 		for_each_node(node) {
43734c16bd32STejun Heo 			pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
43744c16bd32STejun Heo 			RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
43754c16bd32STejun Heo 			put_pwq_unlocked(pwq);
43764c16bd32STejun Heo 		}
43774c16bd32STejun Heo 
43784c16bd32STejun Heo 		/*
43794c16bd32STejun Heo 		 * Put dfl_pwq.  @wq may be freed any time after dfl_pwq is
43804c16bd32STejun Heo 		 * put.  Don't access it afterwards.
43814c16bd32STejun Heo 		 */
43824c16bd32STejun Heo 		pwq = wq->dfl_pwq;
43834c16bd32STejun Heo 		wq->dfl_pwq = NULL;
4384dce90d47STejun Heo 		put_pwq_unlocked(pwq);
438529c91e99STejun Heo 	}
43863af24433SOleg Nesterov }
43873af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
43883af24433SOleg Nesterov 
4389dcd989cbSTejun Heo /**
4390dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
4391dcd989cbSTejun Heo  * @wq: target workqueue
4392dcd989cbSTejun Heo  * @max_active: new max_active value.
4393dcd989cbSTejun Heo  *
4394dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
4395dcd989cbSTejun Heo  *
4396dcd989cbSTejun Heo  * CONTEXT:
4397dcd989cbSTejun Heo  * Don't call from IRQ context.
4398dcd989cbSTejun Heo  */
4399dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4400dcd989cbSTejun Heo {
440149e3cf44STejun Heo 	struct pool_workqueue *pwq;
4402dcd989cbSTejun Heo 
44038719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
44040a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
44058719dceaSTejun Heo 		return;
44068719dceaSTejun Heo 
4407f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4408dcd989cbSTejun Heo 
4409a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4410dcd989cbSTejun Heo 
44110a94efb5STejun Heo 	wq->flags &= ~__WQ_ORDERED;
4412dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4413dcd989cbSTejun Heo 
4414699ce097STejun Heo 	for_each_pwq(pwq, wq)
4415699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4416dcd989cbSTejun Heo 
4417a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4418dcd989cbSTejun Heo }
4419dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4420dcd989cbSTejun Heo 
4421dcd989cbSTejun Heo /**
442227d4ee03SLukas Wunner  * current_work - retrieve %current task's work struct
442327d4ee03SLukas Wunner  *
442427d4ee03SLukas Wunner  * Determine if %current task is a workqueue worker and what it's working on.
442527d4ee03SLukas Wunner  * Useful to find out the context that the %current task is running in.
442627d4ee03SLukas Wunner  *
442727d4ee03SLukas Wunner  * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
442827d4ee03SLukas Wunner  */
442927d4ee03SLukas Wunner struct work_struct *current_work(void)
443027d4ee03SLukas Wunner {
443127d4ee03SLukas Wunner 	struct worker *worker = current_wq_worker();
443227d4ee03SLukas Wunner 
443327d4ee03SLukas Wunner 	return worker ? worker->current_work : NULL;
443427d4ee03SLukas Wunner }
443527d4ee03SLukas Wunner EXPORT_SYMBOL(current_work);
443627d4ee03SLukas Wunner 
443727d4ee03SLukas Wunner /**
4438e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4439e6267616STejun Heo  *
4440e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4441e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4442d185af30SYacine Belkadi  *
4443d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
4444e6267616STejun Heo  */
4445e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4446e6267616STejun Heo {
4447e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4448e6267616STejun Heo 
44496a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
4450e6267616STejun Heo }
4451e6267616STejun Heo 
4452e6267616STejun Heo /**
4453dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4454dcd989cbSTejun Heo  * @cpu: CPU in question
4455dcd989cbSTejun Heo  * @wq: target workqueue
4456dcd989cbSTejun Heo  *
4457dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4458dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4459dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4460dcd989cbSTejun Heo  *
4461d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4462d3251859STejun Heo  * Note that both per-cpu and unbound workqueues may be associated with
4463d3251859STejun Heo  * multiple pool_workqueues which have separate congested states.  A
4464d3251859STejun Heo  * workqueue being congested on one CPU doesn't mean the workqueue is also
4465d3251859STejun Heo  * contested on other CPUs / NUMA nodes.
4466d3251859STejun Heo  *
4467d185af30SYacine Belkadi  * Return:
4468dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4469dcd989cbSTejun Heo  */
4470d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4471dcd989cbSTejun Heo {
44727fb98ea7STejun Heo 	struct pool_workqueue *pwq;
447376af4d93STejun Heo 	bool ret;
447476af4d93STejun Heo 
447588109453SLai Jiangshan 	rcu_read_lock_sched();
44767fb98ea7STejun Heo 
4477d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
4478d3251859STejun Heo 		cpu = smp_processor_id();
4479d3251859STejun Heo 
44807fb98ea7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
44817fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
44827fb98ea7STejun Heo 	else
4483df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4484dcd989cbSTejun Heo 
448576af4d93STejun Heo 	ret = !list_empty(&pwq->delayed_works);
448688109453SLai Jiangshan 	rcu_read_unlock_sched();
448776af4d93STejun Heo 
448876af4d93STejun Heo 	return ret;
4489dcd989cbSTejun Heo }
4490dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4491dcd989cbSTejun Heo 
4492dcd989cbSTejun Heo /**
4493dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4494dcd989cbSTejun Heo  * @work: the work to be tested
4495dcd989cbSTejun Heo  *
4496dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4497dcd989cbSTejun Heo  * synchronization around this function and the test result is
4498dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4499dcd989cbSTejun Heo  *
4500d185af30SYacine Belkadi  * Return:
4501dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
4502dcd989cbSTejun Heo  */
4503dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4504dcd989cbSTejun Heo {
4505fa1b54e6STejun Heo 	struct worker_pool *pool;
4506dcd989cbSTejun Heo 	unsigned long flags;
4507dcd989cbSTejun Heo 	unsigned int ret = 0;
4508dcd989cbSTejun Heo 
4509dcd989cbSTejun Heo 	if (work_pending(work))
4510dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
4511038366c5SLai Jiangshan 
4512fa1b54e6STejun Heo 	local_irq_save(flags);
4513fa1b54e6STejun Heo 	pool = get_work_pool(work);
4514038366c5SLai Jiangshan 	if (pool) {
4515fa1b54e6STejun Heo 		spin_lock(&pool->lock);
4516c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
4517dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
4518fa1b54e6STejun Heo 		spin_unlock(&pool->lock);
4519038366c5SLai Jiangshan 	}
4520fa1b54e6STejun Heo 	local_irq_restore(flags);
4521dcd989cbSTejun Heo 
4522dcd989cbSTejun Heo 	return ret;
4523dcd989cbSTejun Heo }
4524dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
4525dcd989cbSTejun Heo 
45263d1cb205STejun Heo /**
45273d1cb205STejun Heo  * set_worker_desc - set description for the current work item
45283d1cb205STejun Heo  * @fmt: printf-style format string
45293d1cb205STejun Heo  * @...: arguments for the format string
45303d1cb205STejun Heo  *
45313d1cb205STejun Heo  * This function can be called by a running work function to describe what
45323d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
45333d1cb205STejun Heo  * information will be printed out together to help debugging.  The
45343d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
45353d1cb205STejun Heo  */
45363d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
45373d1cb205STejun Heo {
45383d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
45393d1cb205STejun Heo 	va_list args;
45403d1cb205STejun Heo 
45413d1cb205STejun Heo 	if (worker) {
45423d1cb205STejun Heo 		va_start(args, fmt);
45433d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
45443d1cb205STejun Heo 		va_end(args);
45453d1cb205STejun Heo 	}
45463d1cb205STejun Heo }
45475c750d58SSteffen Maier EXPORT_SYMBOL_GPL(set_worker_desc);
45483d1cb205STejun Heo 
45493d1cb205STejun Heo /**
45503d1cb205STejun Heo  * print_worker_info - print out worker information and description
45513d1cb205STejun Heo  * @log_lvl: the log level to use when printing
45523d1cb205STejun Heo  * @task: target task
45533d1cb205STejun Heo  *
45543d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
45553d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
45563d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
45573d1cb205STejun Heo  *
45583d1cb205STejun Heo  * This function can be safely called on any task as long as the
45593d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
45603d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
45613d1cb205STejun Heo  */
45623d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
45633d1cb205STejun Heo {
45643d1cb205STejun Heo 	work_func_t *fn = NULL;
45653d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
45663d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
45673d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
45683d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
45693d1cb205STejun Heo 	struct worker *worker;
45703d1cb205STejun Heo 
45713d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
45723d1cb205STejun Heo 		return;
45733d1cb205STejun Heo 
45743d1cb205STejun Heo 	/*
45753d1cb205STejun Heo 	 * This function is called without any synchronization and @task
45763d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
45773d1cb205STejun Heo 	 */
4578e700591aSPetr Mladek 	worker = kthread_probe_data(task);
45793d1cb205STejun Heo 
45803d1cb205STejun Heo 	/*
45818bf89593STejun Heo 	 * Carefully copy the associated workqueue's workfn, name and desc.
45828bf89593STejun Heo 	 * Keep the original last '\0' in case the original is garbage.
45833d1cb205STejun Heo 	 */
45843d1cb205STejun Heo 	probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
45853d1cb205STejun Heo 	probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
45863d1cb205STejun Heo 	probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
45873d1cb205STejun Heo 	probe_kernel_read(name, wq->name, sizeof(name) - 1);
45883d1cb205STejun Heo 	probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
45893d1cb205STejun Heo 
45903d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
45913d1cb205STejun Heo 		printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
45928bf89593STejun Heo 		if (strcmp(name, desc))
45933d1cb205STejun Heo 			pr_cont(" (%s)", desc);
45943d1cb205STejun Heo 		pr_cont("\n");
45953d1cb205STejun Heo 	}
45963d1cb205STejun Heo }
45973d1cb205STejun Heo 
45983494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
45993494fc30STejun Heo {
46003494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
46013494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
46023494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
46033494fc30STejun Heo 	pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
46043494fc30STejun Heo }
46053494fc30STejun Heo 
46063494fc30STejun Heo static void pr_cont_work(bool comma, struct work_struct *work)
46073494fc30STejun Heo {
46083494fc30STejun Heo 	if (work->func == wq_barrier_func) {
46093494fc30STejun Heo 		struct wq_barrier *barr;
46103494fc30STejun Heo 
46113494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
46123494fc30STejun Heo 
46133494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
46143494fc30STejun Heo 			task_pid_nr(barr->task));
46153494fc30STejun Heo 	} else {
46163494fc30STejun Heo 		pr_cont("%s %pf", comma ? "," : "", work->func);
46173494fc30STejun Heo 	}
46183494fc30STejun Heo }
46193494fc30STejun Heo 
46203494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
46213494fc30STejun Heo {
46223494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
46233494fc30STejun Heo 	struct work_struct *work;
46243494fc30STejun Heo 	struct worker *worker;
46253494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
46263494fc30STejun Heo 	int bkt;
46273494fc30STejun Heo 
46283494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
46293494fc30STejun Heo 	pr_cont_pool_info(pool);
46303494fc30STejun Heo 
46313494fc30STejun Heo 	pr_cont(" active=%d/%d%s\n", pwq->nr_active, pwq->max_active,
46323494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
46333494fc30STejun Heo 
46343494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
46353494fc30STejun Heo 		if (worker->current_pwq == pwq) {
46363494fc30STejun Heo 			has_in_flight = true;
46373494fc30STejun Heo 			break;
46383494fc30STejun Heo 		}
46393494fc30STejun Heo 	}
46403494fc30STejun Heo 	if (has_in_flight) {
46413494fc30STejun Heo 		bool comma = false;
46423494fc30STejun Heo 
46433494fc30STejun Heo 		pr_info("    in-flight:");
46443494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
46453494fc30STejun Heo 			if (worker->current_pwq != pwq)
46463494fc30STejun Heo 				continue;
46473494fc30STejun Heo 
46483494fc30STejun Heo 			pr_cont("%s %d%s:%pf", comma ? "," : "",
46493494fc30STejun Heo 				task_pid_nr(worker->task),
46503494fc30STejun Heo 				worker == pwq->wq->rescuer ? "(RESCUER)" : "",
46513494fc30STejun Heo 				worker->current_func);
46523494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
46533494fc30STejun Heo 				pr_cont_work(false, work);
46543494fc30STejun Heo 			comma = true;
46553494fc30STejun Heo 		}
46563494fc30STejun Heo 		pr_cont("\n");
46573494fc30STejun Heo 	}
46583494fc30STejun Heo 
46593494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
46603494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
46613494fc30STejun Heo 			has_pending = true;
46623494fc30STejun Heo 			break;
46633494fc30STejun Heo 		}
46643494fc30STejun Heo 	}
46653494fc30STejun Heo 	if (has_pending) {
46663494fc30STejun Heo 		bool comma = false;
46673494fc30STejun Heo 
46683494fc30STejun Heo 		pr_info("    pending:");
46693494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
46703494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
46713494fc30STejun Heo 				continue;
46723494fc30STejun Heo 
46733494fc30STejun Heo 			pr_cont_work(comma, work);
46743494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
46753494fc30STejun Heo 		}
46763494fc30STejun Heo 		pr_cont("\n");
46773494fc30STejun Heo 	}
46783494fc30STejun Heo 
46793494fc30STejun Heo 	if (!list_empty(&pwq->delayed_works)) {
46803494fc30STejun Heo 		bool comma = false;
46813494fc30STejun Heo 
46823494fc30STejun Heo 		pr_info("    delayed:");
46833494fc30STejun Heo 		list_for_each_entry(work, &pwq->delayed_works, entry) {
46843494fc30STejun Heo 			pr_cont_work(comma, work);
46853494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
46863494fc30STejun Heo 		}
46873494fc30STejun Heo 		pr_cont("\n");
46883494fc30STejun Heo 	}
46893494fc30STejun Heo }
46903494fc30STejun Heo 
46913494fc30STejun Heo /**
46923494fc30STejun Heo  * show_workqueue_state - dump workqueue state
46933494fc30STejun Heo  *
46947b776af6SRoger Lu  * Called from a sysrq handler or try_to_freeze_tasks() and prints out
46957b776af6SRoger Lu  * all busy workqueues and pools.
46963494fc30STejun Heo  */
46973494fc30STejun Heo void show_workqueue_state(void)
46983494fc30STejun Heo {
46993494fc30STejun Heo 	struct workqueue_struct *wq;
47003494fc30STejun Heo 	struct worker_pool *pool;
47013494fc30STejun Heo 	unsigned long flags;
47023494fc30STejun Heo 	int pi;
47033494fc30STejun Heo 
47043494fc30STejun Heo 	rcu_read_lock_sched();
47053494fc30STejun Heo 
47063494fc30STejun Heo 	pr_info("Showing busy workqueues and worker pools:\n");
47073494fc30STejun Heo 
47083494fc30STejun Heo 	list_for_each_entry_rcu(wq, &workqueues, list) {
47093494fc30STejun Heo 		struct pool_workqueue *pwq;
47103494fc30STejun Heo 		bool idle = true;
47113494fc30STejun Heo 
47123494fc30STejun Heo 		for_each_pwq(pwq, wq) {
47133494fc30STejun Heo 			if (pwq->nr_active || !list_empty(&pwq->delayed_works)) {
47143494fc30STejun Heo 				idle = false;
47153494fc30STejun Heo 				break;
47163494fc30STejun Heo 			}
47173494fc30STejun Heo 		}
47183494fc30STejun Heo 		if (idle)
47193494fc30STejun Heo 			continue;
47203494fc30STejun Heo 
47213494fc30STejun Heo 		pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
47223494fc30STejun Heo 
47233494fc30STejun Heo 		for_each_pwq(pwq, wq) {
47243494fc30STejun Heo 			spin_lock_irqsave(&pwq->pool->lock, flags);
47253494fc30STejun Heo 			if (pwq->nr_active || !list_empty(&pwq->delayed_works))
47263494fc30STejun Heo 				show_pwq(pwq);
47273494fc30STejun Heo 			spin_unlock_irqrestore(&pwq->pool->lock, flags);
472862635ea8SSergey Senozhatsky 			/*
472962635ea8SSergey Senozhatsky 			 * We could be printing a lot from atomic context, e.g.
473062635ea8SSergey Senozhatsky 			 * sysrq-t -> show_workqueue_state(). Avoid triggering
473162635ea8SSergey Senozhatsky 			 * hard lockup.
473262635ea8SSergey Senozhatsky 			 */
473362635ea8SSergey Senozhatsky 			touch_nmi_watchdog();
47343494fc30STejun Heo 		}
47353494fc30STejun Heo 	}
47363494fc30STejun Heo 
47373494fc30STejun Heo 	for_each_pool(pool, pi) {
47383494fc30STejun Heo 		struct worker *worker;
47393494fc30STejun Heo 		bool first = true;
47403494fc30STejun Heo 
47413494fc30STejun Heo 		spin_lock_irqsave(&pool->lock, flags);
47423494fc30STejun Heo 		if (pool->nr_workers == pool->nr_idle)
47433494fc30STejun Heo 			goto next_pool;
47443494fc30STejun Heo 
47453494fc30STejun Heo 		pr_info("pool %d:", pool->id);
47463494fc30STejun Heo 		pr_cont_pool_info(pool);
474782607adcSTejun Heo 		pr_cont(" hung=%us workers=%d",
474882607adcSTejun Heo 			jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000,
474982607adcSTejun Heo 			pool->nr_workers);
47503494fc30STejun Heo 		if (pool->manager)
47513494fc30STejun Heo 			pr_cont(" manager: %d",
47523494fc30STejun Heo 				task_pid_nr(pool->manager->task));
47533494fc30STejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry) {
47543494fc30STejun Heo 			pr_cont(" %s%d", first ? "idle: " : "",
47553494fc30STejun Heo 				task_pid_nr(worker->task));
47563494fc30STejun Heo 			first = false;
47573494fc30STejun Heo 		}
47583494fc30STejun Heo 		pr_cont("\n");
47593494fc30STejun Heo 	next_pool:
47603494fc30STejun Heo 		spin_unlock_irqrestore(&pool->lock, flags);
476162635ea8SSergey Senozhatsky 		/*
476262635ea8SSergey Senozhatsky 		 * We could be printing a lot from atomic context, e.g.
476362635ea8SSergey Senozhatsky 		 * sysrq-t -> show_workqueue_state(). Avoid triggering
476462635ea8SSergey Senozhatsky 		 * hard lockup.
476562635ea8SSergey Senozhatsky 		 */
476662635ea8SSergey Senozhatsky 		touch_nmi_watchdog();
47673494fc30STejun Heo 	}
47683494fc30STejun Heo 
47693494fc30STejun Heo 	rcu_read_unlock_sched();
47703494fc30STejun Heo }
47713494fc30STejun Heo 
47726b59808bSTejun Heo /* used to show worker information through /proc/PID/{comm,stat,status} */
47736b59808bSTejun Heo void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
47746b59808bSTejun Heo {
47756b59808bSTejun Heo 	int off;
47766b59808bSTejun Heo 
47776b59808bSTejun Heo 	/* always show the actual comm */
47786b59808bSTejun Heo 	off = strscpy(buf, task->comm, size);
47796b59808bSTejun Heo 	if (off < 0)
47806b59808bSTejun Heo 		return;
47816b59808bSTejun Heo 
4782197f6accSTejun Heo 	/* stabilize PF_WQ_WORKER and worker pool association */
47836b59808bSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
47846b59808bSTejun Heo 
4785197f6accSTejun Heo 	if (task->flags & PF_WQ_WORKER) {
4786197f6accSTejun Heo 		struct worker *worker = kthread_data(task);
4787197f6accSTejun Heo 		struct worker_pool *pool = worker->pool;
47886b59808bSTejun Heo 
47896b59808bSTejun Heo 		if (pool) {
47906b59808bSTejun Heo 			spin_lock_irq(&pool->lock);
47916b59808bSTejun Heo 			/*
4792197f6accSTejun Heo 			 * ->desc tracks information (wq name or
4793197f6accSTejun Heo 			 * set_worker_desc()) for the latest execution.  If
4794197f6accSTejun Heo 			 * current, prepend '+', otherwise '-'.
47956b59808bSTejun Heo 			 */
47966b59808bSTejun Heo 			if (worker->desc[0] != '\0') {
47976b59808bSTejun Heo 				if (worker->current_work)
47986b59808bSTejun Heo 					scnprintf(buf + off, size - off, "+%s",
47996b59808bSTejun Heo 						  worker->desc);
48006b59808bSTejun Heo 				else
48016b59808bSTejun Heo 					scnprintf(buf + off, size - off, "-%s",
48026b59808bSTejun Heo 						  worker->desc);
48036b59808bSTejun Heo 			}
48046b59808bSTejun Heo 			spin_unlock_irq(&pool->lock);
48056b59808bSTejun Heo 		}
4806197f6accSTejun Heo 	}
48076b59808bSTejun Heo 
48086b59808bSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
48096b59808bSTejun Heo }
48106b59808bSTejun Heo 
481166448bc2SMathieu Malaterre #ifdef CONFIG_SMP
481266448bc2SMathieu Malaterre 
4813db7bccf4STejun Heo /*
4814db7bccf4STejun Heo  * CPU hotplug.
4815db7bccf4STejun Heo  *
4816e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
4817112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
4818706026c2STejun Heo  * pool which make migrating pending and scheduled works very
4819e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
482094cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
4821e22bee78STejun Heo  * blocked draining impractical.
4822e22bee78STejun Heo  *
482324647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
4824628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
4825628c78e7STejun Heo  * cpu comes back online.
4826db7bccf4STejun Heo  */
4827db7bccf4STejun Heo 
4828e8b3f8dbSLai Jiangshan static void unbind_workers(int cpu)
4829db7bccf4STejun Heo {
48304ce62e9eSTejun Heo 	struct worker_pool *pool;
4831db7bccf4STejun Heo 	struct worker *worker;
4832db7bccf4STejun Heo 
4833f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
48341258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
483594cf58bbSTejun Heo 		spin_lock_irq(&pool->lock);
4836e22bee78STejun Heo 
4837f2d5a0eeSTejun Heo 		/*
483892f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
483994cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
484094cf58bbSTejun Heo 		 * except for the ones which are still executing works from
484194cf58bbSTejun Heo 		 * before the last CPU down must be on the cpu.  After
484294cf58bbSTejun Heo 		 * this, they may become diasporas.
4843f2d5a0eeSTejun Heo 		 */
4844da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
4845403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
4846db7bccf4STejun Heo 
484724647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
4848f2d5a0eeSTejun Heo 
484994cf58bbSTejun Heo 		spin_unlock_irq(&pool->lock);
48501258fae7STejun Heo 		mutex_unlock(&wq_pool_attach_mutex);
4851e22bee78STejun Heo 
4852e22bee78STejun Heo 		/*
4853eb283428SLai Jiangshan 		 * Call schedule() so that we cross rq->lock and thus can
4854eb283428SLai Jiangshan 		 * guarantee sched callbacks see the %WORKER_UNBOUND flag.
4855eb283428SLai Jiangshan 		 * This is necessary as scheduler callbacks may be invoked
4856eb283428SLai Jiangshan 		 * from other cpus.
4857628c78e7STejun Heo 		 */
4858628c78e7STejun Heo 		schedule();
4859628c78e7STejun Heo 
4860628c78e7STejun Heo 		/*
4861eb283428SLai Jiangshan 		 * Sched callbacks are disabled now.  Zap nr_running.
4862eb283428SLai Jiangshan 		 * After this, nr_running stays zero and need_more_worker()
4863eb283428SLai Jiangshan 		 * and keep_working() are always true as long as the
4864eb283428SLai Jiangshan 		 * worklist is not empty.  This pool now behaves as an
4865eb283428SLai Jiangshan 		 * unbound (in terms of concurrency management) pool which
4866eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
4867e22bee78STejun Heo 		 */
4868e19e397aSTejun Heo 		atomic_set(&pool->nr_running, 0);
4869eb283428SLai Jiangshan 
4870eb283428SLai Jiangshan 		/*
4871eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
4872eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
4873eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
4874eb283428SLai Jiangshan 		 */
4875eb283428SLai Jiangshan 		spin_lock_irq(&pool->lock);
4876eb283428SLai Jiangshan 		wake_up_worker(pool);
4877eb283428SLai Jiangshan 		spin_unlock_irq(&pool->lock);
4878eb283428SLai Jiangshan 	}
4879db7bccf4STejun Heo }
4880db7bccf4STejun Heo 
4881bd7c089eSTejun Heo /**
4882bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
4883bd7c089eSTejun Heo  * @pool: pool of interest
4884bd7c089eSTejun Heo  *
4885a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
4886bd7c089eSTejun Heo  */
4887bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
4888bd7c089eSTejun Heo {
4889a9ab775bSTejun Heo 	struct worker *worker;
4890bd7c089eSTejun Heo 
48911258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
4892bd7c089eSTejun Heo 
4893bd7c089eSTejun Heo 	/*
4894a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
4895a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
4896402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
4897a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
4898a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
4899bd7c089eSTejun Heo 	 */
4900da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
4901a9ab775bSTejun Heo 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4902a9ab775bSTejun Heo 						  pool->attrs->cpumask) < 0);
4903a9ab775bSTejun Heo 
4904a9ab775bSTejun Heo 	spin_lock_irq(&pool->lock);
4905f7c17d26SWanpeng Li 
49063de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
4907a9ab775bSTejun Heo 
4908da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
4909a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
4910a9ab775bSTejun Heo 
4911a9ab775bSTejun Heo 		/*
4912a9ab775bSTejun Heo 		 * A bound idle worker should actually be on the runqueue
4913a9ab775bSTejun Heo 		 * of the associated CPU for local wake-ups targeting it to
4914a9ab775bSTejun Heo 		 * work.  Kick all idle workers so that they migrate to the
4915a9ab775bSTejun Heo 		 * associated CPU.  Doing this in the same loop as
4916a9ab775bSTejun Heo 		 * replacing UNBOUND with REBOUND is safe as no worker will
4917a9ab775bSTejun Heo 		 * be bound before @pool->lock is released.
4918a9ab775bSTejun Heo 		 */
4919a9ab775bSTejun Heo 		if (worker_flags & WORKER_IDLE)
4920bd7c089eSTejun Heo 			wake_up_process(worker->task);
4921bd7c089eSTejun Heo 
4922bd7c089eSTejun Heo 		/*
4923a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
4924a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
4925a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4926a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
4927a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
4928a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
4929a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
4930a9ab775bSTejun Heo 		 *
4931c95491edSMark Rutland 		 * WRITE_ONCE() is necessary because @worker->flags may be
4932a9ab775bSTejun Heo 		 * tested without holding any lock in
4933a9ab775bSTejun Heo 		 * wq_worker_waking_up().  Without it, NOT_RUNNING test may
4934a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
4935a9ab775bSTejun Heo 		 * management operations.
4936bd7c089eSTejun Heo 		 */
4937a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4938a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
4939a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
4940c95491edSMark Rutland 		WRITE_ONCE(worker->flags, worker_flags);
4941bd7c089eSTejun Heo 	}
4942a9ab775bSTejun Heo 
4943a9ab775bSTejun Heo 	spin_unlock_irq(&pool->lock);
4944bd7c089eSTejun Heo }
4945bd7c089eSTejun Heo 
49467dbc725eSTejun Heo /**
49477dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
49487dbc725eSTejun Heo  * @pool: unbound pool of interest
49497dbc725eSTejun Heo  * @cpu: the CPU which is coming up
49507dbc725eSTejun Heo  *
49517dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
49527dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
49537dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
49547dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
49557dbc725eSTejun Heo  */
49567dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
49577dbc725eSTejun Heo {
49587dbc725eSTejun Heo 	static cpumask_t cpumask;
49597dbc725eSTejun Heo 	struct worker *worker;
49607dbc725eSTejun Heo 
49611258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
49627dbc725eSTejun Heo 
49637dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
49647dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
49657dbc725eSTejun Heo 		return;
49667dbc725eSTejun Heo 
49677dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
49687dbc725eSTejun Heo 
49697dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
4970da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
4971d945b5e9SPeter Zijlstra 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
49727dbc725eSTejun Heo }
49737dbc725eSTejun Heo 
49747ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
49751da177e4SLinus Torvalds {
49764ce62e9eSTejun Heo 	struct worker_pool *pool;
49771da177e4SLinus Torvalds 
4978f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
49793ce63377STejun Heo 		if (pool->nr_workers)
49803ce63377STejun Heo 			continue;
4981051e1850SLai Jiangshan 		if (!create_worker(pool))
49827ee681b2SThomas Gleixner 			return -ENOMEM;
49833af24433SOleg Nesterov 	}
49847ee681b2SThomas Gleixner 	return 0;
49857ee681b2SThomas Gleixner }
49861da177e4SLinus Torvalds 
49877ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
49887ee681b2SThomas Gleixner {
49897ee681b2SThomas Gleixner 	struct worker_pool *pool;
49907ee681b2SThomas Gleixner 	struct workqueue_struct *wq;
49917ee681b2SThomas Gleixner 	int pi;
49927ee681b2SThomas Gleixner 
499368e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
49947dbc725eSTejun Heo 
49957dbc725eSTejun Heo 	for_each_pool(pool, pi) {
49961258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
499794cf58bbSTejun Heo 
4998f05b558dSLai Jiangshan 		if (pool->cpu == cpu)
499994cf58bbSTejun Heo 			rebind_workers(pool);
5000f05b558dSLai Jiangshan 		else if (pool->cpu < 0)
50017dbc725eSTejun Heo 			restore_unbound_workers_cpumask(pool, cpu);
500294cf58bbSTejun Heo 
50031258fae7STejun Heo 		mutex_unlock(&wq_pool_attach_mutex);
500494cf58bbSTejun Heo 	}
50057dbc725eSTejun Heo 
50064c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
50074c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
50084c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, true);
50094c16bd32STejun Heo 
501068e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
50117ee681b2SThomas Gleixner 	return 0;
501265758202STejun Heo }
501365758202STejun Heo 
50147ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
501565758202STejun Heo {
50164c16bd32STejun Heo 	struct workqueue_struct *wq;
50178db25e78STejun Heo 
50184c16bd32STejun Heo 	/* unbinding per-cpu workers should happen on the local CPU */
5019e8b3f8dbSLai Jiangshan 	if (WARN_ON(cpu != smp_processor_id()))
5020e8b3f8dbSLai Jiangshan 		return -1;
5021e8b3f8dbSLai Jiangshan 
5022e8b3f8dbSLai Jiangshan 	unbind_workers(cpu);
50234c16bd32STejun Heo 
50244c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
50254c16bd32STejun Heo 	mutex_lock(&wq_pool_mutex);
50264c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
50274c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, false);
50284c16bd32STejun Heo 	mutex_unlock(&wq_pool_mutex);
50294c16bd32STejun Heo 
50307ee681b2SThomas Gleixner 	return 0;
503165758202STejun Heo }
503265758202STejun Heo 
50332d3854a3SRusty Russell struct work_for_cpu {
5034ed48ece2STejun Heo 	struct work_struct work;
50352d3854a3SRusty Russell 	long (*fn)(void *);
50362d3854a3SRusty Russell 	void *arg;
50372d3854a3SRusty Russell 	long ret;
50382d3854a3SRusty Russell };
50392d3854a3SRusty Russell 
5040ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
50412d3854a3SRusty Russell {
5042ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5043ed48ece2STejun Heo 
50442d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
50452d3854a3SRusty Russell }
50462d3854a3SRusty Russell 
50472d3854a3SRusty Russell /**
504822aceb31SAnna-Maria Gleixner  * work_on_cpu - run a function in thread context on a particular cpu
50492d3854a3SRusty Russell  * @cpu: the cpu to run on
50502d3854a3SRusty Russell  * @fn: the function to run
50512d3854a3SRusty Russell  * @arg: the function arg
50522d3854a3SRusty Russell  *
505331ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
50546b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
5055d185af30SYacine Belkadi  *
5056d185af30SYacine Belkadi  * Return: The value @fn returns.
50572d3854a3SRusty Russell  */
5058d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
50592d3854a3SRusty Russell {
5060ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
50612d3854a3SRusty Russell 
5062ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
5063ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
506412997d1aSBjorn Helgaas 	flush_work(&wfc.work);
5065440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
50662d3854a3SRusty Russell 	return wfc.ret;
50672d3854a3SRusty Russell }
50682d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
50690e8d6a93SThomas Gleixner 
50700e8d6a93SThomas Gleixner /**
50710e8d6a93SThomas Gleixner  * work_on_cpu_safe - run a function in thread context on a particular cpu
50720e8d6a93SThomas Gleixner  * @cpu: the cpu to run on
50730e8d6a93SThomas Gleixner  * @fn:  the function to run
50740e8d6a93SThomas Gleixner  * @arg: the function argument
50750e8d6a93SThomas Gleixner  *
50760e8d6a93SThomas Gleixner  * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
50770e8d6a93SThomas Gleixner  * any locks which would prevent @fn from completing.
50780e8d6a93SThomas Gleixner  *
50790e8d6a93SThomas Gleixner  * Return: The value @fn returns.
50800e8d6a93SThomas Gleixner  */
50810e8d6a93SThomas Gleixner long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
50820e8d6a93SThomas Gleixner {
50830e8d6a93SThomas Gleixner 	long ret = -ENODEV;
50840e8d6a93SThomas Gleixner 
50850e8d6a93SThomas Gleixner 	get_online_cpus();
50860e8d6a93SThomas Gleixner 	if (cpu_online(cpu))
50870e8d6a93SThomas Gleixner 		ret = work_on_cpu(cpu, fn, arg);
50880e8d6a93SThomas Gleixner 	put_online_cpus();
50890e8d6a93SThomas Gleixner 	return ret;
50900e8d6a93SThomas Gleixner }
50910e8d6a93SThomas Gleixner EXPORT_SYMBOL_GPL(work_on_cpu_safe);
50922d3854a3SRusty Russell #endif /* CONFIG_SMP */
50932d3854a3SRusty Russell 
5094a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
5095e7577c50SRusty Russell 
5096a0a1a5fdSTejun Heo /**
5097a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
5098a0a1a5fdSTejun Heo  *
509958a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
5100c5aa87bbSTejun Heo  * workqueues will queue new works to their delayed_works list instead of
5101706026c2STejun Heo  * pool->worklist.
5102a0a1a5fdSTejun Heo  *
5103a0a1a5fdSTejun Heo  * CONTEXT:
5104a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5105a0a1a5fdSTejun Heo  */
5106a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
5107a0a1a5fdSTejun Heo {
510824b8a847STejun Heo 	struct workqueue_struct *wq;
510924b8a847STejun Heo 	struct pool_workqueue *pwq;
5110a0a1a5fdSTejun Heo 
511168e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5112a0a1a5fdSTejun Heo 
51136183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
5114a0a1a5fdSTejun Heo 	workqueue_freezing = true;
5115a0a1a5fdSTejun Heo 
511624b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5117a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5118699ce097STejun Heo 		for_each_pwq(pwq, wq)
5119699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5120a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
5121a1056305STejun Heo 	}
51225bcab335STejun Heo 
512368e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5124a0a1a5fdSTejun Heo }
5125a0a1a5fdSTejun Heo 
5126a0a1a5fdSTejun Heo /**
512758a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
5128a0a1a5fdSTejun Heo  *
5129a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
5130a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
5131a0a1a5fdSTejun Heo  *
5132a0a1a5fdSTejun Heo  * CONTEXT:
513368e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
5134a0a1a5fdSTejun Heo  *
5135d185af30SYacine Belkadi  * Return:
513658a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
513758a69cb4STejun Heo  * is complete.
5138a0a1a5fdSTejun Heo  */
5139a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
5140a0a1a5fdSTejun Heo {
5141a0a1a5fdSTejun Heo 	bool busy = false;
514224b8a847STejun Heo 	struct workqueue_struct *wq;
514324b8a847STejun Heo 	struct pool_workqueue *pwq;
5144a0a1a5fdSTejun Heo 
514568e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5146a0a1a5fdSTejun Heo 
51476183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
5148a0a1a5fdSTejun Heo 
514924b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
515024b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
515124b8a847STejun Heo 			continue;
5152a0a1a5fdSTejun Heo 		/*
5153a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
5154a0a1a5fdSTejun Heo 		 * to peek without lock.
5155a0a1a5fdSTejun Heo 		 */
515688109453SLai Jiangshan 		rcu_read_lock_sched();
515724b8a847STejun Heo 		for_each_pwq(pwq, wq) {
51586183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
5159112202d9STejun Heo 			if (pwq->nr_active) {
5160a0a1a5fdSTejun Heo 				busy = true;
516188109453SLai Jiangshan 				rcu_read_unlock_sched();
5162a0a1a5fdSTejun Heo 				goto out_unlock;
5163a0a1a5fdSTejun Heo 			}
5164a0a1a5fdSTejun Heo 		}
516588109453SLai Jiangshan 		rcu_read_unlock_sched();
5166a0a1a5fdSTejun Heo 	}
5167a0a1a5fdSTejun Heo out_unlock:
516868e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5169a0a1a5fdSTejun Heo 	return busy;
5170a0a1a5fdSTejun Heo }
5171a0a1a5fdSTejun Heo 
5172a0a1a5fdSTejun Heo /**
5173a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
5174a0a1a5fdSTejun Heo  *
5175a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
5176706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
5177a0a1a5fdSTejun Heo  *
5178a0a1a5fdSTejun Heo  * CONTEXT:
5179a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5180a0a1a5fdSTejun Heo  */
5181a0a1a5fdSTejun Heo void thaw_workqueues(void)
5182a0a1a5fdSTejun Heo {
518324b8a847STejun Heo 	struct workqueue_struct *wq;
518424b8a847STejun Heo 	struct pool_workqueue *pwq;
5185a0a1a5fdSTejun Heo 
518668e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5187a0a1a5fdSTejun Heo 
5188a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
5189a0a1a5fdSTejun Heo 		goto out_unlock;
5190a0a1a5fdSTejun Heo 
519174b414eaSLai Jiangshan 	workqueue_freezing = false;
519224b8a847STejun Heo 
519324b8a847STejun Heo 	/* restore max_active and repopulate worklist */
519424b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
5195a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
5196699ce097STejun Heo 		for_each_pwq(pwq, wq)
5197699ce097STejun Heo 			pwq_adjust_max_active(pwq);
5198a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
519924b8a847STejun Heo 	}
520024b8a847STejun Heo 
5201a0a1a5fdSTejun Heo out_unlock:
520268e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5203a0a1a5fdSTejun Heo }
5204a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
5205a0a1a5fdSTejun Heo 
5206042f7df1SLai Jiangshan static int workqueue_apply_unbound_cpumask(void)
5207042f7df1SLai Jiangshan {
5208042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
5209042f7df1SLai Jiangshan 	int ret = 0;
5210042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
5211042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
5212042f7df1SLai Jiangshan 
5213042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5214042f7df1SLai Jiangshan 
5215042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
5216042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
5217042f7df1SLai Jiangshan 			continue;
5218042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
5219042f7df1SLai Jiangshan 		if (wq->flags & __WQ_ORDERED)
5220042f7df1SLai Jiangshan 			continue;
5221042f7df1SLai Jiangshan 
5222042f7df1SLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs);
5223042f7df1SLai Jiangshan 		if (!ctx) {
5224042f7df1SLai Jiangshan 			ret = -ENOMEM;
5225042f7df1SLai Jiangshan 			break;
5226042f7df1SLai Jiangshan 		}
5227042f7df1SLai Jiangshan 
5228042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
5229042f7df1SLai Jiangshan 	}
5230042f7df1SLai Jiangshan 
5231042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
5232042f7df1SLai Jiangshan 		if (!ret)
5233042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
5234042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
5235042f7df1SLai Jiangshan 	}
5236042f7df1SLai Jiangshan 
5237042f7df1SLai Jiangshan 	return ret;
5238042f7df1SLai Jiangshan }
5239042f7df1SLai Jiangshan 
5240042f7df1SLai Jiangshan /**
5241042f7df1SLai Jiangshan  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5242042f7df1SLai Jiangshan  *  @cpumask: the cpumask to set
5243042f7df1SLai Jiangshan  *
5244042f7df1SLai Jiangshan  *  The low-level workqueues cpumask is a global cpumask that limits
5245042f7df1SLai Jiangshan  *  the affinity of all unbound workqueues.  This function check the @cpumask
5246042f7df1SLai Jiangshan  *  and apply it to all unbound workqueues and updates all pwqs of them.
5247042f7df1SLai Jiangshan  *
5248042f7df1SLai Jiangshan  *  Retun:	0	- Success
5249042f7df1SLai Jiangshan  *  		-EINVAL	- Invalid @cpumask
5250042f7df1SLai Jiangshan  *  		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
5251042f7df1SLai Jiangshan  */
5252042f7df1SLai Jiangshan int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5253042f7df1SLai Jiangshan {
5254042f7df1SLai Jiangshan 	int ret = -EINVAL;
5255042f7df1SLai Jiangshan 	cpumask_var_t saved_cpumask;
5256042f7df1SLai Jiangshan 
5257042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&saved_cpumask, GFP_KERNEL))
5258042f7df1SLai Jiangshan 		return -ENOMEM;
5259042f7df1SLai Jiangshan 
5260c98a9805STal Shorer 	/*
5261c98a9805STal Shorer 	 * Not excluding isolated cpus on purpose.
5262c98a9805STal Shorer 	 * If the user wishes to include them, we allow that.
5263c98a9805STal Shorer 	 */
5264042f7df1SLai Jiangshan 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
5265042f7df1SLai Jiangshan 	if (!cpumask_empty(cpumask)) {
5266a0111cf6SLai Jiangshan 		apply_wqattrs_lock();
5267042f7df1SLai Jiangshan 
5268042f7df1SLai Jiangshan 		/* save the old wq_unbound_cpumask. */
5269042f7df1SLai Jiangshan 		cpumask_copy(saved_cpumask, wq_unbound_cpumask);
5270042f7df1SLai Jiangshan 
5271042f7df1SLai Jiangshan 		/* update wq_unbound_cpumask at first and apply it to wqs. */
5272042f7df1SLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, cpumask);
5273042f7df1SLai Jiangshan 		ret = workqueue_apply_unbound_cpumask();
5274042f7df1SLai Jiangshan 
5275042f7df1SLai Jiangshan 		/* restore the wq_unbound_cpumask when failed. */
5276042f7df1SLai Jiangshan 		if (ret < 0)
5277042f7df1SLai Jiangshan 			cpumask_copy(wq_unbound_cpumask, saved_cpumask);
5278042f7df1SLai Jiangshan 
5279a0111cf6SLai Jiangshan 		apply_wqattrs_unlock();
5280042f7df1SLai Jiangshan 	}
5281042f7df1SLai Jiangshan 
5282042f7df1SLai Jiangshan 	free_cpumask_var(saved_cpumask);
5283042f7df1SLai Jiangshan 	return ret;
5284042f7df1SLai Jiangshan }
5285042f7df1SLai Jiangshan 
52866ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
52876ba94429SFrederic Weisbecker /*
52886ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
52896ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
52906ba94429SFrederic Weisbecker  * following attributes.
52916ba94429SFrederic Weisbecker  *
52926ba94429SFrederic Weisbecker  *  per_cpu	RO bool	: whether the workqueue is per-cpu or unbound
52936ba94429SFrederic Weisbecker  *  max_active	RW int	: maximum number of in-flight work items
52946ba94429SFrederic Weisbecker  *
52956ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
52966ba94429SFrederic Weisbecker  *
52979a19b463SWang Long  *  pool_ids	RO int	: the associated pool IDs for each node
52986ba94429SFrederic Weisbecker  *  nice	RW int	: nice value of the workers
52996ba94429SFrederic Weisbecker  *  cpumask	RW mask	: bitmask of allowed CPUs for the workers
53009a19b463SWang Long  *  numa	RW bool	: whether enable NUMA affinity
53016ba94429SFrederic Weisbecker  */
53026ba94429SFrederic Weisbecker struct wq_device {
53036ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
53046ba94429SFrederic Weisbecker 	struct device			dev;
53056ba94429SFrederic Weisbecker };
53066ba94429SFrederic Weisbecker 
53076ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
53086ba94429SFrederic Weisbecker {
53096ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
53106ba94429SFrederic Weisbecker 
53116ba94429SFrederic Weisbecker 	return wq_dev->wq;
53126ba94429SFrederic Weisbecker }
53136ba94429SFrederic Weisbecker 
53146ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
53156ba94429SFrederic Weisbecker 			    char *buf)
53166ba94429SFrederic Weisbecker {
53176ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
53186ba94429SFrederic Weisbecker 
53196ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
53206ba94429SFrederic Weisbecker }
53216ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
53226ba94429SFrederic Weisbecker 
53236ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
53246ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
53256ba94429SFrederic Weisbecker {
53266ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
53276ba94429SFrederic Weisbecker 
53286ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
53296ba94429SFrederic Weisbecker }
53306ba94429SFrederic Weisbecker 
53316ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
53326ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
53336ba94429SFrederic Weisbecker 				size_t count)
53346ba94429SFrederic Weisbecker {
53356ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
53366ba94429SFrederic Weisbecker 	int val;
53376ba94429SFrederic Weisbecker 
53386ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
53396ba94429SFrederic Weisbecker 		return -EINVAL;
53406ba94429SFrederic Weisbecker 
53416ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
53426ba94429SFrederic Weisbecker 	return count;
53436ba94429SFrederic Weisbecker }
53446ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
53456ba94429SFrederic Weisbecker 
53466ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
53476ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
53486ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
53496ba94429SFrederic Weisbecker 	NULL,
53506ba94429SFrederic Weisbecker };
53516ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
53526ba94429SFrederic Weisbecker 
53536ba94429SFrederic Weisbecker static ssize_t wq_pool_ids_show(struct device *dev,
53546ba94429SFrederic Weisbecker 				struct device_attribute *attr, char *buf)
53556ba94429SFrederic Weisbecker {
53566ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
53576ba94429SFrederic Weisbecker 	const char *delim = "";
53586ba94429SFrederic Weisbecker 	int node, written = 0;
53596ba94429SFrederic Weisbecker 
53606ba94429SFrederic Weisbecker 	rcu_read_lock_sched();
53616ba94429SFrederic Weisbecker 	for_each_node(node) {
53626ba94429SFrederic Weisbecker 		written += scnprintf(buf + written, PAGE_SIZE - written,
53636ba94429SFrederic Weisbecker 				     "%s%d:%d", delim, node,
53646ba94429SFrederic Weisbecker 				     unbound_pwq_by_node(wq, node)->pool->id);
53656ba94429SFrederic Weisbecker 		delim = " ";
53666ba94429SFrederic Weisbecker 	}
53676ba94429SFrederic Weisbecker 	written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
53686ba94429SFrederic Weisbecker 	rcu_read_unlock_sched();
53696ba94429SFrederic Weisbecker 
53706ba94429SFrederic Weisbecker 	return written;
53716ba94429SFrederic Weisbecker }
53726ba94429SFrederic Weisbecker 
53736ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
53746ba94429SFrederic Weisbecker 			    char *buf)
53756ba94429SFrederic Weisbecker {
53766ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
53776ba94429SFrederic Weisbecker 	int written;
53786ba94429SFrederic Weisbecker 
53796ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
53806ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
53816ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
53826ba94429SFrederic Weisbecker 
53836ba94429SFrederic Weisbecker 	return written;
53846ba94429SFrederic Weisbecker }
53856ba94429SFrederic Weisbecker 
53866ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
53876ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
53886ba94429SFrederic Weisbecker {
53896ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
53906ba94429SFrederic Weisbecker 
5391899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5392899a94feSLai Jiangshan 
53936ba94429SFrederic Weisbecker 	attrs = alloc_workqueue_attrs(GFP_KERNEL);
53946ba94429SFrederic Weisbecker 	if (!attrs)
53956ba94429SFrederic Weisbecker 		return NULL;
53966ba94429SFrederic Weisbecker 
53976ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
53986ba94429SFrederic Weisbecker 	return attrs;
53996ba94429SFrederic Weisbecker }
54006ba94429SFrederic Weisbecker 
54016ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
54026ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
54036ba94429SFrederic Weisbecker {
54046ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
54056ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5406d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5407d4d3e257SLai Jiangshan 
5408d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
54096ba94429SFrederic Weisbecker 
54106ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
54116ba94429SFrederic Weisbecker 	if (!attrs)
5412d4d3e257SLai Jiangshan 		goto out_unlock;
54136ba94429SFrederic Weisbecker 
54146ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
54156ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5416d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
54176ba94429SFrederic Weisbecker 	else
54186ba94429SFrederic Weisbecker 		ret = -EINVAL;
54196ba94429SFrederic Weisbecker 
5420d4d3e257SLai Jiangshan out_unlock:
5421d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
54226ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
54236ba94429SFrederic Weisbecker 	return ret ?: count;
54246ba94429SFrederic Weisbecker }
54256ba94429SFrederic Weisbecker 
54266ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
54276ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
54286ba94429SFrederic Weisbecker {
54296ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
54306ba94429SFrederic Weisbecker 	int written;
54316ba94429SFrederic Weisbecker 
54326ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
54336ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
54346ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
54356ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
54366ba94429SFrederic Weisbecker 	return written;
54376ba94429SFrederic Weisbecker }
54386ba94429SFrederic Weisbecker 
54396ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
54406ba94429SFrederic Weisbecker 				struct device_attribute *attr,
54416ba94429SFrederic Weisbecker 				const char *buf, size_t count)
54426ba94429SFrederic Weisbecker {
54436ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
54446ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5445d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5446d4d3e257SLai Jiangshan 
5447d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
54486ba94429SFrederic Weisbecker 
54496ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
54506ba94429SFrederic Weisbecker 	if (!attrs)
5451d4d3e257SLai Jiangshan 		goto out_unlock;
54526ba94429SFrederic Weisbecker 
54536ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
54546ba94429SFrederic Weisbecker 	if (!ret)
5455d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
54566ba94429SFrederic Weisbecker 
5457d4d3e257SLai Jiangshan out_unlock:
5458d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
54596ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
54606ba94429SFrederic Weisbecker 	return ret ?: count;
54616ba94429SFrederic Weisbecker }
54626ba94429SFrederic Weisbecker 
54636ba94429SFrederic Weisbecker static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
54646ba94429SFrederic Weisbecker 			    char *buf)
54656ba94429SFrederic Weisbecker {
54666ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
54676ba94429SFrederic Weisbecker 	int written;
54686ba94429SFrederic Weisbecker 
54696ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
54706ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n",
54716ba94429SFrederic Weisbecker 			    !wq->unbound_attrs->no_numa);
54726ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
54736ba94429SFrederic Weisbecker 
54746ba94429SFrederic Weisbecker 	return written;
54756ba94429SFrederic Weisbecker }
54766ba94429SFrederic Weisbecker 
54776ba94429SFrederic Weisbecker static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
54786ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
54796ba94429SFrederic Weisbecker {
54806ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
54816ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5482d4d3e257SLai Jiangshan 	int v, ret = -ENOMEM;
5483d4d3e257SLai Jiangshan 
5484d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
54856ba94429SFrederic Weisbecker 
54866ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
54876ba94429SFrederic Weisbecker 	if (!attrs)
5488d4d3e257SLai Jiangshan 		goto out_unlock;
54896ba94429SFrederic Weisbecker 
54906ba94429SFrederic Weisbecker 	ret = -EINVAL;
54916ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &v) == 1) {
54926ba94429SFrederic Weisbecker 		attrs->no_numa = !v;
5493d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
54946ba94429SFrederic Weisbecker 	}
54956ba94429SFrederic Weisbecker 
5496d4d3e257SLai Jiangshan out_unlock:
5497d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
54986ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
54996ba94429SFrederic Weisbecker 	return ret ?: count;
55006ba94429SFrederic Weisbecker }
55016ba94429SFrederic Weisbecker 
55026ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
55036ba94429SFrederic Weisbecker 	__ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
55046ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
55056ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
55066ba94429SFrederic Weisbecker 	__ATTR(numa, 0644, wq_numa_show, wq_numa_store),
55076ba94429SFrederic Weisbecker 	__ATTR_NULL,
55086ba94429SFrederic Weisbecker };
55096ba94429SFrederic Weisbecker 
55106ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
55116ba94429SFrederic Weisbecker 	.name				= "workqueue",
55126ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
55136ba94429SFrederic Weisbecker };
55146ba94429SFrederic Weisbecker 
5515b05a7928SFrederic Weisbecker static ssize_t wq_unbound_cpumask_show(struct device *dev,
5516b05a7928SFrederic Weisbecker 		struct device_attribute *attr, char *buf)
5517b05a7928SFrederic Weisbecker {
5518b05a7928SFrederic Weisbecker 	int written;
5519b05a7928SFrederic Weisbecker 
5520042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5521b05a7928SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5522b05a7928SFrederic Weisbecker 			    cpumask_pr_args(wq_unbound_cpumask));
5523042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5524b05a7928SFrederic Weisbecker 
5525b05a7928SFrederic Weisbecker 	return written;
5526b05a7928SFrederic Weisbecker }
5527b05a7928SFrederic Weisbecker 
5528042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
5529042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
5530042f7df1SLai Jiangshan {
5531042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
5532042f7df1SLai Jiangshan 	int ret;
5533042f7df1SLai Jiangshan 
5534042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5535042f7df1SLai Jiangshan 		return -ENOMEM;
5536042f7df1SLai Jiangshan 
5537042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
5538042f7df1SLai Jiangshan 	if (!ret)
5539042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
5540042f7df1SLai Jiangshan 
5541042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
5542042f7df1SLai Jiangshan 	return ret ? ret : count;
5543042f7df1SLai Jiangshan }
5544042f7df1SLai Jiangshan 
5545b05a7928SFrederic Weisbecker static struct device_attribute wq_sysfs_cpumask_attr =
5546042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5547042f7df1SLai Jiangshan 	       wq_unbound_cpumask_store);
5548b05a7928SFrederic Weisbecker 
55496ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
55506ba94429SFrederic Weisbecker {
5551b05a7928SFrederic Weisbecker 	int err;
5552b05a7928SFrederic Weisbecker 
5553b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
5554b05a7928SFrederic Weisbecker 	if (err)
5555b05a7928SFrederic Weisbecker 		return err;
5556b05a7928SFrederic Weisbecker 
5557b05a7928SFrederic Weisbecker 	return device_create_file(wq_subsys.dev_root, &wq_sysfs_cpumask_attr);
55586ba94429SFrederic Weisbecker }
55596ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
55606ba94429SFrederic Weisbecker 
55616ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
55626ba94429SFrederic Weisbecker {
55636ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
55646ba94429SFrederic Weisbecker 
55656ba94429SFrederic Weisbecker 	kfree(wq_dev);
55666ba94429SFrederic Weisbecker }
55676ba94429SFrederic Weisbecker 
55686ba94429SFrederic Weisbecker /**
55696ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
55706ba94429SFrederic Weisbecker  * @wq: the workqueue to register
55716ba94429SFrederic Weisbecker  *
55726ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
55736ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
55746ba94429SFrederic Weisbecker  * which is the preferred method.
55756ba94429SFrederic Weisbecker  *
55766ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
55776ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
55786ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
55796ba94429SFrederic Weisbecker  * attributes.
55806ba94429SFrederic Weisbecker  *
55816ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
55826ba94429SFrederic Weisbecker  */
55836ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
55846ba94429SFrederic Weisbecker {
55856ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
55866ba94429SFrederic Weisbecker 	int ret;
55876ba94429SFrederic Weisbecker 
55886ba94429SFrederic Weisbecker 	/*
5589402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
55906ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
55916ba94429SFrederic Weisbecker 	 * workqueues.
55926ba94429SFrederic Weisbecker 	 */
55930a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
55946ba94429SFrederic Weisbecker 		return -EINVAL;
55956ba94429SFrederic Weisbecker 
55966ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
55976ba94429SFrederic Weisbecker 	if (!wq_dev)
55986ba94429SFrederic Weisbecker 		return -ENOMEM;
55996ba94429SFrederic Weisbecker 
56006ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
56016ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
56026ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
560323217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
56046ba94429SFrederic Weisbecker 
56056ba94429SFrederic Weisbecker 	/*
56066ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
56076ba94429SFrederic Weisbecker 	 * everything is ready.
56086ba94429SFrederic Weisbecker 	 */
56096ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
56106ba94429SFrederic Weisbecker 
56116ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
56126ba94429SFrederic Weisbecker 	if (ret) {
5613537f4146SArvind Yadav 		put_device(&wq_dev->dev);
56146ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
56156ba94429SFrederic Weisbecker 		return ret;
56166ba94429SFrederic Weisbecker 	}
56176ba94429SFrederic Weisbecker 
56186ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
56196ba94429SFrederic Weisbecker 		struct device_attribute *attr;
56206ba94429SFrederic Weisbecker 
56216ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
56226ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
56236ba94429SFrederic Weisbecker 			if (ret) {
56246ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
56256ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
56266ba94429SFrederic Weisbecker 				return ret;
56276ba94429SFrederic Weisbecker 			}
56286ba94429SFrederic Weisbecker 		}
56296ba94429SFrederic Weisbecker 	}
56306ba94429SFrederic Weisbecker 
56316ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
56326ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
56336ba94429SFrederic Weisbecker 	return 0;
56346ba94429SFrederic Weisbecker }
56356ba94429SFrederic Weisbecker 
56366ba94429SFrederic Weisbecker /**
56376ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
56386ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
56396ba94429SFrederic Weisbecker  *
56406ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
56416ba94429SFrederic Weisbecker  */
56426ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
56436ba94429SFrederic Weisbecker {
56446ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
56456ba94429SFrederic Weisbecker 
56466ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
56476ba94429SFrederic Weisbecker 		return;
56486ba94429SFrederic Weisbecker 
56496ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
56506ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
56516ba94429SFrederic Weisbecker }
56526ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
56536ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
56546ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
56556ba94429SFrederic Weisbecker 
565682607adcSTejun Heo /*
565782607adcSTejun Heo  * Workqueue watchdog.
565882607adcSTejun Heo  *
565982607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
566082607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
566182607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
566282607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
566382607adcSTejun Heo  * largely opaque.
566482607adcSTejun Heo  *
566582607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
566682607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
566782607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
566882607adcSTejun Heo  *
566982607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
567082607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
567182607adcSTejun Heo  * corresponding sysfs parameter file.
567282607adcSTejun Heo  */
567382607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
567482607adcSTejun Heo 
567582607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
56765cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
567782607adcSTejun Heo 
567882607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
567982607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
568082607adcSTejun Heo 
568182607adcSTejun Heo static void wq_watchdog_reset_touched(void)
568282607adcSTejun Heo {
568382607adcSTejun Heo 	int cpu;
568482607adcSTejun Heo 
568582607adcSTejun Heo 	wq_watchdog_touched = jiffies;
568682607adcSTejun Heo 	for_each_possible_cpu(cpu)
568782607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
568882607adcSTejun Heo }
568982607adcSTejun Heo 
56905cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
569182607adcSTejun Heo {
569282607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
569382607adcSTejun Heo 	bool lockup_detected = false;
569482607adcSTejun Heo 	struct worker_pool *pool;
569582607adcSTejun Heo 	int pi;
569682607adcSTejun Heo 
569782607adcSTejun Heo 	if (!thresh)
569882607adcSTejun Heo 		return;
569982607adcSTejun Heo 
570082607adcSTejun Heo 	rcu_read_lock();
570182607adcSTejun Heo 
570282607adcSTejun Heo 	for_each_pool(pool, pi) {
570382607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
570482607adcSTejun Heo 
570582607adcSTejun Heo 		if (list_empty(&pool->worklist))
570682607adcSTejun Heo 			continue;
570782607adcSTejun Heo 
570882607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
570982607adcSTejun Heo 		pool_ts = READ_ONCE(pool->watchdog_ts);
571082607adcSTejun Heo 		touched = READ_ONCE(wq_watchdog_touched);
571182607adcSTejun Heo 
571282607adcSTejun Heo 		if (time_after(pool_ts, touched))
571382607adcSTejun Heo 			ts = pool_ts;
571482607adcSTejun Heo 		else
571582607adcSTejun Heo 			ts = touched;
571682607adcSTejun Heo 
571782607adcSTejun Heo 		if (pool->cpu >= 0) {
571882607adcSTejun Heo 			unsigned long cpu_touched =
571982607adcSTejun Heo 				READ_ONCE(per_cpu(wq_watchdog_touched_cpu,
572082607adcSTejun Heo 						  pool->cpu));
572182607adcSTejun Heo 			if (time_after(cpu_touched, ts))
572282607adcSTejun Heo 				ts = cpu_touched;
572382607adcSTejun Heo 		}
572482607adcSTejun Heo 
572582607adcSTejun Heo 		/* did we stall? */
572682607adcSTejun Heo 		if (time_after(jiffies, ts + thresh)) {
572782607adcSTejun Heo 			lockup_detected = true;
572882607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
572982607adcSTejun Heo 			pr_cont_pool_info(pool);
573082607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
573182607adcSTejun Heo 				jiffies_to_msecs(jiffies - pool_ts) / 1000);
573282607adcSTejun Heo 		}
573382607adcSTejun Heo 	}
573482607adcSTejun Heo 
573582607adcSTejun Heo 	rcu_read_unlock();
573682607adcSTejun Heo 
573782607adcSTejun Heo 	if (lockup_detected)
573882607adcSTejun Heo 		show_workqueue_state();
573982607adcSTejun Heo 
574082607adcSTejun Heo 	wq_watchdog_reset_touched();
574182607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
574282607adcSTejun Heo }
574382607adcSTejun Heo 
5744cb9d7fd5SVincent Whitchurch notrace void wq_watchdog_touch(int cpu)
574582607adcSTejun Heo {
574682607adcSTejun Heo 	if (cpu >= 0)
574782607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
574882607adcSTejun Heo 	else
574982607adcSTejun Heo 		wq_watchdog_touched = jiffies;
575082607adcSTejun Heo }
575182607adcSTejun Heo 
575282607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
575382607adcSTejun Heo {
575482607adcSTejun Heo 	wq_watchdog_thresh = 0;
575582607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
575682607adcSTejun Heo 
575782607adcSTejun Heo 	if (thresh) {
575882607adcSTejun Heo 		wq_watchdog_thresh = thresh;
575982607adcSTejun Heo 		wq_watchdog_reset_touched();
576082607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
576182607adcSTejun Heo 	}
576282607adcSTejun Heo }
576382607adcSTejun Heo 
576482607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
576582607adcSTejun Heo 					const struct kernel_param *kp)
576682607adcSTejun Heo {
576782607adcSTejun Heo 	unsigned long thresh;
576882607adcSTejun Heo 	int ret;
576982607adcSTejun Heo 
577082607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
577182607adcSTejun Heo 	if (ret)
577282607adcSTejun Heo 		return ret;
577382607adcSTejun Heo 
577482607adcSTejun Heo 	if (system_wq)
577582607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
577682607adcSTejun Heo 	else
577782607adcSTejun Heo 		wq_watchdog_thresh = thresh;
577882607adcSTejun Heo 
577982607adcSTejun Heo 	return 0;
578082607adcSTejun Heo }
578182607adcSTejun Heo 
578282607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
578382607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
578482607adcSTejun Heo 	.get	= param_get_ulong,
578582607adcSTejun Heo };
578682607adcSTejun Heo 
578782607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
578882607adcSTejun Heo 		0644);
578982607adcSTejun Heo 
579082607adcSTejun Heo static void wq_watchdog_init(void)
579182607adcSTejun Heo {
57925cd79d6aSKees Cook 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
579382607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
579482607adcSTejun Heo }
579582607adcSTejun Heo 
579682607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
579782607adcSTejun Heo 
579882607adcSTejun Heo static inline void wq_watchdog_init(void) { }
579982607adcSTejun Heo 
580082607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
580182607adcSTejun Heo 
5802bce90380STejun Heo static void __init wq_numa_init(void)
5803bce90380STejun Heo {
5804bce90380STejun Heo 	cpumask_var_t *tbl;
5805bce90380STejun Heo 	int node, cpu;
5806bce90380STejun Heo 
5807bce90380STejun Heo 	if (num_possible_nodes() <= 1)
5808bce90380STejun Heo 		return;
5809bce90380STejun Heo 
5810d55262c4STejun Heo 	if (wq_disable_numa) {
5811d55262c4STejun Heo 		pr_info("workqueue: NUMA affinity support disabled\n");
5812d55262c4STejun Heo 		return;
5813d55262c4STejun Heo 	}
5814d55262c4STejun Heo 
58154c16bd32STejun Heo 	wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
58164c16bd32STejun Heo 	BUG_ON(!wq_update_unbound_numa_attrs_buf);
58174c16bd32STejun Heo 
5818bce90380STejun Heo 	/*
5819bce90380STejun Heo 	 * We want masks of possible CPUs of each node which isn't readily
5820bce90380STejun Heo 	 * available.  Build one from cpu_to_node() which should have been
5821bce90380STejun Heo 	 * fully initialized by now.
5822bce90380STejun Heo 	 */
58236396bb22SKees Cook 	tbl = kcalloc(nr_node_ids, sizeof(tbl[0]), GFP_KERNEL);
5824bce90380STejun Heo 	BUG_ON(!tbl);
5825bce90380STejun Heo 
5826bce90380STejun Heo 	for_each_node(node)
58275a6024f1SYasuaki Ishimatsu 		BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
58281be0c25dSTejun Heo 				node_online(node) ? node : NUMA_NO_NODE));
5829bce90380STejun Heo 
5830bce90380STejun Heo 	for_each_possible_cpu(cpu) {
5831bce90380STejun Heo 		node = cpu_to_node(cpu);
5832bce90380STejun Heo 		if (WARN_ON(node == NUMA_NO_NODE)) {
5833bce90380STejun Heo 			pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
5834bce90380STejun Heo 			/* happens iff arch is bonkers, let's just proceed */
5835bce90380STejun Heo 			return;
5836bce90380STejun Heo 		}
5837bce90380STejun Heo 		cpumask_set_cpu(cpu, tbl[node]);
5838bce90380STejun Heo 	}
5839bce90380STejun Heo 
5840bce90380STejun Heo 	wq_numa_possible_cpumask = tbl;
5841bce90380STejun Heo 	wq_numa_enabled = true;
5842bce90380STejun Heo }
5843bce90380STejun Heo 
58443347fa09STejun Heo /**
58453347fa09STejun Heo  * workqueue_init_early - early init for workqueue subsystem
58463347fa09STejun Heo  *
58473347fa09STejun Heo  * This is the first half of two-staged workqueue subsystem initialization
58483347fa09STejun Heo  * and invoked as soon as the bare basics - memory allocation, cpumasks and
58493347fa09STejun Heo  * idr are up.  It sets up all the data structures and system workqueues
58503347fa09STejun Heo  * and allows early boot code to create workqueues and queue/cancel work
58513347fa09STejun Heo  * items.  Actual work item execution starts only after kthreads can be
58523347fa09STejun Heo  * created and scheduled right before early initcalls.
58533347fa09STejun Heo  */
58543347fa09STejun Heo int __init workqueue_init_early(void)
58551da177e4SLinus Torvalds {
58567a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
58571bda3f80SFrederic Weisbecker 	int hk_flags = HK_FLAG_DOMAIN | HK_FLAG_WQ;
58587a4e344cSTejun Heo 	int i, cpu;
5859c34056a3STejun Heo 
5860e904e6c2STejun Heo 	WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
5861e904e6c2STejun Heo 
5862b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
58631bda3f80SFrederic Weisbecker 	cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(hk_flags));
5864b05a7928SFrederic Weisbecker 
5865e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
5866e904e6c2STejun Heo 
5867706026c2STejun Heo 	/* initialize CPU pools */
586829c91e99STejun Heo 	for_each_possible_cpu(cpu) {
58694ce62e9eSTejun Heo 		struct worker_pool *pool;
58708b03ae3cSTejun Heo 
58717a4e344cSTejun Heo 		i = 0;
5872f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
58737a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
5874ec22ca5eSTejun Heo 			pool->cpu = cpu;
58757a4e344cSTejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
58767a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
5877f3f90ad4STejun Heo 			pool->node = cpu_to_node(cpu);
58787a4e344cSTejun Heo 
58799daf9e67STejun Heo 			/* alloc pool ID */
588068e13a67SLai Jiangshan 			mutex_lock(&wq_pool_mutex);
58819daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
588268e13a67SLai Jiangshan 			mutex_unlock(&wq_pool_mutex);
58834ce62e9eSTejun Heo 		}
58848b03ae3cSTejun Heo 	}
58858b03ae3cSTejun Heo 
58868a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
588729c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
588829c91e99STejun Heo 		struct workqueue_attrs *attrs;
588929c91e99STejun Heo 
589029c91e99STejun Heo 		BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
589129c91e99STejun Heo 		attrs->nice = std_nice[i];
589229c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
58938a2b7538STejun Heo 
58948a2b7538STejun Heo 		/*
58958a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
58968a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
58978a2b7538STejun Heo 		 * Turn off NUMA so that dfl_pwq is used for all nodes.
58988a2b7538STejun Heo 		 */
58998a2b7538STejun Heo 		BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
59008a2b7538STejun Heo 		attrs->nice = std_nice[i];
59018a2b7538STejun Heo 		attrs->no_numa = true;
59028a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
590329c91e99STejun Heo 	}
590429c91e99STejun Heo 
5905d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
59061aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
5907d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
5908f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
5909f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
591024d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
591124d51addSTejun Heo 					      WQ_FREEZABLE, 0);
59120668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
59130668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
59140668106cSViresh Kumar 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
59150668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
59160668106cSViresh Kumar 					      0);
59171aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
59180668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
59190668106cSViresh Kumar 	       !system_power_efficient_wq ||
59200668106cSViresh Kumar 	       !system_freezable_power_efficient_wq);
592182607adcSTejun Heo 
59223347fa09STejun Heo 	return 0;
59233347fa09STejun Heo }
59243347fa09STejun Heo 
59253347fa09STejun Heo /**
59263347fa09STejun Heo  * workqueue_init - bring workqueue subsystem fully online
59273347fa09STejun Heo  *
59283347fa09STejun Heo  * This is the latter half of two-staged workqueue subsystem initialization
59293347fa09STejun Heo  * and invoked as soon as kthreads can be created and scheduled.
59303347fa09STejun Heo  * Workqueues have been created and work items queued on them, but there
59313347fa09STejun Heo  * are no kworkers executing the work items yet.  Populate the worker pools
59323347fa09STejun Heo  * with the initial workers and enable future kworker creations.
59333347fa09STejun Heo  */
59343347fa09STejun Heo int __init workqueue_init(void)
59353347fa09STejun Heo {
59362186d9f9STejun Heo 	struct workqueue_struct *wq;
59373347fa09STejun Heo 	struct worker_pool *pool;
59383347fa09STejun Heo 	int cpu, bkt;
59393347fa09STejun Heo 
59402186d9f9STejun Heo 	/*
59412186d9f9STejun Heo 	 * It'd be simpler to initialize NUMA in workqueue_init_early() but
59422186d9f9STejun Heo 	 * CPU to node mapping may not be available that early on some
59432186d9f9STejun Heo 	 * archs such as power and arm64.  As per-cpu pools created
59442186d9f9STejun Heo 	 * previously could be missing node hint and unbound pools NUMA
59452186d9f9STejun Heo 	 * affinity, fix them up.
594640c17f75STejun Heo 	 *
594740c17f75STejun Heo 	 * Also, while iterating workqueues, create rescuers if requested.
59482186d9f9STejun Heo 	 */
59492186d9f9STejun Heo 	wq_numa_init();
59502186d9f9STejun Heo 
59512186d9f9STejun Heo 	mutex_lock(&wq_pool_mutex);
59522186d9f9STejun Heo 
59532186d9f9STejun Heo 	for_each_possible_cpu(cpu) {
59542186d9f9STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
59552186d9f9STejun Heo 			pool->node = cpu_to_node(cpu);
59562186d9f9STejun Heo 		}
59572186d9f9STejun Heo 	}
59582186d9f9STejun Heo 
595940c17f75STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
59602186d9f9STejun Heo 		wq_update_unbound_numa(wq, smp_processor_id(), true);
596140c17f75STejun Heo 		WARN(init_rescuer(wq),
596240c17f75STejun Heo 		     "workqueue: failed to create early rescuer for %s",
596340c17f75STejun Heo 		     wq->name);
596440c17f75STejun Heo 	}
59652186d9f9STejun Heo 
59662186d9f9STejun Heo 	mutex_unlock(&wq_pool_mutex);
59672186d9f9STejun Heo 
59683347fa09STejun Heo 	/* create the initial workers */
59693347fa09STejun Heo 	for_each_online_cpu(cpu) {
59703347fa09STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
59713347fa09STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
59723347fa09STejun Heo 			BUG_ON(!create_worker(pool));
59733347fa09STejun Heo 		}
59743347fa09STejun Heo 	}
59753347fa09STejun Heo 
59763347fa09STejun Heo 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
59773347fa09STejun Heo 		BUG_ON(!create_worker(pool));
59783347fa09STejun Heo 
59793347fa09STejun Heo 	wq_online = true;
598082607adcSTejun Heo 	wq_watchdog_init();
598182607adcSTejun Heo 
59826ee0578bSSuresh Siddha 	return 0;
59831da177e4SLinus Torvalds }
5984