xref: /linux-6.15/kernel/workqueue.c (revision 5826cc8f)
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
6992f9c5c4SLai Jiangshan 	 * 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  *
12692f9c5c4SLai Jiangshan  * A: 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 
157*5826cc8fSLai Jiangshan 	int			nr_workers;	/* L: total number of workers */
158*5826cc8fSLai 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 
168bc3a1afcSTejun Heo 	/* see manage_workers() for details on the two manager mutexes */
1692607d7a6STejun Heo 	struct worker		*manager;	/* L: purely informational */
17092f9c5c4SLai Jiangshan 	struct mutex		attach_mutex;	/* attach/detach exclusion */
17192f9c5c4SLai Jiangshan 	struct list_head	workers;	/* A: attached workers */
17260f5a4bcSLai Jiangshan 	struct completion	*detach_completion; /* all workers detached */
173e19e397aSTejun Heo 
1747cda9aaeSLai Jiangshan 	struct ida		worker_ida;	/* worker IDs for task name */
175e19e397aSTejun Heo 
1767a4e344cSTejun Heo 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
17768e13a67SLai Jiangshan 	struct hlist_node	hash_node;	/* PL: unbound_pool_hash node */
17868e13a67SLai Jiangshan 	int			refcnt;		/* PL: refcnt for unbound pools */
1797a4e344cSTejun Heo 
180e19e397aSTejun Heo 	/*
181e19e397aSTejun Heo 	 * The current concurrency level.  As it's likely to be accessed
182e19e397aSTejun Heo 	 * from other CPUs during try_to_wake_up(), put it in a separate
183e19e397aSTejun Heo 	 * cacheline.
184e19e397aSTejun Heo 	 */
185e19e397aSTejun Heo 	atomic_t		nr_running ____cacheline_aligned_in_smp;
18629c91e99STejun Heo 
18729c91e99STejun Heo 	/*
18829c91e99STejun Heo 	 * Destruction of pool is sched-RCU protected to allow dereferences
18929c91e99STejun Heo 	 * from get_work_pool().
19029c91e99STejun Heo 	 */
19129c91e99STejun Heo 	struct rcu_head		rcu;
1928b03ae3cSTejun Heo } ____cacheline_aligned_in_smp;
1938b03ae3cSTejun Heo 
1948b03ae3cSTejun Heo /*
195112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
196112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
197112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
198112202d9STejun Heo  * number of flag bits.
1991da177e4SLinus Torvalds  */
200112202d9STejun Heo struct pool_workqueue {
201bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
2024690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
20373f53c4aSTejun Heo 	int			work_color;	/* L: current color */
20473f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
2058864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
20673f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
20773f53c4aSTejun Heo 						/* L: nr of in_flight works */
2081e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
209a0a1a5fdSTejun Heo 	int			max_active;	/* L: max active works */
2101e19ffc6STejun Heo 	struct list_head	delayed_works;	/* L: delayed works */
2113c25a55dSLai Jiangshan 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
2122e109a28STejun Heo 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
2138864b4e5STejun Heo 
2148864b4e5STejun Heo 	/*
2158864b4e5STejun Heo 	 * Release of unbound pwq is punted to system_wq.  See put_pwq()
2168864b4e5STejun Heo 	 * and pwq_unbound_release_workfn() for details.  pool_workqueue
2178864b4e5STejun Heo 	 * itself is also sched-RCU protected so that the first pwq can be
218b09f4fd3SLai Jiangshan 	 * determined without grabbing wq->mutex.
2198864b4e5STejun Heo 	 */
2208864b4e5STejun Heo 	struct work_struct	unbound_release_work;
2218864b4e5STejun Heo 	struct rcu_head		rcu;
222e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2231da177e4SLinus Torvalds 
2241da177e4SLinus Torvalds /*
22573f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
22673f53c4aSTejun Heo  */
22773f53c4aSTejun Heo struct wq_flusher {
2283c25a55dSLai Jiangshan 	struct list_head	list;		/* WQ: list of flushers */
2293c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: flush color waiting for */
23073f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
23173f53c4aSTejun Heo };
2321da177e4SLinus Torvalds 
233226223abSTejun Heo struct wq_device;
234226223abSTejun Heo 
23573f53c4aSTejun Heo /*
236c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
237c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
2381da177e4SLinus Torvalds  */
2391da177e4SLinus Torvalds struct workqueue_struct {
2403c25a55dSLai Jiangshan 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
241e2dca7adSTejun Heo 	struct list_head	list;		/* PR: list of all workqueues */
24273f53c4aSTejun Heo 
2433c25a55dSLai Jiangshan 	struct mutex		mutex;		/* protects this wq */
2443c25a55dSLai Jiangshan 	int			work_color;	/* WQ: current work color */
2453c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: current flush color */
246112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
2473c25a55dSLai Jiangshan 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
2483c25a55dSLai Jiangshan 	struct list_head	flusher_queue;	/* WQ: flush waiters */
2493c25a55dSLai Jiangshan 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
25073f53c4aSTejun Heo 
2512e109a28STejun Heo 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
252e22bee78STejun Heo 	struct worker		*rescuer;	/* I: rescue worker */
253e22bee78STejun Heo 
25487fc741eSLai Jiangshan 	int			nr_drainers;	/* WQ: drain in progress */
255a357fc03SLai Jiangshan 	int			saved_max_active; /* WQ: saved pwq max_active */
256226223abSTejun Heo 
2575b95e1afSLai Jiangshan 	struct workqueue_attrs	*unbound_attrs;	/* PW: only for unbound wqs */
2585b95e1afSLai Jiangshan 	struct pool_workqueue	*dfl_pwq;	/* PW: only for unbound wqs */
2596029a918STejun Heo 
260226223abSTejun Heo #ifdef CONFIG_SYSFS
261226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
262226223abSTejun Heo #endif
2634e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
2644e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
2654e6045f1SJohannes Berg #endif
266ecf6881fSTejun Heo 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
2672728fd2fSTejun Heo 
268e2dca7adSTejun Heo 	/*
269e2dca7adSTejun Heo 	 * Destruction of workqueue_struct is sched-RCU protected to allow
270e2dca7adSTejun Heo 	 * walking the workqueues list without grabbing wq_pool_mutex.
271e2dca7adSTejun Heo 	 * This is used to dump all workqueues from sysrq.
272e2dca7adSTejun Heo 	 */
273e2dca7adSTejun Heo 	struct rcu_head		rcu;
274e2dca7adSTejun Heo 
2752728fd2fSTejun Heo 	/* hot fields used during command issue, aligned to cacheline */
2762728fd2fSTejun Heo 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
2772728fd2fSTejun Heo 	struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */
2785b95e1afSLai Jiangshan 	struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */
2791da177e4SLinus Torvalds };
2801da177e4SLinus Torvalds 
281e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
282e904e6c2STejun Heo 
283bce90380STejun Heo static cpumask_var_t *wq_numa_possible_cpumask;
284bce90380STejun Heo 					/* possible CPUs of each node */
285bce90380STejun Heo 
286d55262c4STejun Heo static bool wq_disable_numa;
287d55262c4STejun Heo module_param_named(disable_numa, wq_disable_numa, bool, 0444);
288d55262c4STejun Heo 
289cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
290552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
291cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
292cee22a15SViresh Kumar 
293863b710bSTejun Heo static bool wq_online;			/* can kworkers be created yet? */
2943347fa09STejun Heo 
295bce90380STejun Heo static bool wq_numa_enabled;		/* unbound NUMA affinity enabled */
296bce90380STejun Heo 
2974c16bd32STejun Heo /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
2984c16bd32STejun Heo static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf;
2994c16bd32STejun Heo 
30068e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
3012e109a28STejun Heo static DEFINE_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
302692b4825STejun Heo static DECLARE_WAIT_QUEUE_HEAD(wq_manager_wait); /* wait for manager to go away */
3035bcab335STejun Heo 
304e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
30568e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
3067d19c5ceSTejun Heo 
307ef557180SMike Galbraith /* PL: allowable cpus for unbound wqs and work items */
308ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
309ef557180SMike Galbraith 
310ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
311ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
312b05a7928SFrederic Weisbecker 
313f303fccbSTejun Heo /*
314f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
315f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
316f303fccbSTejun Heo  * to uncover usages which depend on it.
317f303fccbSTejun Heo  */
318f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
319f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
320f303fccbSTejun Heo #else
321f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
322f303fccbSTejun Heo #endif
323f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
324f303fccbSTejun Heo 
3257d19c5ceSTejun Heo /* the per-cpu worker pools */
32625528213SPeter Zijlstra static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
3277d19c5ceSTejun Heo 
32868e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
3297d19c5ceSTejun Heo 
33068e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
33129c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
33229c91e99STejun Heo 
333c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
33429c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
33529c91e99STejun Heo 
3368a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
3378a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
3388a2b7538STejun Heo 
339d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
340ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
341044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
3421aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
343044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
344d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
345044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
346f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
347044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
34824d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
3490668106cSViresh Kumar struct workqueue_struct *system_power_efficient_wq __read_mostly;
3500668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
3510668106cSViresh Kumar struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
3520668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
353d320c038STejun Heo 
3547d19c5ceSTejun Heo static int worker_thread(void *__worker);
3556ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
3567d19c5ceSTejun Heo 
35797bd2347STejun Heo #define CREATE_TRACE_POINTS
35897bd2347STejun Heo #include <trace/events/workqueue.h>
35997bd2347STejun Heo 
36068e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
361f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
362f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
36368e13a67SLai Jiangshan 			 "sched RCU or wq_pool_mutex should be held")
3645bcab335STejun Heo 
365b09f4fd3SLai Jiangshan #define assert_rcu_or_wq_mutex(wq)					\
366f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
367f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex),			\
368b09f4fd3SLai Jiangshan 			 "sched RCU or wq->mutex should be held")
36976af4d93STejun Heo 
3705b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
371f78f5b90SPaul E. McKenney 	RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() &&			\
372f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
373f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
3745b95e1afSLai Jiangshan 			 "sched RCU, wq->mutex or wq_pool_mutex should be held")
3755b95e1afSLai Jiangshan 
376f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
377f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
378f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
3797a62c2c8STejun Heo 	     (pool)++)
3804ce62e9eSTejun Heo 
38149e3cf44STejun Heo /**
38217116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
38317116969STejun Heo  * @pool: iteration cursor
384611c92a0STejun Heo  * @pi: integer used for iteration
385fa1b54e6STejun Heo  *
38668e13a67SLai Jiangshan  * This must be called either with wq_pool_mutex held or sched RCU read
38768e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
38868e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
389fa1b54e6STejun Heo  *
390fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
391fa1b54e6STejun Heo  * ignored.
39217116969STejun Heo  */
393611c92a0STejun Heo #define for_each_pool(pool, pi)						\
394611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
39568e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
396fa1b54e6STejun Heo 		else
39717116969STejun Heo 
39817116969STejun Heo /**
399822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
400822d8405STejun Heo  * @worker: iteration cursor
401822d8405STejun Heo  * @pool: worker_pool to iterate workers of
402822d8405STejun Heo  *
40392f9c5c4SLai Jiangshan  * This must be called with @pool->attach_mutex.
404822d8405STejun Heo  *
405822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
406822d8405STejun Heo  * ignored.
407822d8405STejun Heo  */
408da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
409da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
41092f9c5c4SLai Jiangshan 		if (({ lockdep_assert_held(&pool->attach_mutex); false; })) { } \
411822d8405STejun Heo 		else
412822d8405STejun Heo 
413822d8405STejun Heo /**
41449e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
41549e3cf44STejun Heo  * @pwq: iteration cursor
41649e3cf44STejun Heo  * @wq: the target workqueue
41776af4d93STejun Heo  *
418b09f4fd3SLai Jiangshan  * This must be called either with wq->mutex held or sched RCU read locked.
419794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
420794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
42176af4d93STejun Heo  *
42276af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
42376af4d93STejun Heo  * ignored.
42449e3cf44STejun Heo  */
42549e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
42676af4d93STejun Heo 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node)		\
427b09f4fd3SLai Jiangshan 		if (({ assert_rcu_or_wq_mutex(wq); false; })) { }	\
42876af4d93STejun Heo 		else
429f3421797STejun Heo 
430dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
431dc186ad7SThomas Gleixner 
432dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr;
433dc186ad7SThomas Gleixner 
43499777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
43599777288SStanislaw Gruszka {
43699777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
43799777288SStanislaw Gruszka }
43899777288SStanislaw Gruszka 
439b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
440b9fdac7fSDu, Changbin {
441b9fdac7fSDu, Changbin 	struct work_struct *work = addr;
442b9fdac7fSDu, Changbin 
443b9fdac7fSDu, Changbin 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
444b9fdac7fSDu, Changbin }
445b9fdac7fSDu, Changbin 
446dc186ad7SThomas Gleixner /*
447dc186ad7SThomas Gleixner  * fixup_init is called when:
448dc186ad7SThomas Gleixner  * - an active object is initialized
449dc186ad7SThomas Gleixner  */
45002a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
451dc186ad7SThomas Gleixner {
452dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
453dc186ad7SThomas Gleixner 
454dc186ad7SThomas Gleixner 	switch (state) {
455dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
456dc186ad7SThomas Gleixner 		cancel_work_sync(work);
457dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
45802a982a6SDu, Changbin 		return true;
459dc186ad7SThomas Gleixner 	default:
46002a982a6SDu, Changbin 		return false;
461dc186ad7SThomas Gleixner 	}
462dc186ad7SThomas Gleixner }
463dc186ad7SThomas Gleixner 
464dc186ad7SThomas Gleixner /*
465dc186ad7SThomas Gleixner  * fixup_free is called when:
466dc186ad7SThomas Gleixner  * - an active object is freed
467dc186ad7SThomas Gleixner  */
46802a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
469dc186ad7SThomas Gleixner {
470dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
471dc186ad7SThomas Gleixner 
472dc186ad7SThomas Gleixner 	switch (state) {
473dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
474dc186ad7SThomas Gleixner 		cancel_work_sync(work);
475dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
47602a982a6SDu, Changbin 		return true;
477dc186ad7SThomas Gleixner 	default:
47802a982a6SDu, Changbin 		return false;
479dc186ad7SThomas Gleixner 	}
480dc186ad7SThomas Gleixner }
481dc186ad7SThomas Gleixner 
482dc186ad7SThomas Gleixner static struct debug_obj_descr work_debug_descr = {
483dc186ad7SThomas Gleixner 	.name		= "work_struct",
48499777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
485b9fdac7fSDu, Changbin 	.is_static_object = work_is_static_object,
486dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
487dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
488dc186ad7SThomas Gleixner };
489dc186ad7SThomas Gleixner 
490dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
491dc186ad7SThomas Gleixner {
492dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
493dc186ad7SThomas Gleixner }
494dc186ad7SThomas Gleixner 
495dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
496dc186ad7SThomas Gleixner {
497dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
498dc186ad7SThomas Gleixner }
499dc186ad7SThomas Gleixner 
500dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
501dc186ad7SThomas Gleixner {
502dc186ad7SThomas Gleixner 	if (onstack)
503dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
504dc186ad7SThomas Gleixner 	else
505dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
506dc186ad7SThomas Gleixner }
507dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
508dc186ad7SThomas Gleixner 
509dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
510dc186ad7SThomas Gleixner {
511dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
512dc186ad7SThomas Gleixner }
513dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
514dc186ad7SThomas Gleixner 
515ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
516ea2e64f2SThomas Gleixner {
517ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
518ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
519ea2e64f2SThomas Gleixner }
520ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
521ea2e64f2SThomas Gleixner 
522dc186ad7SThomas Gleixner #else
523dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
524dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
525dc186ad7SThomas Gleixner #endif
526dc186ad7SThomas Gleixner 
5274e8b22bdSLi Bin /**
5284e8b22bdSLi Bin  * worker_pool_assign_id - allocate ID and assing it to @pool
5294e8b22bdSLi Bin  * @pool: the pool pointer of interest
5304e8b22bdSLi Bin  *
5314e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
5324e8b22bdSLi Bin  * successfully, -errno on failure.
5334e8b22bdSLi Bin  */
5349daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
5359daf9e67STejun Heo {
5369daf9e67STejun Heo 	int ret;
5379daf9e67STejun Heo 
53868e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5395bcab335STejun Heo 
5404e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
5414e8b22bdSLi Bin 			GFP_KERNEL);
542229641a6STejun Heo 	if (ret >= 0) {
543e68035fbSTejun Heo 		pool->id = ret;
544229641a6STejun Heo 		return 0;
545229641a6STejun Heo 	}
5469daf9e67STejun Heo 	return ret;
5479daf9e67STejun Heo }
5489daf9e67STejun Heo 
54976af4d93STejun Heo /**
550df2d5ae4STejun Heo  * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
551df2d5ae4STejun Heo  * @wq: the target workqueue
552df2d5ae4STejun Heo  * @node: the node ID
553df2d5ae4STejun Heo  *
5545b95e1afSLai Jiangshan  * This must be called with any of wq_pool_mutex, wq->mutex or sched RCU
5555b95e1afSLai Jiangshan  * read locked.
556df2d5ae4STejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
557df2d5ae4STejun Heo  * responsible for guaranteeing that the pwq stays online.
558d185af30SYacine Belkadi  *
559d185af30SYacine Belkadi  * Return: The unbound pool_workqueue for @node.
560df2d5ae4STejun Heo  */
561df2d5ae4STejun Heo static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq,
562df2d5ae4STejun Heo 						  int node)
563df2d5ae4STejun Heo {
5645b95e1afSLai Jiangshan 	assert_rcu_or_wq_mutex_or_pool_mutex(wq);
565d6e022f1STejun Heo 
566d6e022f1STejun Heo 	/*
567d6e022f1STejun Heo 	 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
568d6e022f1STejun Heo 	 * delayed item is pending.  The plan is to keep CPU -> NODE
569d6e022f1STejun Heo 	 * mapping valid and stable across CPU on/offlines.  Once that
570d6e022f1STejun Heo 	 * happens, this workaround can be removed.
571d6e022f1STejun Heo 	 */
572d6e022f1STejun Heo 	if (unlikely(node == NUMA_NO_NODE))
573d6e022f1STejun Heo 		return wq->dfl_pwq;
574d6e022f1STejun Heo 
575df2d5ae4STejun Heo 	return rcu_dereference_raw(wq->numa_pwq_tbl[node]);
576df2d5ae4STejun Heo }
577df2d5ae4STejun Heo 
57873f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
57973f53c4aSTejun Heo {
58073f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
58173f53c4aSTejun Heo }
58273f53c4aSTejun Heo 
58373f53c4aSTejun Heo static int get_work_color(struct work_struct *work)
58473f53c4aSTejun Heo {
58573f53c4aSTejun Heo 	return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
58673f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
58773f53c4aSTejun Heo }
58873f53c4aSTejun Heo 
58973f53c4aSTejun Heo static int work_next_color(int color)
59073f53c4aSTejun Heo {
59173f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
592a848e3b6SOleg Nesterov }
593a848e3b6SOleg Nesterov 
5944594bf15SDavid Howells /*
595112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
596112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
5977c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
5987a22ad75STejun Heo  *
599112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
600112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
601bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
602bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
6037a22ad75STejun Heo  *
604112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6057c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
606112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
6077c3eed5cSTejun Heo  * available only while the work item is queued.
608bbb68dfaSTejun Heo  *
609bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
610bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
611bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
612bbb68dfaSTejun Heo  * try to steal the PENDING bit.
6134594bf15SDavid Howells  */
6147a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6157a22ad75STejun Heo 				 unsigned long flags)
6167a22ad75STejun Heo {
6176183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
6187a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
6197a22ad75STejun Heo }
6207a22ad75STejun Heo 
621112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6224690c4abSTejun Heo 			 unsigned long extra_flags)
623365970a1SDavid Howells {
624112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
625112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
626365970a1SDavid Howells }
627365970a1SDavid Howells 
6284468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6294468a00fSLai Jiangshan 					   int pool_id)
6304468a00fSLai Jiangshan {
6314468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6324468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
6334468a00fSLai Jiangshan }
6344468a00fSLai Jiangshan 
6357c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6367c3eed5cSTejun Heo 					    int pool_id)
6374d707b9fSOleg Nesterov {
63823657bb1STejun Heo 	/*
63923657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
64023657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
64123657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
64223657bb1STejun Heo 	 * owner.
64323657bb1STejun Heo 	 */
64423657bb1STejun Heo 	smp_wmb();
6457c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
646346c09f8SRoman Pen 	/*
647346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
648346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
649346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
650346c09f8SRoman Pen 	 * reordering can lead to a missed execution on attempt to qeueue
651346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
652346c09f8SRoman Pen 	 *
653346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
654346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
655346c09f8SRoman Pen 	 *
656346c09f8SRoman Pen 	 * 1  STORE event_indicated
657346c09f8SRoman Pen 	 * 2  queue_work_on() {
658346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
659346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
660346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
661346c09f8SRoman Pen 	 * 6                                 smp_mb()
662346c09f8SRoman Pen 	 * 7                               work->current_func() {
663346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
664346c09f8SRoman Pen 	 *				   }
665346c09f8SRoman Pen 	 *
666346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
667346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
668346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
669346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
670346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
671346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
672346c09f8SRoman Pen 	 * before actual STORE.
673346c09f8SRoman Pen 	 */
674346c09f8SRoman Pen 	smp_mb();
6754d707b9fSOleg Nesterov }
6764d707b9fSOleg Nesterov 
6777a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
678365970a1SDavid Howells {
6797c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
6807c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
6817a22ad75STejun Heo }
6827a22ad75STejun Heo 
683112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
6847a22ad75STejun Heo {
685e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
6867a22ad75STejun Heo 
687112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
688e120153dSTejun Heo 		return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
689e120153dSTejun Heo 	else
690e120153dSTejun Heo 		return NULL;
6917a22ad75STejun Heo }
6927a22ad75STejun Heo 
6937c3eed5cSTejun Heo /**
6947c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
6957c3eed5cSTejun Heo  * @work: the work item of interest
6967c3eed5cSTejun Heo  *
69768e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
69868e13a67SLai Jiangshan  * access under sched-RCU read lock.  As such, this function should be
69968e13a67SLai Jiangshan  * called under wq_pool_mutex or with preemption disabled.
700fa1b54e6STejun Heo  *
701fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
702fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
703fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
704fa1b54e6STejun Heo  * returned pool is and stays online.
705d185af30SYacine Belkadi  *
706d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
7077c3eed5cSTejun Heo  */
7087c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
7097a22ad75STejun Heo {
710e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
7117c3eed5cSTejun Heo 	int pool_id;
7127a22ad75STejun Heo 
71368e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
714fa1b54e6STejun Heo 
715112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
716112202d9STejun Heo 		return ((struct pool_workqueue *)
7177c3eed5cSTejun Heo 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool;
7187a22ad75STejun Heo 
7197c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
7207c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
7217a22ad75STejun Heo 		return NULL;
7227a22ad75STejun Heo 
723fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
7247c3eed5cSTejun Heo }
7257c3eed5cSTejun Heo 
7267c3eed5cSTejun Heo /**
7277c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
7287c3eed5cSTejun Heo  * @work: the work item of interest
7297c3eed5cSTejun Heo  *
730d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
7317c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
7327c3eed5cSTejun Heo  */
7337c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
7347c3eed5cSTejun Heo {
73554d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
7367c3eed5cSTejun Heo 
737112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
738112202d9STejun Heo 		return ((struct pool_workqueue *)
73954d5b7d0SLai Jiangshan 			(data & WORK_STRUCT_WQ_DATA_MASK))->pool->id;
74054d5b7d0SLai Jiangshan 
74154d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
7427c3eed5cSTejun Heo }
7437c3eed5cSTejun Heo 
744bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
745bbb68dfaSTejun Heo {
7467c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
747bbb68dfaSTejun Heo 
7487c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
7497c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
750bbb68dfaSTejun Heo }
751bbb68dfaSTejun Heo 
752bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
753bbb68dfaSTejun Heo {
754bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
755bbb68dfaSTejun Heo 
756112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
757bbb68dfaSTejun Heo }
758bbb68dfaSTejun Heo 
759e22bee78STejun Heo /*
7603270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
7613270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
762d565ed63STejun Heo  * they're being called with pool->lock held.
763e22bee78STejun Heo  */
764e22bee78STejun Heo 
76563d95a91STejun Heo static bool __need_more_worker(struct worker_pool *pool)
766649027d7STejun Heo {
767e19e397aSTejun Heo 	return !atomic_read(&pool->nr_running);
768649027d7STejun Heo }
769649027d7STejun Heo 
770e22bee78STejun Heo /*
771e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
772e22bee78STejun Heo  * running workers.
773974271c4STejun Heo  *
774974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
775706026c2STejun Heo  * function will always return %true for unbound pools as long as the
776974271c4STejun Heo  * worklist isn't empty.
777e22bee78STejun Heo  */
77863d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
779e22bee78STejun Heo {
78063d95a91STejun Heo 	return !list_empty(&pool->worklist) && __need_more_worker(pool);
781e22bee78STejun Heo }
782e22bee78STejun Heo 
783e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
78463d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
785e22bee78STejun Heo {
78663d95a91STejun Heo 	return pool->nr_idle;
787e22bee78STejun Heo }
788e22bee78STejun Heo 
789e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
79063d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
791e22bee78STejun Heo {
792e19e397aSTejun Heo 	return !list_empty(&pool->worklist) &&
793e19e397aSTejun Heo 		atomic_read(&pool->nr_running) <= 1;
794e22bee78STejun Heo }
795e22bee78STejun Heo 
796e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
79763d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
798e22bee78STejun Heo {
79963d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
800e22bee78STejun Heo }
801e22bee78STejun Heo 
802e22bee78STejun Heo /* Do we have too many workers and should some go away? */
80363d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
804e22bee78STejun Heo {
805692b4825STejun Heo 	bool managing = pool->flags & POOL_MANAGER_ACTIVE;
80663d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
80763d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
808e22bee78STejun Heo 
809e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
810e22bee78STejun Heo }
811e22bee78STejun Heo 
812e22bee78STejun Heo /*
813e22bee78STejun Heo  * Wake up functions.
814e22bee78STejun Heo  */
815e22bee78STejun Heo 
8161037de36SLai Jiangshan /* Return the first idle worker.  Safe with preemption disabled */
8171037de36SLai Jiangshan static struct worker *first_idle_worker(struct worker_pool *pool)
8187e11629dSTejun Heo {
81963d95a91STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
8207e11629dSTejun Heo 		return NULL;
8217e11629dSTejun Heo 
82263d95a91STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
8237e11629dSTejun Heo }
8247e11629dSTejun Heo 
8257e11629dSTejun Heo /**
8267e11629dSTejun Heo  * wake_up_worker - wake up an idle worker
82763d95a91STejun Heo  * @pool: worker pool to wake worker from
8287e11629dSTejun Heo  *
82963d95a91STejun Heo  * Wake up the first idle worker of @pool.
8307e11629dSTejun Heo  *
8317e11629dSTejun Heo  * CONTEXT:
832d565ed63STejun Heo  * spin_lock_irq(pool->lock).
8337e11629dSTejun Heo  */
83463d95a91STejun Heo static void wake_up_worker(struct worker_pool *pool)
8357e11629dSTejun Heo {
8361037de36SLai Jiangshan 	struct worker *worker = first_idle_worker(pool);
8377e11629dSTejun Heo 
8387e11629dSTejun Heo 	if (likely(worker))
8397e11629dSTejun Heo 		wake_up_process(worker->task);
8407e11629dSTejun Heo }
8417e11629dSTejun Heo 
8424690c4abSTejun Heo /**
843e22bee78STejun Heo  * wq_worker_waking_up - a worker is waking up
844e22bee78STejun Heo  * @task: task waking up
845e22bee78STejun Heo  * @cpu: CPU @task is waking up to
846e22bee78STejun Heo  *
847e22bee78STejun Heo  * This function is called during try_to_wake_up() when a worker is
848e22bee78STejun Heo  * being awoken.
849e22bee78STejun Heo  *
850e22bee78STejun Heo  * CONTEXT:
851e22bee78STejun Heo  * spin_lock_irq(rq->lock)
852e22bee78STejun Heo  */
853d84ff051STejun Heo void wq_worker_waking_up(struct task_struct *task, int cpu)
854e22bee78STejun Heo {
855e22bee78STejun Heo 	struct worker *worker = kthread_data(task);
856e22bee78STejun Heo 
85736576000SJoonsoo Kim 	if (!(worker->flags & WORKER_NOT_RUNNING)) {
858ec22ca5eSTejun Heo 		WARN_ON_ONCE(worker->pool->cpu != cpu);
859e19e397aSTejun Heo 		atomic_inc(&worker->pool->nr_running);
860e22bee78STejun Heo 	}
86136576000SJoonsoo Kim }
862e22bee78STejun Heo 
863e22bee78STejun Heo /**
864e22bee78STejun Heo  * wq_worker_sleeping - a worker is going to sleep
865e22bee78STejun Heo  * @task: task going to sleep
866e22bee78STejun Heo  *
867e22bee78STejun Heo  * This function is called during schedule() when a busy worker is
868e22bee78STejun Heo  * going to sleep.  Worker on the same cpu can be woken up by
869e22bee78STejun Heo  * returning pointer to its task.
870e22bee78STejun Heo  *
871e22bee78STejun Heo  * CONTEXT:
872e22bee78STejun Heo  * spin_lock_irq(rq->lock)
873e22bee78STejun Heo  *
874d185af30SYacine Belkadi  * Return:
875e22bee78STejun Heo  * Worker task on @cpu to wake up, %NULL if none.
876e22bee78STejun Heo  */
8779b7f6597SAlexander Gordeev struct task_struct *wq_worker_sleeping(struct task_struct *task)
878e22bee78STejun Heo {
879e22bee78STejun Heo 	struct worker *worker = kthread_data(task), *to_wakeup = NULL;
880111c225aSTejun Heo 	struct worker_pool *pool;
881e22bee78STejun Heo 
882111c225aSTejun Heo 	/*
883111c225aSTejun Heo 	 * Rescuers, which may not have all the fields set up like normal
884111c225aSTejun Heo 	 * workers, also reach here, let's not access anything before
885111c225aSTejun Heo 	 * checking NOT_RUNNING.
886111c225aSTejun Heo 	 */
8872d64672eSSteven Rostedt 	if (worker->flags & WORKER_NOT_RUNNING)
888e22bee78STejun Heo 		return NULL;
889e22bee78STejun Heo 
890111c225aSTejun Heo 	pool = worker->pool;
891111c225aSTejun Heo 
892e22bee78STejun Heo 	/* this can only happen on the local cpu */
8939b7f6597SAlexander Gordeev 	if (WARN_ON_ONCE(pool->cpu != raw_smp_processor_id()))
8946183c009STejun Heo 		return NULL;
895e22bee78STejun Heo 
896e22bee78STejun Heo 	/*
897e22bee78STejun Heo 	 * The counterpart of the following dec_and_test, implied mb,
898e22bee78STejun Heo 	 * worklist not empty test sequence is in insert_work().
899e22bee78STejun Heo 	 * Please read comment there.
900e22bee78STejun Heo 	 *
901628c78e7STejun Heo 	 * NOT_RUNNING is clear.  This means that we're bound to and
902628c78e7STejun Heo 	 * running on the local cpu w/ rq lock held and preemption
903628c78e7STejun Heo 	 * disabled, which in turn means that none else could be
904d565ed63STejun Heo 	 * manipulating idle_list, so dereferencing idle_list without pool
905628c78e7STejun Heo 	 * lock is safe.
906e22bee78STejun Heo 	 */
907e19e397aSTejun Heo 	if (atomic_dec_and_test(&pool->nr_running) &&
908e19e397aSTejun Heo 	    !list_empty(&pool->worklist))
9091037de36SLai Jiangshan 		to_wakeup = first_idle_worker(pool);
910e22bee78STejun Heo 	return to_wakeup ? to_wakeup->task : NULL;
911e22bee78STejun Heo }
912e22bee78STejun Heo 
913e22bee78STejun Heo /**
914e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
915cb444766STejun Heo  * @worker: self
916d302f017STejun Heo  * @flags: flags to set
917d302f017STejun Heo  *
918228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
919d302f017STejun Heo  *
920cb444766STejun Heo  * CONTEXT:
921d565ed63STejun Heo  * spin_lock_irq(pool->lock)
922d302f017STejun Heo  */
923228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
924d302f017STejun Heo {
925bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
926e22bee78STejun Heo 
927cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
928cb444766STejun Heo 
929228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
930e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
931e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
932e19e397aSTejun Heo 		atomic_dec(&pool->nr_running);
933e22bee78STejun Heo 	}
934e22bee78STejun Heo 
935d302f017STejun Heo 	worker->flags |= flags;
936d302f017STejun Heo }
937d302f017STejun Heo 
938d302f017STejun Heo /**
939e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
940cb444766STejun Heo  * @worker: self
941d302f017STejun Heo  * @flags: flags to clear
942d302f017STejun Heo  *
943e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
944d302f017STejun Heo  *
945cb444766STejun Heo  * CONTEXT:
946d565ed63STejun Heo  * spin_lock_irq(pool->lock)
947d302f017STejun Heo  */
948d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
949d302f017STejun Heo {
95063d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
951e22bee78STejun Heo 	unsigned int oflags = worker->flags;
952e22bee78STejun Heo 
953cb444766STejun Heo 	WARN_ON_ONCE(worker->task != current);
954cb444766STejun Heo 
955d302f017STejun Heo 	worker->flags &= ~flags;
956e22bee78STejun Heo 
95742c025f3STejun Heo 	/*
95842c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
95942c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
96042c025f3STejun Heo 	 * of multiple flags, not a single flag.
96142c025f3STejun Heo 	 */
962e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
963e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
964e19e397aSTejun Heo 			atomic_inc(&pool->nr_running);
965d302f017STejun Heo }
966d302f017STejun Heo 
967d302f017STejun Heo /**
9688cca0eeaSTejun Heo  * find_worker_executing_work - find worker which is executing a work
969c9e7cf27STejun Heo  * @pool: pool of interest
9708cca0eeaSTejun Heo  * @work: work to find worker for
9718cca0eeaSTejun Heo  *
972c9e7cf27STejun Heo  * Find a worker which is executing @work on @pool by searching
973c9e7cf27STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
974a2c1c57bSTejun Heo  * to match, its current execution should match the address of @work and
975a2c1c57bSTejun Heo  * its work function.  This is to avoid unwanted dependency between
976a2c1c57bSTejun Heo  * unrelated work executions through a work item being recycled while still
977a2c1c57bSTejun Heo  * being executed.
978a2c1c57bSTejun Heo  *
979a2c1c57bSTejun Heo  * This is a bit tricky.  A work item may be freed once its execution
980a2c1c57bSTejun Heo  * starts and nothing prevents the freed area from being recycled for
981a2c1c57bSTejun Heo  * another work item.  If the same work item address ends up being reused
982a2c1c57bSTejun Heo  * before the original execution finishes, workqueue will identify the
983a2c1c57bSTejun Heo  * recycled work item as currently executing and make it wait until the
984a2c1c57bSTejun Heo  * current execution finishes, introducing an unwanted dependency.
985a2c1c57bSTejun Heo  *
986c5aa87bbSTejun Heo  * This function checks the work item address and work function to avoid
987c5aa87bbSTejun Heo  * false positives.  Note that this isn't complete as one may construct a
988c5aa87bbSTejun Heo  * work function which can introduce dependency onto itself through a
989c5aa87bbSTejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
990c5aa87bbSTejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
991c5aa87bbSTejun Heo  * actually occurs, it should be easy to locate the culprit work function.
9928cca0eeaSTejun Heo  *
9938cca0eeaSTejun Heo  * CONTEXT:
994d565ed63STejun Heo  * spin_lock_irq(pool->lock).
9958cca0eeaSTejun Heo  *
996d185af30SYacine Belkadi  * Return:
997d185af30SYacine Belkadi  * Pointer to worker which is executing @work if found, %NULL
9988cca0eeaSTejun Heo  * otherwise.
9998cca0eeaSTejun Heo  */
1000c9e7cf27STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
10018cca0eeaSTejun Heo 						 struct work_struct *work)
10028cca0eeaSTejun Heo {
100342f8570fSSasha Levin 	struct worker *worker;
100442f8570fSSasha Levin 
1005b67bfe0dSSasha Levin 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1006a2c1c57bSTejun Heo 			       (unsigned long)work)
1007a2c1c57bSTejun Heo 		if (worker->current_work == work &&
1008a2c1c57bSTejun Heo 		    worker->current_func == work->func)
100942f8570fSSasha Levin 			return worker;
101042f8570fSSasha Levin 
101142f8570fSSasha Levin 	return NULL;
10128cca0eeaSTejun Heo }
10138cca0eeaSTejun Heo 
10148cca0eeaSTejun Heo /**
1015bf4ede01STejun Heo  * move_linked_works - move linked works to a list
1016bf4ede01STejun Heo  * @work: start of series of works to be scheduled
1017bf4ede01STejun Heo  * @head: target list to append @work to
1018402dd89dSShailendra Verma  * @nextp: out parameter for nested worklist walking
1019bf4ede01STejun Heo  *
1020bf4ede01STejun Heo  * Schedule linked works starting from @work to @head.  Work series to
1021bf4ede01STejun Heo  * be scheduled starts at @work and includes any consecutive work with
1022bf4ede01STejun Heo  * WORK_STRUCT_LINKED set in its predecessor.
1023bf4ede01STejun Heo  *
1024bf4ede01STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of
1025bf4ede01STejun Heo  * the last scheduled work.  This allows move_linked_works() to be
1026bf4ede01STejun Heo  * nested inside outer list_for_each_entry_safe().
1027bf4ede01STejun Heo  *
1028bf4ede01STejun Heo  * CONTEXT:
1029d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1030bf4ede01STejun Heo  */
1031bf4ede01STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1032bf4ede01STejun Heo 			      struct work_struct **nextp)
1033bf4ede01STejun Heo {
1034bf4ede01STejun Heo 	struct work_struct *n;
1035bf4ede01STejun Heo 
1036bf4ede01STejun Heo 	/*
1037bf4ede01STejun Heo 	 * Linked worklist will always end before the end of the list,
1038bf4ede01STejun Heo 	 * use NULL for list head.
1039bf4ede01STejun Heo 	 */
1040bf4ede01STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1041bf4ede01STejun Heo 		list_move_tail(&work->entry, head);
1042bf4ede01STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1043bf4ede01STejun Heo 			break;
1044bf4ede01STejun Heo 	}
1045bf4ede01STejun Heo 
1046bf4ede01STejun Heo 	/*
1047bf4ede01STejun Heo 	 * If we're already inside safe list traversal and have moved
1048bf4ede01STejun Heo 	 * multiple works to the scheduled queue, the next position
1049bf4ede01STejun Heo 	 * needs to be updated.
1050bf4ede01STejun Heo 	 */
1051bf4ede01STejun Heo 	if (nextp)
1052bf4ede01STejun Heo 		*nextp = n;
1053bf4ede01STejun Heo }
1054bf4ede01STejun Heo 
10558864b4e5STejun Heo /**
10568864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
10578864b4e5STejun Heo  * @pwq: pool_workqueue to get
10588864b4e5STejun Heo  *
10598864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
10608864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
10618864b4e5STejun Heo  */
10628864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
10638864b4e5STejun Heo {
10648864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
10658864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
10668864b4e5STejun Heo 	pwq->refcnt++;
10678864b4e5STejun Heo }
10688864b4e5STejun Heo 
10698864b4e5STejun Heo /**
10708864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
10718864b4e5STejun Heo  * @pwq: pool_workqueue to put
10728864b4e5STejun Heo  *
10738864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
10748864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
10758864b4e5STejun Heo  */
10768864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
10778864b4e5STejun Heo {
10788864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
10798864b4e5STejun Heo 	if (likely(--pwq->refcnt))
10808864b4e5STejun Heo 		return;
10818864b4e5STejun Heo 	if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND)))
10828864b4e5STejun Heo 		return;
10838864b4e5STejun Heo 	/*
10848864b4e5STejun Heo 	 * @pwq can't be released under pool->lock, bounce to
10858864b4e5STejun Heo 	 * pwq_unbound_release_workfn().  This never recurses on the same
10868864b4e5STejun Heo 	 * pool->lock as this path is taken only for unbound workqueues and
10878864b4e5STejun Heo 	 * the release work item is scheduled on a per-cpu workqueue.  To
10888864b4e5STejun Heo 	 * avoid lockdep warning, unbound pool->locks are given lockdep
10898864b4e5STejun Heo 	 * subclass of 1 in get_unbound_pool().
10908864b4e5STejun Heo 	 */
10918864b4e5STejun Heo 	schedule_work(&pwq->unbound_release_work);
10928864b4e5STejun Heo }
10938864b4e5STejun Heo 
1094dce90d47STejun Heo /**
1095dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1096dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1097dce90d47STejun Heo  *
1098dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1099dce90d47STejun Heo  */
1100dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1101dce90d47STejun Heo {
1102dce90d47STejun Heo 	if (pwq) {
1103dce90d47STejun Heo 		/*
1104dce90d47STejun Heo 		 * As both pwqs and pools are sched-RCU protected, the
1105dce90d47STejun Heo 		 * following lock operations are safe.
1106dce90d47STejun Heo 		 */
1107dce90d47STejun Heo 		spin_lock_irq(&pwq->pool->lock);
1108dce90d47STejun Heo 		put_pwq(pwq);
1109dce90d47STejun Heo 		spin_unlock_irq(&pwq->pool->lock);
1110dce90d47STejun Heo 	}
1111dce90d47STejun Heo }
1112dce90d47STejun Heo 
1113112202d9STejun Heo static void pwq_activate_delayed_work(struct work_struct *work)
1114bf4ede01STejun Heo {
1115112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1116bf4ede01STejun Heo 
1117bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
111882607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
111982607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1120112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
1121bf4ede01STejun Heo 	__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1122112202d9STejun Heo 	pwq->nr_active++;
1123bf4ede01STejun Heo }
1124bf4ede01STejun Heo 
1125112202d9STejun Heo static void pwq_activate_first_delayed(struct pool_workqueue *pwq)
11263aa62497SLai Jiangshan {
1127112202d9STejun Heo 	struct work_struct *work = list_first_entry(&pwq->delayed_works,
11283aa62497SLai Jiangshan 						    struct work_struct, entry);
11293aa62497SLai Jiangshan 
1130112202d9STejun Heo 	pwq_activate_delayed_work(work);
11313aa62497SLai Jiangshan }
11323aa62497SLai Jiangshan 
1133bf4ede01STejun Heo /**
1134112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1135112202d9STejun Heo  * @pwq: pwq of interest
1136bf4ede01STejun Heo  * @color: color of work which left the queue
1137bf4ede01STejun Heo  *
1138bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1139112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1140bf4ede01STejun Heo  *
1141bf4ede01STejun Heo  * CONTEXT:
1142d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1143bf4ede01STejun Heo  */
1144112202d9STejun Heo static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, int color)
1145bf4ede01STejun Heo {
11468864b4e5STejun Heo 	/* uncolored work items don't participate in flushing or nr_active */
1147bf4ede01STejun Heo 	if (color == WORK_NO_COLOR)
11488864b4e5STejun Heo 		goto out_put;
1149bf4ede01STejun Heo 
1150112202d9STejun Heo 	pwq->nr_in_flight[color]--;
1151bf4ede01STejun Heo 
1152112202d9STejun Heo 	pwq->nr_active--;
1153112202d9STejun Heo 	if (!list_empty(&pwq->delayed_works)) {
1154bf4ede01STejun Heo 		/* one down, submit a delayed one */
1155112202d9STejun Heo 		if (pwq->nr_active < pwq->max_active)
1156112202d9STejun Heo 			pwq_activate_first_delayed(pwq);
1157bf4ede01STejun Heo 	}
1158bf4ede01STejun Heo 
1159bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1160112202d9STejun Heo 	if (likely(pwq->flush_color != color))
11618864b4e5STejun Heo 		goto out_put;
1162bf4ede01STejun Heo 
1163bf4ede01STejun Heo 	/* are there still in-flight works? */
1164112202d9STejun Heo 	if (pwq->nr_in_flight[color])
11658864b4e5STejun Heo 		goto out_put;
1166bf4ede01STejun Heo 
1167112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1168112202d9STejun Heo 	pwq->flush_color = -1;
1169bf4ede01STejun Heo 
1170bf4ede01STejun Heo 	/*
1171112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1172bf4ede01STejun Heo 	 * will handle the rest.
1173bf4ede01STejun Heo 	 */
1174112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1175112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
11768864b4e5STejun Heo out_put:
11778864b4e5STejun Heo 	put_pwq(pwq);
1178bf4ede01STejun Heo }
1179bf4ede01STejun Heo 
118036e227d2STejun Heo /**
1181bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
118236e227d2STejun Heo  * @work: work item to steal
118336e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1184bbb68dfaSTejun Heo  * @flags: place to store irq state
118536e227d2STejun Heo  *
118636e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1187d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
118836e227d2STejun Heo  *
1189d185af30SYacine Belkadi  * Return:
119036e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
119136e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
119236e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1193bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1194bbb68dfaSTejun Heo  *		for arbitrarily long
119536e227d2STejun Heo  *
1196d185af30SYacine Belkadi  * Note:
1197bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1198e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1199e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1200e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1201bbb68dfaSTejun Heo  *
1202bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1203bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1204bbb68dfaSTejun Heo  *
1205e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1206bf4ede01STejun Heo  */
1207bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1208bbb68dfaSTejun Heo 			       unsigned long *flags)
1209bf4ede01STejun Heo {
1210d565ed63STejun Heo 	struct worker_pool *pool;
1211112202d9STejun Heo 	struct pool_workqueue *pwq;
1212bf4ede01STejun Heo 
1213bbb68dfaSTejun Heo 	local_irq_save(*flags);
1214bbb68dfaSTejun Heo 
121536e227d2STejun Heo 	/* try to steal the timer if it exists */
121636e227d2STejun Heo 	if (is_dwork) {
121736e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
121836e227d2STejun Heo 
1219e0aecdd8STejun Heo 		/*
1220e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
1221e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
1222e0aecdd8STejun Heo 		 * running on the local CPU.
1223e0aecdd8STejun Heo 		 */
122436e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
122536e227d2STejun Heo 			return 1;
122636e227d2STejun Heo 	}
122736e227d2STejun Heo 
122836e227d2STejun Heo 	/* try to claim PENDING the normal way */
1229bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1230bf4ede01STejun Heo 		return 0;
1231bf4ede01STejun Heo 
1232bf4ede01STejun Heo 	/*
1233bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
1234bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1235bf4ede01STejun Heo 	 */
1236d565ed63STejun Heo 	pool = get_work_pool(work);
1237d565ed63STejun Heo 	if (!pool)
1238bbb68dfaSTejun Heo 		goto fail;
1239bf4ede01STejun Heo 
1240d565ed63STejun Heo 	spin_lock(&pool->lock);
1241bf4ede01STejun Heo 	/*
1242112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
1243112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
1244112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
1245112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
1246112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
12470b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
1248bf4ede01STejun Heo 	 */
1249112202d9STejun Heo 	pwq = get_work_pwq(work);
1250112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
1251bf4ede01STejun Heo 		debug_work_deactivate(work);
12523aa62497SLai Jiangshan 
12533aa62497SLai Jiangshan 		/*
125416062836STejun Heo 		 * A delayed work item cannot be grabbed directly because
125516062836STejun Heo 		 * it might have linked NO_COLOR work items which, if left
1256112202d9STejun Heo 		 * on the delayed_list, will confuse pwq->nr_active
125716062836STejun Heo 		 * management later on and cause stall.  Make sure the work
125816062836STejun Heo 		 * item is activated before grabbing.
12593aa62497SLai Jiangshan 		 */
12603aa62497SLai Jiangshan 		if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
1261112202d9STejun Heo 			pwq_activate_delayed_work(work);
12623aa62497SLai Jiangshan 
1263bf4ede01STejun Heo 		list_del_init(&work->entry);
12649c34a704SLai Jiangshan 		pwq_dec_nr_in_flight(pwq, get_work_color(work));
126536e227d2STejun Heo 
1266112202d9STejun Heo 		/* work->data points to pwq iff queued, point to pool */
12674468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
12684468a00fSLai Jiangshan 
1269d565ed63STejun Heo 		spin_unlock(&pool->lock);
127036e227d2STejun Heo 		return 1;
1271bf4ede01STejun Heo 	}
1272d565ed63STejun Heo 	spin_unlock(&pool->lock);
1273bbb68dfaSTejun Heo fail:
1274bbb68dfaSTejun Heo 	local_irq_restore(*flags);
1275bbb68dfaSTejun Heo 	if (work_is_canceling(work))
1276bbb68dfaSTejun Heo 		return -ENOENT;
1277bbb68dfaSTejun Heo 	cpu_relax();
127836e227d2STejun Heo 	return -EAGAIN;
1279bf4ede01STejun Heo }
1280bf4ede01STejun Heo 
1281bf4ede01STejun Heo /**
1282706026c2STejun Heo  * insert_work - insert a work into a pool
1283112202d9STejun Heo  * @pwq: pwq @work belongs to
12844690c4abSTejun Heo  * @work: work to insert
12854690c4abSTejun Heo  * @head: insertion point
12864690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
12874690c4abSTejun Heo  *
1288112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
1289706026c2STejun Heo  * work_struct flags.
12904690c4abSTejun Heo  *
12914690c4abSTejun Heo  * CONTEXT:
1292d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1293365970a1SDavid Howells  */
1294112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1295112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
1296b89deed3SOleg Nesterov {
1297112202d9STejun Heo 	struct worker_pool *pool = pwq->pool;
1298e1d8aa9fSFrederic Weisbecker 
12994690c4abSTejun Heo 	/* we own @work, set data and link */
1300112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
13011a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
13028864b4e5STejun Heo 	get_pwq(pwq);
1303e22bee78STejun Heo 
1304e22bee78STejun Heo 	/*
1305c5aa87bbSTejun Heo 	 * Ensure either wq_worker_sleeping() sees the above
1306c5aa87bbSTejun Heo 	 * list_add_tail() or we see zero nr_running to avoid workers lying
1307c5aa87bbSTejun Heo 	 * around lazily while there are works to be processed.
1308e22bee78STejun Heo 	 */
1309e22bee78STejun Heo 	smp_mb();
1310e22bee78STejun Heo 
131163d95a91STejun Heo 	if (__need_more_worker(pool))
131263d95a91STejun Heo 		wake_up_worker(pool);
1313b89deed3SOleg Nesterov }
1314b89deed3SOleg Nesterov 
1315c8efcc25STejun Heo /*
1316c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
13178d03ecfeSTejun Heo  * same workqueue.
1318c8efcc25STejun Heo  */
1319c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1320c8efcc25STejun Heo {
1321c8efcc25STejun Heo 	struct worker *worker;
1322c8efcc25STejun Heo 
13238d03ecfeSTejun Heo 	worker = current_wq_worker();
1324c8efcc25STejun Heo 	/*
13258d03ecfeSTejun Heo 	 * Return %true iff I'm a worker execuing a work item on @wq.  If
13268d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
1327c8efcc25STejun Heo 	 */
1328112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
1329c8efcc25STejun Heo }
1330c8efcc25STejun Heo 
1331ef557180SMike Galbraith /*
1332ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
1333ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
1334ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
1335ef557180SMike Galbraith  */
1336ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1337ef557180SMike Galbraith {
1338f303fccbSTejun Heo 	static bool printed_dbg_warning;
1339ef557180SMike Galbraith 	int new_cpu;
1340ef557180SMike Galbraith 
1341f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
1342ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1343ef557180SMike Galbraith 			return cpu;
1344f303fccbSTejun Heo 	} else if (!printed_dbg_warning) {
1345f303fccbSTejun Heo 		pr_warn("workqueue: round-robin CPU selection forced, expect performance impact\n");
1346f303fccbSTejun Heo 		printed_dbg_warning = true;
1347f303fccbSTejun Heo 	}
1348f303fccbSTejun Heo 
1349ef557180SMike Galbraith 	if (cpumask_empty(wq_unbound_cpumask))
1350ef557180SMike Galbraith 		return cpu;
1351ef557180SMike Galbraith 
1352ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
1353ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1354ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
1355ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1356ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
1357ef557180SMike Galbraith 			return cpu;
1358ef557180SMike Galbraith 	}
1359ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
1360ef557180SMike Galbraith 
1361ef557180SMike Galbraith 	return new_cpu;
1362ef557180SMike Galbraith }
1363ef557180SMike Galbraith 
1364d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
13651da177e4SLinus Torvalds 			 struct work_struct *work)
13661da177e4SLinus Torvalds {
1367112202d9STejun Heo 	struct pool_workqueue *pwq;
1368c9178087STejun Heo 	struct worker_pool *last_pool;
13691e19ffc6STejun Heo 	struct list_head *worklist;
13708a2e8e5dSTejun Heo 	unsigned int work_flags;
1371b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
13728930cabaSTejun Heo 
13738930cabaSTejun Heo 	/*
13748930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
13758930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
13768930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
13778930cabaSTejun Heo 	 * happen with IRQ disabled.
13788930cabaSTejun Heo 	 */
13798e8eb730SFrederic Weisbecker 	lockdep_assert_irqs_disabled();
13801da177e4SLinus Torvalds 
1381dc186ad7SThomas Gleixner 	debug_work_activate(work);
13821e19ffc6STejun Heo 
13839ef28a73SLi Bin 	/* if draining, only works from the same workqueue are allowed */
1384618b01ebSTejun Heo 	if (unlikely(wq->flags & __WQ_DRAINING) &&
1385c8efcc25STejun Heo 	    WARN_ON_ONCE(!is_chained_work(wq)))
1386e41e704bSTejun Heo 		return;
13879e8cd2f5STejun Heo retry:
1388df2d5ae4STejun Heo 	if (req_cpu == WORK_CPU_UNBOUND)
1389ef557180SMike Galbraith 		cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1390df2d5ae4STejun Heo 
1391df2d5ae4STejun Heo 	/* pwq which will be used unless @work is executing elsewhere */
1392df2d5ae4STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
1393c9178087STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
1394df2d5ae4STejun Heo 	else
1395df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
1396f3421797STejun Heo 
139718aa9effSTejun Heo 	/*
1398c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
1399c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
1400c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
140118aa9effSTejun Heo 	 */
1402c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
1403112202d9STejun Heo 	if (last_pool && last_pool != pwq->pool) {
140418aa9effSTejun Heo 		struct worker *worker;
140518aa9effSTejun Heo 
1406d565ed63STejun Heo 		spin_lock(&last_pool->lock);
140718aa9effSTejun Heo 
1408c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
140918aa9effSTejun Heo 
1410112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
1411c9178087STejun Heo 			pwq = worker->current_pwq;
14128594fadeSLai Jiangshan 		} else {
141318aa9effSTejun Heo 			/* meh... not running there, queue here */
1414d565ed63STejun Heo 			spin_unlock(&last_pool->lock);
1415112202d9STejun Heo 			spin_lock(&pwq->pool->lock);
141618aa9effSTejun Heo 		}
14178930cabaSTejun Heo 	} else {
1418112202d9STejun Heo 		spin_lock(&pwq->pool->lock);
14198930cabaSTejun Heo 	}
1420502ca9d8STejun Heo 
14219e8cd2f5STejun Heo 	/*
14229e8cd2f5STejun Heo 	 * pwq is determined and locked.  For unbound pools, we could have
14239e8cd2f5STejun Heo 	 * raced with pwq release and it could already be dead.  If its
14249e8cd2f5STejun Heo 	 * refcnt is zero, repeat pwq selection.  Note that pwqs never die
1425df2d5ae4STejun Heo 	 * without another pwq replacing it in the numa_pwq_tbl or while
1426df2d5ae4STejun Heo 	 * work items are executing on it, so the retrying is guaranteed to
14279e8cd2f5STejun Heo 	 * make forward-progress.
14289e8cd2f5STejun Heo 	 */
14299e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
14309e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
14319e8cd2f5STejun Heo 			spin_unlock(&pwq->pool->lock);
14329e8cd2f5STejun Heo 			cpu_relax();
14339e8cd2f5STejun Heo 			goto retry;
14349e8cd2f5STejun Heo 		}
14359e8cd2f5STejun Heo 		/* oops */
14369e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
14379e8cd2f5STejun Heo 			  wq->name, cpu);
14389e8cd2f5STejun Heo 	}
14399e8cd2f5STejun Heo 
1440112202d9STejun Heo 	/* pwq determined, queue */
1441112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
1442502ca9d8STejun Heo 
1443f5b2552bSDan Carpenter 	if (WARN_ON(!list_empty(&work->entry))) {
1444112202d9STejun Heo 		spin_unlock(&pwq->pool->lock);
1445f5b2552bSDan Carpenter 		return;
1446f5b2552bSDan Carpenter 	}
14471e19ffc6STejun Heo 
1448112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
1449112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
14501e19ffc6STejun Heo 
1451112202d9STejun Heo 	if (likely(pwq->nr_active < pwq->max_active)) {
1452cdadf009STejun Heo 		trace_workqueue_activate_work(work);
1453112202d9STejun Heo 		pwq->nr_active++;
1454112202d9STejun Heo 		worklist = &pwq->pool->worklist;
145582607adcSTejun Heo 		if (list_empty(worklist))
145682607adcSTejun Heo 			pwq->pool->watchdog_ts = jiffies;
14578a2e8e5dSTejun Heo 	} else {
14588a2e8e5dSTejun Heo 		work_flags |= WORK_STRUCT_DELAYED;
1459112202d9STejun Heo 		worklist = &pwq->delayed_works;
14608a2e8e5dSTejun Heo 	}
14611e19ffc6STejun Heo 
1462112202d9STejun Heo 	insert_work(pwq, work, worklist, work_flags);
14631e19ffc6STejun Heo 
1464112202d9STejun Heo 	spin_unlock(&pwq->pool->lock);
14651da177e4SLinus Torvalds }
14661da177e4SLinus Torvalds 
14670fcb78c2SRolf Eike Beer /**
1468c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
1469c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
1470c1a220e7SZhang Rui  * @wq: workqueue to use
1471c1a220e7SZhang Rui  * @work: work to queue
1472c1a220e7SZhang Rui  *
1473c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
1474c1a220e7SZhang Rui  * can't go away.
1475d185af30SYacine Belkadi  *
1476d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
1477c1a220e7SZhang Rui  */
1478d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1479d4283e93STejun Heo 		   struct work_struct *work)
1480c1a220e7SZhang Rui {
1481d4283e93STejun Heo 	bool ret = false;
14828930cabaSTejun Heo 	unsigned long flags;
14838930cabaSTejun Heo 
14848930cabaSTejun Heo 	local_irq_save(flags);
1485c1a220e7SZhang Rui 
148622df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
14874690c4abSTejun Heo 		__queue_work(cpu, wq, work);
1488d4283e93STejun Heo 		ret = true;
1489c1a220e7SZhang Rui 	}
14908930cabaSTejun Heo 
14918930cabaSTejun Heo 	local_irq_restore(flags);
1492c1a220e7SZhang Rui 	return ret;
1493c1a220e7SZhang Rui }
1494ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1495c1a220e7SZhang Rui 
14968c20feb6SKees Cook void delayed_work_timer_fn(struct timer_list *t)
14971da177e4SLinus Torvalds {
14988c20feb6SKees Cook 	struct delayed_work *dwork = from_timer(dwork, t, timer);
14991da177e4SLinus Torvalds 
1500e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
150160c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
15021da177e4SLinus Torvalds }
15031438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
15041da177e4SLinus Torvalds 
15057beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
150652bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
15071da177e4SLinus Torvalds {
15087beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
15097beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
15101da177e4SLinus Torvalds 
1511637fdbaeSTejun Heo 	WARN_ON_ONCE(!wq);
1512841b86f3SKees Cook 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
1513fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
1514fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
15157beb2edfSTejun Heo 
15168852aac2STejun Heo 	/*
15178852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
15188852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
15198852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
15208852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
15218852aac2STejun Heo 	 */
15228852aac2STejun Heo 	if (!delay) {
15238852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
15248852aac2STejun Heo 		return;
15258852aac2STejun Heo 	}
15268852aac2STejun Heo 
152760c057bcSLai Jiangshan 	dwork->wq = wq;
15281265057fSTejun Heo 	dwork->cpu = cpu;
15297beb2edfSTejun Heo 	timer->expires = jiffies + delay;
15307beb2edfSTejun Heo 
1531041bd12eSTejun Heo 	if (unlikely(cpu != WORK_CPU_UNBOUND))
15327beb2edfSTejun Heo 		add_timer_on(timer, cpu);
1533041bd12eSTejun Heo 	else
1534041bd12eSTejun Heo 		add_timer(timer);
15357beb2edfSTejun Heo }
15361da177e4SLinus Torvalds 
15370fcb78c2SRolf Eike Beer /**
15380fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
15390fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
15400fcb78c2SRolf Eike Beer  * @wq: workqueue to use
1541af9997e4SRandy Dunlap  * @dwork: work to queue
15420fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
15430fcb78c2SRolf Eike Beer  *
1544d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
1545715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
1546715f1300STejun Heo  * execution.
15470fcb78c2SRolf Eike Beer  */
1548d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
154952bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
15507a6bc1cdSVenkatesh Pallipadi {
155152bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
1552d4283e93STejun Heo 	bool ret = false;
15538930cabaSTejun Heo 	unsigned long flags;
15548930cabaSTejun Heo 
15558930cabaSTejun Heo 	/* read the comment in __queue_work() */
15568930cabaSTejun Heo 	local_irq_save(flags);
15577a6bc1cdSVenkatesh Pallipadi 
155822df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
15597beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
1560d4283e93STejun Heo 		ret = true;
15617a6bc1cdSVenkatesh Pallipadi 	}
15628930cabaSTejun Heo 
15638930cabaSTejun Heo 	local_irq_restore(flags);
15647a6bc1cdSVenkatesh Pallipadi 	return ret;
15657a6bc1cdSVenkatesh Pallipadi }
1566ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
15671da177e4SLinus Torvalds 
1568c8e55f36STejun Heo /**
15698376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
15708376fe22STejun Heo  * @cpu: CPU number to execute work on
15718376fe22STejun Heo  * @wq: workqueue to use
15728376fe22STejun Heo  * @dwork: work to queue
15738376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
15748376fe22STejun Heo  *
15758376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
15768376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
15778376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
15788376fe22STejun Heo  * current state.
15798376fe22STejun Heo  *
1580d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
15818376fe22STejun Heo  * pending and its timer was modified.
15828376fe22STejun Heo  *
1583e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
15848376fe22STejun Heo  * See try_to_grab_pending() for details.
15858376fe22STejun Heo  */
15868376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
15878376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
15888376fe22STejun Heo {
15898376fe22STejun Heo 	unsigned long flags;
15908376fe22STejun Heo 	int ret;
15918376fe22STejun Heo 
15928376fe22STejun Heo 	do {
15938376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
15948376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
15958376fe22STejun Heo 
15968376fe22STejun Heo 	if (likely(ret >= 0)) {
15978376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
15988376fe22STejun Heo 		local_irq_restore(flags);
15998376fe22STejun Heo 	}
16008376fe22STejun Heo 
16018376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
16028376fe22STejun Heo 	return ret;
16038376fe22STejun Heo }
16048376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
16058376fe22STejun Heo 
160605f0fe6bSTejun Heo static void rcu_work_rcufn(struct rcu_head *rcu)
160705f0fe6bSTejun Heo {
160805f0fe6bSTejun Heo 	struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
160905f0fe6bSTejun Heo 
161005f0fe6bSTejun Heo 	/* read the comment in __queue_work() */
161105f0fe6bSTejun Heo 	local_irq_disable();
161205f0fe6bSTejun Heo 	__queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
161305f0fe6bSTejun Heo 	local_irq_enable();
161405f0fe6bSTejun Heo }
161505f0fe6bSTejun Heo 
161605f0fe6bSTejun Heo /**
161705f0fe6bSTejun Heo  * queue_rcu_work - queue work after a RCU grace period
161805f0fe6bSTejun Heo  * @wq: workqueue to use
161905f0fe6bSTejun Heo  * @rwork: work to queue
162005f0fe6bSTejun Heo  *
162105f0fe6bSTejun Heo  * Return: %false if @rwork was already pending, %true otherwise.  Note
162205f0fe6bSTejun Heo  * that a full RCU grace period is guaranteed only after a %true return.
162305f0fe6bSTejun Heo  * While @rwork is guarnateed to be executed after a %false return, the
162405f0fe6bSTejun Heo  * execution may happen before a full RCU grace period has passed.
162505f0fe6bSTejun Heo  */
162605f0fe6bSTejun Heo bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
162705f0fe6bSTejun Heo {
162805f0fe6bSTejun Heo 	struct work_struct *work = &rwork->work;
162905f0fe6bSTejun Heo 
163005f0fe6bSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
163105f0fe6bSTejun Heo 		rwork->wq = wq;
163205f0fe6bSTejun Heo 		call_rcu(&rwork->rcu, rcu_work_rcufn);
163305f0fe6bSTejun Heo 		return true;
163405f0fe6bSTejun Heo 	}
163505f0fe6bSTejun Heo 
163605f0fe6bSTejun Heo 	return false;
163705f0fe6bSTejun Heo }
163805f0fe6bSTejun Heo EXPORT_SYMBOL(queue_rcu_work);
163905f0fe6bSTejun Heo 
16408376fe22STejun Heo /**
1641c8e55f36STejun Heo  * worker_enter_idle - enter idle state
1642c8e55f36STejun Heo  * @worker: worker which is entering idle state
1643c8e55f36STejun Heo  *
1644c8e55f36STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1645c8e55f36STejun Heo  * necessary.
1646c8e55f36STejun Heo  *
1647c8e55f36STejun Heo  * LOCKING:
1648d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1649c8e55f36STejun Heo  */
1650c8e55f36STejun Heo static void worker_enter_idle(struct worker *worker)
16511da177e4SLinus Torvalds {
1652bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1653c8e55f36STejun Heo 
16546183c009STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
16556183c009STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
16566183c009STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
16576183c009STejun Heo 		return;
1658c8e55f36STejun Heo 
1659051e1850SLai Jiangshan 	/* can't use worker_set_flags(), also called from create_worker() */
1660cb444766STejun Heo 	worker->flags |= WORKER_IDLE;
1661bd7bdd43STejun Heo 	pool->nr_idle++;
1662e22bee78STejun Heo 	worker->last_active = jiffies;
1663c8e55f36STejun Heo 
1664c8e55f36STejun Heo 	/* idle_list is LIFO */
1665bd7bdd43STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1666db7bccf4STejun Heo 
166763d95a91STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1668628c78e7STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1669cb444766STejun Heo 
1670544ecf31STejun Heo 	/*
1671e8b3f8dbSLai Jiangshan 	 * Sanity check nr_running.  Because unbind_workers() releases
1672d565ed63STejun Heo 	 * pool->lock between setting %WORKER_UNBOUND and zapping
1673628c78e7STejun Heo 	 * nr_running, the warning may trigger spuriously.  Check iff
1674628c78e7STejun Heo 	 * unbind is not in progress.
1675544ecf31STejun Heo 	 */
167624647570STejun Heo 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
1677bd7bdd43STejun Heo 		     pool->nr_workers == pool->nr_idle &&
1678e19e397aSTejun Heo 		     atomic_read(&pool->nr_running));
1679c8e55f36STejun Heo }
1680c8e55f36STejun Heo 
1681c8e55f36STejun Heo /**
1682c8e55f36STejun Heo  * worker_leave_idle - leave idle state
1683c8e55f36STejun Heo  * @worker: worker which is leaving idle state
1684c8e55f36STejun Heo  *
1685c8e55f36STejun Heo  * @worker is leaving idle state.  Update stats.
1686c8e55f36STejun Heo  *
1687c8e55f36STejun Heo  * LOCKING:
1688d565ed63STejun Heo  * spin_lock_irq(pool->lock).
1689c8e55f36STejun Heo  */
1690c8e55f36STejun Heo static void worker_leave_idle(struct worker *worker)
1691c8e55f36STejun Heo {
1692bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1693c8e55f36STejun Heo 
16946183c009STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
16956183c009STejun Heo 		return;
1696d302f017STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1697bd7bdd43STejun Heo 	pool->nr_idle--;
1698c8e55f36STejun Heo 	list_del_init(&worker->entry);
1699c8e55f36STejun Heo }
1700c8e55f36STejun Heo 
1701f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
1702c34056a3STejun Heo {
1703c34056a3STejun Heo 	struct worker *worker;
1704c34056a3STejun Heo 
1705f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
1706c8e55f36STejun Heo 	if (worker) {
1707c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
1708affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
1709da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
1710e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
1711e22bee78STejun Heo 		worker->flags = WORKER_PREP;
1712c8e55f36STejun Heo 	}
1713c34056a3STejun Heo 	return worker;
1714c34056a3STejun Heo }
1715c34056a3STejun Heo 
1716c34056a3STejun Heo /**
17174736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
17184736cbf7SLai Jiangshan  * @worker: worker to be attached
17194736cbf7SLai Jiangshan  * @pool: the target pool
17204736cbf7SLai Jiangshan  *
17214736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
17224736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
17234736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
17244736cbf7SLai Jiangshan  */
17254736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
17264736cbf7SLai Jiangshan 				   struct worker_pool *pool)
17274736cbf7SLai Jiangshan {
17284736cbf7SLai Jiangshan 	mutex_lock(&pool->attach_mutex);
17294736cbf7SLai Jiangshan 
17304736cbf7SLai Jiangshan 	/*
17314736cbf7SLai Jiangshan 	 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
17324736cbf7SLai Jiangshan 	 * online CPUs.  It'll be re-applied when any of the CPUs come up.
17334736cbf7SLai Jiangshan 	 */
17344736cbf7SLai Jiangshan 	set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask);
17354736cbf7SLai Jiangshan 
17364736cbf7SLai Jiangshan 	/*
17374736cbf7SLai Jiangshan 	 * The pool->attach_mutex ensures %POOL_DISASSOCIATED remains
17384736cbf7SLai Jiangshan 	 * stable across this function.  See the comments above the
17394736cbf7SLai Jiangshan 	 * flag definition for details.
17404736cbf7SLai Jiangshan 	 */
17414736cbf7SLai Jiangshan 	if (pool->flags & POOL_DISASSOCIATED)
17424736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
17434736cbf7SLai Jiangshan 
17444736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
17454736cbf7SLai Jiangshan 
17464736cbf7SLai Jiangshan 	mutex_unlock(&pool->attach_mutex);
17474736cbf7SLai Jiangshan }
17484736cbf7SLai Jiangshan 
17494736cbf7SLai Jiangshan /**
175060f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
175160f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
175260f5a4bcSLai Jiangshan  * @pool: the pool @worker is attached to
175360f5a4bcSLai Jiangshan  *
17544736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
17554736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
17564736cbf7SLai Jiangshan  * other reference to the pool.
175760f5a4bcSLai Jiangshan  */
175860f5a4bcSLai Jiangshan static void worker_detach_from_pool(struct worker *worker,
175960f5a4bcSLai Jiangshan 				    struct worker_pool *pool)
176060f5a4bcSLai Jiangshan {
176160f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
176260f5a4bcSLai Jiangshan 
176392f9c5c4SLai Jiangshan 	mutex_lock(&pool->attach_mutex);
1764da028469SLai Jiangshan 	list_del(&worker->node);
1765da028469SLai Jiangshan 	if (list_empty(&pool->workers))
176660f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
176792f9c5c4SLai Jiangshan 	mutex_unlock(&pool->attach_mutex);
176860f5a4bcSLai Jiangshan 
1769b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
1770b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
1771b62c0751SLai Jiangshan 
177260f5a4bcSLai Jiangshan 	if (detach_completion)
177360f5a4bcSLai Jiangshan 		complete(detach_completion);
177460f5a4bcSLai Jiangshan }
177560f5a4bcSLai Jiangshan 
177660f5a4bcSLai Jiangshan /**
1777c34056a3STejun Heo  * create_worker - create a new workqueue worker
177863d95a91STejun Heo  * @pool: pool the new worker will belong to
1779c34056a3STejun Heo  *
1780051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
1781c34056a3STejun Heo  *
1782c34056a3STejun Heo  * CONTEXT:
1783c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
1784c34056a3STejun Heo  *
1785d185af30SYacine Belkadi  * Return:
1786c34056a3STejun Heo  * Pointer to the newly created worker.
1787c34056a3STejun Heo  */
1788bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
1789c34056a3STejun Heo {
1790c34056a3STejun Heo 	struct worker *worker = NULL;
1791f3421797STejun Heo 	int id = -1;
1792e3c916a4STejun Heo 	char id_buf[16];
1793c34056a3STejun Heo 
17947cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
17957cda9aaeSLai Jiangshan 	id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL);
1796822d8405STejun Heo 	if (id < 0)
1797c34056a3STejun Heo 		goto fail;
1798c34056a3STejun Heo 
1799f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
1800c34056a3STejun Heo 	if (!worker)
1801c34056a3STejun Heo 		goto fail;
1802c34056a3STejun Heo 
1803bd7bdd43STejun Heo 	worker->pool = pool;
1804c34056a3STejun Heo 	worker->id = id;
1805c34056a3STejun Heo 
180629c91e99STejun Heo 	if (pool->cpu >= 0)
1807e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
1808e3c916a4STejun Heo 			 pool->attrs->nice < 0  ? "H" : "");
1809f3421797STejun Heo 	else
1810e3c916a4STejun Heo 		snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
1811e3c916a4STejun Heo 
1812f3f90ad4STejun Heo 	worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
1813e3c916a4STejun Heo 					      "kworker/%s", id_buf);
1814c34056a3STejun Heo 	if (IS_ERR(worker->task))
1815c34056a3STejun Heo 		goto fail;
1816c34056a3STejun Heo 
181791151228SOleg Nesterov 	set_user_nice(worker->task, pool->attrs->nice);
181825834c73SPeter Zijlstra 	kthread_bind_mask(worker->task, pool->attrs->cpumask);
181991151228SOleg Nesterov 
1820da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
18214736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
1822822d8405STejun Heo 
1823051e1850SLai Jiangshan 	/* start the newly created worker */
1824051e1850SLai Jiangshan 	spin_lock_irq(&pool->lock);
1825051e1850SLai Jiangshan 	worker->pool->nr_workers++;
1826051e1850SLai Jiangshan 	worker_enter_idle(worker);
1827051e1850SLai Jiangshan 	wake_up_process(worker->task);
1828051e1850SLai Jiangshan 	spin_unlock_irq(&pool->lock);
1829051e1850SLai Jiangshan 
1830c34056a3STejun Heo 	return worker;
1831822d8405STejun Heo 
1832c34056a3STejun Heo fail:
18339625ab17SLai Jiangshan 	if (id >= 0)
18347cda9aaeSLai Jiangshan 		ida_simple_remove(&pool->worker_ida, id);
1835c34056a3STejun Heo 	kfree(worker);
1836c34056a3STejun Heo 	return NULL;
1837c34056a3STejun Heo }
1838c34056a3STejun Heo 
1839c34056a3STejun Heo /**
1840c34056a3STejun Heo  * destroy_worker - destroy a workqueue worker
1841c34056a3STejun Heo  * @worker: worker to be destroyed
1842c34056a3STejun Heo  *
184373eb7fe7SLai Jiangshan  * Destroy @worker and adjust @pool stats accordingly.  The worker should
184473eb7fe7SLai Jiangshan  * be idle.
1845c8e55f36STejun Heo  *
1846c8e55f36STejun Heo  * CONTEXT:
184760f5a4bcSLai Jiangshan  * spin_lock_irq(pool->lock).
1848c34056a3STejun Heo  */
1849c34056a3STejun Heo static void destroy_worker(struct worker *worker)
1850c34056a3STejun Heo {
1851bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
1852c34056a3STejun Heo 
1853cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
1854cd549687STejun Heo 
1855c34056a3STejun Heo 	/* sanity check frenzy */
18566183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
185773eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
185873eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
18596183c009STejun Heo 		return;
1860c34056a3STejun Heo 
1861bd7bdd43STejun Heo 	pool->nr_workers--;
1862bd7bdd43STejun Heo 	pool->nr_idle--;
1863c8e55f36STejun Heo 
1864c8e55f36STejun Heo 	list_del_init(&worker->entry);
1865cb444766STejun Heo 	worker->flags |= WORKER_DIE;
186660f5a4bcSLai Jiangshan 	wake_up_process(worker->task);
1867c34056a3STejun Heo }
1868c34056a3STejun Heo 
186932a6c723SKees Cook static void idle_worker_timeout(struct timer_list *t)
1870e22bee78STejun Heo {
187132a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, idle_timer);
1872e22bee78STejun Heo 
1873d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1874e22bee78STejun Heo 
18753347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
1876e22bee78STejun Heo 		struct worker *worker;
1877e22bee78STejun Heo 		unsigned long expires;
1878e22bee78STejun Heo 
1879e22bee78STejun Heo 		/* idle_list is kept in LIFO order, check the last one */
188063d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
1881e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1882e22bee78STejun Heo 
18833347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
188463d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
18853347fc9fSLai Jiangshan 			break;
1886e22bee78STejun Heo 		}
18873347fc9fSLai Jiangshan 
18883347fc9fSLai Jiangshan 		destroy_worker(worker);
1889e22bee78STejun Heo 	}
1890e22bee78STejun Heo 
1891d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
1892e22bee78STejun Heo }
1893e22bee78STejun Heo 
1894493a1724STejun Heo static void send_mayday(struct work_struct *work)
1895e22bee78STejun Heo {
1896112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
1897112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
1898493a1724STejun Heo 
18992e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
1900e22bee78STejun Heo 
1901493008a8STejun Heo 	if (!wq->rescuer)
1902493a1724STejun Heo 		return;
1903e22bee78STejun Heo 
1904e22bee78STejun Heo 	/* mayday mayday mayday */
1905493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
190677668c8bSLai Jiangshan 		/*
190777668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
190877668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
190977668c8bSLai Jiangshan 		 * rescuer is done with it.
191077668c8bSLai Jiangshan 		 */
191177668c8bSLai Jiangshan 		get_pwq(pwq);
1912493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
1913e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
1914493a1724STejun Heo 	}
1915e22bee78STejun Heo }
1916e22bee78STejun Heo 
191732a6c723SKees Cook static void pool_mayday_timeout(struct timer_list *t)
1918e22bee78STejun Heo {
191932a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, mayday_timer);
1920e22bee78STejun Heo 	struct work_struct *work;
1921e22bee78STejun Heo 
1922b2d82909STejun Heo 	spin_lock_irq(&pool->lock);
1923b2d82909STejun Heo 	spin_lock(&wq_mayday_lock);		/* for wq->maydays */
1924e22bee78STejun Heo 
192563d95a91STejun Heo 	if (need_to_create_worker(pool)) {
1926e22bee78STejun Heo 		/*
1927e22bee78STejun Heo 		 * We've been trying to create a new worker but
1928e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
1929e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
1930e22bee78STejun Heo 		 * rescuers.
1931e22bee78STejun Heo 		 */
193263d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
1933e22bee78STejun Heo 			send_mayday(work);
1934e22bee78STejun Heo 	}
1935e22bee78STejun Heo 
1936b2d82909STejun Heo 	spin_unlock(&wq_mayday_lock);
1937b2d82909STejun Heo 	spin_unlock_irq(&pool->lock);
1938e22bee78STejun Heo 
193963d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
1940e22bee78STejun Heo }
1941e22bee78STejun Heo 
1942e22bee78STejun Heo /**
1943e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
194463d95a91STejun Heo  * @pool: pool to create a new worker for
1945e22bee78STejun Heo  *
194663d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
1947e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
1948e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
194963d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
1950e22bee78STejun Heo  * possible allocation deadlock.
1951e22bee78STejun Heo  *
1952c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
1953c5aa87bbSTejun Heo  * may_start_working() %true.
1954e22bee78STejun Heo  *
1955e22bee78STejun Heo  * LOCKING:
1956d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
1957e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
1958e22bee78STejun Heo  * manager.
1959e22bee78STejun Heo  */
196029187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
1961d565ed63STejun Heo __releases(&pool->lock)
1962d565ed63STejun Heo __acquires(&pool->lock)
1963e22bee78STejun Heo {
1964e22bee78STejun Heo restart:
1965d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
19669f9c2364STejun Heo 
1967e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
196863d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1969e22bee78STejun Heo 
1970e22bee78STejun Heo 	while (true) {
1971051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
1972e22bee78STejun Heo 			break;
1973e22bee78STejun Heo 
1974e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
19759f9c2364STejun Heo 
197663d95a91STejun Heo 		if (!need_to_create_worker(pool))
1977e22bee78STejun Heo 			break;
1978e22bee78STejun Heo 	}
1979e22bee78STejun Heo 
198063d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
1981d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
1982051e1850SLai Jiangshan 	/*
1983051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
1984051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
1985051e1850SLai Jiangshan 	 * already become busy.
1986051e1850SLai Jiangshan 	 */
198763d95a91STejun Heo 	if (need_to_create_worker(pool))
1988e22bee78STejun Heo 		goto restart;
1989e22bee78STejun Heo }
1990e22bee78STejun Heo 
1991e22bee78STejun Heo /**
1992e22bee78STejun Heo  * manage_workers - manage worker pool
1993e22bee78STejun Heo  * @worker: self
1994e22bee78STejun Heo  *
1995706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
1996e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
1997706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
1998e22bee78STejun Heo  *
1999e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2000e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2001e22bee78STejun Heo  * and may_start_working() is true.
2002e22bee78STejun Heo  *
2003e22bee78STejun Heo  * CONTEXT:
2004d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2005e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2006e22bee78STejun Heo  *
2007d185af30SYacine Belkadi  * Return:
200829187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
200929187a9eSTejun Heo  * start processing works, %true if management function was performed and
201029187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
201129187a9eSTejun Heo  * no longer be true.
2012e22bee78STejun Heo  */
2013e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2014e22bee78STejun Heo {
201563d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2016e22bee78STejun Heo 
2017692b4825STejun Heo 	if (pool->flags & POOL_MANAGER_ACTIVE)
201829187a9eSTejun Heo 		return false;
2019692b4825STejun Heo 
2020692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
20212607d7a6STejun Heo 	pool->manager = worker;
2022e22bee78STejun Heo 
202329187a9eSTejun Heo 	maybe_create_worker(pool);
2024e22bee78STejun Heo 
20252607d7a6STejun Heo 	pool->manager = NULL;
2026692b4825STejun Heo 	pool->flags &= ~POOL_MANAGER_ACTIVE;
2027692b4825STejun Heo 	wake_up(&wq_manager_wait);
202829187a9eSTejun Heo 	return true;
2029e22bee78STejun Heo }
2030e22bee78STejun Heo 
2031a62428c0STejun Heo /**
2032a62428c0STejun Heo  * process_one_work - process single work
2033c34056a3STejun Heo  * @worker: self
2034a62428c0STejun Heo  * @work: work to process
2035a62428c0STejun Heo  *
2036a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2037a62428c0STejun Heo  * process a single work including synchronization against and
2038a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2039a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2040a62428c0STejun Heo  * call this function to process a work.
2041a62428c0STejun Heo  *
2042a62428c0STejun Heo  * CONTEXT:
2043d565ed63STejun Heo  * spin_lock_irq(pool->lock) which is released and regrabbed.
2044a62428c0STejun Heo  */
2045c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2046d565ed63STejun Heo __releases(&pool->lock)
2047d565ed63STejun Heo __acquires(&pool->lock)
20481da177e4SLinus Torvalds {
2049112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2050bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2051112202d9STejun Heo 	bool cpu_intensive = pwq->wq->flags & WQ_CPU_INTENSIVE;
205273f53c4aSTejun Heo 	int work_color;
20537e11629dSTejun Heo 	struct worker *collision;
20544e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
20554e6045f1SJohannes Berg 	/*
2056a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
2057a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
2058a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
2059a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
2060a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
20614e6045f1SJohannes Berg 	 */
20624d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
20634d82a1deSPeter Zijlstra 
20644d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
20654e6045f1SJohannes Berg #endif
2066807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
206785327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2068ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
206925511a47STejun Heo 
20707e11629dSTejun Heo 	/*
20717e11629dSTejun Heo 	 * A single work shouldn't be executed concurrently by
20727e11629dSTejun Heo 	 * multiple workers on a single cpu.  Check whether anyone is
20737e11629dSTejun Heo 	 * already processing the work.  If so, defer the work to the
20747e11629dSTejun Heo 	 * currently executing one.
20757e11629dSTejun Heo 	 */
2076c9e7cf27STejun Heo 	collision = find_worker_executing_work(pool, work);
20777e11629dSTejun Heo 	if (unlikely(collision)) {
20787e11629dSTejun Heo 		move_linked_works(work, &collision->scheduled, NULL);
20797e11629dSTejun Heo 		return;
20807e11629dSTejun Heo 	}
20811da177e4SLinus Torvalds 
20828930cabaSTejun Heo 	/* claim and dequeue */
20831da177e4SLinus Torvalds 	debug_work_deactivate(work);
2084c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2085c34056a3STejun Heo 	worker->current_work = work;
2086a2c1c57bSTejun Heo 	worker->current_func = work->func;
2087112202d9STejun Heo 	worker->current_pwq = pwq;
208873f53c4aSTejun Heo 	work_color = get_work_color(work);
20897a22ad75STejun Heo 
2090a62428c0STejun Heo 	list_del_init(&work->entry);
2091a62428c0STejun Heo 
2092649027d7STejun Heo 	/*
2093228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
2094228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
2095228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
2096228f1d00SLai Jiangshan 	 * execution of the pending work items.
2097fb0e7bebSTejun Heo 	 */
2098fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2099228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2100fb0e7bebSTejun Heo 
2101974271c4STejun Heo 	/*
2102a489a03eSLai Jiangshan 	 * Wake up another worker if necessary.  The condition is always
2103a489a03eSLai Jiangshan 	 * false for normal per-cpu workers since nr_running would always
2104a489a03eSLai Jiangshan 	 * be >= 1 at this point.  This is used to chain execution of the
2105a489a03eSLai Jiangshan 	 * pending work items for WORKER_NOT_RUNNING workers such as the
2106228f1d00SLai Jiangshan 	 * UNBOUND and CPU_INTENSIVE ones.
2107974271c4STejun Heo 	 */
2108a489a03eSLai Jiangshan 	if (need_more_worker(pool))
210963d95a91STejun Heo 		wake_up_worker(pool);
2110974271c4STejun Heo 
21118930cabaSTejun Heo 	/*
21127c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
2113d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
211423657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
211523657bb1STejun Heo 	 * disabled.
21168930cabaSTejun Heo 	 */
21177c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
21181da177e4SLinus Torvalds 
2119d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2120365970a1SDavid Howells 
2121a1d14934SPeter Zijlstra 	lock_map_acquire(&pwq->wq->lockdep_map);
21223295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
2123e6f3faa7SPeter Zijlstra 	/*
2124f52be570SPeter Zijlstra 	 * Strictly speaking we should mark the invariant state without holding
2125f52be570SPeter Zijlstra 	 * any locks, that is, before these two lock_map_acquire()'s.
2126e6f3faa7SPeter Zijlstra 	 *
2127e6f3faa7SPeter Zijlstra 	 * However, that would result in:
2128e6f3faa7SPeter Zijlstra 	 *
2129e6f3faa7SPeter Zijlstra 	 *   A(W1)
2130e6f3faa7SPeter Zijlstra 	 *   WFC(C)
2131e6f3faa7SPeter Zijlstra 	 *		A(W1)
2132e6f3faa7SPeter Zijlstra 	 *		C(C)
2133e6f3faa7SPeter Zijlstra 	 *
2134e6f3faa7SPeter Zijlstra 	 * Which would create W1->C->W1 dependencies, even though there is no
2135e6f3faa7SPeter Zijlstra 	 * actual deadlock possible. There are two solutions, using a
2136e6f3faa7SPeter Zijlstra 	 * read-recursive acquire on the work(queue) 'locks', but this will then
2137f52be570SPeter Zijlstra 	 * hit the lockdep limitation on recursive locks, or simply discard
2138e6f3faa7SPeter Zijlstra 	 * these locks.
2139e6f3faa7SPeter Zijlstra 	 *
2140e6f3faa7SPeter Zijlstra 	 * AFAICT there is no possible deadlock scenario between the
2141e6f3faa7SPeter Zijlstra 	 * flush_work() and complete() primitives (except for single-threaded
2142e6f3faa7SPeter Zijlstra 	 * workqueues), so hiding them isn't a problem.
2143e6f3faa7SPeter Zijlstra 	 */
2144f52be570SPeter Zijlstra 	lockdep_invariant_state(true);
2145e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
2146a2c1c57bSTejun Heo 	worker->current_func(work);
2147e36c886aSArjan van de Ven 	/*
2148e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
2149e36c886aSArjan van de Ven 	 * point will only record its address.
2150e36c886aSArjan van de Ven 	 */
2151e36c886aSArjan van de Ven 	trace_workqueue_execute_end(work);
21523295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
2153112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
21541da177e4SLinus Torvalds 
2155d5abe669SPeter Zijlstra 	if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2156044c782cSValentin Ilie 		pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2157044c782cSValentin Ilie 		       "     last function: %pf\n",
2158a2c1c57bSTejun Heo 		       current->comm, preempt_count(), task_pid_nr(current),
2159a2c1c57bSTejun Heo 		       worker->current_func);
2160d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
2161d5abe669SPeter Zijlstra 		dump_stack();
2162d5abe669SPeter Zijlstra 	}
2163d5abe669SPeter Zijlstra 
2164b22ce278STejun Heo 	/*
2165b22ce278STejun Heo 	 * The following prevents a kworker from hogging CPU on !PREEMPT
2166b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
2167b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
2168b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
2169789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
2170789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
2171b22ce278STejun Heo 	 */
2172a7e6425eSPaul E. McKenney 	cond_resched();
2173b22ce278STejun Heo 
2174d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2175a62428c0STejun Heo 
2176fb0e7bebSTejun Heo 	/* clear cpu intensive status */
2177fb0e7bebSTejun Heo 	if (unlikely(cpu_intensive))
2178fb0e7bebSTejun Heo 		worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2179fb0e7bebSTejun Heo 
2180a62428c0STejun Heo 	/* we're done with it, release */
218142f8570fSSasha Levin 	hash_del(&worker->hentry);
2182c34056a3STejun Heo 	worker->current_work = NULL;
2183a2c1c57bSTejun Heo 	worker->current_func = NULL;
2184112202d9STejun Heo 	worker->current_pwq = NULL;
21853d1cb205STejun Heo 	worker->desc_valid = false;
2186112202d9STejun Heo 	pwq_dec_nr_in_flight(pwq, work_color);
21871da177e4SLinus Torvalds }
21881da177e4SLinus Torvalds 
2189affee4b2STejun Heo /**
2190affee4b2STejun Heo  * process_scheduled_works - process scheduled works
2191affee4b2STejun Heo  * @worker: self
2192affee4b2STejun Heo  *
2193affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
2194affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
2195affee4b2STejun Heo  * fetches a work from the top and executes it.
2196affee4b2STejun Heo  *
2197affee4b2STejun Heo  * CONTEXT:
2198d565ed63STejun Heo  * spin_lock_irq(pool->lock) which may be released and regrabbed
2199affee4b2STejun Heo  * multiple times.
2200affee4b2STejun Heo  */
2201affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
22021da177e4SLinus Torvalds {
2203affee4b2STejun Heo 	while (!list_empty(&worker->scheduled)) {
2204affee4b2STejun Heo 		struct work_struct *work = list_first_entry(&worker->scheduled,
2205a62428c0STejun Heo 						struct work_struct, entry);
2206c34056a3STejun Heo 		process_one_work(worker, work);
2207a62428c0STejun Heo 	}
22081da177e4SLinus Torvalds }
22091da177e4SLinus Torvalds 
22104690c4abSTejun Heo /**
22114690c4abSTejun Heo  * worker_thread - the worker thread function
2212c34056a3STejun Heo  * @__worker: self
22134690c4abSTejun Heo  *
2214c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
2215c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
2216c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
2217c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
2218c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
2219d185af30SYacine Belkadi  *
2220d185af30SYacine Belkadi  * Return: 0
22214690c4abSTejun Heo  */
2222c34056a3STejun Heo static int worker_thread(void *__worker)
22231da177e4SLinus Torvalds {
2224c34056a3STejun Heo 	struct worker *worker = __worker;
2225bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
22261da177e4SLinus Torvalds 
2227e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
2228e22bee78STejun Heo 	worker->task->flags |= PF_WQ_WORKER;
2229c8e55f36STejun Heo woke_up:
2230d565ed63STejun Heo 	spin_lock_irq(&pool->lock);
2231affee4b2STejun Heo 
2232a9ab775bSTejun Heo 	/* am I supposed to die? */
2233a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
2234d565ed63STejun Heo 		spin_unlock_irq(&pool->lock);
2235a9ab775bSTejun Heo 		WARN_ON_ONCE(!list_empty(&worker->entry));
2236e22bee78STejun Heo 		worker->task->flags &= ~PF_WQ_WORKER;
223760f5a4bcSLai Jiangshan 
223860f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
22397cda9aaeSLai Jiangshan 		ida_simple_remove(&pool->worker_ida, worker->id);
224060f5a4bcSLai Jiangshan 		worker_detach_from_pool(worker, pool);
224160f5a4bcSLai Jiangshan 		kfree(worker);
2242c8e55f36STejun Heo 		return 0;
2243c8e55f36STejun Heo 	}
2244c8e55f36STejun Heo 
2245c8e55f36STejun Heo 	worker_leave_idle(worker);
2246db7bccf4STejun Heo recheck:
2247e22bee78STejun Heo 	/* no more worker necessary? */
224863d95a91STejun Heo 	if (!need_more_worker(pool))
2249e22bee78STejun Heo 		goto sleep;
2250e22bee78STejun Heo 
2251e22bee78STejun Heo 	/* do we need to manage? */
225263d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2253e22bee78STejun Heo 		goto recheck;
2254e22bee78STejun Heo 
2255c8e55f36STejun Heo 	/*
2256c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
2257c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
2258c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
2259c8e55f36STejun Heo 	 */
22606183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
2261c8e55f36STejun Heo 
2262e22bee78STejun Heo 	/*
2263a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
2264a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
2265a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
2266a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
2267a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
2268e22bee78STejun Heo 	 */
2269a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2270e22bee78STejun Heo 
2271e22bee78STejun Heo 	do {
2272affee4b2STejun Heo 		struct work_struct *work =
2273bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
2274affee4b2STejun Heo 					 struct work_struct, entry);
2275affee4b2STejun Heo 
227682607adcSTejun Heo 		pool->watchdog_ts = jiffies;
227782607adcSTejun Heo 
2278c8e55f36STejun Heo 		if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2279affee4b2STejun Heo 			/* optimization path, not strictly necessary */
2280affee4b2STejun Heo 			process_one_work(worker, work);
2281affee4b2STejun Heo 			if (unlikely(!list_empty(&worker->scheduled)))
2282affee4b2STejun Heo 				process_scheduled_works(worker);
2283affee4b2STejun Heo 		} else {
2284c8e55f36STejun Heo 			move_linked_works(work, &worker->scheduled, NULL);
2285affee4b2STejun Heo 			process_scheduled_works(worker);
2286affee4b2STejun Heo 		}
228763d95a91STejun Heo 	} while (keep_working(pool));
2288affee4b2STejun Heo 
2289228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
2290d313dd85STejun Heo sleep:
2291c8e55f36STejun Heo 	/*
2292d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
2293d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
2294d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
2295d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
2296d565ed63STejun Heo 	 * event.
2297c8e55f36STejun Heo 	 */
2298c8e55f36STejun Heo 	worker_enter_idle(worker);
2299c5a94a61SPeter Zijlstra 	__set_current_state(TASK_IDLE);
2300d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
23011da177e4SLinus Torvalds 	schedule();
2302c8e55f36STejun Heo 	goto woke_up;
23031da177e4SLinus Torvalds }
23041da177e4SLinus Torvalds 
2305e22bee78STejun Heo /**
2306e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
2307111c225aSTejun Heo  * @__rescuer: self
2308e22bee78STejun Heo  *
2309e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
2310493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
2311e22bee78STejun Heo  *
2312706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
2313e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
2314e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
2315e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2316e22bee78STejun Heo  * the problem rescuer solves.
2317e22bee78STejun Heo  *
2318706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
2319706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
2320e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
2321e22bee78STejun Heo  *
2322e22bee78STejun Heo  * This should happen rarely.
2323d185af30SYacine Belkadi  *
2324d185af30SYacine Belkadi  * Return: 0
2325e22bee78STejun Heo  */
2326111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2327e22bee78STejun Heo {
2328111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
2329111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
2330e22bee78STejun Heo 	struct list_head *scheduled = &rescuer->scheduled;
23314d595b86SLai Jiangshan 	bool should_stop;
2332e22bee78STejun Heo 
2333e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
2334111c225aSTejun Heo 
2335111c225aSTejun Heo 	/*
2336111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
2337111c225aSTejun Heo 	 * doesn't participate in concurrency management.
2338111c225aSTejun Heo 	 */
2339111c225aSTejun Heo 	rescuer->task->flags |= PF_WQ_WORKER;
2340e22bee78STejun Heo repeat:
2341c5a94a61SPeter Zijlstra 	set_current_state(TASK_IDLE);
23421da177e4SLinus Torvalds 
23434d595b86SLai Jiangshan 	/*
23444d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
23454d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
23464d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
23474d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
23484d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
23494d595b86SLai Jiangshan 	 * list is always empty on exit.
23504d595b86SLai Jiangshan 	 */
23514d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
23521da177e4SLinus Torvalds 
2353493a1724STejun Heo 	/* see whether any pwq is asking for help */
23542e109a28STejun Heo 	spin_lock_irq(&wq_mayday_lock);
2355493a1724STejun Heo 
2356493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
2357493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2358493a1724STejun Heo 					struct pool_workqueue, mayday_node);
2359112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
2360e22bee78STejun Heo 		struct work_struct *work, *n;
236182607adcSTejun Heo 		bool first = true;
2362e22bee78STejun Heo 
2363e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
2364493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
2365493a1724STejun Heo 
23662e109a28STejun Heo 		spin_unlock_irq(&wq_mayday_lock);
2367e22bee78STejun Heo 
236851697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
236951697d39SLai Jiangshan 
237051697d39SLai Jiangshan 		spin_lock_irq(&pool->lock);
2371b3104104SLai Jiangshan 		rescuer->pool = pool;
2372e22bee78STejun Heo 
2373e22bee78STejun Heo 		/*
2374e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
2375e22bee78STejun Heo 		 * process'em.
2376e22bee78STejun Heo 		 */
23770479c8c5STejun Heo 		WARN_ON_ONCE(!list_empty(scheduled));
237882607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
237982607adcSTejun Heo 			if (get_work_pwq(work) == pwq) {
238082607adcSTejun Heo 				if (first)
238182607adcSTejun Heo 					pool->watchdog_ts = jiffies;
2382e22bee78STejun Heo 				move_linked_works(work, scheduled, &n);
238382607adcSTejun Heo 			}
238482607adcSTejun Heo 			first = false;
238582607adcSTejun Heo 		}
2386e22bee78STejun Heo 
2387008847f6SNeilBrown 		if (!list_empty(scheduled)) {
2388e22bee78STejun Heo 			process_scheduled_works(rescuer);
23897576958aSTejun Heo 
23907576958aSTejun Heo 			/*
2391008847f6SNeilBrown 			 * The above execution of rescued work items could
2392008847f6SNeilBrown 			 * have created more to rescue through
2393008847f6SNeilBrown 			 * pwq_activate_first_delayed() or chained
2394008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
2395008847f6SNeilBrown 			 * that such back-to-back work items, which may be
2396008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
2397008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
2398008847f6SNeilBrown 			 */
2399008847f6SNeilBrown 			if (need_to_create_worker(pool)) {
2400008847f6SNeilBrown 				spin_lock(&wq_mayday_lock);
2401008847f6SNeilBrown 				get_pwq(pwq);
2402008847f6SNeilBrown 				list_move_tail(&pwq->mayday_node, &wq->maydays);
2403008847f6SNeilBrown 				spin_unlock(&wq_mayday_lock);
2404008847f6SNeilBrown 			}
2405008847f6SNeilBrown 		}
2406008847f6SNeilBrown 
2407008847f6SNeilBrown 		/*
240877668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
240913b1d625SLai Jiangshan 		 * go away while we're still attached to it.
241077668c8bSLai Jiangshan 		 */
241177668c8bSLai Jiangshan 		put_pwq(pwq);
241277668c8bSLai Jiangshan 
241377668c8bSLai Jiangshan 		/*
2414d8ca83e6SLai Jiangshan 		 * Leave this pool.  If need_more_worker() is %true, notify a
24157576958aSTejun Heo 		 * regular worker; otherwise, we end up with 0 concurrency
24167576958aSTejun Heo 		 * and stalling the execution.
24177576958aSTejun Heo 		 */
2418d8ca83e6SLai Jiangshan 		if (need_more_worker(pool))
241963d95a91STejun Heo 			wake_up_worker(pool);
24207576958aSTejun Heo 
2421b3104104SLai Jiangshan 		rescuer->pool = NULL;
242213b1d625SLai Jiangshan 		spin_unlock_irq(&pool->lock);
242313b1d625SLai Jiangshan 
242413b1d625SLai Jiangshan 		worker_detach_from_pool(rescuer, pool);
242513b1d625SLai Jiangshan 
242613b1d625SLai Jiangshan 		spin_lock_irq(&wq_mayday_lock);
24271da177e4SLinus Torvalds 	}
24281da177e4SLinus Torvalds 
24292e109a28STejun Heo 	spin_unlock_irq(&wq_mayday_lock);
2430493a1724STejun Heo 
24314d595b86SLai Jiangshan 	if (should_stop) {
24324d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
24334d595b86SLai Jiangshan 		rescuer->task->flags &= ~PF_WQ_WORKER;
24344d595b86SLai Jiangshan 		return 0;
24354d595b86SLai Jiangshan 	}
24364d595b86SLai Jiangshan 
2437111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
2438111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2439e22bee78STejun Heo 	schedule();
2440e22bee78STejun Heo 	goto repeat;
24411da177e4SLinus Torvalds }
24421da177e4SLinus Torvalds 
2443fca839c0STejun Heo /**
2444fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
2445fca839c0STejun Heo  * @target_wq: workqueue being flushed
2446fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
2447fca839c0STejun Heo  *
2448fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
2449fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2450fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
2451fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2452fca839c0STejun Heo  * a deadlock.
2453fca839c0STejun Heo  */
2454fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
2455fca839c0STejun Heo 				   struct work_struct *target_work)
2456fca839c0STejun Heo {
2457fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
2458fca839c0STejun Heo 	struct worker *worker;
2459fca839c0STejun Heo 
2460fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
2461fca839c0STejun Heo 		return;
2462fca839c0STejun Heo 
2463fca839c0STejun Heo 	worker = current_wq_worker();
2464fca839c0STejun Heo 
2465fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
2466fca839c0STejun Heo 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%pf",
2467fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
246823d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
246923d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2470fca839c0STejun Heo 		  "workqueue: WQ_MEM_RECLAIM %s:%pf is flushing !WQ_MEM_RECLAIM %s:%pf",
2471fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
2472fca839c0STejun Heo 		  target_wq->name, target_func);
2473fca839c0STejun Heo }
2474fca839c0STejun Heo 
2475fc2e4d70SOleg Nesterov struct wq_barrier {
2476fc2e4d70SOleg Nesterov 	struct work_struct	work;
2477fc2e4d70SOleg Nesterov 	struct completion	done;
24782607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
2479fc2e4d70SOleg Nesterov };
2480fc2e4d70SOleg Nesterov 
2481fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2482fc2e4d70SOleg Nesterov {
2483fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2484fc2e4d70SOleg Nesterov 	complete(&barr->done);
2485fc2e4d70SOleg Nesterov }
2486fc2e4d70SOleg Nesterov 
24874690c4abSTejun Heo /**
24884690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
2489112202d9STejun Heo  * @pwq: pwq to insert barrier into
24904690c4abSTejun Heo  * @barr: wq_barrier to insert
2491affee4b2STejun Heo  * @target: target work to attach @barr to
2492affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
24934690c4abSTejun Heo  *
2494affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
2495affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
2496affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
2497affee4b2STejun Heo  * cpu.
2498affee4b2STejun Heo  *
2499affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
2500affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
2501affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
2502affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
2503affee4b2STejun Heo  * after a work with LINKED flag set.
2504affee4b2STejun Heo  *
2505affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
2506112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
25074690c4abSTejun Heo  *
25084690c4abSTejun Heo  * CONTEXT:
2509d565ed63STejun Heo  * spin_lock_irq(pool->lock).
25104690c4abSTejun Heo  */
2511112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
2512affee4b2STejun Heo 			      struct wq_barrier *barr,
2513affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
2514fc2e4d70SOleg Nesterov {
2515affee4b2STejun Heo 	struct list_head *head;
2516affee4b2STejun Heo 	unsigned int linked = 0;
2517affee4b2STejun Heo 
2518dc186ad7SThomas Gleixner 	/*
2519d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
2520dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
2521dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
2522dc186ad7SThomas Gleixner 	 * might deadlock.
2523dc186ad7SThomas Gleixner 	 */
2524ca1cab37SAndrew Morton 	INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
252522df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
252652fa5bc5SBoqun Feng 
2527fd1a5b04SByungchul Park 	init_completion_map(&barr->done, &target->lockdep_map);
2528fd1a5b04SByungchul Park 
25292607d7a6STejun Heo 	barr->task = current;
253083c22520SOleg Nesterov 
2531affee4b2STejun Heo 	/*
2532affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
2533affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
2534affee4b2STejun Heo 	 */
2535affee4b2STejun Heo 	if (worker)
2536affee4b2STejun Heo 		head = worker->scheduled.next;
2537affee4b2STejun Heo 	else {
2538affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
2539affee4b2STejun Heo 
2540affee4b2STejun Heo 		head = target->entry.next;
2541affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
2542affee4b2STejun Heo 		linked = *bits & WORK_STRUCT_LINKED;
2543affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
2544affee4b2STejun Heo 	}
2545affee4b2STejun Heo 
2546dc186ad7SThomas Gleixner 	debug_work_activate(&barr->work);
2547112202d9STejun Heo 	insert_work(pwq, &barr->work, head,
2548affee4b2STejun Heo 		    work_color_to_flags(WORK_NO_COLOR) | linked);
2549fc2e4d70SOleg Nesterov }
2550fc2e4d70SOleg Nesterov 
255173f53c4aSTejun Heo /**
2552112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
255373f53c4aSTejun Heo  * @wq: workqueue being flushed
255473f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
255573f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
255673f53c4aSTejun Heo  *
2557112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
255873f53c4aSTejun Heo  *
2559112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
2560112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
2561112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
2562112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
2563112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
256473f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
256573f53c4aSTejun Heo  *
256673f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
256773f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
256873f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
256973f53c4aSTejun Heo  * is returned.
257073f53c4aSTejun Heo  *
2571112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
257273f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
257373f53c4aSTejun Heo  * advanced to @work_color.
257473f53c4aSTejun Heo  *
257573f53c4aSTejun Heo  * CONTEXT:
25763c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
257773f53c4aSTejun Heo  *
2578d185af30SYacine Belkadi  * Return:
257973f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
258073f53c4aSTejun Heo  * otherwise.
258173f53c4aSTejun Heo  */
2582112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
258373f53c4aSTejun Heo 				      int flush_color, int work_color)
25841da177e4SLinus Torvalds {
258573f53c4aSTejun Heo 	bool wait = false;
258649e3cf44STejun Heo 	struct pool_workqueue *pwq;
25871da177e4SLinus Torvalds 
258873f53c4aSTejun Heo 	if (flush_color >= 0) {
25896183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
2590112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
2591dc186ad7SThomas Gleixner 	}
259214441960SOleg Nesterov 
259349e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2594112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
25951da177e4SLinus Torvalds 
2596b09f4fd3SLai Jiangshan 		spin_lock_irq(&pool->lock);
259773f53c4aSTejun Heo 
259873f53c4aSTejun Heo 		if (flush_color >= 0) {
25996183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
260073f53c4aSTejun Heo 
2601112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
2602112202d9STejun Heo 				pwq->flush_color = flush_color;
2603112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
260473f53c4aSTejun Heo 				wait = true;
26051da177e4SLinus Torvalds 			}
260673f53c4aSTejun Heo 		}
260773f53c4aSTejun Heo 
260873f53c4aSTejun Heo 		if (work_color >= 0) {
26096183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
2610112202d9STejun Heo 			pwq->work_color = work_color;
261173f53c4aSTejun Heo 		}
261273f53c4aSTejun Heo 
2613b09f4fd3SLai Jiangshan 		spin_unlock_irq(&pool->lock);
26141da177e4SLinus Torvalds 	}
26151da177e4SLinus Torvalds 
2616112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
261773f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
261873f53c4aSTejun Heo 
261973f53c4aSTejun Heo 	return wait;
262083c22520SOleg Nesterov }
26211da177e4SLinus Torvalds 
26220fcb78c2SRolf Eike Beer /**
26231da177e4SLinus Torvalds  * flush_workqueue - ensure that any scheduled work has run to completion.
26240fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
26251da177e4SLinus Torvalds  *
2626c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
2627c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
26281da177e4SLinus Torvalds  */
26297ad5b3a5SHarvey Harrison void flush_workqueue(struct workqueue_struct *wq)
26301da177e4SLinus Torvalds {
263173f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
263273f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
263373f53c4aSTejun Heo 		.flush_color = -1,
2634fd1a5b04SByungchul Park 		.done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
263573f53c4aSTejun Heo 	};
263673f53c4aSTejun Heo 	int next_color;
2637b1f4ec17SOleg Nesterov 
26383347fa09STejun Heo 	if (WARN_ON(!wq_online))
26393347fa09STejun Heo 		return;
26403347fa09STejun Heo 
26413c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
264273f53c4aSTejun Heo 
264373f53c4aSTejun Heo 	/*
264473f53c4aSTejun Heo 	 * Start-to-wait phase
264573f53c4aSTejun Heo 	 */
264673f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
264773f53c4aSTejun Heo 
264873f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
264973f53c4aSTejun Heo 		/*
265073f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
265173f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
265273f53c4aSTejun Heo 		 * by one.
265373f53c4aSTejun Heo 		 */
26546183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
265573f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
265673f53c4aSTejun Heo 		wq->work_color = next_color;
265773f53c4aSTejun Heo 
265873f53c4aSTejun Heo 		if (!wq->first_flusher) {
265973f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
26606183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
266173f53c4aSTejun Heo 
266273f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
266373f53c4aSTejun Heo 
2664112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
266573f53c4aSTejun Heo 						       wq->work_color)) {
266673f53c4aSTejun Heo 				/* nothing to flush, done */
266773f53c4aSTejun Heo 				wq->flush_color = next_color;
266873f53c4aSTejun Heo 				wq->first_flusher = NULL;
266973f53c4aSTejun Heo 				goto out_unlock;
267073f53c4aSTejun Heo 			}
267173f53c4aSTejun Heo 		} else {
267273f53c4aSTejun Heo 			/* wait in queue */
26736183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
267473f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
2675112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
267673f53c4aSTejun Heo 		}
267773f53c4aSTejun Heo 	} else {
267873f53c4aSTejun Heo 		/*
267973f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
268073f53c4aSTejun Heo 		 * The next flush completion will assign us
268173f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
268273f53c4aSTejun Heo 		 */
268373f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
268473f53c4aSTejun Heo 	}
268573f53c4aSTejun Heo 
2686fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
2687fca839c0STejun Heo 
26883c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
268973f53c4aSTejun Heo 
269073f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
269173f53c4aSTejun Heo 
269273f53c4aSTejun Heo 	/*
269373f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
269473f53c4aSTejun Heo 	 *
269573f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
269673f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
269773f53c4aSTejun Heo 	 */
269873f53c4aSTejun Heo 	if (wq->first_flusher != &this_flusher)
269973f53c4aSTejun Heo 		return;
270073f53c4aSTejun Heo 
27013c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
270273f53c4aSTejun Heo 
27034ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
27044ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
27054ce48b37STejun Heo 		goto out_unlock;
27064ce48b37STejun Heo 
270773f53c4aSTejun Heo 	wq->first_flusher = NULL;
270873f53c4aSTejun Heo 
27096183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
27106183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
271173f53c4aSTejun Heo 
271273f53c4aSTejun Heo 	while (true) {
271373f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
271473f53c4aSTejun Heo 
271573f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
271673f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
271773f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
271873f53c4aSTejun Heo 				break;
271973f53c4aSTejun Heo 			list_del_init(&next->list);
272073f53c4aSTejun Heo 			complete(&next->done);
272173f53c4aSTejun Heo 		}
272273f53c4aSTejun Heo 
27236183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
272473f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
272573f53c4aSTejun Heo 
272673f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
272773f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
272873f53c4aSTejun Heo 
272973f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
273073f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
273173f53c4aSTejun Heo 			/*
273273f53c4aSTejun Heo 			 * Assign the same color to all overflowed
273373f53c4aSTejun Heo 			 * flushers, advance work_color and append to
273473f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
273573f53c4aSTejun Heo 			 * phase for these overflowed flushers.
273673f53c4aSTejun Heo 			 */
273773f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
273873f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
273973f53c4aSTejun Heo 
274073f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
274173f53c4aSTejun Heo 
274273f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
274373f53c4aSTejun Heo 					      &wq->flusher_queue);
2744112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
274573f53c4aSTejun Heo 		}
274673f53c4aSTejun Heo 
274773f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
27486183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
274973f53c4aSTejun Heo 			break;
275073f53c4aSTejun Heo 		}
275173f53c4aSTejun Heo 
275273f53c4aSTejun Heo 		/*
275373f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
2754112202d9STejun Heo 		 * the new first flusher and arm pwqs.
275573f53c4aSTejun Heo 		 */
27566183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
27576183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
275873f53c4aSTejun Heo 
275973f53c4aSTejun Heo 		list_del_init(&next->list);
276073f53c4aSTejun Heo 		wq->first_flusher = next;
276173f53c4aSTejun Heo 
2762112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
276373f53c4aSTejun Heo 			break;
276473f53c4aSTejun Heo 
276573f53c4aSTejun Heo 		/*
276673f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
276773f53c4aSTejun Heo 		 * flusher and repeat cascading.
276873f53c4aSTejun Heo 		 */
276973f53c4aSTejun Heo 		wq->first_flusher = NULL;
277073f53c4aSTejun Heo 	}
277173f53c4aSTejun Heo 
277273f53c4aSTejun Heo out_unlock:
27733c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
27741da177e4SLinus Torvalds }
27751dadafa8STim Gardner EXPORT_SYMBOL(flush_workqueue);
27761da177e4SLinus Torvalds 
27779c5a2ba7STejun Heo /**
27789c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
27799c5a2ba7STejun Heo  * @wq: workqueue to drain
27809c5a2ba7STejun Heo  *
27819c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
27829c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
27839c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
2784b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
27859c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
27869c5a2ba7STejun Heo  * takes too long.
27879c5a2ba7STejun Heo  */
27889c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
27899c5a2ba7STejun Heo {
27909c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
279149e3cf44STejun Heo 	struct pool_workqueue *pwq;
27929c5a2ba7STejun Heo 
27939c5a2ba7STejun Heo 	/*
27949c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
27959c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
2796618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
27979c5a2ba7STejun Heo 	 */
279887fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
27999c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
2800618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
280187fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
28029c5a2ba7STejun Heo reflush:
28039c5a2ba7STejun Heo 	flush_workqueue(wq);
28049c5a2ba7STejun Heo 
2805b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
280676af4d93STejun Heo 
280749e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
2808fa2563e4SThomas Tuttle 		bool drained;
28099c5a2ba7STejun Heo 
2810b09f4fd3SLai Jiangshan 		spin_lock_irq(&pwq->pool->lock);
2811112202d9STejun Heo 		drained = !pwq->nr_active && list_empty(&pwq->delayed_works);
2812b09f4fd3SLai Jiangshan 		spin_unlock_irq(&pwq->pool->lock);
2813fa2563e4SThomas Tuttle 
2814fa2563e4SThomas Tuttle 		if (drained)
28159c5a2ba7STejun Heo 			continue;
28169c5a2ba7STejun Heo 
28179c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
28189c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2819c5aa87bbSTejun Heo 			pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
28209c5a2ba7STejun Heo 				wq->name, flush_cnt);
282176af4d93STejun Heo 
2822b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
28239c5a2ba7STejun Heo 		goto reflush;
28249c5a2ba7STejun Heo 	}
28259c5a2ba7STejun Heo 
28269c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
2827618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
282887fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
28299c5a2ba7STejun Heo }
28309c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
28319c5a2ba7STejun Heo 
2832606a5020STejun Heo static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr)
2833baf59022STejun Heo {
2834baf59022STejun Heo 	struct worker *worker = NULL;
2835c9e7cf27STejun Heo 	struct worker_pool *pool;
2836112202d9STejun Heo 	struct pool_workqueue *pwq;
2837baf59022STejun Heo 
2838baf59022STejun Heo 	might_sleep();
2839baf59022STejun Heo 
2840fa1b54e6STejun Heo 	local_irq_disable();
2841fa1b54e6STejun Heo 	pool = get_work_pool(work);
2842fa1b54e6STejun Heo 	if (!pool) {
2843fa1b54e6STejun Heo 		local_irq_enable();
2844fa1b54e6STejun Heo 		return false;
2845fa1b54e6STejun Heo 	}
2846fa1b54e6STejun Heo 
2847fa1b54e6STejun Heo 	spin_lock(&pool->lock);
28480b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
2849112202d9STejun Heo 	pwq = get_work_pwq(work);
2850112202d9STejun Heo 	if (pwq) {
2851112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
2852baf59022STejun Heo 			goto already_gone;
2853606a5020STejun Heo 	} else {
2854c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
2855baf59022STejun Heo 		if (!worker)
2856baf59022STejun Heo 			goto already_gone;
2857112202d9STejun Heo 		pwq = worker->current_pwq;
2858606a5020STejun Heo 	}
2859baf59022STejun Heo 
2860fca839c0STejun Heo 	check_flush_dependency(pwq->wq, work);
2861fca839c0STejun Heo 
2862112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
2863d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2864baf59022STejun Heo 
2865e159489bSTejun Heo 	/*
2866a1d14934SPeter Zijlstra 	 * Force a lock recursion deadlock when using flush_work() inside a
2867a1d14934SPeter Zijlstra 	 * single-threaded or rescuer equipped workqueue.
2868a1d14934SPeter Zijlstra 	 *
2869a1d14934SPeter Zijlstra 	 * For single threaded workqueues the deadlock happens when the work
2870a1d14934SPeter Zijlstra 	 * is after the work issuing the flush_work(). For rescuer equipped
2871a1d14934SPeter Zijlstra 	 * workqueues the deadlock happens when the rescuer stalls, blocking
2872a1d14934SPeter Zijlstra 	 * forward progress.
2873e159489bSTejun Heo 	 */
2874a1d14934SPeter Zijlstra 	if (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer) {
2875112202d9STejun Heo 		lock_map_acquire(&pwq->wq->lockdep_map);
2876112202d9STejun Heo 		lock_map_release(&pwq->wq->lockdep_map);
2877a1d14934SPeter Zijlstra 	}
2878e159489bSTejun Heo 
2879baf59022STejun Heo 	return true;
2880baf59022STejun Heo already_gone:
2881d565ed63STejun Heo 	spin_unlock_irq(&pool->lock);
2882baf59022STejun Heo 	return false;
2883baf59022STejun Heo }
2884baf59022STejun Heo 
2885db700897SOleg Nesterov /**
2886401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
2887401a8d04STejun Heo  * @work: the work to flush
2888db700897SOleg Nesterov  *
2889606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
2890606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
2891401a8d04STejun Heo  *
2892d185af30SYacine Belkadi  * Return:
2893401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
2894401a8d04STejun Heo  * %false if it was already idle.
2895db700897SOleg Nesterov  */
2896401a8d04STejun Heo bool flush_work(struct work_struct *work)
2897db700897SOleg Nesterov {
289812997d1aSBjorn Helgaas 	struct wq_barrier barr;
289912997d1aSBjorn Helgaas 
29003347fa09STejun Heo 	if (WARN_ON(!wq_online))
29013347fa09STejun Heo 		return false;
29023347fa09STejun Heo 
290312997d1aSBjorn Helgaas 	if (start_flush_work(work, &barr)) {
290412997d1aSBjorn Helgaas 		wait_for_completion(&barr.done);
290512997d1aSBjorn Helgaas 		destroy_work_on_stack(&barr.work);
290612997d1aSBjorn Helgaas 		return true;
290712997d1aSBjorn Helgaas 	} else {
290812997d1aSBjorn Helgaas 		return false;
290912997d1aSBjorn Helgaas 	}
2910606a5020STejun Heo }
2911db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
2912db700897SOleg Nesterov 
29138603e1b3STejun Heo struct cwt_wait {
2914ac6424b9SIngo Molnar 	wait_queue_entry_t		wait;
29158603e1b3STejun Heo 	struct work_struct	*work;
29168603e1b3STejun Heo };
29178603e1b3STejun Heo 
2918ac6424b9SIngo Molnar static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
29198603e1b3STejun Heo {
29208603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
29218603e1b3STejun Heo 
29228603e1b3STejun Heo 	if (cwait->work != key)
29238603e1b3STejun Heo 		return 0;
29248603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
29258603e1b3STejun Heo }
29268603e1b3STejun Heo 
292736e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
2928401a8d04STejun Heo {
29298603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
2930bbb68dfaSTejun Heo 	unsigned long flags;
29311f1f642eSOleg Nesterov 	int ret;
29321f1f642eSOleg Nesterov 
29331f1f642eSOleg Nesterov 	do {
2934bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
2935bbb68dfaSTejun Heo 		/*
29368603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
29378603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
29388603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
29398603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
29408603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
29418603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
29428603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
29438603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
29448603e1b3STejun Heo 		 * we're hogging the CPU.
29458603e1b3STejun Heo 		 *
29468603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
29478603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
29488603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
29498603e1b3STejun Heo 		 * wait and wakeup.
2950bbb68dfaSTejun Heo 		 */
29518603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
29528603e1b3STejun Heo 			struct cwt_wait cwait;
29538603e1b3STejun Heo 
29548603e1b3STejun Heo 			init_wait(&cwait.wait);
29558603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
29568603e1b3STejun Heo 			cwait.work = work;
29578603e1b3STejun Heo 
29588603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
29598603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
29608603e1b3STejun Heo 			if (work_is_canceling(work))
29618603e1b3STejun Heo 				schedule();
29628603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
29638603e1b3STejun Heo 		}
29641f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
29651f1f642eSOleg Nesterov 
2966bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
2967bbb68dfaSTejun Heo 	mark_work_canceling(work);
2968bbb68dfaSTejun Heo 	local_irq_restore(flags);
2969bbb68dfaSTejun Heo 
29703347fa09STejun Heo 	/*
29713347fa09STejun Heo 	 * This allows canceling during early boot.  We know that @work
29723347fa09STejun Heo 	 * isn't executing.
29733347fa09STejun Heo 	 */
29743347fa09STejun Heo 	if (wq_online)
2975606a5020STejun Heo 		flush_work(work);
29763347fa09STejun Heo 
29777a22ad75STejun Heo 	clear_work_data(work);
29788603e1b3STejun Heo 
29798603e1b3STejun Heo 	/*
29808603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
29818603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
29828603e1b3STejun Heo 	 * visible there.
29838603e1b3STejun Heo 	 */
29848603e1b3STejun Heo 	smp_mb();
29858603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
29868603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
29878603e1b3STejun Heo 
29881f1f642eSOleg Nesterov 	return ret;
29891f1f642eSOleg Nesterov }
29901f1f642eSOleg Nesterov 
29916e84d644SOleg Nesterov /**
2992401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
2993401a8d04STejun Heo  * @work: the work to cancel
29946e84d644SOleg Nesterov  *
2995401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
2996401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
2997401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
2998401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
29991f1f642eSOleg Nesterov  *
3000401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
3001401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
30026e84d644SOleg Nesterov  *
3003401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
30046e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
3005401a8d04STejun Heo  *
3006d185af30SYacine Belkadi  * Return:
3007401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
30086e84d644SOleg Nesterov  */
3009401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
30106e84d644SOleg Nesterov {
301136e227d2STejun Heo 	return __cancel_work_timer(work, false);
3012b89deed3SOleg Nesterov }
301328e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
3014b89deed3SOleg Nesterov 
30156e84d644SOleg Nesterov /**
3016401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
3017401a8d04STejun Heo  * @dwork: the delayed work to flush
30186e84d644SOleg Nesterov  *
3019401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
3020401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
3021401a8d04STejun Heo  * considers the last queueing instance of @dwork.
30221f1f642eSOleg Nesterov  *
3023d185af30SYacine Belkadi  * Return:
3024401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3025401a8d04STejun Heo  * %false if it was already idle.
30266e84d644SOleg Nesterov  */
3027401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
3028401a8d04STejun Heo {
30298930cabaSTejun Heo 	local_irq_disable();
3030401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
303160c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
30328930cabaSTejun Heo 	local_irq_enable();
3033401a8d04STejun Heo 	return flush_work(&dwork->work);
3034401a8d04STejun Heo }
3035401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3036401a8d04STejun Heo 
303705f0fe6bSTejun Heo /**
303805f0fe6bSTejun Heo  * flush_rcu_work - wait for a rwork to finish executing the last queueing
303905f0fe6bSTejun Heo  * @rwork: the rcu work to flush
304005f0fe6bSTejun Heo  *
304105f0fe6bSTejun Heo  * Return:
304205f0fe6bSTejun Heo  * %true if flush_rcu_work() waited for the work to finish execution,
304305f0fe6bSTejun Heo  * %false if it was already idle.
304405f0fe6bSTejun Heo  */
304505f0fe6bSTejun Heo bool flush_rcu_work(struct rcu_work *rwork)
304605f0fe6bSTejun Heo {
304705f0fe6bSTejun Heo 	if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
304805f0fe6bSTejun Heo 		rcu_barrier();
304905f0fe6bSTejun Heo 		flush_work(&rwork->work);
305005f0fe6bSTejun Heo 		return true;
305105f0fe6bSTejun Heo 	} else {
305205f0fe6bSTejun Heo 		return flush_work(&rwork->work);
305305f0fe6bSTejun Heo 	}
305405f0fe6bSTejun Heo }
305505f0fe6bSTejun Heo EXPORT_SYMBOL(flush_rcu_work);
305605f0fe6bSTejun Heo 
3057f72b8792SJens Axboe static bool __cancel_work(struct work_struct *work, bool is_dwork)
3058f72b8792SJens Axboe {
3059f72b8792SJens Axboe 	unsigned long flags;
3060f72b8792SJens Axboe 	int ret;
3061f72b8792SJens Axboe 
3062f72b8792SJens Axboe 	do {
3063f72b8792SJens Axboe 		ret = try_to_grab_pending(work, is_dwork, &flags);
3064f72b8792SJens Axboe 	} while (unlikely(ret == -EAGAIN));
3065f72b8792SJens Axboe 
3066f72b8792SJens Axboe 	if (unlikely(ret < 0))
3067f72b8792SJens Axboe 		return false;
3068f72b8792SJens Axboe 
3069f72b8792SJens Axboe 	set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3070f72b8792SJens Axboe 	local_irq_restore(flags);
3071f72b8792SJens Axboe 	return ret;
3072f72b8792SJens Axboe }
3073f72b8792SJens Axboe 
3074f72b8792SJens Axboe /*
3075f72b8792SJens Axboe  * See cancel_delayed_work()
3076f72b8792SJens Axboe  */
3077f72b8792SJens Axboe bool cancel_work(struct work_struct *work)
3078f72b8792SJens Axboe {
3079f72b8792SJens Axboe 	return __cancel_work(work, false);
3080f72b8792SJens Axboe }
3081f72b8792SJens Axboe 
3082401a8d04STejun Heo /**
308357b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
308457b30ae7STejun Heo  * @dwork: delayed_work to cancel
308509383498STejun Heo  *
3086d185af30SYacine Belkadi  * Kill off a pending delayed_work.
3087d185af30SYacine Belkadi  *
3088d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
3089d185af30SYacine Belkadi  * pending.
3090d185af30SYacine Belkadi  *
3091d185af30SYacine Belkadi  * Note:
3092d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
3093d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
3094d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
309509383498STejun Heo  *
309657b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
309709383498STejun Heo  */
309857b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
309909383498STejun Heo {
3100f72b8792SJens Axboe 	return __cancel_work(&dwork->work, true);
310109383498STejun Heo }
310257b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
310309383498STejun Heo 
310409383498STejun Heo /**
3105401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3106401a8d04STejun Heo  * @dwork: the delayed work cancel
3107401a8d04STejun Heo  *
3108401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
3109401a8d04STejun Heo  *
3110d185af30SYacine Belkadi  * Return:
3111401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
3112401a8d04STejun Heo  */
3113401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
31146e84d644SOleg Nesterov {
311536e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
31166e84d644SOleg Nesterov }
3117f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
31181da177e4SLinus Torvalds 
31190fcb78c2SRolf Eike Beer /**
312031ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
3121b6136773SAndrew Morton  * @func: the function to call
3122b6136773SAndrew Morton  *
312331ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
312431ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
3125b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
312631ddd871STejun Heo  *
3127d185af30SYacine Belkadi  * Return:
312831ddd871STejun Heo  * 0 on success, -errno on failure.
3129b6136773SAndrew Morton  */
313065f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
313115316ba8SChristoph Lameter {
313215316ba8SChristoph Lameter 	int cpu;
313338f51568SNamhyung Kim 	struct work_struct __percpu *works;
313415316ba8SChristoph Lameter 
3135b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
3136b6136773SAndrew Morton 	if (!works)
313715316ba8SChristoph Lameter 		return -ENOMEM;
3138b6136773SAndrew Morton 
313995402b38SGautham R Shenoy 	get_online_cpus();
314093981800STejun Heo 
314115316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
31429bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
31439bfb1839SIngo Molnar 
31449bfb1839SIngo Molnar 		INIT_WORK(work, func);
31458de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
314615316ba8SChristoph Lameter 	}
314793981800STejun Heo 
314893981800STejun Heo 	for_each_online_cpu(cpu)
31498616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
315093981800STejun Heo 
315195402b38SGautham R Shenoy 	put_online_cpus();
3152b6136773SAndrew Morton 	free_percpu(works);
315315316ba8SChristoph Lameter 	return 0;
315415316ba8SChristoph Lameter }
315515316ba8SChristoph Lameter 
3156eef6a7d5SAlan Stern /**
31571fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
31581fa44ecaSJames Bottomley  * @fn:		the function to execute
31591fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
31601fa44ecaSJames Bottomley  *		be available when the work executes)
31611fa44ecaSJames Bottomley  *
31621fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
31631fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
31641fa44ecaSJames Bottomley  *
3165d185af30SYacine Belkadi  * Return:	0 - function was executed
31661fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
31671fa44ecaSJames Bottomley  */
316865f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
31691fa44ecaSJames Bottomley {
31701fa44ecaSJames Bottomley 	if (!in_interrupt()) {
317165f27f38SDavid Howells 		fn(&ew->work);
31721fa44ecaSJames Bottomley 		return 0;
31731fa44ecaSJames Bottomley 	}
31741fa44ecaSJames Bottomley 
317565f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
31761fa44ecaSJames Bottomley 	schedule_work(&ew->work);
31771fa44ecaSJames Bottomley 
31781fa44ecaSJames Bottomley 	return 1;
31791fa44ecaSJames Bottomley }
31801fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
31811fa44ecaSJames Bottomley 
31827a4e344cSTejun Heo /**
31837a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
31847a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
31857a4e344cSTejun Heo  *
31867a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
31877a4e344cSTejun Heo  */
31887a4e344cSTejun Heo void free_workqueue_attrs(struct workqueue_attrs *attrs)
31897a4e344cSTejun Heo {
31907a4e344cSTejun Heo 	if (attrs) {
31917a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
31927a4e344cSTejun Heo 		kfree(attrs);
31937a4e344cSTejun Heo 	}
31947a4e344cSTejun Heo }
31957a4e344cSTejun Heo 
31967a4e344cSTejun Heo /**
31977a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
31987a4e344cSTejun Heo  * @gfp_mask: allocation mask to use
31997a4e344cSTejun Heo  *
32007a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
3201d185af30SYacine Belkadi  * return it.
3202d185af30SYacine Belkadi  *
3203d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
32047a4e344cSTejun Heo  */
32057a4e344cSTejun Heo struct workqueue_attrs *alloc_workqueue_attrs(gfp_t gfp_mask)
32067a4e344cSTejun Heo {
32077a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
32087a4e344cSTejun Heo 
32097a4e344cSTejun Heo 	attrs = kzalloc(sizeof(*attrs), gfp_mask);
32107a4e344cSTejun Heo 	if (!attrs)
32117a4e344cSTejun Heo 		goto fail;
32127a4e344cSTejun Heo 	if (!alloc_cpumask_var(&attrs->cpumask, gfp_mask))
32137a4e344cSTejun Heo 		goto fail;
32147a4e344cSTejun Heo 
321513e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
32167a4e344cSTejun Heo 	return attrs;
32177a4e344cSTejun Heo fail:
32187a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
32197a4e344cSTejun Heo 	return NULL;
32207a4e344cSTejun Heo }
32217a4e344cSTejun Heo 
322229c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
322329c91e99STejun Heo 				 const struct workqueue_attrs *from)
322429c91e99STejun Heo {
322529c91e99STejun Heo 	to->nice = from->nice;
322629c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
32272865a8fbSShaohua Li 	/*
32282865a8fbSShaohua Li 	 * Unlike hash and equality test, this function doesn't ignore
32292865a8fbSShaohua Li 	 * ->no_numa as it is used for both pool and wq attrs.  Instead,
32302865a8fbSShaohua Li 	 * get_unbound_pool() explicitly clears ->no_numa after copying.
32312865a8fbSShaohua Li 	 */
32322865a8fbSShaohua Li 	to->no_numa = from->no_numa;
323329c91e99STejun Heo }
323429c91e99STejun Heo 
323529c91e99STejun Heo /* hash value of the content of @attr */
323629c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
323729c91e99STejun Heo {
323829c91e99STejun Heo 	u32 hash = 0;
323929c91e99STejun Heo 
324029c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
324113e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
324213e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
324329c91e99STejun Heo 	return hash;
324429c91e99STejun Heo }
324529c91e99STejun Heo 
324629c91e99STejun Heo /* content equality test */
324729c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
324829c91e99STejun Heo 			  const struct workqueue_attrs *b)
324929c91e99STejun Heo {
325029c91e99STejun Heo 	if (a->nice != b->nice)
325129c91e99STejun Heo 		return false;
325229c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
325329c91e99STejun Heo 		return false;
325429c91e99STejun Heo 	return true;
325529c91e99STejun Heo }
325629c91e99STejun Heo 
32577a4e344cSTejun Heo /**
32587a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
32597a4e344cSTejun Heo  * @pool: worker_pool to initialize
32607a4e344cSTejun Heo  *
3261402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
3262d185af30SYacine Belkadi  *
3263d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
326429c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
326529c91e99STejun Heo  * on @pool safely to release it.
32667a4e344cSTejun Heo  */
32677a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
32684e1a1f9aSTejun Heo {
32694e1a1f9aSTejun Heo 	spin_lock_init(&pool->lock);
327029c91e99STejun Heo 	pool->id = -1;
327129c91e99STejun Heo 	pool->cpu = -1;
3272f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
32734e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
327482607adcSTejun Heo 	pool->watchdog_ts = jiffies;
32754e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
32764e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
32774e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
32784e1a1f9aSTejun Heo 
327932a6c723SKees Cook 	timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
32804e1a1f9aSTejun Heo 
328132a6c723SKees Cook 	timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
32824e1a1f9aSTejun Heo 
328392f9c5c4SLai Jiangshan 	mutex_init(&pool->attach_mutex);
3284da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
32857a4e344cSTejun Heo 
32867cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
328729c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
328829c91e99STejun Heo 	pool->refcnt = 1;
328929c91e99STejun Heo 
329029c91e99STejun Heo 	/* shouldn't fail above this point */
32917a4e344cSTejun Heo 	pool->attrs = alloc_workqueue_attrs(GFP_KERNEL);
32927a4e344cSTejun Heo 	if (!pool->attrs)
32937a4e344cSTejun Heo 		return -ENOMEM;
32947a4e344cSTejun Heo 	return 0;
32954e1a1f9aSTejun Heo }
32964e1a1f9aSTejun Heo 
3297e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
3298e2dca7adSTejun Heo {
3299e2dca7adSTejun Heo 	struct workqueue_struct *wq =
3300e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
3301e2dca7adSTejun Heo 
3302e2dca7adSTejun Heo 	if (!(wq->flags & WQ_UNBOUND))
3303e2dca7adSTejun Heo 		free_percpu(wq->cpu_pwqs);
3304e2dca7adSTejun Heo 	else
3305e2dca7adSTejun Heo 		free_workqueue_attrs(wq->unbound_attrs);
3306e2dca7adSTejun Heo 
3307e2dca7adSTejun Heo 	kfree(wq->rescuer);
3308e2dca7adSTejun Heo 	kfree(wq);
3309e2dca7adSTejun Heo }
3310e2dca7adSTejun Heo 
331129c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
331229c91e99STejun Heo {
331329c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
331429c91e99STejun Heo 
33157cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
331629c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
331729c91e99STejun Heo 	kfree(pool);
331829c91e99STejun Heo }
331929c91e99STejun Heo 
332029c91e99STejun Heo /**
332129c91e99STejun Heo  * put_unbound_pool - put a worker_pool
332229c91e99STejun Heo  * @pool: worker_pool to put
332329c91e99STejun Heo  *
332429c91e99STejun Heo  * Put @pool.  If its refcnt reaches zero, it gets destroyed in sched-RCU
3325c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
3326c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
3327c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
3328a892caccSTejun Heo  *
3329a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
333029c91e99STejun Heo  */
333129c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
333229c91e99STejun Heo {
333360f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
333429c91e99STejun Heo 	struct worker *worker;
333529c91e99STejun Heo 
3336a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3337a892caccSTejun Heo 
3338a892caccSTejun Heo 	if (--pool->refcnt)
333929c91e99STejun Heo 		return;
334029c91e99STejun Heo 
334129c91e99STejun Heo 	/* sanity checks */
334261d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
3343a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
334429c91e99STejun Heo 		return;
334529c91e99STejun Heo 
334629c91e99STejun Heo 	/* release id and unhash */
334729c91e99STejun Heo 	if (pool->id >= 0)
334829c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
334929c91e99STejun Heo 	hash_del(&pool->hash_node);
335029c91e99STejun Heo 
3351c5aa87bbSTejun Heo 	/*
3352692b4825STejun Heo 	 * Become the manager and destroy all workers.  This prevents
3353692b4825STejun Heo 	 * @pool's workers from blocking on attach_mutex.  We're the last
3354692b4825STejun Heo 	 * manager and @pool gets freed with the flag set.
3355c5aa87bbSTejun Heo 	 */
335660f5a4bcSLai Jiangshan 	spin_lock_irq(&pool->lock);
3357692b4825STejun Heo 	wait_event_lock_irq(wq_manager_wait,
3358692b4825STejun Heo 			    !(pool->flags & POOL_MANAGER_ACTIVE), pool->lock);
3359692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
3360692b4825STejun Heo 
33611037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
336229c91e99STejun Heo 		destroy_worker(worker);
336329c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
336429c91e99STejun Heo 	spin_unlock_irq(&pool->lock);
336560f5a4bcSLai Jiangshan 
336692f9c5c4SLai Jiangshan 	mutex_lock(&pool->attach_mutex);
3367da028469SLai Jiangshan 	if (!list_empty(&pool->workers))
336860f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
336992f9c5c4SLai Jiangshan 	mutex_unlock(&pool->attach_mutex);
337060f5a4bcSLai Jiangshan 
337160f5a4bcSLai Jiangshan 	if (pool->detach_completion)
337260f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
337360f5a4bcSLai Jiangshan 
337429c91e99STejun Heo 	/* shut down the timers */
337529c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
337629c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
337729c91e99STejun Heo 
337829c91e99STejun Heo 	/* sched-RCU protected to allow dereferences from get_work_pool() */
337929c91e99STejun Heo 	call_rcu_sched(&pool->rcu, rcu_free_pool);
338029c91e99STejun Heo }
338129c91e99STejun Heo 
338229c91e99STejun Heo /**
338329c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
338429c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
338529c91e99STejun Heo  *
338629c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
338729c91e99STejun Heo  * reference count and return it.  If there already is a matching
338829c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
3389d185af30SYacine Belkadi  * create a new one.
3390a892caccSTejun Heo  *
3391a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
3392d185af30SYacine Belkadi  *
3393d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
3394d185af30SYacine Belkadi  * On failure, %NULL.
339529c91e99STejun Heo  */
339629c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
339729c91e99STejun Heo {
339829c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
339929c91e99STejun Heo 	struct worker_pool *pool;
3400f3f90ad4STejun Heo 	int node;
3401e2273584SXunlei Pang 	int target_node = NUMA_NO_NODE;
340229c91e99STejun Heo 
3403a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
340429c91e99STejun Heo 
340529c91e99STejun Heo 	/* do we already have a matching pool? */
340629c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
340729c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
340829c91e99STejun Heo 			pool->refcnt++;
34093fb1823cSLai Jiangshan 			return pool;
341029c91e99STejun Heo 		}
341129c91e99STejun Heo 	}
341229c91e99STejun Heo 
3413e2273584SXunlei Pang 	/* if cpumask is contained inside a NUMA node, we belong to that node */
3414e2273584SXunlei Pang 	if (wq_numa_enabled) {
3415e2273584SXunlei Pang 		for_each_node(node) {
3416e2273584SXunlei Pang 			if (cpumask_subset(attrs->cpumask,
3417e2273584SXunlei Pang 					   wq_numa_possible_cpumask[node])) {
3418e2273584SXunlei Pang 				target_node = node;
3419e2273584SXunlei Pang 				break;
3420e2273584SXunlei Pang 			}
3421e2273584SXunlei Pang 		}
3422e2273584SXunlei Pang 	}
3423e2273584SXunlei Pang 
342429c91e99STejun Heo 	/* nope, create a new one */
3425e2273584SXunlei Pang 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node);
342629c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
342729c91e99STejun Heo 		goto fail;
342829c91e99STejun Heo 
34298864b4e5STejun Heo 	lockdep_set_subclass(&pool->lock, 1);	/* see put_pwq() */
343029c91e99STejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
3431e2273584SXunlei Pang 	pool->node = target_node;
343229c91e99STejun Heo 
34332865a8fbSShaohua Li 	/*
34342865a8fbSShaohua Li 	 * no_numa isn't a worker_pool attribute, always clear it.  See
34352865a8fbSShaohua Li 	 * 'struct workqueue_attrs' comments for detail.
34362865a8fbSShaohua Li 	 */
34372865a8fbSShaohua Li 	pool->attrs->no_numa = false;
34382865a8fbSShaohua Li 
343929c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
344029c91e99STejun Heo 		goto fail;
344129c91e99STejun Heo 
344229c91e99STejun Heo 	/* create and start the initial worker */
34433347fa09STejun Heo 	if (wq_online && !create_worker(pool))
344429c91e99STejun Heo 		goto fail;
344529c91e99STejun Heo 
344629c91e99STejun Heo 	/* install */
344729c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
34483fb1823cSLai Jiangshan 
344929c91e99STejun Heo 	return pool;
345029c91e99STejun Heo fail:
345129c91e99STejun Heo 	if (pool)
345229c91e99STejun Heo 		put_unbound_pool(pool);
345329c91e99STejun Heo 	return NULL;
345429c91e99STejun Heo }
345529c91e99STejun Heo 
34568864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
34578864b4e5STejun Heo {
34588864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
34598864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
34608864b4e5STejun Heo }
34618864b4e5STejun Heo 
34628864b4e5STejun Heo /*
34638864b4e5STejun Heo  * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
34648864b4e5STejun Heo  * and needs to be destroyed.
34658864b4e5STejun Heo  */
34668864b4e5STejun Heo static void pwq_unbound_release_workfn(struct work_struct *work)
34678864b4e5STejun Heo {
34688864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
34698864b4e5STejun Heo 						  unbound_release_work);
34708864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
34718864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
3472bc0caf09STejun Heo 	bool is_last;
34738864b4e5STejun Heo 
34748864b4e5STejun Heo 	if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)))
34758864b4e5STejun Heo 		return;
34768864b4e5STejun Heo 
34773c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
34788864b4e5STejun Heo 	list_del_rcu(&pwq->pwqs_node);
3479bc0caf09STejun Heo 	is_last = list_empty(&wq->pwqs);
34803c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
34818864b4e5STejun Heo 
3482a892caccSTejun Heo 	mutex_lock(&wq_pool_mutex);
34838864b4e5STejun Heo 	put_unbound_pool(pool);
3484a892caccSTejun Heo 	mutex_unlock(&wq_pool_mutex);
3485a892caccSTejun Heo 
34868864b4e5STejun Heo 	call_rcu_sched(&pwq->rcu, rcu_free_pwq);
34878864b4e5STejun Heo 
34888864b4e5STejun Heo 	/*
34898864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
3490e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
34918864b4e5STejun Heo 	 */
3492e2dca7adSTejun Heo 	if (is_last)
3493e2dca7adSTejun Heo 		call_rcu_sched(&wq->rcu, rcu_free_wq);
34946029a918STejun Heo }
34958864b4e5STejun Heo 
34960fbd95aaSTejun Heo /**
3497699ce097STejun Heo  * pwq_adjust_max_active - update a pwq's max_active to the current setting
34980fbd95aaSTejun Heo  * @pwq: target pool_workqueue
34990fbd95aaSTejun Heo  *
3500699ce097STejun Heo  * If @pwq isn't freezing, set @pwq->max_active to the associated
3501699ce097STejun Heo  * workqueue's saved_max_active and activate delayed work items
3502699ce097STejun Heo  * accordingly.  If @pwq is freezing, clear @pwq->max_active to zero.
35030fbd95aaSTejun Heo  */
3504699ce097STejun Heo static void pwq_adjust_max_active(struct pool_workqueue *pwq)
35050fbd95aaSTejun Heo {
3506699ce097STejun Heo 	struct workqueue_struct *wq = pwq->wq;
3507699ce097STejun Heo 	bool freezable = wq->flags & WQ_FREEZABLE;
35083347fa09STejun Heo 	unsigned long flags;
3509699ce097STejun Heo 
3510699ce097STejun Heo 	/* for @wq->saved_max_active */
3511a357fc03SLai Jiangshan 	lockdep_assert_held(&wq->mutex);
3512699ce097STejun Heo 
3513699ce097STejun Heo 	/* fast exit for non-freezable wqs */
3514699ce097STejun Heo 	if (!freezable && pwq->max_active == wq->saved_max_active)
3515699ce097STejun Heo 		return;
3516699ce097STejun Heo 
35173347fa09STejun Heo 	/* this function can be called during early boot w/ irq disabled */
35183347fa09STejun Heo 	spin_lock_irqsave(&pwq->pool->lock, flags);
3519699ce097STejun Heo 
352074b414eaSLai Jiangshan 	/*
352174b414eaSLai Jiangshan 	 * During [un]freezing, the caller is responsible for ensuring that
352274b414eaSLai Jiangshan 	 * this function is called at least once after @workqueue_freezing
352374b414eaSLai Jiangshan 	 * is updated and visible.
352474b414eaSLai Jiangshan 	 */
352574b414eaSLai Jiangshan 	if (!freezable || !workqueue_freezing) {
3526699ce097STejun Heo 		pwq->max_active = wq->saved_max_active;
35270fbd95aaSTejun Heo 
35280fbd95aaSTejun Heo 		while (!list_empty(&pwq->delayed_works) &&
35290fbd95aaSTejun Heo 		       pwq->nr_active < pwq->max_active)
35300fbd95aaSTejun Heo 			pwq_activate_first_delayed(pwq);
3531951a078aSLai Jiangshan 
3532951a078aSLai Jiangshan 		/*
3533951a078aSLai Jiangshan 		 * Need to kick a worker after thawed or an unbound wq's
3534951a078aSLai Jiangshan 		 * max_active is bumped.  It's a slow path.  Do it always.
3535951a078aSLai Jiangshan 		 */
3536951a078aSLai Jiangshan 		wake_up_worker(pwq->pool);
3537699ce097STejun Heo 	} else {
3538699ce097STejun Heo 		pwq->max_active = 0;
3539699ce097STejun Heo 	}
3540699ce097STejun Heo 
35413347fa09STejun Heo 	spin_unlock_irqrestore(&pwq->pool->lock, flags);
35420fbd95aaSTejun Heo }
35430fbd95aaSTejun Heo 
3544e50aba9aSTejun Heo /* initialize newly alloced @pwq which is associated with @wq and @pool */
3545f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
3546f147f29eSTejun Heo 		     struct worker_pool *pool)
3547d2c1d404STejun Heo {
3548d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
3549d2c1d404STejun Heo 
3550e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
3551e50aba9aSTejun Heo 
3552d2c1d404STejun Heo 	pwq->pool = pool;
3553d2c1d404STejun Heo 	pwq->wq = wq;
3554d2c1d404STejun Heo 	pwq->flush_color = -1;
35558864b4e5STejun Heo 	pwq->refcnt = 1;
3556d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->delayed_works);
35571befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
3558d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
35598864b4e5STejun Heo 	INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn);
3560f147f29eSTejun Heo }
3561d2c1d404STejun Heo 
3562f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
35631befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
3564f147f29eSTejun Heo {
3565f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
3566f147f29eSTejun Heo 
3567f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
356875ccf595STejun Heo 
35691befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
35701befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
35711befcf30STejun Heo 		return;
35721befcf30STejun Heo 
357329b1cb41SLai Jiangshan 	/* set the matching work_color */
357475ccf595STejun Heo 	pwq->work_color = wq->work_color;
3575983ca25eSTejun Heo 
3576983ca25eSTejun Heo 	/* sync max_active to the current setting */
3577983ca25eSTejun Heo 	pwq_adjust_max_active(pwq);
3578983ca25eSTejun Heo 
3579983ca25eSTejun Heo 	/* link in @pwq */
35809e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
3581df2d5ae4STejun Heo }
35826029a918STejun Heo 
3583f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3584f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
3585f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
3586f147f29eSTejun Heo {
3587f147f29eSTejun Heo 	struct worker_pool *pool;
3588f147f29eSTejun Heo 	struct pool_workqueue *pwq;
3589f147f29eSTejun Heo 
3590f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
3591f147f29eSTejun Heo 
3592f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
3593f147f29eSTejun Heo 	if (!pool)
3594f147f29eSTejun Heo 		return NULL;
3595f147f29eSTejun Heo 
3596e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
3597f147f29eSTejun Heo 	if (!pwq) {
3598f147f29eSTejun Heo 		put_unbound_pool(pool);
3599f147f29eSTejun Heo 		return NULL;
3600f147f29eSTejun Heo 	}
3601f147f29eSTejun Heo 
3602f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
3603f147f29eSTejun Heo 	return pwq;
3604d2c1d404STejun Heo }
3605d2c1d404STejun Heo 
36064c16bd32STejun Heo /**
360730186c6fSGong Zhaogang  * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
3608042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
36094c16bd32STejun Heo  * @node: the target NUMA node
36104c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
36114c16bd32STejun Heo  * @cpumask: outarg, the resulting cpumask
36124c16bd32STejun Heo  *
36134c16bd32STejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @node.  If
36144c16bd32STejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during
3615d185af30SYacine Belkadi  * calculation.  The result is stored in @cpumask.
36164c16bd32STejun Heo  *
36174c16bd32STejun Heo  * If NUMA affinity is not enabled, @attrs->cpumask is always used.  If
36184c16bd32STejun Heo  * enabled and @node has online CPUs requested by @attrs, the returned
36194c16bd32STejun Heo  * cpumask is the intersection of the possible CPUs of @node and
36204c16bd32STejun Heo  * @attrs->cpumask.
36214c16bd32STejun Heo  *
36224c16bd32STejun Heo  * The caller is responsible for ensuring that the cpumask of @node stays
36234c16bd32STejun Heo  * stable.
3624d185af30SYacine Belkadi  *
3625d185af30SYacine Belkadi  * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3626d185af30SYacine Belkadi  * %false if equal.
36274c16bd32STejun Heo  */
36284c16bd32STejun Heo static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node,
36294c16bd32STejun Heo 				 int cpu_going_down, cpumask_t *cpumask)
36304c16bd32STejun Heo {
3631d55262c4STejun Heo 	if (!wq_numa_enabled || attrs->no_numa)
36324c16bd32STejun Heo 		goto use_dfl;
36334c16bd32STejun Heo 
36344c16bd32STejun Heo 	/* does @node have any online CPUs @attrs wants? */
36354c16bd32STejun Heo 	cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask);
36364c16bd32STejun Heo 	if (cpu_going_down >= 0)
36374c16bd32STejun Heo 		cpumask_clear_cpu(cpu_going_down, cpumask);
36384c16bd32STejun Heo 
36394c16bd32STejun Heo 	if (cpumask_empty(cpumask))
36404c16bd32STejun Heo 		goto use_dfl;
36414c16bd32STejun Heo 
36424c16bd32STejun Heo 	/* yeap, return possible CPUs in @node that @attrs wants */
36434c16bd32STejun Heo 	cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]);
36441ad0f0a7SMichael Bringmann 
36451ad0f0a7SMichael Bringmann 	if (cpumask_empty(cpumask)) {
36461ad0f0a7SMichael Bringmann 		pr_warn_once("WARNING: workqueue cpumask: online intersect > "
36471ad0f0a7SMichael Bringmann 				"possible intersect\n");
36481ad0f0a7SMichael Bringmann 		return false;
36491ad0f0a7SMichael Bringmann 	}
36501ad0f0a7SMichael Bringmann 
36514c16bd32STejun Heo 	return !cpumask_equal(cpumask, attrs->cpumask);
36524c16bd32STejun Heo 
36534c16bd32STejun Heo use_dfl:
36544c16bd32STejun Heo 	cpumask_copy(cpumask, attrs->cpumask);
36554c16bd32STejun Heo 	return false;
36564c16bd32STejun Heo }
36574c16bd32STejun Heo 
36581befcf30STejun Heo /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
36591befcf30STejun Heo static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq,
36601befcf30STejun Heo 						   int node,
36611befcf30STejun Heo 						   struct pool_workqueue *pwq)
36621befcf30STejun Heo {
36631befcf30STejun Heo 	struct pool_workqueue *old_pwq;
36641befcf30STejun Heo 
36655b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
36661befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
36671befcf30STejun Heo 
36681befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
36691befcf30STejun Heo 	link_pwq(pwq);
36701befcf30STejun Heo 
36711befcf30STejun Heo 	old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
36721befcf30STejun Heo 	rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq);
36731befcf30STejun Heo 	return old_pwq;
36741befcf30STejun Heo }
36751befcf30STejun Heo 
36762d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
36772d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
36782d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
36792d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
3680042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
36812d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
36822d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
36832d5f0764SLai Jiangshan };
36842d5f0764SLai Jiangshan 
36852d5f0764SLai Jiangshan /* free the resources after success or abort */
36862d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
36872d5f0764SLai Jiangshan {
36882d5f0764SLai Jiangshan 	if (ctx) {
36892d5f0764SLai Jiangshan 		int node;
36902d5f0764SLai Jiangshan 
36912d5f0764SLai Jiangshan 		for_each_node(node)
36922d5f0764SLai Jiangshan 			put_pwq_unlocked(ctx->pwq_tbl[node]);
36932d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
36942d5f0764SLai Jiangshan 
36952d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
36962d5f0764SLai Jiangshan 
36972d5f0764SLai Jiangshan 		kfree(ctx);
36982d5f0764SLai Jiangshan 	}
36992d5f0764SLai Jiangshan }
37002d5f0764SLai Jiangshan 
37012d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
37022d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
37032d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
37042d5f0764SLai Jiangshan 		      const struct workqueue_attrs *attrs)
37052d5f0764SLai Jiangshan {
37062d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
37072d5f0764SLai Jiangshan 	struct workqueue_attrs *new_attrs, *tmp_attrs;
37082d5f0764SLai Jiangshan 	int node;
37092d5f0764SLai Jiangshan 
37102d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
37112d5f0764SLai Jiangshan 
37122d5f0764SLai Jiangshan 	ctx = kzalloc(sizeof(*ctx) + nr_node_ids * sizeof(ctx->pwq_tbl[0]),
37132d5f0764SLai Jiangshan 		      GFP_KERNEL);
37142d5f0764SLai Jiangshan 
37152d5f0764SLai Jiangshan 	new_attrs = alloc_workqueue_attrs(GFP_KERNEL);
37162d5f0764SLai Jiangshan 	tmp_attrs = alloc_workqueue_attrs(GFP_KERNEL);
37172d5f0764SLai Jiangshan 	if (!ctx || !new_attrs || !tmp_attrs)
37182d5f0764SLai Jiangshan 		goto out_free;
37192d5f0764SLai Jiangshan 
3720042f7df1SLai Jiangshan 	/*
3721042f7df1SLai Jiangshan 	 * Calculate the attrs of the default pwq.
3722042f7df1SLai Jiangshan 	 * If the user configured cpumask doesn't overlap with the
3723042f7df1SLai Jiangshan 	 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
3724042f7df1SLai Jiangshan 	 */
37252d5f0764SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
3726b05a7928SFrederic Weisbecker 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, wq_unbound_cpumask);
3727042f7df1SLai Jiangshan 	if (unlikely(cpumask_empty(new_attrs->cpumask)))
3728042f7df1SLai Jiangshan 		cpumask_copy(new_attrs->cpumask, wq_unbound_cpumask);
37292d5f0764SLai Jiangshan 
37302d5f0764SLai Jiangshan 	/*
37312d5f0764SLai Jiangshan 	 * We may create multiple pwqs with differing cpumasks.  Make a
37322d5f0764SLai Jiangshan 	 * copy of @new_attrs which will be modified and used to obtain
37332d5f0764SLai Jiangshan 	 * pools.
37342d5f0764SLai Jiangshan 	 */
37352d5f0764SLai Jiangshan 	copy_workqueue_attrs(tmp_attrs, new_attrs);
37362d5f0764SLai Jiangshan 
37372d5f0764SLai Jiangshan 	/*
37382d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
37392d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
37402d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
37412d5f0764SLai Jiangshan 	 */
37422d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
37432d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
37442d5f0764SLai Jiangshan 		goto out_free;
37452d5f0764SLai Jiangshan 
37462d5f0764SLai Jiangshan 	for_each_node(node) {
3747042f7df1SLai Jiangshan 		if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) {
37482d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs);
37492d5f0764SLai Jiangshan 			if (!ctx->pwq_tbl[node])
37502d5f0764SLai Jiangshan 				goto out_free;
37512d5f0764SLai Jiangshan 		} else {
37522d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
37532d5f0764SLai Jiangshan 			ctx->pwq_tbl[node] = ctx->dfl_pwq;
37542d5f0764SLai Jiangshan 		}
37552d5f0764SLai Jiangshan 	}
37562d5f0764SLai Jiangshan 
3757042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
3758042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
3759042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
37602d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
3761042f7df1SLai Jiangshan 
37622d5f0764SLai Jiangshan 	ctx->wq = wq;
37632d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
37642d5f0764SLai Jiangshan 	return ctx;
37652d5f0764SLai Jiangshan 
37662d5f0764SLai Jiangshan out_free:
37672d5f0764SLai Jiangshan 	free_workqueue_attrs(tmp_attrs);
37682d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
37692d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
37702d5f0764SLai Jiangshan 	return NULL;
37712d5f0764SLai Jiangshan }
37722d5f0764SLai Jiangshan 
37732d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
37742d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
37752d5f0764SLai Jiangshan {
37762d5f0764SLai Jiangshan 	int node;
37772d5f0764SLai Jiangshan 
37782d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
37792d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
37802d5f0764SLai Jiangshan 
37812d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
37822d5f0764SLai Jiangshan 
37832d5f0764SLai Jiangshan 	/* save the previous pwq and install the new one */
37842d5f0764SLai Jiangshan 	for_each_node(node)
37852d5f0764SLai Jiangshan 		ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node,
37862d5f0764SLai Jiangshan 							  ctx->pwq_tbl[node]);
37872d5f0764SLai Jiangshan 
37882d5f0764SLai Jiangshan 	/* @dfl_pwq might not have been used, ensure it's linked */
37892d5f0764SLai Jiangshan 	link_pwq(ctx->dfl_pwq);
37902d5f0764SLai Jiangshan 	swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
37912d5f0764SLai Jiangshan 
37922d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
37932d5f0764SLai Jiangshan }
37942d5f0764SLai Jiangshan 
3795a0111cf6SLai Jiangshan static void apply_wqattrs_lock(void)
3796a0111cf6SLai Jiangshan {
3797a0111cf6SLai Jiangshan 	/* CPUs should stay stable across pwq creations and installations */
3798a0111cf6SLai Jiangshan 	get_online_cpus();
3799a0111cf6SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
3800a0111cf6SLai Jiangshan }
3801a0111cf6SLai Jiangshan 
3802a0111cf6SLai Jiangshan static void apply_wqattrs_unlock(void)
3803a0111cf6SLai Jiangshan {
3804a0111cf6SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
3805a0111cf6SLai Jiangshan 	put_online_cpus();
3806a0111cf6SLai Jiangshan }
3807a0111cf6SLai Jiangshan 
3808a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
3809a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
3810a0111cf6SLai Jiangshan {
3811a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
3812a0111cf6SLai Jiangshan 
3813a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
3814a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
3815a0111cf6SLai Jiangshan 		return -EINVAL;
3816a0111cf6SLai Jiangshan 
3817a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
38180a94efb5STejun Heo 	if (!list_empty(&wq->pwqs)) {
38190a94efb5STejun Heo 		if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
3820a0111cf6SLai Jiangshan 			return -EINVAL;
3821a0111cf6SLai Jiangshan 
38220a94efb5STejun Heo 		wq->flags &= ~__WQ_ORDERED;
38230a94efb5STejun Heo 	}
38240a94efb5STejun Heo 
3825a0111cf6SLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs);
38266201171eSwanghaibin 	if (!ctx)
38276201171eSwanghaibin 		return -ENOMEM;
3828a0111cf6SLai Jiangshan 
3829a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
3830a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
3831a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
3832a0111cf6SLai Jiangshan 
38336201171eSwanghaibin 	return 0;
3834a0111cf6SLai Jiangshan }
3835a0111cf6SLai Jiangshan 
38369e8cd2f5STejun Heo /**
38379e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
38389e8cd2f5STejun Heo  * @wq: the target workqueue
38399e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
38409e8cd2f5STejun Heo  *
38414c16bd32STejun Heo  * Apply @attrs to an unbound workqueue @wq.  Unless disabled, on NUMA
38424c16bd32STejun Heo  * machines, this function maps a separate pwq to each NUMA node with
38434c16bd32STejun Heo  * possibles CPUs in @attrs->cpumask so that work items are affine to the
38444c16bd32STejun Heo  * NUMA node it was issued on.  Older pwqs are released as in-flight work
38454c16bd32STejun Heo  * items finish.  Note that a work item which repeatedly requeues itself
38464c16bd32STejun Heo  * back-to-back will stay on its current pwq.
38479e8cd2f5STejun Heo  *
3848d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
3849d185af30SYacine Belkadi  *
3850d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
38519e8cd2f5STejun Heo  */
38529e8cd2f5STejun Heo int apply_workqueue_attrs(struct workqueue_struct *wq,
38539e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
38549e8cd2f5STejun Heo {
3855a0111cf6SLai Jiangshan 	int ret;
38569e8cd2f5STejun Heo 
3857a0111cf6SLai Jiangshan 	apply_wqattrs_lock();
3858a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
3859a0111cf6SLai Jiangshan 	apply_wqattrs_unlock();
38602d5f0764SLai Jiangshan 
38612d5f0764SLai Jiangshan 	return ret;
38629e8cd2f5STejun Heo }
38636106c0f8SNeilBrown EXPORT_SYMBOL_GPL(apply_workqueue_attrs);
38649e8cd2f5STejun Heo 
38654c16bd32STejun Heo /**
38664c16bd32STejun Heo  * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
38674c16bd32STejun Heo  * @wq: the target workqueue
38684c16bd32STejun Heo  * @cpu: the CPU coming up or going down
38694c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
38704c16bd32STejun Heo  *
38714c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
38724c16bd32STejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update NUMA affinity of
38734c16bd32STejun Heo  * @wq accordingly.
38744c16bd32STejun Heo  *
38754c16bd32STejun Heo  * If NUMA affinity can't be adjusted due to memory allocation failure, it
38764c16bd32STejun Heo  * falls back to @wq->dfl_pwq which may not be optimal but is always
38774c16bd32STejun Heo  * correct.
38784c16bd32STejun Heo  *
38794c16bd32STejun Heo  * Note that when the last allowed CPU of a NUMA node goes offline for a
38804c16bd32STejun Heo  * workqueue with a cpumask spanning multiple nodes, the workers which were
38814c16bd32STejun Heo  * already executing the work items for the workqueue will lose their CPU
38824c16bd32STejun Heo  * affinity and may execute on any CPU.  This is similar to how per-cpu
38834c16bd32STejun Heo  * workqueues behave on CPU_DOWN.  If a workqueue user wants strict
38844c16bd32STejun Heo  * affinity, it's the user's responsibility to flush the work item from
38854c16bd32STejun Heo  * CPU_DOWN_PREPARE.
38864c16bd32STejun Heo  */
38874c16bd32STejun Heo static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu,
38884c16bd32STejun Heo 				   bool online)
38894c16bd32STejun Heo {
38904c16bd32STejun Heo 	int node = cpu_to_node(cpu);
38914c16bd32STejun Heo 	int cpu_off = online ? -1 : cpu;
38924c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
38934c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
38944c16bd32STejun Heo 	cpumask_t *cpumask;
38954c16bd32STejun Heo 
38964c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
38974c16bd32STejun Heo 
3898f7142ed4SLai Jiangshan 	if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) ||
3899f7142ed4SLai Jiangshan 	    wq->unbound_attrs->no_numa)
39004c16bd32STejun Heo 		return;
39014c16bd32STejun Heo 
39024c16bd32STejun Heo 	/*
39034c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
39044c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
39054c16bd32STejun Heo 	 * CPU hotplug exclusion.
39064c16bd32STejun Heo 	 */
39074c16bd32STejun Heo 	target_attrs = wq_update_unbound_numa_attrs_buf;
39084c16bd32STejun Heo 	cpumask = target_attrs->cpumask;
39094c16bd32STejun Heo 
39104c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
39114c16bd32STejun Heo 	pwq = unbound_pwq_by_node(wq, node);
39124c16bd32STejun Heo 
39134c16bd32STejun Heo 	/*
39144c16bd32STejun Heo 	 * Let's determine what needs to be done.  If the target cpumask is
3915042f7df1SLai Jiangshan 	 * different from the default pwq's, we need to compare it to @pwq's
3916042f7df1SLai Jiangshan 	 * and create a new one if they don't match.  If the target cpumask
3917042f7df1SLai Jiangshan 	 * equals the default pwq's, the default pwq should be used.
39184c16bd32STejun Heo 	 */
3919042f7df1SLai Jiangshan 	if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) {
39204c16bd32STejun Heo 		if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask))
3921f7142ed4SLai Jiangshan 			return;
39224c16bd32STejun Heo 	} else {
39234c16bd32STejun Heo 		goto use_dfl_pwq;
39244c16bd32STejun Heo 	}
39254c16bd32STejun Heo 
39264c16bd32STejun Heo 	/* create a new pwq */
39274c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
39284c16bd32STejun Heo 	if (!pwq) {
39292d916033SFabian Frederick 		pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
39304c16bd32STejun Heo 			wq->name);
393177f300b1SDaeseok Youn 		goto use_dfl_pwq;
39324c16bd32STejun Heo 	}
39334c16bd32STejun Heo 
3934f7142ed4SLai Jiangshan 	/* Install the new pwq. */
39354c16bd32STejun Heo 	mutex_lock(&wq->mutex);
39364c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, pwq);
39374c16bd32STejun Heo 	goto out_unlock;
39384c16bd32STejun Heo 
39394c16bd32STejun Heo use_dfl_pwq:
3940f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
39414c16bd32STejun Heo 	spin_lock_irq(&wq->dfl_pwq->pool->lock);
39424c16bd32STejun Heo 	get_pwq(wq->dfl_pwq);
39434c16bd32STejun Heo 	spin_unlock_irq(&wq->dfl_pwq->pool->lock);
39444c16bd32STejun Heo 	old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq);
39454c16bd32STejun Heo out_unlock:
39464c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
39474c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
39484c16bd32STejun Heo }
39494c16bd32STejun Heo 
395030cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
39511da177e4SLinus Torvalds {
395249e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
39538a2b7538STejun Heo 	int cpu, ret;
3954e1d8aa9fSFrederic Weisbecker 
395530cdf249STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
3956420c0ddbSTejun Heo 		wq->cpu_pwqs = alloc_percpu(struct pool_workqueue);
3957420c0ddbSTejun Heo 		if (!wq->cpu_pwqs)
395830cdf249STejun Heo 			return -ENOMEM;
395930cdf249STejun Heo 
396030cdf249STejun Heo 		for_each_possible_cpu(cpu) {
39617fb98ea7STejun Heo 			struct pool_workqueue *pwq =
39627fb98ea7STejun Heo 				per_cpu_ptr(wq->cpu_pwqs, cpu);
39637a62c2c8STejun Heo 			struct worker_pool *cpu_pools =
3964f02ae73aSTejun Heo 				per_cpu(cpu_worker_pools, cpu);
396530cdf249STejun Heo 
3966f147f29eSTejun Heo 			init_pwq(pwq, wq, &cpu_pools[highpri]);
3967f147f29eSTejun Heo 
3968f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
39691befcf30STejun Heo 			link_pwq(pwq);
3970f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
397130cdf249STejun Heo 		}
397230cdf249STejun Heo 		return 0;
39738a2b7538STejun Heo 	} else if (wq->flags & __WQ_ORDERED) {
39748a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
39758a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
39768a2b7538STejun Heo 		WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
39778a2b7538STejun Heo 			      wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
39788a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
39798a2b7538STejun Heo 		return ret;
39809e8cd2f5STejun Heo 	} else {
39819e8cd2f5STejun Heo 		return apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
39829e8cd2f5STejun Heo 	}
39830f900049STejun Heo }
39840f900049STejun Heo 
3985f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
3986f3421797STejun Heo 			       const char *name)
3987b71ab8c2STejun Heo {
3988f3421797STejun Heo 	int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
3989f3421797STejun Heo 
3990f3421797STejun Heo 	if (max_active < 1 || max_active > lim)
3991044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3992f3421797STejun Heo 			max_active, name, 1, lim);
3993b71ab8c2STejun Heo 
3994f3421797STejun Heo 	return clamp_val(max_active, 1, lim);
3995b71ab8c2STejun Heo }
3996b71ab8c2STejun Heo 
3997983c7515STejun Heo /*
3998983c7515STejun Heo  * Workqueues which may be used during memory reclaim should have a rescuer
3999983c7515STejun Heo  * to guarantee forward progress.
4000983c7515STejun Heo  */
4001983c7515STejun Heo static int init_rescuer(struct workqueue_struct *wq)
4002983c7515STejun Heo {
4003983c7515STejun Heo 	struct worker *rescuer;
4004983c7515STejun Heo 	int ret;
4005983c7515STejun Heo 
4006983c7515STejun Heo 	if (!(wq->flags & WQ_MEM_RECLAIM))
4007983c7515STejun Heo 		return 0;
4008983c7515STejun Heo 
4009983c7515STejun Heo 	rescuer = alloc_worker(NUMA_NO_NODE);
4010983c7515STejun Heo 	if (!rescuer)
4011983c7515STejun Heo 		return -ENOMEM;
4012983c7515STejun Heo 
4013983c7515STejun Heo 	rescuer->rescue_wq = wq;
4014983c7515STejun Heo 	rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name);
4015983c7515STejun Heo 	ret = PTR_ERR_OR_ZERO(rescuer->task);
4016983c7515STejun Heo 	if (ret) {
4017983c7515STejun Heo 		kfree(rescuer);
4018983c7515STejun Heo 		return ret;
4019983c7515STejun Heo 	}
4020983c7515STejun Heo 
4021983c7515STejun Heo 	wq->rescuer = rescuer;
4022983c7515STejun Heo 	kthread_bind_mask(rescuer->task, cpu_possible_mask);
4023983c7515STejun Heo 	wake_up_process(rescuer->task);
4024983c7515STejun Heo 
4025983c7515STejun Heo 	return 0;
4026983c7515STejun Heo }
4027983c7515STejun Heo 
4028b196be89STejun Heo struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
402997e37d7bSTejun Heo 					       unsigned int flags,
40301e19ffc6STejun Heo 					       int max_active,
4031eb13ba87SJohannes Berg 					       struct lock_class_key *key,
4032b196be89STejun Heo 					       const char *lock_name, ...)
40333af24433SOleg Nesterov {
4034df2d5ae4STejun Heo 	size_t tbl_size = 0;
4035ecf6881fSTejun Heo 	va_list args;
40363af24433SOleg Nesterov 	struct workqueue_struct *wq;
403749e3cf44STejun Heo 	struct pool_workqueue *pwq;
4038b196be89STejun Heo 
40395c0338c6STejun Heo 	/*
40405c0338c6STejun Heo 	 * Unbound && max_active == 1 used to imply ordered, which is no
40415c0338c6STejun Heo 	 * longer the case on NUMA machines due to per-node pools.  While
40425c0338c6STejun Heo 	 * alloc_ordered_workqueue() is the right way to create an ordered
40435c0338c6STejun Heo 	 * workqueue, keep the previous behavior to avoid subtle breakages
40445c0338c6STejun Heo 	 * on NUMA.
40455c0338c6STejun Heo 	 */
40465c0338c6STejun Heo 	if ((flags & WQ_UNBOUND) && max_active == 1)
40475c0338c6STejun Heo 		flags |= __WQ_ORDERED;
40485c0338c6STejun Heo 
4049cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
4050cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4051cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
4052cee22a15SViresh Kumar 
4053ecf6881fSTejun Heo 	/* allocate wq and format name */
4054df2d5ae4STejun Heo 	if (flags & WQ_UNBOUND)
4055ddcb57e2SLai Jiangshan 		tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]);
4056df2d5ae4STejun Heo 
4057df2d5ae4STejun Heo 	wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL);
4058b196be89STejun Heo 	if (!wq)
4059d2c1d404STejun Heo 		return NULL;
4060b196be89STejun Heo 
40616029a918STejun Heo 	if (flags & WQ_UNBOUND) {
40626029a918STejun Heo 		wq->unbound_attrs = alloc_workqueue_attrs(GFP_KERNEL);
40636029a918STejun Heo 		if (!wq->unbound_attrs)
40646029a918STejun Heo 			goto err_free_wq;
40656029a918STejun Heo 	}
40666029a918STejun Heo 
4067ecf6881fSTejun Heo 	va_start(args, lock_name);
4068ecf6881fSTejun Heo 	vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4069b196be89STejun Heo 	va_end(args);
40703af24433SOleg Nesterov 
4071d320c038STejun Heo 	max_active = max_active ?: WQ_DFL_ACTIVE;
4072b196be89STejun Heo 	max_active = wq_clamp_max_active(max_active, flags, wq->name);
40733af24433SOleg Nesterov 
4074b196be89STejun Heo 	/* init wq */
407597e37d7bSTejun Heo 	wq->flags = flags;
4076a0a1a5fdSTejun Heo 	wq->saved_max_active = max_active;
40773c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
4078112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
407930cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
408073f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
408173f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
4082493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
40833af24433SOleg Nesterov 
4084eb13ba87SJohannes Berg 	lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
4085cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
40863af24433SOleg Nesterov 
408730cdf249STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
4088d2c1d404STejun Heo 		goto err_free_wq;
40891537663fSTejun Heo 
409040c17f75STejun Heo 	if (wq_online && init_rescuer(wq) < 0)
4091d2c1d404STejun Heo 		goto err_destroy;
4092e22bee78STejun Heo 
4093226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4094226223abSTejun Heo 		goto err_destroy;
4095226223abSTejun Heo 
40966af8bf3dSOleg Nesterov 	/*
409768e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
409868e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
409968e13a67SLai Jiangshan 	 * list.
41006af8bf3dSOleg Nesterov 	 */
410168e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4102a0a1a5fdSTejun Heo 
4103a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
410449e3cf44STejun Heo 	for_each_pwq(pwq, wq)
4105699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4106a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4107a0a1a5fdSTejun Heo 
4108e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
4109a0a1a5fdSTejun Heo 
411068e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
41113af24433SOleg Nesterov 
41123af24433SOleg Nesterov 	return wq;
4113d2c1d404STejun Heo 
4114d2c1d404STejun Heo err_free_wq:
41156029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
41164690c4abSTejun Heo 	kfree(wq);
4117d2c1d404STejun Heo 	return NULL;
4118d2c1d404STejun Heo err_destroy:
4119d2c1d404STejun Heo 	destroy_workqueue(wq);
41204690c4abSTejun Heo 	return NULL;
41211da177e4SLinus Torvalds }
4122d320c038STejun Heo EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
41231da177e4SLinus Torvalds 
41243af24433SOleg Nesterov /**
41253af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
41263af24433SOleg Nesterov  * @wq: target workqueue
41273af24433SOleg Nesterov  *
41283af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
41293af24433SOleg Nesterov  */
41303af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
41313af24433SOleg Nesterov {
413249e3cf44STejun Heo 	struct pool_workqueue *pwq;
41334c16bd32STejun Heo 	int node;
41343af24433SOleg Nesterov 
41359c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
41369c5a2ba7STejun Heo 	drain_workqueue(wq);
4137c8efcc25STejun Heo 
41386183c009STejun Heo 	/* sanity checks */
4139b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
414049e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
41416183c009STejun Heo 		int i;
41426183c009STejun Heo 
414376af4d93STejun Heo 		for (i = 0; i < WORK_NR_COLORS; i++) {
414476af4d93STejun Heo 			if (WARN_ON(pwq->nr_in_flight[i])) {
4145b09f4fd3SLai Jiangshan 				mutex_unlock(&wq->mutex);
4146fa07fb6aSTejun Heo 				show_workqueue_state();
41476183c009STejun Heo 				return;
414876af4d93STejun Heo 			}
414976af4d93STejun Heo 		}
415076af4d93STejun Heo 
41515c529597SLai Jiangshan 		if (WARN_ON((pwq != wq->dfl_pwq) && (pwq->refcnt > 1)) ||
41528864b4e5STejun Heo 		    WARN_ON(pwq->nr_active) ||
415376af4d93STejun Heo 		    WARN_ON(!list_empty(&pwq->delayed_works))) {
4154b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
4155fa07fb6aSTejun Heo 			show_workqueue_state();
41566183c009STejun Heo 			return;
41576183c009STejun Heo 		}
415876af4d93STejun Heo 	}
4159b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
41606183c009STejun Heo 
4161a0a1a5fdSTejun Heo 	/*
4162a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
4163a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
4164a0a1a5fdSTejun Heo 	 */
416568e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4166e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
416768e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
41683af24433SOleg Nesterov 
4169226223abSTejun Heo 	workqueue_sysfs_unregister(wq);
4170226223abSTejun Heo 
4171e2dca7adSTejun Heo 	if (wq->rescuer)
4172e22bee78STejun Heo 		kthread_stop(wq->rescuer->task);
4173e22bee78STejun Heo 
41748864b4e5STejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
417529c91e99STejun Heo 		/*
41768864b4e5STejun Heo 		 * The base ref is never dropped on per-cpu pwqs.  Directly
4177e2dca7adSTejun Heo 		 * schedule RCU free.
417829c91e99STejun Heo 		 */
4179e2dca7adSTejun Heo 		call_rcu_sched(&wq->rcu, rcu_free_wq);
41808864b4e5STejun Heo 	} else {
41818864b4e5STejun Heo 		/*
41828864b4e5STejun Heo 		 * We're the sole accessor of @wq at this point.  Directly
41834c16bd32STejun Heo 		 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
41844c16bd32STejun Heo 		 * @wq will be freed when the last pwq is released.
41858864b4e5STejun Heo 		 */
41864c16bd32STejun Heo 		for_each_node(node) {
41874c16bd32STejun Heo 			pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]);
41884c16bd32STejun Heo 			RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL);
41894c16bd32STejun Heo 			put_pwq_unlocked(pwq);
41904c16bd32STejun Heo 		}
41914c16bd32STejun Heo 
41924c16bd32STejun Heo 		/*
41934c16bd32STejun Heo 		 * Put dfl_pwq.  @wq may be freed any time after dfl_pwq is
41944c16bd32STejun Heo 		 * put.  Don't access it afterwards.
41954c16bd32STejun Heo 		 */
41964c16bd32STejun Heo 		pwq = wq->dfl_pwq;
41974c16bd32STejun Heo 		wq->dfl_pwq = NULL;
4198dce90d47STejun Heo 		put_pwq_unlocked(pwq);
419929c91e99STejun Heo 	}
42003af24433SOleg Nesterov }
42013af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
42023af24433SOleg Nesterov 
4203dcd989cbSTejun Heo /**
4204dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
4205dcd989cbSTejun Heo  * @wq: target workqueue
4206dcd989cbSTejun Heo  * @max_active: new max_active value.
4207dcd989cbSTejun Heo  *
4208dcd989cbSTejun Heo  * Set max_active of @wq to @max_active.
4209dcd989cbSTejun Heo  *
4210dcd989cbSTejun Heo  * CONTEXT:
4211dcd989cbSTejun Heo  * Don't call from IRQ context.
4212dcd989cbSTejun Heo  */
4213dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4214dcd989cbSTejun Heo {
421549e3cf44STejun Heo 	struct pool_workqueue *pwq;
4216dcd989cbSTejun Heo 
42178719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
42180a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
42198719dceaSTejun Heo 		return;
42208719dceaSTejun Heo 
4221f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4222dcd989cbSTejun Heo 
4223a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
4224dcd989cbSTejun Heo 
42250a94efb5STejun Heo 	wq->flags &= ~__WQ_ORDERED;
4226dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
4227dcd989cbSTejun Heo 
4228699ce097STejun Heo 	for_each_pwq(pwq, wq)
4229699ce097STejun Heo 		pwq_adjust_max_active(pwq);
4230dcd989cbSTejun Heo 
4231a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
4232dcd989cbSTejun Heo }
4233dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4234dcd989cbSTejun Heo 
4235dcd989cbSTejun Heo /**
423627d4ee03SLukas Wunner  * current_work - retrieve %current task's work struct
423727d4ee03SLukas Wunner  *
423827d4ee03SLukas Wunner  * Determine if %current task is a workqueue worker and what it's working on.
423927d4ee03SLukas Wunner  * Useful to find out the context that the %current task is running in.
424027d4ee03SLukas Wunner  *
424127d4ee03SLukas Wunner  * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
424227d4ee03SLukas Wunner  */
424327d4ee03SLukas Wunner struct work_struct *current_work(void)
424427d4ee03SLukas Wunner {
424527d4ee03SLukas Wunner 	struct worker *worker = current_wq_worker();
424627d4ee03SLukas Wunner 
424727d4ee03SLukas Wunner 	return worker ? worker->current_work : NULL;
424827d4ee03SLukas Wunner }
424927d4ee03SLukas Wunner EXPORT_SYMBOL(current_work);
425027d4ee03SLukas Wunner 
425127d4ee03SLukas Wunner /**
4252e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
4253e6267616STejun Heo  *
4254e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
4255e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
4256d185af30SYacine Belkadi  *
4257d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
4258e6267616STejun Heo  */
4259e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4260e6267616STejun Heo {
4261e6267616STejun Heo 	struct worker *worker = current_wq_worker();
4262e6267616STejun Heo 
42636a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
4264e6267616STejun Heo }
4265e6267616STejun Heo 
4266e6267616STejun Heo /**
4267dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
4268dcd989cbSTejun Heo  * @cpu: CPU in question
4269dcd989cbSTejun Heo  * @wq: target workqueue
4270dcd989cbSTejun Heo  *
4271dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
4272dcd989cbSTejun Heo  * no synchronization around this function and the test result is
4273dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4274dcd989cbSTejun Heo  *
4275d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4276d3251859STejun Heo  * Note that both per-cpu and unbound workqueues may be associated with
4277d3251859STejun Heo  * multiple pool_workqueues which have separate congested states.  A
4278d3251859STejun Heo  * workqueue being congested on one CPU doesn't mean the workqueue is also
4279d3251859STejun Heo  * contested on other CPUs / NUMA nodes.
4280d3251859STejun Heo  *
4281d185af30SYacine Belkadi  * Return:
4282dcd989cbSTejun Heo  * %true if congested, %false otherwise.
4283dcd989cbSTejun Heo  */
4284d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4285dcd989cbSTejun Heo {
42867fb98ea7STejun Heo 	struct pool_workqueue *pwq;
428776af4d93STejun Heo 	bool ret;
428876af4d93STejun Heo 
428988109453SLai Jiangshan 	rcu_read_lock_sched();
42907fb98ea7STejun Heo 
4291d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
4292d3251859STejun Heo 		cpu = smp_processor_id();
4293d3251859STejun Heo 
42947fb98ea7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
42957fb98ea7STejun Heo 		pwq = per_cpu_ptr(wq->cpu_pwqs, cpu);
42967fb98ea7STejun Heo 	else
4297df2d5ae4STejun Heo 		pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu));
4298dcd989cbSTejun Heo 
429976af4d93STejun Heo 	ret = !list_empty(&pwq->delayed_works);
430088109453SLai Jiangshan 	rcu_read_unlock_sched();
430176af4d93STejun Heo 
430276af4d93STejun Heo 	return ret;
4303dcd989cbSTejun Heo }
4304dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4305dcd989cbSTejun Heo 
4306dcd989cbSTejun Heo /**
4307dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
4308dcd989cbSTejun Heo  * @work: the work to be tested
4309dcd989cbSTejun Heo  *
4310dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
4311dcd989cbSTejun Heo  * synchronization around this function and the test result is
4312dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
4313dcd989cbSTejun Heo  *
4314d185af30SYacine Belkadi  * Return:
4315dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
4316dcd989cbSTejun Heo  */
4317dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4318dcd989cbSTejun Heo {
4319fa1b54e6STejun Heo 	struct worker_pool *pool;
4320dcd989cbSTejun Heo 	unsigned long flags;
4321dcd989cbSTejun Heo 	unsigned int ret = 0;
4322dcd989cbSTejun Heo 
4323dcd989cbSTejun Heo 	if (work_pending(work))
4324dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
4325038366c5SLai Jiangshan 
4326fa1b54e6STejun Heo 	local_irq_save(flags);
4327fa1b54e6STejun Heo 	pool = get_work_pool(work);
4328038366c5SLai Jiangshan 	if (pool) {
4329fa1b54e6STejun Heo 		spin_lock(&pool->lock);
4330c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
4331dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
4332fa1b54e6STejun Heo 		spin_unlock(&pool->lock);
4333038366c5SLai Jiangshan 	}
4334fa1b54e6STejun Heo 	local_irq_restore(flags);
4335dcd989cbSTejun Heo 
4336dcd989cbSTejun Heo 	return ret;
4337dcd989cbSTejun Heo }
4338dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
4339dcd989cbSTejun Heo 
43403d1cb205STejun Heo /**
43413d1cb205STejun Heo  * set_worker_desc - set description for the current work item
43423d1cb205STejun Heo  * @fmt: printf-style format string
43433d1cb205STejun Heo  * @...: arguments for the format string
43443d1cb205STejun Heo  *
43453d1cb205STejun Heo  * This function can be called by a running work function to describe what
43463d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
43473d1cb205STejun Heo  * information will be printed out together to help debugging.  The
43483d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
43493d1cb205STejun Heo  */
43503d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
43513d1cb205STejun Heo {
43523d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
43533d1cb205STejun Heo 	va_list args;
43543d1cb205STejun Heo 
43553d1cb205STejun Heo 	if (worker) {
43563d1cb205STejun Heo 		va_start(args, fmt);
43573d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
43583d1cb205STejun Heo 		va_end(args);
43593d1cb205STejun Heo 		worker->desc_valid = true;
43603d1cb205STejun Heo 	}
43613d1cb205STejun Heo }
43623d1cb205STejun Heo 
43633d1cb205STejun Heo /**
43643d1cb205STejun Heo  * print_worker_info - print out worker information and description
43653d1cb205STejun Heo  * @log_lvl: the log level to use when printing
43663d1cb205STejun Heo  * @task: target task
43673d1cb205STejun Heo  *
43683d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
43693d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
43703d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
43713d1cb205STejun Heo  *
43723d1cb205STejun Heo  * This function can be safely called on any task as long as the
43733d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
43743d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
43753d1cb205STejun Heo  */
43763d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
43773d1cb205STejun Heo {
43783d1cb205STejun Heo 	work_func_t *fn = NULL;
43793d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
43803d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
43813d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
43823d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
43833d1cb205STejun Heo 	bool desc_valid = false;
43843d1cb205STejun Heo 	struct worker *worker;
43853d1cb205STejun Heo 
43863d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
43873d1cb205STejun Heo 		return;
43883d1cb205STejun Heo 
43893d1cb205STejun Heo 	/*
43903d1cb205STejun Heo 	 * This function is called without any synchronization and @task
43913d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
43923d1cb205STejun Heo 	 */
4393e700591aSPetr Mladek 	worker = kthread_probe_data(task);
43943d1cb205STejun Heo 
43953d1cb205STejun Heo 	/*
43963d1cb205STejun Heo 	 * Carefully copy the associated workqueue's workfn and name.  Keep
43973d1cb205STejun Heo 	 * the original last '\0' in case the original contains garbage.
43983d1cb205STejun Heo 	 */
43993d1cb205STejun Heo 	probe_kernel_read(&fn, &worker->current_func, sizeof(fn));
44003d1cb205STejun Heo 	probe_kernel_read(&pwq, &worker->current_pwq, sizeof(pwq));
44013d1cb205STejun Heo 	probe_kernel_read(&wq, &pwq->wq, sizeof(wq));
44023d1cb205STejun Heo 	probe_kernel_read(name, wq->name, sizeof(name) - 1);
44033d1cb205STejun Heo 
44043d1cb205STejun Heo 	/* copy worker description */
44053d1cb205STejun Heo 	probe_kernel_read(&desc_valid, &worker->desc_valid, sizeof(desc_valid));
44063d1cb205STejun Heo 	if (desc_valid)
44073d1cb205STejun Heo 		probe_kernel_read(desc, worker->desc, sizeof(desc) - 1);
44083d1cb205STejun Heo 
44093d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
44103d1cb205STejun Heo 		printk("%sWorkqueue: %s %pf", log_lvl, name, fn);
44113d1cb205STejun Heo 		if (desc[0])
44123d1cb205STejun Heo 			pr_cont(" (%s)", desc);
44133d1cb205STejun Heo 		pr_cont("\n");
44143d1cb205STejun Heo 	}
44153d1cb205STejun Heo }
44163d1cb205STejun Heo 
44173494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
44183494fc30STejun Heo {
44193494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
44203494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
44213494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
44223494fc30STejun Heo 	pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
44233494fc30STejun Heo }
44243494fc30STejun Heo 
44253494fc30STejun Heo static void pr_cont_work(bool comma, struct work_struct *work)
44263494fc30STejun Heo {
44273494fc30STejun Heo 	if (work->func == wq_barrier_func) {
44283494fc30STejun Heo 		struct wq_barrier *barr;
44293494fc30STejun Heo 
44303494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
44313494fc30STejun Heo 
44323494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
44333494fc30STejun Heo 			task_pid_nr(barr->task));
44343494fc30STejun Heo 	} else {
44353494fc30STejun Heo 		pr_cont("%s %pf", comma ? "," : "", work->func);
44363494fc30STejun Heo 	}
44373494fc30STejun Heo }
44383494fc30STejun Heo 
44393494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
44403494fc30STejun Heo {
44413494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
44423494fc30STejun Heo 	struct work_struct *work;
44433494fc30STejun Heo 	struct worker *worker;
44443494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
44453494fc30STejun Heo 	int bkt;
44463494fc30STejun Heo 
44473494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
44483494fc30STejun Heo 	pr_cont_pool_info(pool);
44493494fc30STejun Heo 
44503494fc30STejun Heo 	pr_cont(" active=%d/%d%s\n", pwq->nr_active, pwq->max_active,
44513494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
44523494fc30STejun Heo 
44533494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
44543494fc30STejun Heo 		if (worker->current_pwq == pwq) {
44553494fc30STejun Heo 			has_in_flight = true;
44563494fc30STejun Heo 			break;
44573494fc30STejun Heo 		}
44583494fc30STejun Heo 	}
44593494fc30STejun Heo 	if (has_in_flight) {
44603494fc30STejun Heo 		bool comma = false;
44613494fc30STejun Heo 
44623494fc30STejun Heo 		pr_info("    in-flight:");
44633494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
44643494fc30STejun Heo 			if (worker->current_pwq != pwq)
44653494fc30STejun Heo 				continue;
44663494fc30STejun Heo 
44673494fc30STejun Heo 			pr_cont("%s %d%s:%pf", comma ? "," : "",
44683494fc30STejun Heo 				task_pid_nr(worker->task),
44693494fc30STejun Heo 				worker == pwq->wq->rescuer ? "(RESCUER)" : "",
44703494fc30STejun Heo 				worker->current_func);
44713494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
44723494fc30STejun Heo 				pr_cont_work(false, work);
44733494fc30STejun Heo 			comma = true;
44743494fc30STejun Heo 		}
44753494fc30STejun Heo 		pr_cont("\n");
44763494fc30STejun Heo 	}
44773494fc30STejun Heo 
44783494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
44793494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
44803494fc30STejun Heo 			has_pending = true;
44813494fc30STejun Heo 			break;
44823494fc30STejun Heo 		}
44833494fc30STejun Heo 	}
44843494fc30STejun Heo 	if (has_pending) {
44853494fc30STejun Heo 		bool comma = false;
44863494fc30STejun Heo 
44873494fc30STejun Heo 		pr_info("    pending:");
44883494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
44893494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
44903494fc30STejun Heo 				continue;
44913494fc30STejun Heo 
44923494fc30STejun Heo 			pr_cont_work(comma, work);
44933494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
44943494fc30STejun Heo 		}
44953494fc30STejun Heo 		pr_cont("\n");
44963494fc30STejun Heo 	}
44973494fc30STejun Heo 
44983494fc30STejun Heo 	if (!list_empty(&pwq->delayed_works)) {
44993494fc30STejun Heo 		bool comma = false;
45003494fc30STejun Heo 
45013494fc30STejun Heo 		pr_info("    delayed:");
45023494fc30STejun Heo 		list_for_each_entry(work, &pwq->delayed_works, entry) {
45033494fc30STejun Heo 			pr_cont_work(comma, work);
45043494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
45053494fc30STejun Heo 		}
45063494fc30STejun Heo 		pr_cont("\n");
45073494fc30STejun Heo 	}
45083494fc30STejun Heo }
45093494fc30STejun Heo 
45103494fc30STejun Heo /**
45113494fc30STejun Heo  * show_workqueue_state - dump workqueue state
45123494fc30STejun Heo  *
45137b776af6SRoger Lu  * Called from a sysrq handler or try_to_freeze_tasks() and prints out
45147b776af6SRoger Lu  * all busy workqueues and pools.
45153494fc30STejun Heo  */
45163494fc30STejun Heo void show_workqueue_state(void)
45173494fc30STejun Heo {
45183494fc30STejun Heo 	struct workqueue_struct *wq;
45193494fc30STejun Heo 	struct worker_pool *pool;
45203494fc30STejun Heo 	unsigned long flags;
45213494fc30STejun Heo 	int pi;
45223494fc30STejun Heo 
45233494fc30STejun Heo 	rcu_read_lock_sched();
45243494fc30STejun Heo 
45253494fc30STejun Heo 	pr_info("Showing busy workqueues and worker pools:\n");
45263494fc30STejun Heo 
45273494fc30STejun Heo 	list_for_each_entry_rcu(wq, &workqueues, list) {
45283494fc30STejun Heo 		struct pool_workqueue *pwq;
45293494fc30STejun Heo 		bool idle = true;
45303494fc30STejun Heo 
45313494fc30STejun Heo 		for_each_pwq(pwq, wq) {
45323494fc30STejun Heo 			if (pwq->nr_active || !list_empty(&pwq->delayed_works)) {
45333494fc30STejun Heo 				idle = false;
45343494fc30STejun Heo 				break;
45353494fc30STejun Heo 			}
45363494fc30STejun Heo 		}
45373494fc30STejun Heo 		if (idle)
45383494fc30STejun Heo 			continue;
45393494fc30STejun Heo 
45403494fc30STejun Heo 		pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
45413494fc30STejun Heo 
45423494fc30STejun Heo 		for_each_pwq(pwq, wq) {
45433494fc30STejun Heo 			spin_lock_irqsave(&pwq->pool->lock, flags);
45443494fc30STejun Heo 			if (pwq->nr_active || !list_empty(&pwq->delayed_works))
45453494fc30STejun Heo 				show_pwq(pwq);
45463494fc30STejun Heo 			spin_unlock_irqrestore(&pwq->pool->lock, flags);
454762635ea8SSergey Senozhatsky 			/*
454862635ea8SSergey Senozhatsky 			 * We could be printing a lot from atomic context, e.g.
454962635ea8SSergey Senozhatsky 			 * sysrq-t -> show_workqueue_state(). Avoid triggering
455062635ea8SSergey Senozhatsky 			 * hard lockup.
455162635ea8SSergey Senozhatsky 			 */
455262635ea8SSergey Senozhatsky 			touch_nmi_watchdog();
45533494fc30STejun Heo 		}
45543494fc30STejun Heo 	}
45553494fc30STejun Heo 
45563494fc30STejun Heo 	for_each_pool(pool, pi) {
45573494fc30STejun Heo 		struct worker *worker;
45583494fc30STejun Heo 		bool first = true;
45593494fc30STejun Heo 
45603494fc30STejun Heo 		spin_lock_irqsave(&pool->lock, flags);
45613494fc30STejun Heo 		if (pool->nr_workers == pool->nr_idle)
45623494fc30STejun Heo 			goto next_pool;
45633494fc30STejun Heo 
45643494fc30STejun Heo 		pr_info("pool %d:", pool->id);
45653494fc30STejun Heo 		pr_cont_pool_info(pool);
456682607adcSTejun Heo 		pr_cont(" hung=%us workers=%d",
456782607adcSTejun Heo 			jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000,
456882607adcSTejun Heo 			pool->nr_workers);
45693494fc30STejun Heo 		if (pool->manager)
45703494fc30STejun Heo 			pr_cont(" manager: %d",
45713494fc30STejun Heo 				task_pid_nr(pool->manager->task));
45723494fc30STejun Heo 		list_for_each_entry(worker, &pool->idle_list, entry) {
45733494fc30STejun Heo 			pr_cont(" %s%d", first ? "idle: " : "",
45743494fc30STejun Heo 				task_pid_nr(worker->task));
45753494fc30STejun Heo 			first = false;
45763494fc30STejun Heo 		}
45773494fc30STejun Heo 		pr_cont("\n");
45783494fc30STejun Heo 	next_pool:
45793494fc30STejun Heo 		spin_unlock_irqrestore(&pool->lock, flags);
458062635ea8SSergey Senozhatsky 		/*
458162635ea8SSergey Senozhatsky 		 * We could be printing a lot from atomic context, e.g.
458262635ea8SSergey Senozhatsky 		 * sysrq-t -> show_workqueue_state(). Avoid triggering
458362635ea8SSergey Senozhatsky 		 * hard lockup.
458462635ea8SSergey Senozhatsky 		 */
458562635ea8SSergey Senozhatsky 		touch_nmi_watchdog();
45863494fc30STejun Heo 	}
45873494fc30STejun Heo 
45883494fc30STejun Heo 	rcu_read_unlock_sched();
45893494fc30STejun Heo }
45903494fc30STejun Heo 
4591db7bccf4STejun Heo /*
4592db7bccf4STejun Heo  * CPU hotplug.
4593db7bccf4STejun Heo  *
4594e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
4595112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
4596706026c2STejun Heo  * pool which make migrating pending and scheduled works very
4597e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
459894cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
4599e22bee78STejun Heo  * blocked draining impractical.
4600e22bee78STejun Heo  *
460124647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
4602628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
4603628c78e7STejun Heo  * cpu comes back online.
4604db7bccf4STejun Heo  */
4605db7bccf4STejun Heo 
4606e8b3f8dbSLai Jiangshan static void unbind_workers(int cpu)
4607db7bccf4STejun Heo {
46084ce62e9eSTejun Heo 	struct worker_pool *pool;
4609db7bccf4STejun Heo 	struct worker *worker;
4610db7bccf4STejun Heo 
4611f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
461292f9c5c4SLai Jiangshan 		mutex_lock(&pool->attach_mutex);
461394cf58bbSTejun Heo 		spin_lock_irq(&pool->lock);
4614e22bee78STejun Heo 
4615f2d5a0eeSTejun Heo 		/*
461692f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
461794cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
461894cf58bbSTejun Heo 		 * except for the ones which are still executing works from
461994cf58bbSTejun Heo 		 * before the last CPU down must be on the cpu.  After
462094cf58bbSTejun Heo 		 * this, they may become diasporas.
4621f2d5a0eeSTejun Heo 		 */
4622da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
4623403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
4624db7bccf4STejun Heo 
462524647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
4626f2d5a0eeSTejun Heo 
462794cf58bbSTejun Heo 		spin_unlock_irq(&pool->lock);
462892f9c5c4SLai Jiangshan 		mutex_unlock(&pool->attach_mutex);
4629e22bee78STejun Heo 
4630e22bee78STejun Heo 		/*
4631eb283428SLai Jiangshan 		 * Call schedule() so that we cross rq->lock and thus can
4632eb283428SLai Jiangshan 		 * guarantee sched callbacks see the %WORKER_UNBOUND flag.
4633eb283428SLai Jiangshan 		 * This is necessary as scheduler callbacks may be invoked
4634eb283428SLai Jiangshan 		 * from other cpus.
4635628c78e7STejun Heo 		 */
4636628c78e7STejun Heo 		schedule();
4637628c78e7STejun Heo 
4638628c78e7STejun Heo 		/*
4639eb283428SLai Jiangshan 		 * Sched callbacks are disabled now.  Zap nr_running.
4640eb283428SLai Jiangshan 		 * After this, nr_running stays zero and need_more_worker()
4641eb283428SLai Jiangshan 		 * and keep_working() are always true as long as the
4642eb283428SLai Jiangshan 		 * worklist is not empty.  This pool now behaves as an
4643eb283428SLai Jiangshan 		 * unbound (in terms of concurrency management) pool which
4644eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
4645e22bee78STejun Heo 		 */
4646e19e397aSTejun Heo 		atomic_set(&pool->nr_running, 0);
4647eb283428SLai Jiangshan 
4648eb283428SLai Jiangshan 		/*
4649eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
4650eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
4651eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
4652eb283428SLai Jiangshan 		 */
4653eb283428SLai Jiangshan 		spin_lock_irq(&pool->lock);
4654eb283428SLai Jiangshan 		wake_up_worker(pool);
4655eb283428SLai Jiangshan 		spin_unlock_irq(&pool->lock);
4656eb283428SLai Jiangshan 	}
4657db7bccf4STejun Heo }
4658db7bccf4STejun Heo 
4659bd7c089eSTejun Heo /**
4660bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
4661bd7c089eSTejun Heo  * @pool: pool of interest
4662bd7c089eSTejun Heo  *
4663a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
4664bd7c089eSTejun Heo  */
4665bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
4666bd7c089eSTejun Heo {
4667a9ab775bSTejun Heo 	struct worker *worker;
4668bd7c089eSTejun Heo 
466992f9c5c4SLai Jiangshan 	lockdep_assert_held(&pool->attach_mutex);
4670bd7c089eSTejun Heo 
4671bd7c089eSTejun Heo 	/*
4672a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
4673a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
4674402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
4675a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
4676a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
4677bd7c089eSTejun Heo 	 */
4678da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
4679a9ab775bSTejun Heo 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
4680a9ab775bSTejun Heo 						  pool->attrs->cpumask) < 0);
4681a9ab775bSTejun Heo 
4682a9ab775bSTejun Heo 	spin_lock_irq(&pool->lock);
4683f7c17d26SWanpeng Li 
46843de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
4685a9ab775bSTejun Heo 
4686da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
4687a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
4688a9ab775bSTejun Heo 
4689a9ab775bSTejun Heo 		/*
4690a9ab775bSTejun Heo 		 * A bound idle worker should actually be on the runqueue
4691a9ab775bSTejun Heo 		 * of the associated CPU for local wake-ups targeting it to
4692a9ab775bSTejun Heo 		 * work.  Kick all idle workers so that they migrate to the
4693a9ab775bSTejun Heo 		 * associated CPU.  Doing this in the same loop as
4694a9ab775bSTejun Heo 		 * replacing UNBOUND with REBOUND is safe as no worker will
4695a9ab775bSTejun Heo 		 * be bound before @pool->lock is released.
4696a9ab775bSTejun Heo 		 */
4697a9ab775bSTejun Heo 		if (worker_flags & WORKER_IDLE)
4698bd7c089eSTejun Heo 			wake_up_process(worker->task);
4699bd7c089eSTejun Heo 
4700bd7c089eSTejun Heo 		/*
4701a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
4702a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
4703a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4704a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
4705a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
4706a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
4707a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
4708a9ab775bSTejun Heo 		 *
4709c95491edSMark Rutland 		 * WRITE_ONCE() is necessary because @worker->flags may be
4710a9ab775bSTejun Heo 		 * tested without holding any lock in
4711a9ab775bSTejun Heo 		 * wq_worker_waking_up().  Without it, NOT_RUNNING test may
4712a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
4713a9ab775bSTejun Heo 		 * management operations.
4714bd7c089eSTejun Heo 		 */
4715a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
4716a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
4717a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
4718c95491edSMark Rutland 		WRITE_ONCE(worker->flags, worker_flags);
4719bd7c089eSTejun Heo 	}
4720a9ab775bSTejun Heo 
4721a9ab775bSTejun Heo 	spin_unlock_irq(&pool->lock);
4722bd7c089eSTejun Heo }
4723bd7c089eSTejun Heo 
47247dbc725eSTejun Heo /**
47257dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
47267dbc725eSTejun Heo  * @pool: unbound pool of interest
47277dbc725eSTejun Heo  * @cpu: the CPU which is coming up
47287dbc725eSTejun Heo  *
47297dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
47307dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
47317dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
47327dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
47337dbc725eSTejun Heo  */
47347dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
47357dbc725eSTejun Heo {
47367dbc725eSTejun Heo 	static cpumask_t cpumask;
47377dbc725eSTejun Heo 	struct worker *worker;
47387dbc725eSTejun Heo 
473992f9c5c4SLai Jiangshan 	lockdep_assert_held(&pool->attach_mutex);
47407dbc725eSTejun Heo 
47417dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
47427dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
47437dbc725eSTejun Heo 		return;
47447dbc725eSTejun Heo 
47457dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
47467dbc725eSTejun Heo 
47477dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
4748da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
4749d945b5e9SPeter Zijlstra 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
47507dbc725eSTejun Heo }
47517dbc725eSTejun Heo 
47527ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
47531da177e4SLinus Torvalds {
47544ce62e9eSTejun Heo 	struct worker_pool *pool;
47551da177e4SLinus Torvalds 
4756f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
47573ce63377STejun Heo 		if (pool->nr_workers)
47583ce63377STejun Heo 			continue;
4759051e1850SLai Jiangshan 		if (!create_worker(pool))
47607ee681b2SThomas Gleixner 			return -ENOMEM;
47613af24433SOleg Nesterov 	}
47627ee681b2SThomas Gleixner 	return 0;
47637ee681b2SThomas Gleixner }
47641da177e4SLinus Torvalds 
47657ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
47667ee681b2SThomas Gleixner {
47677ee681b2SThomas Gleixner 	struct worker_pool *pool;
47687ee681b2SThomas Gleixner 	struct workqueue_struct *wq;
47697ee681b2SThomas Gleixner 	int pi;
47707ee681b2SThomas Gleixner 
477168e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
47727dbc725eSTejun Heo 
47737dbc725eSTejun Heo 	for_each_pool(pool, pi) {
477492f9c5c4SLai Jiangshan 		mutex_lock(&pool->attach_mutex);
477594cf58bbSTejun Heo 
4776f05b558dSLai Jiangshan 		if (pool->cpu == cpu)
477794cf58bbSTejun Heo 			rebind_workers(pool);
4778f05b558dSLai Jiangshan 		else if (pool->cpu < 0)
47797dbc725eSTejun Heo 			restore_unbound_workers_cpumask(pool, cpu);
478094cf58bbSTejun Heo 
478192f9c5c4SLai Jiangshan 		mutex_unlock(&pool->attach_mutex);
478294cf58bbSTejun Heo 	}
47837dbc725eSTejun Heo 
47844c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
47854c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
47864c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, true);
47874c16bd32STejun Heo 
478868e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
47897ee681b2SThomas Gleixner 	return 0;
479065758202STejun Heo }
479165758202STejun Heo 
47927ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
479365758202STejun Heo {
47944c16bd32STejun Heo 	struct workqueue_struct *wq;
47958db25e78STejun Heo 
47964c16bd32STejun Heo 	/* unbinding per-cpu workers should happen on the local CPU */
4797e8b3f8dbSLai Jiangshan 	if (WARN_ON(cpu != smp_processor_id()))
4798e8b3f8dbSLai Jiangshan 		return -1;
4799e8b3f8dbSLai Jiangshan 
4800e8b3f8dbSLai Jiangshan 	unbind_workers(cpu);
48014c16bd32STejun Heo 
48024c16bd32STejun Heo 	/* update NUMA affinity of unbound workqueues */
48034c16bd32STejun Heo 	mutex_lock(&wq_pool_mutex);
48044c16bd32STejun Heo 	list_for_each_entry(wq, &workqueues, list)
48054c16bd32STejun Heo 		wq_update_unbound_numa(wq, cpu, false);
48064c16bd32STejun Heo 	mutex_unlock(&wq_pool_mutex);
48074c16bd32STejun Heo 
48087ee681b2SThomas Gleixner 	return 0;
480965758202STejun Heo }
481065758202STejun Heo 
48112d3854a3SRusty Russell #ifdef CONFIG_SMP
48128ccad40dSRusty Russell 
48132d3854a3SRusty Russell struct work_for_cpu {
4814ed48ece2STejun Heo 	struct work_struct work;
48152d3854a3SRusty Russell 	long (*fn)(void *);
48162d3854a3SRusty Russell 	void *arg;
48172d3854a3SRusty Russell 	long ret;
48182d3854a3SRusty Russell };
48192d3854a3SRusty Russell 
4820ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
48212d3854a3SRusty Russell {
4822ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
4823ed48ece2STejun Heo 
48242d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
48252d3854a3SRusty Russell }
48262d3854a3SRusty Russell 
48272d3854a3SRusty Russell /**
482822aceb31SAnna-Maria Gleixner  * work_on_cpu - run a function in thread context on a particular cpu
48292d3854a3SRusty Russell  * @cpu: the cpu to run on
48302d3854a3SRusty Russell  * @fn: the function to run
48312d3854a3SRusty Russell  * @arg: the function arg
48322d3854a3SRusty Russell  *
483331ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
48346b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
4835d185af30SYacine Belkadi  *
4836d185af30SYacine Belkadi  * Return: The value @fn returns.
48372d3854a3SRusty Russell  */
4838d84ff051STejun Heo long work_on_cpu(int cpu, long (*fn)(void *), void *arg)
48392d3854a3SRusty Russell {
4840ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
48412d3854a3SRusty Russell 
4842ed48ece2STejun Heo 	INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
4843ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
484412997d1aSBjorn Helgaas 	flush_work(&wfc.work);
4845440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
48462d3854a3SRusty Russell 	return wfc.ret;
48472d3854a3SRusty Russell }
48482d3854a3SRusty Russell EXPORT_SYMBOL_GPL(work_on_cpu);
48490e8d6a93SThomas Gleixner 
48500e8d6a93SThomas Gleixner /**
48510e8d6a93SThomas Gleixner  * work_on_cpu_safe - run a function in thread context on a particular cpu
48520e8d6a93SThomas Gleixner  * @cpu: the cpu to run on
48530e8d6a93SThomas Gleixner  * @fn:  the function to run
48540e8d6a93SThomas Gleixner  * @arg: the function argument
48550e8d6a93SThomas Gleixner  *
48560e8d6a93SThomas Gleixner  * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
48570e8d6a93SThomas Gleixner  * any locks which would prevent @fn from completing.
48580e8d6a93SThomas Gleixner  *
48590e8d6a93SThomas Gleixner  * Return: The value @fn returns.
48600e8d6a93SThomas Gleixner  */
48610e8d6a93SThomas Gleixner long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg)
48620e8d6a93SThomas Gleixner {
48630e8d6a93SThomas Gleixner 	long ret = -ENODEV;
48640e8d6a93SThomas Gleixner 
48650e8d6a93SThomas Gleixner 	get_online_cpus();
48660e8d6a93SThomas Gleixner 	if (cpu_online(cpu))
48670e8d6a93SThomas Gleixner 		ret = work_on_cpu(cpu, fn, arg);
48680e8d6a93SThomas Gleixner 	put_online_cpus();
48690e8d6a93SThomas Gleixner 	return ret;
48700e8d6a93SThomas Gleixner }
48710e8d6a93SThomas Gleixner EXPORT_SYMBOL_GPL(work_on_cpu_safe);
48722d3854a3SRusty Russell #endif /* CONFIG_SMP */
48732d3854a3SRusty Russell 
4874a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
4875e7577c50SRusty Russell 
4876a0a1a5fdSTejun Heo /**
4877a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
4878a0a1a5fdSTejun Heo  *
487958a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
4880c5aa87bbSTejun Heo  * workqueues will queue new works to their delayed_works list instead of
4881706026c2STejun Heo  * pool->worklist.
4882a0a1a5fdSTejun Heo  *
4883a0a1a5fdSTejun Heo  * CONTEXT:
4884a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4885a0a1a5fdSTejun Heo  */
4886a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
4887a0a1a5fdSTejun Heo {
488824b8a847STejun Heo 	struct workqueue_struct *wq;
488924b8a847STejun Heo 	struct pool_workqueue *pwq;
4890a0a1a5fdSTejun Heo 
489168e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4892a0a1a5fdSTejun Heo 
48936183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
4894a0a1a5fdSTejun Heo 	workqueue_freezing = true;
4895a0a1a5fdSTejun Heo 
489624b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
4897a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
4898699ce097STejun Heo 		for_each_pwq(pwq, wq)
4899699ce097STejun Heo 			pwq_adjust_max_active(pwq);
4900a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
4901a1056305STejun Heo 	}
49025bcab335STejun Heo 
490368e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4904a0a1a5fdSTejun Heo }
4905a0a1a5fdSTejun Heo 
4906a0a1a5fdSTejun Heo /**
490758a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
4908a0a1a5fdSTejun Heo  *
4909a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
4910a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
4911a0a1a5fdSTejun Heo  *
4912a0a1a5fdSTejun Heo  * CONTEXT:
491368e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
4914a0a1a5fdSTejun Heo  *
4915d185af30SYacine Belkadi  * Return:
491658a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
491758a69cb4STejun Heo  * is complete.
4918a0a1a5fdSTejun Heo  */
4919a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
4920a0a1a5fdSTejun Heo {
4921a0a1a5fdSTejun Heo 	bool busy = false;
492224b8a847STejun Heo 	struct workqueue_struct *wq;
492324b8a847STejun Heo 	struct pool_workqueue *pwq;
4924a0a1a5fdSTejun Heo 
492568e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4926a0a1a5fdSTejun Heo 
49276183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
4928a0a1a5fdSTejun Heo 
492924b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
493024b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
493124b8a847STejun Heo 			continue;
4932a0a1a5fdSTejun Heo 		/*
4933a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
4934a0a1a5fdSTejun Heo 		 * to peek without lock.
4935a0a1a5fdSTejun Heo 		 */
493688109453SLai Jiangshan 		rcu_read_lock_sched();
493724b8a847STejun Heo 		for_each_pwq(pwq, wq) {
49386183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
4939112202d9STejun Heo 			if (pwq->nr_active) {
4940a0a1a5fdSTejun Heo 				busy = true;
494188109453SLai Jiangshan 				rcu_read_unlock_sched();
4942a0a1a5fdSTejun Heo 				goto out_unlock;
4943a0a1a5fdSTejun Heo 			}
4944a0a1a5fdSTejun Heo 		}
494588109453SLai Jiangshan 		rcu_read_unlock_sched();
4946a0a1a5fdSTejun Heo 	}
4947a0a1a5fdSTejun Heo out_unlock:
494868e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4949a0a1a5fdSTejun Heo 	return busy;
4950a0a1a5fdSTejun Heo }
4951a0a1a5fdSTejun Heo 
4952a0a1a5fdSTejun Heo /**
4953a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
4954a0a1a5fdSTejun Heo  *
4955a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
4956706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
4957a0a1a5fdSTejun Heo  *
4958a0a1a5fdSTejun Heo  * CONTEXT:
4959a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4960a0a1a5fdSTejun Heo  */
4961a0a1a5fdSTejun Heo void thaw_workqueues(void)
4962a0a1a5fdSTejun Heo {
496324b8a847STejun Heo 	struct workqueue_struct *wq;
496424b8a847STejun Heo 	struct pool_workqueue *pwq;
4965a0a1a5fdSTejun Heo 
496668e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
4967a0a1a5fdSTejun Heo 
4968a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
4969a0a1a5fdSTejun Heo 		goto out_unlock;
4970a0a1a5fdSTejun Heo 
497174b414eaSLai Jiangshan 	workqueue_freezing = false;
497224b8a847STejun Heo 
497324b8a847STejun Heo 	/* restore max_active and repopulate worklist */
497424b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
4975a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
4976699ce097STejun Heo 		for_each_pwq(pwq, wq)
4977699ce097STejun Heo 			pwq_adjust_max_active(pwq);
4978a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
497924b8a847STejun Heo 	}
498024b8a847STejun Heo 
4981a0a1a5fdSTejun Heo out_unlock:
498268e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
4983a0a1a5fdSTejun Heo }
4984a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
4985a0a1a5fdSTejun Heo 
4986042f7df1SLai Jiangshan static int workqueue_apply_unbound_cpumask(void)
4987042f7df1SLai Jiangshan {
4988042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
4989042f7df1SLai Jiangshan 	int ret = 0;
4990042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
4991042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
4992042f7df1SLai Jiangshan 
4993042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
4994042f7df1SLai Jiangshan 
4995042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
4996042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
4997042f7df1SLai Jiangshan 			continue;
4998042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
4999042f7df1SLai Jiangshan 		if (wq->flags & __WQ_ORDERED)
5000042f7df1SLai Jiangshan 			continue;
5001042f7df1SLai Jiangshan 
5002042f7df1SLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs);
5003042f7df1SLai Jiangshan 		if (!ctx) {
5004042f7df1SLai Jiangshan 			ret = -ENOMEM;
5005042f7df1SLai Jiangshan 			break;
5006042f7df1SLai Jiangshan 		}
5007042f7df1SLai Jiangshan 
5008042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
5009042f7df1SLai Jiangshan 	}
5010042f7df1SLai Jiangshan 
5011042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
5012042f7df1SLai Jiangshan 		if (!ret)
5013042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
5014042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
5015042f7df1SLai Jiangshan 	}
5016042f7df1SLai Jiangshan 
5017042f7df1SLai Jiangshan 	return ret;
5018042f7df1SLai Jiangshan }
5019042f7df1SLai Jiangshan 
5020042f7df1SLai Jiangshan /**
5021042f7df1SLai Jiangshan  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5022042f7df1SLai Jiangshan  *  @cpumask: the cpumask to set
5023042f7df1SLai Jiangshan  *
5024042f7df1SLai Jiangshan  *  The low-level workqueues cpumask is a global cpumask that limits
5025042f7df1SLai Jiangshan  *  the affinity of all unbound workqueues.  This function check the @cpumask
5026042f7df1SLai Jiangshan  *  and apply it to all unbound workqueues and updates all pwqs of them.
5027042f7df1SLai Jiangshan  *
5028042f7df1SLai Jiangshan  *  Retun:	0	- Success
5029042f7df1SLai Jiangshan  *  		-EINVAL	- Invalid @cpumask
5030042f7df1SLai Jiangshan  *  		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
5031042f7df1SLai Jiangshan  */
5032042f7df1SLai Jiangshan int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5033042f7df1SLai Jiangshan {
5034042f7df1SLai Jiangshan 	int ret = -EINVAL;
5035042f7df1SLai Jiangshan 	cpumask_var_t saved_cpumask;
5036042f7df1SLai Jiangshan 
5037042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&saved_cpumask, GFP_KERNEL))
5038042f7df1SLai Jiangshan 		return -ENOMEM;
5039042f7df1SLai Jiangshan 
5040c98a9805STal Shorer 	/*
5041c98a9805STal Shorer 	 * Not excluding isolated cpus on purpose.
5042c98a9805STal Shorer 	 * If the user wishes to include them, we allow that.
5043c98a9805STal Shorer 	 */
5044042f7df1SLai Jiangshan 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
5045042f7df1SLai Jiangshan 	if (!cpumask_empty(cpumask)) {
5046a0111cf6SLai Jiangshan 		apply_wqattrs_lock();
5047042f7df1SLai Jiangshan 
5048042f7df1SLai Jiangshan 		/* save the old wq_unbound_cpumask. */
5049042f7df1SLai Jiangshan 		cpumask_copy(saved_cpumask, wq_unbound_cpumask);
5050042f7df1SLai Jiangshan 
5051042f7df1SLai Jiangshan 		/* update wq_unbound_cpumask at first and apply it to wqs. */
5052042f7df1SLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, cpumask);
5053042f7df1SLai Jiangshan 		ret = workqueue_apply_unbound_cpumask();
5054042f7df1SLai Jiangshan 
5055042f7df1SLai Jiangshan 		/* restore the wq_unbound_cpumask when failed. */
5056042f7df1SLai Jiangshan 		if (ret < 0)
5057042f7df1SLai Jiangshan 			cpumask_copy(wq_unbound_cpumask, saved_cpumask);
5058042f7df1SLai Jiangshan 
5059a0111cf6SLai Jiangshan 		apply_wqattrs_unlock();
5060042f7df1SLai Jiangshan 	}
5061042f7df1SLai Jiangshan 
5062042f7df1SLai Jiangshan 	free_cpumask_var(saved_cpumask);
5063042f7df1SLai Jiangshan 	return ret;
5064042f7df1SLai Jiangshan }
5065042f7df1SLai Jiangshan 
50666ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
50676ba94429SFrederic Weisbecker /*
50686ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
50696ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
50706ba94429SFrederic Weisbecker  * following attributes.
50716ba94429SFrederic Weisbecker  *
50726ba94429SFrederic Weisbecker  *  per_cpu	RO bool	: whether the workqueue is per-cpu or unbound
50736ba94429SFrederic Weisbecker  *  max_active	RW int	: maximum number of in-flight work items
50746ba94429SFrederic Weisbecker  *
50756ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
50766ba94429SFrederic Weisbecker  *
50779a19b463SWang Long  *  pool_ids	RO int	: the associated pool IDs for each node
50786ba94429SFrederic Weisbecker  *  nice	RW int	: nice value of the workers
50796ba94429SFrederic Weisbecker  *  cpumask	RW mask	: bitmask of allowed CPUs for the workers
50809a19b463SWang Long  *  numa	RW bool	: whether enable NUMA affinity
50816ba94429SFrederic Weisbecker  */
50826ba94429SFrederic Weisbecker struct wq_device {
50836ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
50846ba94429SFrederic Weisbecker 	struct device			dev;
50856ba94429SFrederic Weisbecker };
50866ba94429SFrederic Weisbecker 
50876ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
50886ba94429SFrederic Weisbecker {
50896ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
50906ba94429SFrederic Weisbecker 
50916ba94429SFrederic Weisbecker 	return wq_dev->wq;
50926ba94429SFrederic Weisbecker }
50936ba94429SFrederic Weisbecker 
50946ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
50956ba94429SFrederic Weisbecker 			    char *buf)
50966ba94429SFrederic Weisbecker {
50976ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
50986ba94429SFrederic Weisbecker 
50996ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
51006ba94429SFrederic Weisbecker }
51016ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
51026ba94429SFrederic Weisbecker 
51036ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
51046ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
51056ba94429SFrederic Weisbecker {
51066ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
51076ba94429SFrederic Weisbecker 
51086ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
51096ba94429SFrederic Weisbecker }
51106ba94429SFrederic Weisbecker 
51116ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
51126ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
51136ba94429SFrederic Weisbecker 				size_t count)
51146ba94429SFrederic Weisbecker {
51156ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
51166ba94429SFrederic Weisbecker 	int val;
51176ba94429SFrederic Weisbecker 
51186ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
51196ba94429SFrederic Weisbecker 		return -EINVAL;
51206ba94429SFrederic Weisbecker 
51216ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
51226ba94429SFrederic Weisbecker 	return count;
51236ba94429SFrederic Weisbecker }
51246ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
51256ba94429SFrederic Weisbecker 
51266ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
51276ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
51286ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
51296ba94429SFrederic Weisbecker 	NULL,
51306ba94429SFrederic Weisbecker };
51316ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
51326ba94429SFrederic Weisbecker 
51336ba94429SFrederic Weisbecker static ssize_t wq_pool_ids_show(struct device *dev,
51346ba94429SFrederic Weisbecker 				struct device_attribute *attr, char *buf)
51356ba94429SFrederic Weisbecker {
51366ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
51376ba94429SFrederic Weisbecker 	const char *delim = "";
51386ba94429SFrederic Weisbecker 	int node, written = 0;
51396ba94429SFrederic Weisbecker 
51406ba94429SFrederic Weisbecker 	rcu_read_lock_sched();
51416ba94429SFrederic Weisbecker 	for_each_node(node) {
51426ba94429SFrederic Weisbecker 		written += scnprintf(buf + written, PAGE_SIZE - written,
51436ba94429SFrederic Weisbecker 				     "%s%d:%d", delim, node,
51446ba94429SFrederic Weisbecker 				     unbound_pwq_by_node(wq, node)->pool->id);
51456ba94429SFrederic Weisbecker 		delim = " ";
51466ba94429SFrederic Weisbecker 	}
51476ba94429SFrederic Weisbecker 	written += scnprintf(buf + written, PAGE_SIZE - written, "\n");
51486ba94429SFrederic Weisbecker 	rcu_read_unlock_sched();
51496ba94429SFrederic Weisbecker 
51506ba94429SFrederic Weisbecker 	return written;
51516ba94429SFrederic Weisbecker }
51526ba94429SFrederic Weisbecker 
51536ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
51546ba94429SFrederic Weisbecker 			    char *buf)
51556ba94429SFrederic Weisbecker {
51566ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
51576ba94429SFrederic Weisbecker 	int written;
51586ba94429SFrederic Weisbecker 
51596ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
51606ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
51616ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
51626ba94429SFrederic Weisbecker 
51636ba94429SFrederic Weisbecker 	return written;
51646ba94429SFrederic Weisbecker }
51656ba94429SFrederic Weisbecker 
51666ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
51676ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
51686ba94429SFrederic Weisbecker {
51696ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
51706ba94429SFrederic Weisbecker 
5171899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
5172899a94feSLai Jiangshan 
51736ba94429SFrederic Weisbecker 	attrs = alloc_workqueue_attrs(GFP_KERNEL);
51746ba94429SFrederic Weisbecker 	if (!attrs)
51756ba94429SFrederic Weisbecker 		return NULL;
51766ba94429SFrederic Weisbecker 
51776ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
51786ba94429SFrederic Weisbecker 	return attrs;
51796ba94429SFrederic Weisbecker }
51806ba94429SFrederic Weisbecker 
51816ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
51826ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
51836ba94429SFrederic Weisbecker {
51846ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
51856ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5186d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5187d4d3e257SLai Jiangshan 
5188d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
51896ba94429SFrederic Weisbecker 
51906ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
51916ba94429SFrederic Weisbecker 	if (!attrs)
5192d4d3e257SLai Jiangshan 		goto out_unlock;
51936ba94429SFrederic Weisbecker 
51946ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
51956ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
5196d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
51976ba94429SFrederic Weisbecker 	else
51986ba94429SFrederic Weisbecker 		ret = -EINVAL;
51996ba94429SFrederic Weisbecker 
5200d4d3e257SLai Jiangshan out_unlock:
5201d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
52026ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
52036ba94429SFrederic Weisbecker 	return ret ?: count;
52046ba94429SFrederic Weisbecker }
52056ba94429SFrederic Weisbecker 
52066ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
52076ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
52086ba94429SFrederic Weisbecker {
52096ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
52106ba94429SFrederic Weisbecker 	int written;
52116ba94429SFrederic Weisbecker 
52126ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
52136ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
52146ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
52156ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
52166ba94429SFrederic Weisbecker 	return written;
52176ba94429SFrederic Weisbecker }
52186ba94429SFrederic Weisbecker 
52196ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
52206ba94429SFrederic Weisbecker 				struct device_attribute *attr,
52216ba94429SFrederic Weisbecker 				const char *buf, size_t count)
52226ba94429SFrederic Weisbecker {
52236ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
52246ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5225d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
5226d4d3e257SLai Jiangshan 
5227d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
52286ba94429SFrederic Weisbecker 
52296ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
52306ba94429SFrederic Weisbecker 	if (!attrs)
5231d4d3e257SLai Jiangshan 		goto out_unlock;
52326ba94429SFrederic Weisbecker 
52336ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
52346ba94429SFrederic Weisbecker 	if (!ret)
5235d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
52366ba94429SFrederic Weisbecker 
5237d4d3e257SLai Jiangshan out_unlock:
5238d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
52396ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
52406ba94429SFrederic Weisbecker 	return ret ?: count;
52416ba94429SFrederic Weisbecker }
52426ba94429SFrederic Weisbecker 
52436ba94429SFrederic Weisbecker static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr,
52446ba94429SFrederic Weisbecker 			    char *buf)
52456ba94429SFrederic Weisbecker {
52466ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
52476ba94429SFrederic Weisbecker 	int written;
52486ba94429SFrederic Weisbecker 
52496ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
52506ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n",
52516ba94429SFrederic Weisbecker 			    !wq->unbound_attrs->no_numa);
52526ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
52536ba94429SFrederic Weisbecker 
52546ba94429SFrederic Weisbecker 	return written;
52556ba94429SFrederic Weisbecker }
52566ba94429SFrederic Weisbecker 
52576ba94429SFrederic Weisbecker static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr,
52586ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
52596ba94429SFrederic Weisbecker {
52606ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
52616ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
5262d4d3e257SLai Jiangshan 	int v, ret = -ENOMEM;
5263d4d3e257SLai Jiangshan 
5264d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
52656ba94429SFrederic Weisbecker 
52666ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
52676ba94429SFrederic Weisbecker 	if (!attrs)
5268d4d3e257SLai Jiangshan 		goto out_unlock;
52696ba94429SFrederic Weisbecker 
52706ba94429SFrederic Weisbecker 	ret = -EINVAL;
52716ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &v) == 1) {
52726ba94429SFrederic Weisbecker 		attrs->no_numa = !v;
5273d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
52746ba94429SFrederic Weisbecker 	}
52756ba94429SFrederic Weisbecker 
5276d4d3e257SLai Jiangshan out_unlock:
5277d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
52786ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
52796ba94429SFrederic Weisbecker 	return ret ?: count;
52806ba94429SFrederic Weisbecker }
52816ba94429SFrederic Weisbecker 
52826ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
52836ba94429SFrederic Weisbecker 	__ATTR(pool_ids, 0444, wq_pool_ids_show, NULL),
52846ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
52856ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
52866ba94429SFrederic Weisbecker 	__ATTR(numa, 0644, wq_numa_show, wq_numa_store),
52876ba94429SFrederic Weisbecker 	__ATTR_NULL,
52886ba94429SFrederic Weisbecker };
52896ba94429SFrederic Weisbecker 
52906ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
52916ba94429SFrederic Weisbecker 	.name				= "workqueue",
52926ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
52936ba94429SFrederic Weisbecker };
52946ba94429SFrederic Weisbecker 
5295b05a7928SFrederic Weisbecker static ssize_t wq_unbound_cpumask_show(struct device *dev,
5296b05a7928SFrederic Weisbecker 		struct device_attribute *attr, char *buf)
5297b05a7928SFrederic Weisbecker {
5298b05a7928SFrederic Weisbecker 	int written;
5299b05a7928SFrederic Weisbecker 
5300042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5301b05a7928SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
5302b05a7928SFrederic Weisbecker 			    cpumask_pr_args(wq_unbound_cpumask));
5303042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
5304b05a7928SFrederic Weisbecker 
5305b05a7928SFrederic Weisbecker 	return written;
5306b05a7928SFrederic Weisbecker }
5307b05a7928SFrederic Weisbecker 
5308042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
5309042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
5310042f7df1SLai Jiangshan {
5311042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
5312042f7df1SLai Jiangshan 	int ret;
5313042f7df1SLai Jiangshan 
5314042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
5315042f7df1SLai Jiangshan 		return -ENOMEM;
5316042f7df1SLai Jiangshan 
5317042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
5318042f7df1SLai Jiangshan 	if (!ret)
5319042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
5320042f7df1SLai Jiangshan 
5321042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
5322042f7df1SLai Jiangshan 	return ret ? ret : count;
5323042f7df1SLai Jiangshan }
5324042f7df1SLai Jiangshan 
5325b05a7928SFrederic Weisbecker static struct device_attribute wq_sysfs_cpumask_attr =
5326042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
5327042f7df1SLai Jiangshan 	       wq_unbound_cpumask_store);
5328b05a7928SFrederic Weisbecker 
53296ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
53306ba94429SFrederic Weisbecker {
5331b05a7928SFrederic Weisbecker 	int err;
5332b05a7928SFrederic Weisbecker 
5333b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
5334b05a7928SFrederic Weisbecker 	if (err)
5335b05a7928SFrederic Weisbecker 		return err;
5336b05a7928SFrederic Weisbecker 
5337b05a7928SFrederic Weisbecker 	return device_create_file(wq_subsys.dev_root, &wq_sysfs_cpumask_attr);
53386ba94429SFrederic Weisbecker }
53396ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
53406ba94429SFrederic Weisbecker 
53416ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
53426ba94429SFrederic Weisbecker {
53436ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
53446ba94429SFrederic Weisbecker 
53456ba94429SFrederic Weisbecker 	kfree(wq_dev);
53466ba94429SFrederic Weisbecker }
53476ba94429SFrederic Weisbecker 
53486ba94429SFrederic Weisbecker /**
53496ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
53506ba94429SFrederic Weisbecker  * @wq: the workqueue to register
53516ba94429SFrederic Weisbecker  *
53526ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
53536ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
53546ba94429SFrederic Weisbecker  * which is the preferred method.
53556ba94429SFrederic Weisbecker  *
53566ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
53576ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
53586ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
53596ba94429SFrederic Weisbecker  * attributes.
53606ba94429SFrederic Weisbecker  *
53616ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
53626ba94429SFrederic Weisbecker  */
53636ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
53646ba94429SFrederic Weisbecker {
53656ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
53666ba94429SFrederic Weisbecker 	int ret;
53676ba94429SFrederic Weisbecker 
53686ba94429SFrederic Weisbecker 	/*
5369402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
53706ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
53716ba94429SFrederic Weisbecker 	 * workqueues.
53726ba94429SFrederic Weisbecker 	 */
53730a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
53746ba94429SFrederic Weisbecker 		return -EINVAL;
53756ba94429SFrederic Weisbecker 
53766ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
53776ba94429SFrederic Weisbecker 	if (!wq_dev)
53786ba94429SFrederic Weisbecker 		return -ENOMEM;
53796ba94429SFrederic Weisbecker 
53806ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
53816ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
53826ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
538323217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
53846ba94429SFrederic Weisbecker 
53856ba94429SFrederic Weisbecker 	/*
53866ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
53876ba94429SFrederic Weisbecker 	 * everything is ready.
53886ba94429SFrederic Weisbecker 	 */
53896ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
53906ba94429SFrederic Weisbecker 
53916ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
53926ba94429SFrederic Weisbecker 	if (ret) {
53936ba94429SFrederic Weisbecker 		kfree(wq_dev);
53946ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
53956ba94429SFrederic Weisbecker 		return ret;
53966ba94429SFrederic Weisbecker 	}
53976ba94429SFrederic Weisbecker 
53986ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
53996ba94429SFrederic Weisbecker 		struct device_attribute *attr;
54006ba94429SFrederic Weisbecker 
54016ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
54026ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
54036ba94429SFrederic Weisbecker 			if (ret) {
54046ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
54056ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
54066ba94429SFrederic Weisbecker 				return ret;
54076ba94429SFrederic Weisbecker 			}
54086ba94429SFrederic Weisbecker 		}
54096ba94429SFrederic Weisbecker 	}
54106ba94429SFrederic Weisbecker 
54116ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
54126ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
54136ba94429SFrederic Weisbecker 	return 0;
54146ba94429SFrederic Weisbecker }
54156ba94429SFrederic Weisbecker 
54166ba94429SFrederic Weisbecker /**
54176ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
54186ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
54196ba94429SFrederic Weisbecker  *
54206ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
54216ba94429SFrederic Weisbecker  */
54226ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
54236ba94429SFrederic Weisbecker {
54246ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
54256ba94429SFrederic Weisbecker 
54266ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
54276ba94429SFrederic Weisbecker 		return;
54286ba94429SFrederic Weisbecker 
54296ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
54306ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
54316ba94429SFrederic Weisbecker }
54326ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
54336ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
54346ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
54356ba94429SFrederic Weisbecker 
543682607adcSTejun Heo /*
543782607adcSTejun Heo  * Workqueue watchdog.
543882607adcSTejun Heo  *
543982607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
544082607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
544182607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
544282607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
544382607adcSTejun Heo  * largely opaque.
544482607adcSTejun Heo  *
544582607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
544682607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
544782607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
544882607adcSTejun Heo  *
544982607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
545082607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
545182607adcSTejun Heo  * corresponding sysfs parameter file.
545282607adcSTejun Heo  */
545382607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
545482607adcSTejun Heo 
545582607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
54565cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
545782607adcSTejun Heo 
545882607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
545982607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
546082607adcSTejun Heo 
546182607adcSTejun Heo static void wq_watchdog_reset_touched(void)
546282607adcSTejun Heo {
546382607adcSTejun Heo 	int cpu;
546482607adcSTejun Heo 
546582607adcSTejun Heo 	wq_watchdog_touched = jiffies;
546682607adcSTejun Heo 	for_each_possible_cpu(cpu)
546782607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
546882607adcSTejun Heo }
546982607adcSTejun Heo 
54705cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
547182607adcSTejun Heo {
547282607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
547382607adcSTejun Heo 	bool lockup_detected = false;
547482607adcSTejun Heo 	struct worker_pool *pool;
547582607adcSTejun Heo 	int pi;
547682607adcSTejun Heo 
547782607adcSTejun Heo 	if (!thresh)
547882607adcSTejun Heo 		return;
547982607adcSTejun Heo 
548082607adcSTejun Heo 	rcu_read_lock();
548182607adcSTejun Heo 
548282607adcSTejun Heo 	for_each_pool(pool, pi) {
548382607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
548482607adcSTejun Heo 
548582607adcSTejun Heo 		if (list_empty(&pool->worklist))
548682607adcSTejun Heo 			continue;
548782607adcSTejun Heo 
548882607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
548982607adcSTejun Heo 		pool_ts = READ_ONCE(pool->watchdog_ts);
549082607adcSTejun Heo 		touched = READ_ONCE(wq_watchdog_touched);
549182607adcSTejun Heo 
549282607adcSTejun Heo 		if (time_after(pool_ts, touched))
549382607adcSTejun Heo 			ts = pool_ts;
549482607adcSTejun Heo 		else
549582607adcSTejun Heo 			ts = touched;
549682607adcSTejun Heo 
549782607adcSTejun Heo 		if (pool->cpu >= 0) {
549882607adcSTejun Heo 			unsigned long cpu_touched =
549982607adcSTejun Heo 				READ_ONCE(per_cpu(wq_watchdog_touched_cpu,
550082607adcSTejun Heo 						  pool->cpu));
550182607adcSTejun Heo 			if (time_after(cpu_touched, ts))
550282607adcSTejun Heo 				ts = cpu_touched;
550382607adcSTejun Heo 		}
550482607adcSTejun Heo 
550582607adcSTejun Heo 		/* did we stall? */
550682607adcSTejun Heo 		if (time_after(jiffies, ts + thresh)) {
550782607adcSTejun Heo 			lockup_detected = true;
550882607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
550982607adcSTejun Heo 			pr_cont_pool_info(pool);
551082607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
551182607adcSTejun Heo 				jiffies_to_msecs(jiffies - pool_ts) / 1000);
551282607adcSTejun Heo 		}
551382607adcSTejun Heo 	}
551482607adcSTejun Heo 
551582607adcSTejun Heo 	rcu_read_unlock();
551682607adcSTejun Heo 
551782607adcSTejun Heo 	if (lockup_detected)
551882607adcSTejun Heo 		show_workqueue_state();
551982607adcSTejun Heo 
552082607adcSTejun Heo 	wq_watchdog_reset_touched();
552182607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
552282607adcSTejun Heo }
552382607adcSTejun Heo 
552482607adcSTejun Heo void wq_watchdog_touch(int cpu)
552582607adcSTejun Heo {
552682607adcSTejun Heo 	if (cpu >= 0)
552782607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
552882607adcSTejun Heo 	else
552982607adcSTejun Heo 		wq_watchdog_touched = jiffies;
553082607adcSTejun Heo }
553182607adcSTejun Heo 
553282607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
553382607adcSTejun Heo {
553482607adcSTejun Heo 	wq_watchdog_thresh = 0;
553582607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
553682607adcSTejun Heo 
553782607adcSTejun Heo 	if (thresh) {
553882607adcSTejun Heo 		wq_watchdog_thresh = thresh;
553982607adcSTejun Heo 		wq_watchdog_reset_touched();
554082607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
554182607adcSTejun Heo 	}
554282607adcSTejun Heo }
554382607adcSTejun Heo 
554482607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
554582607adcSTejun Heo 					const struct kernel_param *kp)
554682607adcSTejun Heo {
554782607adcSTejun Heo 	unsigned long thresh;
554882607adcSTejun Heo 	int ret;
554982607adcSTejun Heo 
555082607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
555182607adcSTejun Heo 	if (ret)
555282607adcSTejun Heo 		return ret;
555382607adcSTejun Heo 
555482607adcSTejun Heo 	if (system_wq)
555582607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
555682607adcSTejun Heo 	else
555782607adcSTejun Heo 		wq_watchdog_thresh = thresh;
555882607adcSTejun Heo 
555982607adcSTejun Heo 	return 0;
556082607adcSTejun Heo }
556182607adcSTejun Heo 
556282607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
556382607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
556482607adcSTejun Heo 	.get	= param_get_ulong,
556582607adcSTejun Heo };
556682607adcSTejun Heo 
556782607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
556882607adcSTejun Heo 		0644);
556982607adcSTejun Heo 
557082607adcSTejun Heo static void wq_watchdog_init(void)
557182607adcSTejun Heo {
55725cd79d6aSKees Cook 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
557382607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
557482607adcSTejun Heo }
557582607adcSTejun Heo 
557682607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
557782607adcSTejun Heo 
557882607adcSTejun Heo static inline void wq_watchdog_init(void) { }
557982607adcSTejun Heo 
558082607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
558182607adcSTejun Heo 
5582bce90380STejun Heo static void __init wq_numa_init(void)
5583bce90380STejun Heo {
5584bce90380STejun Heo 	cpumask_var_t *tbl;
5585bce90380STejun Heo 	int node, cpu;
5586bce90380STejun Heo 
5587bce90380STejun Heo 	if (num_possible_nodes() <= 1)
5588bce90380STejun Heo 		return;
5589bce90380STejun Heo 
5590d55262c4STejun Heo 	if (wq_disable_numa) {
5591d55262c4STejun Heo 		pr_info("workqueue: NUMA affinity support disabled\n");
5592d55262c4STejun Heo 		return;
5593d55262c4STejun Heo 	}
5594d55262c4STejun Heo 
55954c16bd32STejun Heo 	wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(GFP_KERNEL);
55964c16bd32STejun Heo 	BUG_ON(!wq_update_unbound_numa_attrs_buf);
55974c16bd32STejun Heo 
5598bce90380STejun Heo 	/*
5599bce90380STejun Heo 	 * We want masks of possible CPUs of each node which isn't readily
5600bce90380STejun Heo 	 * available.  Build one from cpu_to_node() which should have been
5601bce90380STejun Heo 	 * fully initialized by now.
5602bce90380STejun Heo 	 */
5603ddcb57e2SLai Jiangshan 	tbl = kzalloc(nr_node_ids * sizeof(tbl[0]), GFP_KERNEL);
5604bce90380STejun Heo 	BUG_ON(!tbl);
5605bce90380STejun Heo 
5606bce90380STejun Heo 	for_each_node(node)
56075a6024f1SYasuaki Ishimatsu 		BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL,
56081be0c25dSTejun Heo 				node_online(node) ? node : NUMA_NO_NODE));
5609bce90380STejun Heo 
5610bce90380STejun Heo 	for_each_possible_cpu(cpu) {
5611bce90380STejun Heo 		node = cpu_to_node(cpu);
5612bce90380STejun Heo 		if (WARN_ON(node == NUMA_NO_NODE)) {
5613bce90380STejun Heo 			pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu);
5614bce90380STejun Heo 			/* happens iff arch is bonkers, let's just proceed */
5615bce90380STejun Heo 			return;
5616bce90380STejun Heo 		}
5617bce90380STejun Heo 		cpumask_set_cpu(cpu, tbl[node]);
5618bce90380STejun Heo 	}
5619bce90380STejun Heo 
5620bce90380STejun Heo 	wq_numa_possible_cpumask = tbl;
5621bce90380STejun Heo 	wq_numa_enabled = true;
5622bce90380STejun Heo }
5623bce90380STejun Heo 
56243347fa09STejun Heo /**
56253347fa09STejun Heo  * workqueue_init_early - early init for workqueue subsystem
56263347fa09STejun Heo  *
56273347fa09STejun Heo  * This is the first half of two-staged workqueue subsystem initialization
56283347fa09STejun Heo  * and invoked as soon as the bare basics - memory allocation, cpumasks and
56293347fa09STejun Heo  * idr are up.  It sets up all the data structures and system workqueues
56303347fa09STejun Heo  * and allows early boot code to create workqueues and queue/cancel work
56313347fa09STejun Heo  * items.  Actual work item execution starts only after kthreads can be
56323347fa09STejun Heo  * created and scheduled right before early initcalls.
56333347fa09STejun Heo  */
56343347fa09STejun Heo int __init workqueue_init_early(void)
56351da177e4SLinus Torvalds {
56367a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
56377a4e344cSTejun Heo 	int i, cpu;
5638c34056a3STejun Heo 
5639e904e6c2STejun Heo 	WARN_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
5640e904e6c2STejun Heo 
5641b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
5642c98a9805STal Shorer 	cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(HK_FLAG_DOMAIN));
5643b05a7928SFrederic Weisbecker 
5644e904e6c2STejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
5645e904e6c2STejun Heo 
5646706026c2STejun Heo 	/* initialize CPU pools */
564729c91e99STejun Heo 	for_each_possible_cpu(cpu) {
56484ce62e9eSTejun Heo 		struct worker_pool *pool;
56498b03ae3cSTejun Heo 
56507a4e344cSTejun Heo 		i = 0;
5651f02ae73aSTejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
56527a4e344cSTejun Heo 			BUG_ON(init_worker_pool(pool));
5653ec22ca5eSTejun Heo 			pool->cpu = cpu;
56547a4e344cSTejun Heo 			cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
56557a4e344cSTejun Heo 			pool->attrs->nice = std_nice[i++];
5656f3f90ad4STejun Heo 			pool->node = cpu_to_node(cpu);
56577a4e344cSTejun Heo 
56589daf9e67STejun Heo 			/* alloc pool ID */
565968e13a67SLai Jiangshan 			mutex_lock(&wq_pool_mutex);
56609daf9e67STejun Heo 			BUG_ON(worker_pool_assign_id(pool));
566168e13a67SLai Jiangshan 			mutex_unlock(&wq_pool_mutex);
56624ce62e9eSTejun Heo 		}
56638b03ae3cSTejun Heo 	}
56648b03ae3cSTejun Heo 
56658a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
566629c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
566729c91e99STejun Heo 		struct workqueue_attrs *attrs;
566829c91e99STejun Heo 
566929c91e99STejun Heo 		BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
567029c91e99STejun Heo 		attrs->nice = std_nice[i];
567129c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
56728a2b7538STejun Heo 
56738a2b7538STejun Heo 		/*
56748a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
56758a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
56768a2b7538STejun Heo 		 * Turn off NUMA so that dfl_pwq is used for all nodes.
56778a2b7538STejun Heo 		 */
56788a2b7538STejun Heo 		BUG_ON(!(attrs = alloc_workqueue_attrs(GFP_KERNEL)));
56798a2b7538STejun Heo 		attrs->nice = std_nice[i];
56808a2b7538STejun Heo 		attrs->no_numa = true;
56818a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
568229c91e99STejun Heo 	}
568329c91e99STejun Heo 
5684d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
56851aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
5686d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
5687f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
5688f3421797STejun Heo 					    WQ_UNBOUND_MAX_ACTIVE);
568924d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
569024d51addSTejun Heo 					      WQ_FREEZABLE, 0);
56910668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
56920668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
56930668106cSViresh Kumar 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
56940668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
56950668106cSViresh Kumar 					      0);
56961aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
56970668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
56980668106cSViresh Kumar 	       !system_power_efficient_wq ||
56990668106cSViresh Kumar 	       !system_freezable_power_efficient_wq);
570082607adcSTejun Heo 
57013347fa09STejun Heo 	return 0;
57023347fa09STejun Heo }
57033347fa09STejun Heo 
57043347fa09STejun Heo /**
57053347fa09STejun Heo  * workqueue_init - bring workqueue subsystem fully online
57063347fa09STejun Heo  *
57073347fa09STejun Heo  * This is the latter half of two-staged workqueue subsystem initialization
57083347fa09STejun Heo  * and invoked as soon as kthreads can be created and scheduled.
57093347fa09STejun Heo  * Workqueues have been created and work items queued on them, but there
57103347fa09STejun Heo  * are no kworkers executing the work items yet.  Populate the worker pools
57113347fa09STejun Heo  * with the initial workers and enable future kworker creations.
57123347fa09STejun Heo  */
57133347fa09STejun Heo int __init workqueue_init(void)
57143347fa09STejun Heo {
57152186d9f9STejun Heo 	struct workqueue_struct *wq;
57163347fa09STejun Heo 	struct worker_pool *pool;
57173347fa09STejun Heo 	int cpu, bkt;
57183347fa09STejun Heo 
57192186d9f9STejun Heo 	/*
57202186d9f9STejun Heo 	 * It'd be simpler to initialize NUMA in workqueue_init_early() but
57212186d9f9STejun Heo 	 * CPU to node mapping may not be available that early on some
57222186d9f9STejun Heo 	 * archs such as power and arm64.  As per-cpu pools created
57232186d9f9STejun Heo 	 * previously could be missing node hint and unbound pools NUMA
57242186d9f9STejun Heo 	 * affinity, fix them up.
572540c17f75STejun Heo 	 *
572640c17f75STejun Heo 	 * Also, while iterating workqueues, create rescuers if requested.
57272186d9f9STejun Heo 	 */
57282186d9f9STejun Heo 	wq_numa_init();
57292186d9f9STejun Heo 
57302186d9f9STejun Heo 	mutex_lock(&wq_pool_mutex);
57312186d9f9STejun Heo 
57322186d9f9STejun Heo 	for_each_possible_cpu(cpu) {
57332186d9f9STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
57342186d9f9STejun Heo 			pool->node = cpu_to_node(cpu);
57352186d9f9STejun Heo 		}
57362186d9f9STejun Heo 	}
57372186d9f9STejun Heo 
573840c17f75STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
57392186d9f9STejun Heo 		wq_update_unbound_numa(wq, smp_processor_id(), true);
574040c17f75STejun Heo 		WARN(init_rescuer(wq),
574140c17f75STejun Heo 		     "workqueue: failed to create early rescuer for %s",
574240c17f75STejun Heo 		     wq->name);
574340c17f75STejun Heo 	}
57442186d9f9STejun Heo 
57452186d9f9STejun Heo 	mutex_unlock(&wq_pool_mutex);
57462186d9f9STejun Heo 
57473347fa09STejun Heo 	/* create the initial workers */
57483347fa09STejun Heo 	for_each_online_cpu(cpu) {
57493347fa09STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
57503347fa09STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
57513347fa09STejun Heo 			BUG_ON(!create_worker(pool));
57523347fa09STejun Heo 		}
57533347fa09STejun Heo 	}
57543347fa09STejun Heo 
57553347fa09STejun Heo 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
57563347fa09STejun Heo 		BUG_ON(!create_worker(pool));
57573347fa09STejun Heo 
57583347fa09STejun Heo 	wq_online = true;
575982607adcSTejun Heo 	wq_watchdog_init();
576082607adcSTejun Heo 
57616ee0578bSSuresh Siddha 	return 0;
57621da177e4SLinus Torvalds }
5763