xref: /linux-6.15/kernel/workqueue.c (revision 96068b60)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
3c54fce6eSTejun Heo  * kernel/workqueue.c - generic async execution with shared worker pool
41da177e4SLinus Torvalds  *
5c54fce6eSTejun Heo  * Copyright (C) 2002		Ingo Molnar
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  *   Derived from the taskqueue/keventd code by:
81da177e4SLinus Torvalds  *     David Woodhouse <[email protected]>
9e1f8e874SFrancois Cami  *     Andrew Morton
101da177e4SLinus Torvalds  *     Kai Petzke <[email protected]>
111da177e4SLinus Torvalds  *     Theodore Ts'o <[email protected]>
1289ada679SChristoph Lameter  *
13cde53535SChristoph Lameter  * Made to use alloc_percpu by Christoph Lameter.
14c54fce6eSTejun Heo  *
15c54fce6eSTejun Heo  * Copyright (C) 2010		SUSE Linux Products GmbH
16c54fce6eSTejun Heo  * Copyright (C) 2010		Tejun Heo <[email protected]>
17c54fce6eSTejun Heo  *
18c54fce6eSTejun Heo  * This is the generic async execution mechanism.  Work items as are
19c54fce6eSTejun Heo  * executed in process context.  The worker pool is shared and
20b11895c4SLibin  * automatically managed.  There are two worker pools for each CPU (one for
21b11895c4SLibin  * normal work items and the other for high priority ones) and some extra
22b11895c4SLibin  * pools for workqueues which are not bound to any specific CPU - the
23b11895c4SLibin  * number of these backing pools is dynamic.
24c54fce6eSTejun Heo  *
259a261491SBenjamin Peterson  * Please read Documentation/core-api/workqueue.rst for details.
261da177e4SLinus Torvalds  */
271da177e4SLinus Torvalds 
289984de1aSPaul Gortmaker #include <linux/export.h>
291da177e4SLinus Torvalds #include <linux/kernel.h>
301da177e4SLinus Torvalds #include <linux/sched.h>
311da177e4SLinus Torvalds #include <linux/init.h>
324cb1ef64STejun Heo #include <linux/interrupt.h>
331da177e4SLinus Torvalds #include <linux/signal.h>
341da177e4SLinus Torvalds #include <linux/completion.h>
351da177e4SLinus Torvalds #include <linux/workqueue.h>
361da177e4SLinus Torvalds #include <linux/slab.h>
371da177e4SLinus Torvalds #include <linux/cpu.h>
381da177e4SLinus Torvalds #include <linux/notifier.h>
391da177e4SLinus Torvalds #include <linux/kthread.h>
401fa44ecaSJames Bottomley #include <linux/hardirq.h>
4146934023SChristoph Lameter #include <linux/mempolicy.h>
42341a5958SRafael J. Wysocki #include <linux/freezer.h>
43d5abe669SPeter Zijlstra #include <linux/debug_locks.h>
444e6045f1SJohannes Berg #include <linux/lockdep.h>
45c34056a3STejun Heo #include <linux/idr.h>
4629c91e99STejun Heo #include <linux/jhash.h>
4742f8570fSSasha Levin #include <linux/hashtable.h>
4876af4d93STejun Heo #include <linux/rculist.h>
49bce90380STejun Heo #include <linux/nodemask.h>
504c16bd32STejun Heo #include <linux/moduleparam.h>
513d1cb205STejun Heo #include <linux/uaccess.h>
52c98a9805STal Shorer #include <linux/sched/isolation.h>
53cd2440d6SPetr Mladek #include <linux/sched/debug.h>
5462635ea8SSergey Senozhatsky #include <linux/nmi.h>
55940d71c6SSergey Senozhatsky #include <linux/kvm_para.h>
56aa6fde93STejun Heo #include <linux/delay.h>
57e22bee78STejun Heo 
58ea138446STejun Heo #include "workqueue_internal.h"
591da177e4SLinus Torvalds 
60e563d0a7STejun Heo enum worker_pool_flags {
61bc2ae0f5STejun Heo 	/*
6224647570STejun Heo 	 * worker_pool flags
63bc2ae0f5STejun Heo 	 *
6424647570STejun Heo 	 * A bound pool is either associated or disassociated with its CPU.
65bc2ae0f5STejun Heo 	 * While associated (!DISASSOCIATED), all workers are bound to the
66bc2ae0f5STejun Heo 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
67bc2ae0f5STejun Heo 	 * is in effect.
68bc2ae0f5STejun Heo 	 *
69bc2ae0f5STejun Heo 	 * While DISASSOCIATED, the cpu may be offline and all workers have
70bc2ae0f5STejun Heo 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
7124647570STejun Heo 	 * be executing on any CPU.  The pool behaves as an unbound one.
72bc2ae0f5STejun Heo 	 *
73bc3a1afcSTejun Heo 	 * Note that DISASSOCIATED should be flipped only while holding
741258fae7STejun Heo 	 * wq_pool_attach_mutex to avoid changing binding state while
754736cbf7SLai Jiangshan 	 * worker_attach_to_pool() is in progress.
764cb1ef64STejun Heo 	 *
774cb1ef64STejun Heo 	 * As there can only be one concurrent BH execution context per CPU, a
784cb1ef64STejun Heo 	 * BH pool is per-CPU and always DISASSOCIATED.
79bc2ae0f5STejun Heo 	 */
804cb1ef64STejun Heo 	POOL_BH			= 1 << 0,	/* is a BH pool */
814cb1ef64STejun Heo 	POOL_MANAGER_ACTIVE	= 1 << 1,	/* being managed */
8224647570STejun Heo 	POOL_DISASSOCIATED	= 1 << 2,	/* cpu can't serve workers */
83e563d0a7STejun Heo };
84db7bccf4STejun Heo 
85e563d0a7STejun Heo enum worker_flags {
86c8e55f36STejun Heo 	/* worker flags */
87c8e55f36STejun Heo 	WORKER_DIE		= 1 << 1,	/* die die die */
88c8e55f36STejun Heo 	WORKER_IDLE		= 1 << 2,	/* is idle */
89e22bee78STejun Heo 	WORKER_PREP		= 1 << 3,	/* preparing to run works */
90fb0e7bebSTejun Heo 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
91f3421797STejun Heo 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
92a9ab775bSTejun Heo 	WORKER_REBOUND		= 1 << 8,	/* worker was rebound */
93e22bee78STejun Heo 
94a9ab775bSTejun Heo 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_CPU_INTENSIVE |
95a9ab775bSTejun Heo 				  WORKER_UNBOUND | WORKER_REBOUND,
96e563d0a7STejun Heo };
97db7bccf4STejun Heo 
98e563d0a7STejun Heo enum wq_internal_consts {
99e34cdddbSTejun Heo 	NR_STD_WORKER_POOLS	= 2,		/* # standard pools per cpu */
1004ce62e9eSTejun Heo 
10129c91e99STejun Heo 	UNBOUND_POOL_HASH_ORDER	= 6,		/* hashed by pool->attrs */
102c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
103db7bccf4STejun Heo 
104e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
105e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
106e22bee78STejun Heo 
1073233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
1083233cdbdSTejun Heo 						/* call for help after 10ms
1093233cdbdSTejun Heo 						   (min two ticks) */
110e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
111e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
1121da177e4SLinus Torvalds 
1131da177e4SLinus Torvalds 	/*
114e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
1158698a745SDongsheng Yang 	 * all cpus.  Give MIN_NICE.
116e22bee78STejun Heo 	 */
1178698a745SDongsheng Yang 	RESCUER_NICE_LEVEL	= MIN_NICE,
1188698a745SDongsheng Yang 	HIGHPRI_NICE_LEVEL	= MIN_NICE,
119ecf6881fSTejun Heo 
12031c89007SAudra Mitchell 	WQ_NAME_LEN		= 32,
121c8e55f36STejun Heo };
122c8e55f36STejun Heo 
1231da177e4SLinus Torvalds /*
1244cb1ef64STejun Heo  * We don't want to trap softirq for too long. See MAX_SOFTIRQ_TIME and
1254cb1ef64STejun Heo  * MAX_SOFTIRQ_RESTART in kernel/softirq.c. These are macros because
1264cb1ef64STejun Heo  * msecs_to_jiffies() can't be an initializer.
1274cb1ef64STejun Heo  */
1284cb1ef64STejun Heo #define BH_WORKER_JIFFIES	msecs_to_jiffies(2)
1294cb1ef64STejun Heo #define BH_WORKER_RESTARTS	10
1304cb1ef64STejun Heo 
1314cb1ef64STejun Heo /*
1324690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1334690c4abSTejun Heo  *
134e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
135e41e704bSTejun Heo  *    everyone else.
1364690c4abSTejun Heo  *
137e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
138e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
139e22bee78STejun Heo  *
140d565ed63STejun Heo  * L: pool->lock protected.  Access with pool->lock held.
1414690c4abSTejun Heo  *
1425797b1c1STejun Heo  * LN: pool->lock and wq_node_nr_active->lock protected for writes. Either for
1435797b1c1STejun Heo  *     reads.
1445797b1c1STejun Heo  *
145bdf8b9bfSTejun Heo  * K: Only modified by worker while holding pool->lock. Can be safely read by
146bdf8b9bfSTejun Heo  *    self, while holding pool->lock or from IRQ context if %current is the
147bdf8b9bfSTejun Heo  *    kworker.
148bdf8b9bfSTejun Heo  *
149bdf8b9bfSTejun Heo  * S: Only modified by worker self.
150bdf8b9bfSTejun Heo  *
1511258fae7STejun Heo  * A: wq_pool_attach_mutex protected.
152822d8405STejun Heo  *
15368e13a67SLai Jiangshan  * PL: wq_pool_mutex protected.
15476af4d93STejun Heo  *
15524acfb71SThomas Gleixner  * PR: wq_pool_mutex protected for writes.  RCU protected for reads.
1565bcab335STejun Heo  *
1575b95e1afSLai Jiangshan  * PW: wq_pool_mutex and wq->mutex protected for writes.  Either for reads.
1585b95e1afSLai Jiangshan  *
1595b95e1afSLai Jiangshan  * PWR: wq_pool_mutex and wq->mutex protected for writes.  Either or
16024acfb71SThomas Gleixner  *      RCU for reads.
1615b95e1afSLai Jiangshan  *
1623c25a55dSLai Jiangshan  * WQ: wq->mutex protected.
1633c25a55dSLai Jiangshan  *
16424acfb71SThomas Gleixner  * WR: wq->mutex protected for writes.  RCU protected for reads.
1652e109a28STejun Heo  *
166a045a272STejun Heo  * WO: wq->mutex protected for writes. Updated with WRITE_ONCE() and can be read
167a045a272STejun Heo  *     with READ_ONCE() without locking.
168a045a272STejun Heo  *
1692e109a28STejun Heo  * MD: wq_mayday_lock protected.
170cd2440d6SPetr Mladek  *
171cd2440d6SPetr Mladek  * WD: Used internally by the watchdog.
1724690c4abSTejun Heo  */
1734690c4abSTejun Heo 
1742eaebdb3STejun Heo /* struct worker is defined in workqueue_internal.h */
175c34056a3STejun Heo 
176bd7bdd43STejun Heo struct worker_pool {
177a9b8a985SSebastian Andrzej Siewior 	raw_spinlock_t		lock;		/* the pool lock */
178d84ff051STejun Heo 	int			cpu;		/* I: the associated cpu */
179f3f90ad4STejun Heo 	int			node;		/* I: the associated node ID */
1809daf9e67STejun Heo 	int			id;		/* I: pool ID */
181bc8b50c2STejun Heo 	unsigned int		flags;		/* L: flags */
182bd7bdd43STejun Heo 
18382607adcSTejun Heo 	unsigned long		watchdog_ts;	/* L: watchdog timestamp */
184cd2440d6SPetr Mladek 	bool			cpu_stall;	/* WD: stalled cpu bound pool */
18582607adcSTejun Heo 
186bc35f7efSLai Jiangshan 	/*
187bc35f7efSLai Jiangshan 	 * The counter is incremented in a process context on the associated CPU
188bc35f7efSLai Jiangshan 	 * w/ preemption disabled, and decremented or reset in the same context
189bc35f7efSLai Jiangshan 	 * but w/ pool->lock held. The readers grab pool->lock and are
190bc35f7efSLai Jiangshan 	 * guaranteed to see if the counter reached zero.
191bc35f7efSLai Jiangshan 	 */
192bc35f7efSLai Jiangshan 	int			nr_running;
19384f91c62SLai Jiangshan 
194bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
195ea1abd61SLai Jiangshan 
1965826cc8fSLai Jiangshan 	int			nr_workers;	/* L: total number of workers */
1975826cc8fSLai Jiangshan 	int			nr_idle;	/* L: currently idle workers */
198bd7bdd43STejun Heo 
1992c1f1a91SLai Jiangshan 	struct list_head	idle_list;	/* L: list of idle workers */
200bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
2013f959aa3SValentin Schneider 	struct work_struct      idle_cull_work; /* L: worker idle cleanup */
2023f959aa3SValentin Schneider 
203bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	  /* L: SOS timer for workers */
204bd7bdd43STejun Heo 
205c5aa87bbSTejun Heo 	/* a workers is either on busy_hash or idle_list, or the manager */
206c9e7cf27STejun Heo 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
207c9e7cf27STejun Heo 						/* L: hash of busy workers */
208c9e7cf27STejun Heo 
2092607d7a6STejun Heo 	struct worker		*manager;	/* L: purely informational */
21092f9c5c4SLai Jiangshan 	struct list_head	workers;	/* A: attached workers */
211e02b9312SValentin Schneider 	struct list_head        dying_workers;  /* A: workers about to die */
21260f5a4bcSLai Jiangshan 	struct completion	*detach_completion; /* all workers detached */
213e19e397aSTejun Heo 
2147cda9aaeSLai Jiangshan 	struct ida		worker_ida;	/* worker IDs for task name */
215e19e397aSTejun Heo 
2167a4e344cSTejun Heo 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
21768e13a67SLai Jiangshan 	struct hlist_node	hash_node;	/* PL: unbound_pool_hash node */
21868e13a67SLai Jiangshan 	int			refcnt;		/* PL: refcnt for unbound pools */
2197a4e344cSTejun Heo 
220e19e397aSTejun Heo 	/*
22124acfb71SThomas Gleixner 	 * Destruction of pool is RCU protected to allow dereferences
22229c91e99STejun Heo 	 * from get_work_pool().
22329c91e99STejun Heo 	 */
22429c91e99STejun Heo 	struct rcu_head		rcu;
22584f91c62SLai Jiangshan };
2268b03ae3cSTejun Heo 
2278b03ae3cSTejun Heo /*
228725e8ec5STejun Heo  * Per-pool_workqueue statistics. These can be monitored using
229725e8ec5STejun Heo  * tools/workqueue/wq_monitor.py.
230725e8ec5STejun Heo  */
231725e8ec5STejun Heo enum pool_workqueue_stats {
232725e8ec5STejun Heo 	PWQ_STAT_STARTED,	/* work items started execution */
233725e8ec5STejun Heo 	PWQ_STAT_COMPLETED,	/* work items completed execution */
2348a1dd1e5STejun Heo 	PWQ_STAT_CPU_TIME,	/* total CPU time consumed */
235616db877STejun Heo 	PWQ_STAT_CPU_INTENSIVE,	/* wq_cpu_intensive_thresh_us violations */
236725e8ec5STejun Heo 	PWQ_STAT_CM_WAKEUP,	/* concurrency-management worker wakeups */
2378639ecebSTejun Heo 	PWQ_STAT_REPATRIATED,	/* unbound workers brought back into scope */
238725e8ec5STejun Heo 	PWQ_STAT_MAYDAY,	/* maydays to rescuer */
239725e8ec5STejun Heo 	PWQ_STAT_RESCUED,	/* linked work items executed by rescuer */
240725e8ec5STejun Heo 
241725e8ec5STejun Heo 	PWQ_NR_STATS,
242725e8ec5STejun Heo };
243725e8ec5STejun Heo 
244725e8ec5STejun Heo /*
245112202d9STejun Heo  * The per-pool workqueue.  While queued, the lower WORK_STRUCT_FLAG_BITS
246112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
247112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
248112202d9STejun Heo  * number of flag bits.
2491da177e4SLinus Torvalds  */
250112202d9STejun Heo struct pool_workqueue {
251bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
2524690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
25373f53c4aSTejun Heo 	int			work_color;	/* L: current color */
25473f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
2558864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
25673f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
25773f53c4aSTejun Heo 						/* L: nr of in_flight works */
258018f3a13SLai Jiangshan 
259018f3a13SLai Jiangshan 	/*
260018f3a13SLai Jiangshan 	 * nr_active management and WORK_STRUCT_INACTIVE:
261018f3a13SLai Jiangshan 	 *
262018f3a13SLai Jiangshan 	 * When pwq->nr_active >= max_active, new work item is queued to
263018f3a13SLai Jiangshan 	 * pwq->inactive_works instead of pool->worklist and marked with
264018f3a13SLai Jiangshan 	 * WORK_STRUCT_INACTIVE.
265018f3a13SLai Jiangshan 	 *
2665797b1c1STejun Heo 	 * All work items marked with WORK_STRUCT_INACTIVE do not participate in
2675797b1c1STejun Heo 	 * nr_active and all work items in pwq->inactive_works are marked with
2685797b1c1STejun Heo 	 * WORK_STRUCT_INACTIVE. But not all WORK_STRUCT_INACTIVE work items are
2695797b1c1STejun Heo 	 * in pwq->inactive_works. Some of them are ready to run in
2705797b1c1STejun Heo 	 * pool->worklist or worker->scheduled. Those work itmes are only struct
2715797b1c1STejun Heo 	 * wq_barrier which is used for flush_work() and should not participate
2725797b1c1STejun Heo 	 * in nr_active. For non-barrier work item, it is marked with
2735797b1c1STejun Heo 	 * WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
274018f3a13SLai Jiangshan 	 */
2751e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
276f97a4a1aSLai Jiangshan 	struct list_head	inactive_works;	/* L: inactive works */
2775797b1c1STejun Heo 	struct list_head	pending_node;	/* LN: node on wq_node_nr_active->pending_pwqs */
2783c25a55dSLai Jiangshan 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
2792e109a28STejun Heo 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
2808864b4e5STejun Heo 
281725e8ec5STejun Heo 	u64			stats[PWQ_NR_STATS];
282725e8ec5STejun Heo 
2838864b4e5STejun Heo 	/*
284967b494eSTejun Heo 	 * Release of unbound pwq is punted to a kthread_worker. See put_pwq()
285687a9aa5STejun Heo 	 * and pwq_release_workfn() for details. pool_workqueue itself is also
286687a9aa5STejun Heo 	 * RCU protected so that the first pwq can be determined without
287967b494eSTejun Heo 	 * grabbing wq->mutex.
2888864b4e5STejun Heo 	 */
289687a9aa5STejun Heo 	struct kthread_work	release_work;
2908864b4e5STejun Heo 	struct rcu_head		rcu;
291e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2921da177e4SLinus Torvalds 
2931da177e4SLinus Torvalds /*
29473f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
29573f53c4aSTejun Heo  */
29673f53c4aSTejun Heo struct wq_flusher {
2973c25a55dSLai Jiangshan 	struct list_head	list;		/* WQ: list of flushers */
2983c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: flush color waiting for */
29973f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
30073f53c4aSTejun Heo };
3011da177e4SLinus Torvalds 
302226223abSTejun Heo struct wq_device;
303226223abSTejun Heo 
30473f53c4aSTejun Heo /*
30591ccc6e7STejun Heo  * Unlike in a per-cpu workqueue where max_active limits its concurrency level
30691ccc6e7STejun Heo  * on each CPU, in an unbound workqueue, max_active applies to the whole system.
30791ccc6e7STejun Heo  * As sharing a single nr_active across multiple sockets can be very expensive,
30891ccc6e7STejun Heo  * the counting and enforcement is per NUMA node.
3095797b1c1STejun Heo  *
3105797b1c1STejun Heo  * The following struct is used to enforce per-node max_active. When a pwq wants
3115797b1c1STejun Heo  * to start executing a work item, it should increment ->nr using
3125797b1c1STejun Heo  * tryinc_node_nr_active(). If acquisition fails due to ->nr already being over
3135797b1c1STejun Heo  * ->max, the pwq is queued on ->pending_pwqs. As in-flight work items finish
3145797b1c1STejun Heo  * and decrement ->nr, node_activate_pending_pwq() activates the pending pwqs in
3155797b1c1STejun Heo  * round-robin order.
31691ccc6e7STejun Heo  */
31791ccc6e7STejun Heo struct wq_node_nr_active {
3185797b1c1STejun Heo 	int			max;		/* per-node max_active */
3195797b1c1STejun Heo 	atomic_t		nr;		/* per-node nr_active */
3205797b1c1STejun Heo 	raw_spinlock_t		lock;		/* nests inside pool locks */
3215797b1c1STejun Heo 	struct list_head	pending_pwqs;	/* LN: pwqs with inactive works */
32291ccc6e7STejun Heo };
32391ccc6e7STejun Heo 
32491ccc6e7STejun Heo /*
325c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
326c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
3271da177e4SLinus Torvalds  */
3281da177e4SLinus Torvalds struct workqueue_struct {
3293c25a55dSLai Jiangshan 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
330e2dca7adSTejun Heo 	struct list_head	list;		/* PR: list of all workqueues */
33173f53c4aSTejun Heo 
3323c25a55dSLai Jiangshan 	struct mutex		mutex;		/* protects this wq */
3333c25a55dSLai Jiangshan 	int			work_color;	/* WQ: current work color */
3343c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: current flush color */
335112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
3363c25a55dSLai Jiangshan 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
3373c25a55dSLai Jiangshan 	struct list_head	flusher_queue;	/* WQ: flush waiters */
3383c25a55dSLai Jiangshan 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
33973f53c4aSTejun Heo 
3402e109a28STejun Heo 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
34130ae2fc0STejun Heo 	struct worker		*rescuer;	/* MD: rescue worker */
342e22bee78STejun Heo 
34387fc741eSLai Jiangshan 	int			nr_drainers;	/* WQ: drain in progress */
3445797b1c1STejun Heo 
3455797b1c1STejun Heo 	/* See alloc_workqueue() function comment for info on min/max_active */
346a045a272STejun Heo 	int			max_active;	/* WO: max active works */
3475797b1c1STejun Heo 	int			min_active;	/* WO: min active works */
348a045a272STejun Heo 	int			saved_max_active; /* WQ: saved max_active */
3495797b1c1STejun Heo 	int			saved_min_active; /* WQ: saved min_active */
350226223abSTejun Heo 
3515b95e1afSLai Jiangshan 	struct workqueue_attrs	*unbound_attrs;	/* PW: only for unbound wqs */
3529f66cff2STejun Heo 	struct pool_workqueue __rcu *dfl_pwq;   /* PW: only for unbound wqs */
3536029a918STejun Heo 
354226223abSTejun Heo #ifdef CONFIG_SYSFS
355226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
356226223abSTejun Heo #endif
3574e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
358669de8bdSBart Van Assche 	char			*lock_name;
359669de8bdSBart Van Assche 	struct lock_class_key	key;
3604e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
3614e6045f1SJohannes Berg #endif
362ecf6881fSTejun Heo 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
3632728fd2fSTejun Heo 
364e2dca7adSTejun Heo 	/*
36524acfb71SThomas Gleixner 	 * Destruction of workqueue_struct is RCU protected to allow walking
36624acfb71SThomas Gleixner 	 * the workqueues list without grabbing wq_pool_mutex.
367e2dca7adSTejun Heo 	 * This is used to dump all workqueues from sysrq.
368e2dca7adSTejun Heo 	 */
369e2dca7adSTejun Heo 	struct rcu_head		rcu;
370e2dca7adSTejun Heo 
3712728fd2fSTejun Heo 	/* hot fields used during command issue, aligned to cacheline */
3722728fd2fSTejun Heo 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
373636b927eSTejun Heo 	struct pool_workqueue __percpu __rcu **cpu_pwq; /* I: per-cpu pwqs */
37491ccc6e7STejun Heo 	struct wq_node_nr_active *node_nr_active[]; /* I: per-node nr_active */
3751da177e4SLinus Torvalds };
3761da177e4SLinus Torvalds 
377e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
378e904e6c2STejun Heo 
37984193c07STejun Heo /*
38084193c07STejun Heo  * Each pod type describes how CPUs should be grouped for unbound workqueues.
38184193c07STejun Heo  * See the comment above workqueue_attrs->affn_scope.
38284193c07STejun Heo  */
38384193c07STejun Heo struct wq_pod_type {
38484193c07STejun Heo 	int			nr_pods;	/* number of pods */
38584193c07STejun Heo 	cpumask_var_t		*pod_cpus;	/* pod -> cpus */
38684193c07STejun Heo 	int			*pod_node;	/* pod -> node */
38784193c07STejun Heo 	int			*cpu_pod;	/* cpu -> pod */
38884193c07STejun Heo };
38984193c07STejun Heo 
39084193c07STejun Heo static struct wq_pod_type wq_pod_types[WQ_AFFN_NR_TYPES];
391523a301eSTejun Heo static enum wq_affn_scope wq_affn_dfl = WQ_AFFN_CACHE;
39263c5484eSTejun Heo 
39363c5484eSTejun Heo static const char *wq_affn_names[WQ_AFFN_NR_TYPES] = {
394523a301eSTejun Heo 	[WQ_AFFN_DFL]			= "default",
39563c5484eSTejun Heo 	[WQ_AFFN_CPU]			= "cpu",
39663c5484eSTejun Heo 	[WQ_AFFN_SMT]			= "smt",
39763c5484eSTejun Heo 	[WQ_AFFN_CACHE]			= "cache",
39863c5484eSTejun Heo 	[WQ_AFFN_NUMA]			= "numa",
39963c5484eSTejun Heo 	[WQ_AFFN_SYSTEM]		= "system",
40063c5484eSTejun Heo };
401bce90380STejun Heo 
402c5f8cd6cSTejun Heo static bool wq_topo_initialized __read_mostly = false;
403c5f8cd6cSTejun Heo 
404616db877STejun Heo /*
405616db877STejun Heo  * Per-cpu work items which run for longer than the following threshold are
406616db877STejun Heo  * automatically considered CPU intensive and excluded from concurrency
407616db877STejun Heo  * management to prevent them from noticeably delaying other per-cpu work items.
408aa6fde93STejun Heo  * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
409aa6fde93STejun Heo  * The actual value is initialized in wq_cpu_intensive_thresh_init().
410616db877STejun Heo  */
411aa6fde93STejun Heo static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
412616db877STejun Heo module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
413616db877STejun Heo 
414cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
415552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
416cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
417cee22a15SViresh Kumar 
418863b710bSTejun Heo static bool wq_online;			/* can kworkers be created yet? */
4193347fa09STejun Heo 
420fef59c9cSTejun Heo /* buf for wq_update_unbound_pod_attrs(), protected by CPU hotplug exclusion */
421fef59c9cSTejun Heo static struct workqueue_attrs *wq_update_pod_attrs_buf;
4224c16bd32STejun Heo 
42368e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
4241258fae7STejun Heo static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
425a9b8a985SSebastian Andrzej Siewior static DEFINE_RAW_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
426d8bb65abSSebastian Andrzej Siewior /* wait for manager to go away */
427d8bb65abSSebastian Andrzej Siewior static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
4285bcab335STejun Heo 
429e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
43068e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
4317d19c5ceSTejun Heo 
43299c621efSLai Jiangshan /* PL&A: allowable cpus for unbound wqs and work items */
433ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
434ef557180SMike Galbraith 
435fe28f631SWaiman Long /* PL: user requested unbound cpumask via sysfs */
436fe28f631SWaiman Long static cpumask_var_t wq_requested_unbound_cpumask;
437fe28f631SWaiman Long 
438fe28f631SWaiman Long /* PL: isolated cpumask to be excluded from unbound cpumask */
439fe28f631SWaiman Long static cpumask_var_t wq_isolated_cpumask;
440fe28f631SWaiman Long 
441ace3c549Stiozhang /* for further constrain wq_unbound_cpumask by cmdline parameter*/
442ace3c549Stiozhang static struct cpumask wq_cmdline_cpumask __initdata;
443ace3c549Stiozhang 
444ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
445ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
446b05a7928SFrederic Weisbecker 
447f303fccbSTejun Heo /*
448f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
449f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
450f303fccbSTejun Heo  * to uncover usages which depend on it.
451f303fccbSTejun Heo  */
452f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
453f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
454f303fccbSTejun Heo #else
455f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
456f303fccbSTejun Heo #endif
457f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
458f303fccbSTejun Heo 
4594cb1ef64STejun Heo /* the BH worker pools */
4604cb1ef64STejun Heo static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
4614cb1ef64STejun Heo 				     bh_worker_pools);
4624cb1ef64STejun Heo 
4637d19c5ceSTejun Heo /* the per-cpu worker pools */
4644cb1ef64STejun Heo static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
4654cb1ef64STejun Heo 				     cpu_worker_pools);
4667d19c5ceSTejun Heo 
46768e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
4687d19c5ceSTejun Heo 
46968e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
47029c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
47129c91e99STejun Heo 
472c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
47329c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
47429c91e99STejun Heo 
4758a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
4768a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
4778a2b7538STejun Heo 
478967b494eSTejun Heo /*
479967b494eSTejun Heo  * I: kthread_worker to release pwq's. pwq release needs to be bounced to a
480967b494eSTejun Heo  * process context while holding a pool lock. Bounce to a dedicated kthread
481967b494eSTejun Heo  * worker to avoid A-A deadlocks.
482967b494eSTejun Heo  */
48368279f9cSAlexey Dobriyan static struct kthread_worker *pwq_release_worker __ro_after_init;
484967b494eSTejun Heo 
48568279f9cSAlexey Dobriyan struct workqueue_struct *system_wq __ro_after_init;
486ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
48768279f9cSAlexey Dobriyan struct workqueue_struct *system_highpri_wq __ro_after_init;
4881aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
48968279f9cSAlexey Dobriyan struct workqueue_struct *system_long_wq __ro_after_init;
490d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
49168279f9cSAlexey Dobriyan struct workqueue_struct *system_unbound_wq __ro_after_init;
492f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
49368279f9cSAlexey Dobriyan struct workqueue_struct *system_freezable_wq __ro_after_init;
49424d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
49568279f9cSAlexey Dobriyan struct workqueue_struct *system_power_efficient_wq __ro_after_init;
4960668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
49768279f9cSAlexey Dobriyan struct workqueue_struct *system_freezable_power_efficient_wq __ro_after_init;
4980668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
4994cb1ef64STejun Heo struct workqueue_struct *system_bh_wq;
5004cb1ef64STejun Heo EXPORT_SYMBOL_GPL(system_bh_wq);
5014cb1ef64STejun Heo struct workqueue_struct *system_bh_highpri_wq;
5024cb1ef64STejun Heo EXPORT_SYMBOL_GPL(system_bh_highpri_wq);
503d320c038STejun Heo 
5047d19c5ceSTejun Heo static int worker_thread(void *__worker);
5056ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
506c29eb853STejun Heo static void show_pwq(struct pool_workqueue *pwq);
50755df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool);
5087d19c5ceSTejun Heo 
50997bd2347STejun Heo #define CREATE_TRACE_POINTS
51097bd2347STejun Heo #include <trace/events/workqueue.h>
51197bd2347STejun Heo 
51268e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
51324acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
514f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
51524acfb71SThomas Gleixner 			 "RCU or wq_pool_mutex should be held")
5165bcab335STejun Heo 
5175b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
51824acfb71SThomas Gleixner 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
519f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
520f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
52124acfb71SThomas Gleixner 			 "RCU, wq->mutex or wq_pool_mutex should be held")
5225b95e1afSLai Jiangshan 
5234cb1ef64STejun Heo #define for_each_bh_worker_pool(pool, cpu)				\
5244cb1ef64STejun Heo 	for ((pool) = &per_cpu(bh_worker_pools, cpu)[0];		\
5254cb1ef64STejun Heo 	     (pool) < &per_cpu(bh_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
5264cb1ef64STejun Heo 	     (pool)++)
5274cb1ef64STejun Heo 
528f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
529f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
530f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
5317a62c2c8STejun Heo 	     (pool)++)
5324ce62e9eSTejun Heo 
53349e3cf44STejun Heo /**
53417116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
53517116969STejun Heo  * @pool: iteration cursor
536611c92a0STejun Heo  * @pi: integer used for iteration
537fa1b54e6STejun Heo  *
53824acfb71SThomas Gleixner  * This must be called either with wq_pool_mutex held or RCU read
53968e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
54068e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
541fa1b54e6STejun Heo  *
542fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
543fa1b54e6STejun Heo  * ignored.
54417116969STejun Heo  */
545611c92a0STejun Heo #define for_each_pool(pool, pi)						\
546611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
54768e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
548fa1b54e6STejun Heo 		else
54917116969STejun Heo 
55017116969STejun Heo /**
551822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
552822d8405STejun Heo  * @worker: iteration cursor
553822d8405STejun Heo  * @pool: worker_pool to iterate workers of
554822d8405STejun Heo  *
5551258fae7STejun Heo  * This must be called with wq_pool_attach_mutex.
556822d8405STejun Heo  *
557822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
558822d8405STejun Heo  * ignored.
559822d8405STejun Heo  */
560da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
561da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
5621258fae7STejun Heo 		if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
563822d8405STejun Heo 		else
564822d8405STejun Heo 
565822d8405STejun Heo /**
56649e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
56749e3cf44STejun Heo  * @pwq: iteration cursor
56849e3cf44STejun Heo  * @wq: the target workqueue
56976af4d93STejun Heo  *
57024acfb71SThomas Gleixner  * This must be called either with wq->mutex held or RCU read locked.
571794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
572794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
57376af4d93STejun Heo  *
57476af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
57576af4d93STejun Heo  * ignored.
57649e3cf44STejun Heo  */
57749e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
57849e9d1a9SSebastian Andrzej Siewior 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node,		\
5795a644662SJoel Fernandes (Google) 				 lockdep_is_held(&(wq->mutex)))
580f3421797STejun Heo 
581dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
582dc186ad7SThomas Gleixner 
583f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr;
584dc186ad7SThomas Gleixner 
58599777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
58699777288SStanislaw Gruszka {
58799777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
58899777288SStanislaw Gruszka }
58999777288SStanislaw Gruszka 
590b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
591b9fdac7fSDu, Changbin {
592b9fdac7fSDu, Changbin 	struct work_struct *work = addr;
593b9fdac7fSDu, Changbin 
594b9fdac7fSDu, Changbin 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
595b9fdac7fSDu, Changbin }
596b9fdac7fSDu, Changbin 
597dc186ad7SThomas Gleixner /*
598dc186ad7SThomas Gleixner  * fixup_init is called when:
599dc186ad7SThomas Gleixner  * - an active object is initialized
600dc186ad7SThomas Gleixner  */
60102a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
602dc186ad7SThomas Gleixner {
603dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
604dc186ad7SThomas Gleixner 
605dc186ad7SThomas Gleixner 	switch (state) {
606dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
607dc186ad7SThomas Gleixner 		cancel_work_sync(work);
608dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
60902a982a6SDu, Changbin 		return true;
610dc186ad7SThomas Gleixner 	default:
61102a982a6SDu, Changbin 		return false;
612dc186ad7SThomas Gleixner 	}
613dc186ad7SThomas Gleixner }
614dc186ad7SThomas Gleixner 
615dc186ad7SThomas Gleixner /*
616dc186ad7SThomas Gleixner  * fixup_free is called when:
617dc186ad7SThomas Gleixner  * - an active object is freed
618dc186ad7SThomas Gleixner  */
61902a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
620dc186ad7SThomas Gleixner {
621dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
622dc186ad7SThomas Gleixner 
623dc186ad7SThomas Gleixner 	switch (state) {
624dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
625dc186ad7SThomas Gleixner 		cancel_work_sync(work);
626dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
62702a982a6SDu, Changbin 		return true;
628dc186ad7SThomas Gleixner 	default:
62902a982a6SDu, Changbin 		return false;
630dc186ad7SThomas Gleixner 	}
631dc186ad7SThomas Gleixner }
632dc186ad7SThomas Gleixner 
633f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr = {
634dc186ad7SThomas Gleixner 	.name		= "work_struct",
63599777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
636b9fdac7fSDu, Changbin 	.is_static_object = work_is_static_object,
637dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
638dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
639dc186ad7SThomas Gleixner };
640dc186ad7SThomas Gleixner 
641dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
642dc186ad7SThomas Gleixner {
643dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
644dc186ad7SThomas Gleixner }
645dc186ad7SThomas Gleixner 
646dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
647dc186ad7SThomas Gleixner {
648dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
649dc186ad7SThomas Gleixner }
650dc186ad7SThomas Gleixner 
651dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
652dc186ad7SThomas Gleixner {
653dc186ad7SThomas Gleixner 	if (onstack)
654dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
655dc186ad7SThomas Gleixner 	else
656dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
657dc186ad7SThomas Gleixner }
658dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
659dc186ad7SThomas Gleixner 
660dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
661dc186ad7SThomas Gleixner {
662dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
663dc186ad7SThomas Gleixner }
664dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
665dc186ad7SThomas Gleixner 
666ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
667ea2e64f2SThomas Gleixner {
668ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
669ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
670ea2e64f2SThomas Gleixner }
671ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
672ea2e64f2SThomas Gleixner 
673dc186ad7SThomas Gleixner #else
674dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
675dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
676dc186ad7SThomas Gleixner #endif
677dc186ad7SThomas Gleixner 
6784e8b22bdSLi Bin /**
67967dc8325SCai Huoqing  * worker_pool_assign_id - allocate ID and assign it to @pool
6804e8b22bdSLi Bin  * @pool: the pool pointer of interest
6814e8b22bdSLi Bin  *
6824e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
6834e8b22bdSLi Bin  * successfully, -errno on failure.
6844e8b22bdSLi Bin  */
6859daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
6869daf9e67STejun Heo {
6879daf9e67STejun Heo 	int ret;
6889daf9e67STejun Heo 
68968e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
6905bcab335STejun Heo 
6914e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
6924e8b22bdSLi Bin 			GFP_KERNEL);
693229641a6STejun Heo 	if (ret >= 0) {
694e68035fbSTejun Heo 		pool->id = ret;
695229641a6STejun Heo 		return 0;
696229641a6STejun Heo 	}
6979daf9e67STejun Heo 	return ret;
6989daf9e67STejun Heo }
6999daf9e67STejun Heo 
7009f66cff2STejun Heo static struct pool_workqueue __rcu **
7019f66cff2STejun Heo unbound_pwq_slot(struct workqueue_struct *wq, int cpu)
7029f66cff2STejun Heo {
7039f66cff2STejun Heo        if (cpu >= 0)
7049f66cff2STejun Heo                return per_cpu_ptr(wq->cpu_pwq, cpu);
7059f66cff2STejun Heo        else
7069f66cff2STejun Heo                return &wq->dfl_pwq;
7079f66cff2STejun Heo }
7089f66cff2STejun Heo 
7099f66cff2STejun Heo /* @cpu < 0 for dfl_pwq */
7109f66cff2STejun Heo static struct pool_workqueue *unbound_pwq(struct workqueue_struct *wq, int cpu)
7119f66cff2STejun Heo {
7129f66cff2STejun Heo 	return rcu_dereference_check(*unbound_pwq_slot(wq, cpu),
7139f66cff2STejun Heo 				     lockdep_is_held(&wq_pool_mutex) ||
7149f66cff2STejun Heo 				     lockdep_is_held(&wq->mutex));
7159f66cff2STejun Heo }
7169f66cff2STejun Heo 
7175797b1c1STejun Heo /**
7185797b1c1STejun Heo  * unbound_effective_cpumask - effective cpumask of an unbound workqueue
7195797b1c1STejun Heo  * @wq: workqueue of interest
7205797b1c1STejun Heo  *
7215797b1c1STejun Heo  * @wq->unbound_attrs->cpumask contains the cpumask requested by the user which
7225797b1c1STejun Heo  * is masked with wq_unbound_cpumask to determine the effective cpumask. The
7235797b1c1STejun Heo  * default pwq is always mapped to the pool with the current effective cpumask.
7245797b1c1STejun Heo  */
7255797b1c1STejun Heo static struct cpumask *unbound_effective_cpumask(struct workqueue_struct *wq)
7265797b1c1STejun Heo {
7275797b1c1STejun Heo 	return unbound_pwq(wq, -1)->pool->attrs->__pod_cpumask;
7285797b1c1STejun Heo }
7295797b1c1STejun Heo 
73073f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
73173f53c4aSTejun Heo {
73273f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
73373f53c4aSTejun Heo }
73473f53c4aSTejun Heo 
735c4560c2cSLai Jiangshan static int get_work_color(unsigned long work_data)
73673f53c4aSTejun Heo {
737c4560c2cSLai Jiangshan 	return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
73873f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
73973f53c4aSTejun Heo }
74073f53c4aSTejun Heo 
74173f53c4aSTejun Heo static int work_next_color(int color)
74273f53c4aSTejun Heo {
74373f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
744a848e3b6SOleg Nesterov }
745a848e3b6SOleg Nesterov 
7464594bf15SDavid Howells /*
747112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
748112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
7497c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
7507a22ad75STejun Heo  *
751112202d9STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
752112202d9STejun Heo  * and clear_work_data() can be used to set the pwq, pool or clear
753bbb68dfaSTejun Heo  * work->data.  These functions should only be called while the work is
754bbb68dfaSTejun Heo  * owned - ie. while the PENDING bit is set.
7557a22ad75STejun Heo  *
756112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
7577c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
758112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
7597c3eed5cSTejun Heo  * available only while the work item is queued.
760bbb68dfaSTejun Heo  *
761bbb68dfaSTejun Heo  * %WORK_OFFQ_CANCELING is used to mark a work item which is being
762bbb68dfaSTejun Heo  * canceled.  While being canceled, a work item may have its PENDING set
763bbb68dfaSTejun Heo  * but stay off timer and worklist for arbitrarily long and nobody should
764bbb68dfaSTejun Heo  * try to steal the PENDING bit.
7654594bf15SDavid Howells  */
7667a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
7677a22ad75STejun Heo 				 unsigned long flags)
7687a22ad75STejun Heo {
7696183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
7707a22ad75STejun Heo 	atomic_long_set(&work->data, data | flags | work_static(work));
7717a22ad75STejun Heo }
7727a22ad75STejun Heo 
773112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
7744690c4abSTejun Heo 			 unsigned long extra_flags)
775365970a1SDavid Howells {
776112202d9STejun Heo 	set_work_data(work, (unsigned long)pwq,
777112202d9STejun Heo 		      WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
778365970a1SDavid Howells }
779365970a1SDavid Howells 
7804468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
7814468a00fSLai Jiangshan 					   int pool_id)
7824468a00fSLai Jiangshan {
7834468a00fSLai Jiangshan 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
7844468a00fSLai Jiangshan 		      WORK_STRUCT_PENDING);
7854468a00fSLai Jiangshan }
7864468a00fSLai Jiangshan 
7877c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
7887c3eed5cSTejun Heo 					    int pool_id)
7894d707b9fSOleg Nesterov {
79023657bb1STejun Heo 	/*
79123657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
79223657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
79323657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
79423657bb1STejun Heo 	 * owner.
79523657bb1STejun Heo 	 */
79623657bb1STejun Heo 	smp_wmb();
7977c3eed5cSTejun Heo 	set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
798346c09f8SRoman Pen 	/*
799346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
800346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
801346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
8028bdc6201SLiu Song 	 * reordering can lead to a missed execution on attempt to queue
803346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
804346c09f8SRoman Pen 	 *
805346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
806346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
807346c09f8SRoman Pen 	 *
808346c09f8SRoman Pen 	 * 1  STORE event_indicated
809346c09f8SRoman Pen 	 * 2  queue_work_on() {
810346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
811346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
812346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
813346c09f8SRoman Pen 	 * 6                                 smp_mb()
814346c09f8SRoman Pen 	 * 7                               work->current_func() {
815346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
816346c09f8SRoman Pen 	 *				   }
817346c09f8SRoman Pen 	 *
818346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
819346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
820346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
821346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
822346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
823346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
824346c09f8SRoman Pen 	 * before actual STORE.
825346c09f8SRoman Pen 	 */
826346c09f8SRoman Pen 	smp_mb();
8274d707b9fSOleg Nesterov }
8284d707b9fSOleg Nesterov 
8297a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
830365970a1SDavid Howells {
8317c3eed5cSTejun Heo 	smp_wmb();	/* see set_work_pool_and_clear_pending() */
8327c3eed5cSTejun Heo 	set_work_data(work, WORK_STRUCT_NO_POOL, 0);
8337a22ad75STejun Heo }
8347a22ad75STejun Heo 
835afa4bb77SLinus Torvalds static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
836afa4bb77SLinus Torvalds {
837afa4bb77SLinus Torvalds 	return (struct pool_workqueue *)(data & WORK_STRUCT_WQ_DATA_MASK);
838afa4bb77SLinus Torvalds }
839afa4bb77SLinus Torvalds 
840112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
8417a22ad75STejun Heo {
842e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
8437a22ad75STejun Heo 
844112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
845afa4bb77SLinus Torvalds 		return work_struct_pwq(data);
846e120153dSTejun Heo 	else
847e120153dSTejun Heo 		return NULL;
8487a22ad75STejun Heo }
8497a22ad75STejun Heo 
8507c3eed5cSTejun Heo /**
8517c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
8527c3eed5cSTejun Heo  * @work: the work item of interest
8537c3eed5cSTejun Heo  *
85468e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
85524acfb71SThomas Gleixner  * access under RCU read lock.  As such, this function should be
85624acfb71SThomas Gleixner  * called under wq_pool_mutex or inside of a rcu_read_lock() region.
857fa1b54e6STejun Heo  *
858fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
859fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
860fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
861fa1b54e6STejun Heo  * returned pool is and stays online.
862d185af30SYacine Belkadi  *
863d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
8647c3eed5cSTejun Heo  */
8657c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
8667a22ad75STejun Heo {
867e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
8687c3eed5cSTejun Heo 	int pool_id;
8697a22ad75STejun Heo 
87068e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
871fa1b54e6STejun Heo 
872112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
873afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool;
8747a22ad75STejun Heo 
8757c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
8767c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
8777a22ad75STejun Heo 		return NULL;
8787a22ad75STejun Heo 
879fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
8807c3eed5cSTejun Heo }
8817c3eed5cSTejun Heo 
8827c3eed5cSTejun Heo /**
8837c3eed5cSTejun Heo  * get_work_pool_id - return the worker pool ID a given work is associated with
8847c3eed5cSTejun Heo  * @work: the work item of interest
8857c3eed5cSTejun Heo  *
886d185af30SYacine Belkadi  * Return: The worker_pool ID @work was last associated with.
8877c3eed5cSTejun Heo  * %WORK_OFFQ_POOL_NONE if none.
8887c3eed5cSTejun Heo  */
8897c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
8907c3eed5cSTejun Heo {
89154d5b7d0SLai Jiangshan 	unsigned long data = atomic_long_read(&work->data);
8927c3eed5cSTejun Heo 
893112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
894afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool->id;
89554d5b7d0SLai Jiangshan 
89654d5b7d0SLai Jiangshan 	return data >> WORK_OFFQ_POOL_SHIFT;
8977c3eed5cSTejun Heo }
8987c3eed5cSTejun Heo 
899bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
900bbb68dfaSTejun Heo {
9017c3eed5cSTejun Heo 	unsigned long pool_id = get_work_pool_id(work);
902bbb68dfaSTejun Heo 
9037c3eed5cSTejun Heo 	pool_id <<= WORK_OFFQ_POOL_SHIFT;
9047c3eed5cSTejun Heo 	set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
905bbb68dfaSTejun Heo }
906bbb68dfaSTejun Heo 
907bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
908bbb68dfaSTejun Heo {
909bbb68dfaSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
910bbb68dfaSTejun Heo 
911112202d9STejun Heo 	return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
912bbb68dfaSTejun Heo }
913bbb68dfaSTejun Heo 
914e22bee78STejun Heo /*
9153270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
9163270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
917d565ed63STejun Heo  * they're being called with pool->lock held.
918e22bee78STejun Heo  */
919e22bee78STejun Heo 
920e22bee78STejun Heo /*
921e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
922e22bee78STejun Heo  * running workers.
923974271c4STejun Heo  *
924974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
925706026c2STejun Heo  * function will always return %true for unbound pools as long as the
926974271c4STejun Heo  * worklist isn't empty.
927e22bee78STejun Heo  */
92863d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
929e22bee78STejun Heo {
9300219a352STejun Heo 	return !list_empty(&pool->worklist) && !pool->nr_running;
931e22bee78STejun Heo }
932e22bee78STejun Heo 
933e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
93463d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
935e22bee78STejun Heo {
93663d95a91STejun Heo 	return pool->nr_idle;
937e22bee78STejun Heo }
938e22bee78STejun Heo 
939e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
94063d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
941e22bee78STejun Heo {
942bc35f7efSLai Jiangshan 	return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
943e22bee78STejun Heo }
944e22bee78STejun Heo 
945e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
94663d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
947e22bee78STejun Heo {
94863d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
949e22bee78STejun Heo }
950e22bee78STejun Heo 
951e22bee78STejun Heo /* Do we have too many workers and should some go away? */
95263d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
953e22bee78STejun Heo {
954692b4825STejun Heo 	bool managing = pool->flags & POOL_MANAGER_ACTIVE;
95563d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
95663d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
957e22bee78STejun Heo 
958e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
959e22bee78STejun Heo }
960e22bee78STejun Heo 
9614690c4abSTejun Heo /**
962e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
963cb444766STejun Heo  * @worker: self
964d302f017STejun Heo  * @flags: flags to set
965d302f017STejun Heo  *
966228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
967d302f017STejun Heo  */
968228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
969d302f017STejun Heo {
970bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
971e22bee78STejun Heo 
972bc8b50c2STejun Heo 	lockdep_assert_held(&pool->lock);
973cb444766STejun Heo 
974228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
975e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
976e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
977bc35f7efSLai Jiangshan 		pool->nr_running--;
978e22bee78STejun Heo 	}
979e22bee78STejun Heo 
980d302f017STejun Heo 	worker->flags |= flags;
981d302f017STejun Heo }
982d302f017STejun Heo 
983d302f017STejun Heo /**
984e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
985cb444766STejun Heo  * @worker: self
986d302f017STejun Heo  * @flags: flags to clear
987d302f017STejun Heo  *
988e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
989d302f017STejun Heo  */
990d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
991d302f017STejun Heo {
99263d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
993e22bee78STejun Heo 	unsigned int oflags = worker->flags;
994e22bee78STejun Heo 
995bc8b50c2STejun Heo 	lockdep_assert_held(&pool->lock);
996cb444766STejun Heo 
997d302f017STejun Heo 	worker->flags &= ~flags;
998e22bee78STejun Heo 
99942c025f3STejun Heo 	/*
100042c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
100142c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
100242c025f3STejun Heo 	 * of multiple flags, not a single flag.
100342c025f3STejun Heo 	 */
1004e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
1005e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
1006bc35f7efSLai Jiangshan 			pool->nr_running++;
1007d302f017STejun Heo }
1008d302f017STejun Heo 
1009797e8345STejun Heo /* Return the first idle worker.  Called with pool->lock held. */
1010797e8345STejun Heo static struct worker *first_idle_worker(struct worker_pool *pool)
1011797e8345STejun Heo {
1012797e8345STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
1013797e8345STejun Heo 		return NULL;
1014797e8345STejun Heo 
1015797e8345STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
1016797e8345STejun Heo }
1017797e8345STejun Heo 
1018797e8345STejun Heo /**
1019797e8345STejun Heo  * worker_enter_idle - enter idle state
1020797e8345STejun Heo  * @worker: worker which is entering idle state
1021797e8345STejun Heo  *
1022797e8345STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1023797e8345STejun Heo  * necessary.
1024797e8345STejun Heo  *
1025797e8345STejun Heo  * LOCKING:
1026797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1027797e8345STejun Heo  */
1028797e8345STejun Heo static void worker_enter_idle(struct worker *worker)
1029797e8345STejun Heo {
1030797e8345STejun Heo 	struct worker_pool *pool = worker->pool;
1031797e8345STejun Heo 
1032797e8345STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1033797e8345STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
1034797e8345STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
1035797e8345STejun Heo 		return;
1036797e8345STejun Heo 
1037797e8345STejun Heo 	/* can't use worker_set_flags(), also called from create_worker() */
1038797e8345STejun Heo 	worker->flags |= WORKER_IDLE;
1039797e8345STejun Heo 	pool->nr_idle++;
1040797e8345STejun Heo 	worker->last_active = jiffies;
1041797e8345STejun Heo 
1042797e8345STejun Heo 	/* idle_list is LIFO */
1043797e8345STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1044797e8345STejun Heo 
1045797e8345STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1046797e8345STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1047797e8345STejun Heo 
1048797e8345STejun Heo 	/* Sanity check nr_running. */
1049797e8345STejun Heo 	WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
1050797e8345STejun Heo }
1051797e8345STejun Heo 
1052797e8345STejun Heo /**
1053797e8345STejun Heo  * worker_leave_idle - leave idle state
1054797e8345STejun Heo  * @worker: worker which is leaving idle state
1055797e8345STejun Heo  *
1056797e8345STejun Heo  * @worker is leaving idle state.  Update stats.
1057797e8345STejun Heo  *
1058797e8345STejun Heo  * LOCKING:
1059797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1060797e8345STejun Heo  */
1061797e8345STejun Heo static void worker_leave_idle(struct worker *worker)
1062797e8345STejun Heo {
1063797e8345STejun Heo 	struct worker_pool *pool = worker->pool;
1064797e8345STejun Heo 
1065797e8345STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1066797e8345STejun Heo 		return;
1067797e8345STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1068797e8345STejun Heo 	pool->nr_idle--;
1069797e8345STejun Heo 	list_del_init(&worker->entry);
1070797e8345STejun Heo }
1071797e8345STejun Heo 
1072797e8345STejun Heo /**
1073797e8345STejun Heo  * find_worker_executing_work - find worker which is executing a work
1074797e8345STejun Heo  * @pool: pool of interest
1075797e8345STejun Heo  * @work: work to find worker for
1076797e8345STejun Heo  *
1077797e8345STejun Heo  * Find a worker which is executing @work on @pool by searching
1078797e8345STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
1079797e8345STejun Heo  * to match, its current execution should match the address of @work and
1080797e8345STejun Heo  * its work function.  This is to avoid unwanted dependency between
1081797e8345STejun Heo  * unrelated work executions through a work item being recycled while still
1082797e8345STejun Heo  * being executed.
1083797e8345STejun Heo  *
1084797e8345STejun Heo  * This is a bit tricky.  A work item may be freed once its execution
1085797e8345STejun Heo  * starts and nothing prevents the freed area from being recycled for
1086797e8345STejun Heo  * another work item.  If the same work item address ends up being reused
1087797e8345STejun Heo  * before the original execution finishes, workqueue will identify the
1088797e8345STejun Heo  * recycled work item as currently executing and make it wait until the
1089797e8345STejun Heo  * current execution finishes, introducing an unwanted dependency.
1090797e8345STejun Heo  *
1091797e8345STejun Heo  * This function checks the work item address and work function to avoid
1092797e8345STejun Heo  * false positives.  Note that this isn't complete as one may construct a
1093797e8345STejun Heo  * work function which can introduce dependency onto itself through a
1094797e8345STejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
1095797e8345STejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
1096797e8345STejun Heo  * actually occurs, it should be easy to locate the culprit work function.
1097797e8345STejun Heo  *
1098797e8345STejun Heo  * CONTEXT:
1099797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1100797e8345STejun Heo  *
1101797e8345STejun Heo  * Return:
1102797e8345STejun Heo  * Pointer to worker which is executing @work if found, %NULL
1103797e8345STejun Heo  * otherwise.
1104797e8345STejun Heo  */
1105797e8345STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
1106797e8345STejun Heo 						 struct work_struct *work)
1107797e8345STejun Heo {
1108797e8345STejun Heo 	struct worker *worker;
1109797e8345STejun Heo 
1110797e8345STejun Heo 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1111797e8345STejun Heo 			       (unsigned long)work)
1112797e8345STejun Heo 		if (worker->current_work == work &&
1113797e8345STejun Heo 		    worker->current_func == work->func)
1114797e8345STejun Heo 			return worker;
1115797e8345STejun Heo 
1116797e8345STejun Heo 	return NULL;
1117797e8345STejun Heo }
1118797e8345STejun Heo 
1119797e8345STejun Heo /**
1120797e8345STejun Heo  * move_linked_works - move linked works to a list
1121797e8345STejun Heo  * @work: start of series of works to be scheduled
1122797e8345STejun Heo  * @head: target list to append @work to
1123797e8345STejun Heo  * @nextp: out parameter for nested worklist walking
1124797e8345STejun Heo  *
1125873eaca6STejun Heo  * Schedule linked works starting from @work to @head. Work series to be
1126873eaca6STejun Heo  * scheduled starts at @work and includes any consecutive work with
1127873eaca6STejun Heo  * WORK_STRUCT_LINKED set in its predecessor. See assign_work() for details on
1128873eaca6STejun Heo  * @nextp.
1129797e8345STejun Heo  *
1130797e8345STejun Heo  * CONTEXT:
1131797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1132797e8345STejun Heo  */
1133797e8345STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1134797e8345STejun Heo 			      struct work_struct **nextp)
1135797e8345STejun Heo {
1136797e8345STejun Heo 	struct work_struct *n;
1137797e8345STejun Heo 
1138797e8345STejun Heo 	/*
1139797e8345STejun Heo 	 * Linked worklist will always end before the end of the list,
1140797e8345STejun Heo 	 * use NULL for list head.
1141797e8345STejun Heo 	 */
1142797e8345STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1143797e8345STejun Heo 		list_move_tail(&work->entry, head);
1144797e8345STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1145797e8345STejun Heo 			break;
1146797e8345STejun Heo 	}
1147797e8345STejun Heo 
1148797e8345STejun Heo 	/*
1149797e8345STejun Heo 	 * If we're already inside safe list traversal and have moved
1150797e8345STejun Heo 	 * multiple works to the scheduled queue, the next position
1151797e8345STejun Heo 	 * needs to be updated.
1152797e8345STejun Heo 	 */
1153797e8345STejun Heo 	if (nextp)
1154797e8345STejun Heo 		*nextp = n;
1155797e8345STejun Heo }
1156797e8345STejun Heo 
1157797e8345STejun Heo /**
1158873eaca6STejun Heo  * assign_work - assign a work item and its linked work items to a worker
1159873eaca6STejun Heo  * @work: work to assign
1160873eaca6STejun Heo  * @worker: worker to assign to
1161873eaca6STejun Heo  * @nextp: out parameter for nested worklist walking
1162873eaca6STejun Heo  *
1163873eaca6STejun Heo  * Assign @work and its linked work items to @worker. If @work is already being
1164873eaca6STejun Heo  * executed by another worker in the same pool, it'll be punted there.
1165873eaca6STejun Heo  *
1166873eaca6STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of the last
1167873eaca6STejun Heo  * scheduled work. This allows assign_work() to be nested inside
1168873eaca6STejun Heo  * list_for_each_entry_safe().
1169873eaca6STejun Heo  *
1170873eaca6STejun Heo  * Returns %true if @work was successfully assigned to @worker. %false if @work
1171873eaca6STejun Heo  * was punted to another worker already executing it.
1172873eaca6STejun Heo  */
1173873eaca6STejun Heo static bool assign_work(struct work_struct *work, struct worker *worker,
1174873eaca6STejun Heo 			struct work_struct **nextp)
1175873eaca6STejun Heo {
1176873eaca6STejun Heo 	struct worker_pool *pool = worker->pool;
1177873eaca6STejun Heo 	struct worker *collision;
1178873eaca6STejun Heo 
1179873eaca6STejun Heo 	lockdep_assert_held(&pool->lock);
1180873eaca6STejun Heo 
1181873eaca6STejun Heo 	/*
1182873eaca6STejun Heo 	 * A single work shouldn't be executed concurrently by multiple workers.
1183873eaca6STejun Heo 	 * __queue_work() ensures that @work doesn't jump to a different pool
1184873eaca6STejun Heo 	 * while still running in the previous pool. Here, we should ensure that
1185873eaca6STejun Heo 	 * @work is not executed concurrently by multiple workers from the same
1186873eaca6STejun Heo 	 * pool. Check whether anyone is already processing the work. If so,
1187873eaca6STejun Heo 	 * defer the work to the currently executing one.
1188873eaca6STejun Heo 	 */
1189873eaca6STejun Heo 	collision = find_worker_executing_work(pool, work);
1190873eaca6STejun Heo 	if (unlikely(collision)) {
1191873eaca6STejun Heo 		move_linked_works(work, &collision->scheduled, nextp);
1192873eaca6STejun Heo 		return false;
1193873eaca6STejun Heo 	}
1194873eaca6STejun Heo 
1195873eaca6STejun Heo 	move_linked_works(work, &worker->scheduled, nextp);
1196873eaca6STejun Heo 	return true;
1197873eaca6STejun Heo }
1198873eaca6STejun Heo 
1199873eaca6STejun Heo /**
12000219a352STejun Heo  * kick_pool - wake up an idle worker if necessary
12010219a352STejun Heo  * @pool: pool to kick
1202797e8345STejun Heo  *
12030219a352STejun Heo  * @pool may have pending work items. Wake up worker if necessary. Returns
12040219a352STejun Heo  * whether a worker was woken up.
1205797e8345STejun Heo  */
12060219a352STejun Heo static bool kick_pool(struct worker_pool *pool)
1207797e8345STejun Heo {
1208797e8345STejun Heo 	struct worker *worker = first_idle_worker(pool);
12098639ecebSTejun Heo 	struct task_struct *p;
1210797e8345STejun Heo 
12110219a352STejun Heo 	lockdep_assert_held(&pool->lock);
12120219a352STejun Heo 
12130219a352STejun Heo 	if (!need_more_worker(pool) || !worker)
12140219a352STejun Heo 		return false;
12150219a352STejun Heo 
12164cb1ef64STejun Heo 	if (pool->flags & POOL_BH) {
12174cb1ef64STejun Heo 		if (pool->attrs->nice == HIGHPRI_NICE_LEVEL)
12184cb1ef64STejun Heo 			raise_softirq_irqoff(HI_SOFTIRQ);
12194cb1ef64STejun Heo 		else
12204cb1ef64STejun Heo 			raise_softirq_irqoff(TASKLET_SOFTIRQ);
12214cb1ef64STejun Heo 		return true;
12224cb1ef64STejun Heo 	}
12234cb1ef64STejun Heo 
12248639ecebSTejun Heo 	p = worker->task;
12258639ecebSTejun Heo 
12268639ecebSTejun Heo #ifdef CONFIG_SMP
12278639ecebSTejun Heo 	/*
12288639ecebSTejun Heo 	 * Idle @worker is about to execute @work and waking up provides an
12298639ecebSTejun Heo 	 * opportunity to migrate @worker at a lower cost by setting the task's
12308639ecebSTejun Heo 	 * wake_cpu field. Let's see if we want to move @worker to improve
12318639ecebSTejun Heo 	 * execution locality.
12328639ecebSTejun Heo 	 *
12338639ecebSTejun Heo 	 * We're waking the worker that went idle the latest and there's some
12348639ecebSTejun Heo 	 * chance that @worker is marked idle but hasn't gone off CPU yet. If
12358639ecebSTejun Heo 	 * so, setting the wake_cpu won't do anything. As this is a best-effort
12368639ecebSTejun Heo 	 * optimization and the race window is narrow, let's leave as-is for
12378639ecebSTejun Heo 	 * now. If this becomes pronounced, we can skip over workers which are
12388639ecebSTejun Heo 	 * still on cpu when picking an idle worker.
12398639ecebSTejun Heo 	 *
12408639ecebSTejun Heo 	 * If @pool has non-strict affinity, @worker might have ended up outside
12418639ecebSTejun Heo 	 * its affinity scope. Repatriate.
12428639ecebSTejun Heo 	 */
12438639ecebSTejun Heo 	if (!pool->attrs->affn_strict &&
12448639ecebSTejun Heo 	    !cpumask_test_cpu(p->wake_cpu, pool->attrs->__pod_cpumask)) {
12458639ecebSTejun Heo 		struct work_struct *work = list_first_entry(&pool->worklist,
12468639ecebSTejun Heo 						struct work_struct, entry);
12478639ecebSTejun Heo 		p->wake_cpu = cpumask_any_distribute(pool->attrs->__pod_cpumask);
12488639ecebSTejun Heo 		get_work_pwq(work)->stats[PWQ_STAT_REPATRIATED]++;
12498639ecebSTejun Heo 	}
12508639ecebSTejun Heo #endif
12518639ecebSTejun Heo 	wake_up_process(p);
12520219a352STejun Heo 	return true;
1253797e8345STejun Heo }
1254797e8345STejun Heo 
125563638450STejun Heo #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
125663638450STejun Heo 
125763638450STejun Heo /*
125863638450STejun Heo  * Concurrency-managed per-cpu work items that hog CPU for longer than
125963638450STejun Heo  * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
126063638450STejun Heo  * which prevents them from stalling other concurrency-managed work items. If a
126163638450STejun Heo  * work function keeps triggering this mechanism, it's likely that the work item
126263638450STejun Heo  * should be using an unbound workqueue instead.
126363638450STejun Heo  *
126463638450STejun Heo  * wq_cpu_intensive_report() tracks work functions which trigger such conditions
126563638450STejun Heo  * and report them so that they can be examined and converted to use unbound
126663638450STejun Heo  * workqueues as appropriate. To avoid flooding the console, each violating work
126763638450STejun Heo  * function is tracked and reported with exponential backoff.
126863638450STejun Heo  */
126963638450STejun Heo #define WCI_MAX_ENTS 128
127063638450STejun Heo 
127163638450STejun Heo struct wci_ent {
127263638450STejun Heo 	work_func_t		func;
127363638450STejun Heo 	atomic64_t		cnt;
127463638450STejun Heo 	struct hlist_node	hash_node;
127563638450STejun Heo };
127663638450STejun Heo 
127763638450STejun Heo static struct wci_ent wci_ents[WCI_MAX_ENTS];
127863638450STejun Heo static int wci_nr_ents;
127963638450STejun Heo static DEFINE_RAW_SPINLOCK(wci_lock);
128063638450STejun Heo static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
128163638450STejun Heo 
128263638450STejun Heo static struct wci_ent *wci_find_ent(work_func_t func)
128363638450STejun Heo {
128463638450STejun Heo 	struct wci_ent *ent;
128563638450STejun Heo 
128663638450STejun Heo 	hash_for_each_possible_rcu(wci_hash, ent, hash_node,
128763638450STejun Heo 				   (unsigned long)func) {
128863638450STejun Heo 		if (ent->func == func)
128963638450STejun Heo 			return ent;
129063638450STejun Heo 	}
129163638450STejun Heo 	return NULL;
129263638450STejun Heo }
129363638450STejun Heo 
129463638450STejun Heo static void wq_cpu_intensive_report(work_func_t func)
129563638450STejun Heo {
129663638450STejun Heo 	struct wci_ent *ent;
129763638450STejun Heo 
129863638450STejun Heo restart:
129963638450STejun Heo 	ent = wci_find_ent(func);
130063638450STejun Heo 	if (ent) {
130163638450STejun Heo 		u64 cnt;
130263638450STejun Heo 
130363638450STejun Heo 		/*
130463638450STejun Heo 		 * Start reporting from the fourth time and back off
130563638450STejun Heo 		 * exponentially.
130663638450STejun Heo 		 */
130763638450STejun Heo 		cnt = atomic64_inc_return_relaxed(&ent->cnt);
130863638450STejun Heo 		if (cnt >= 4 && is_power_of_2(cnt))
130963638450STejun Heo 			printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
131063638450STejun Heo 					ent->func, wq_cpu_intensive_thresh_us,
131163638450STejun Heo 					atomic64_read(&ent->cnt));
131263638450STejun Heo 		return;
131363638450STejun Heo 	}
131463638450STejun Heo 
131563638450STejun Heo 	/*
131663638450STejun Heo 	 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
131763638450STejun Heo 	 * is exhausted, something went really wrong and we probably made enough
131863638450STejun Heo 	 * noise already.
131963638450STejun Heo 	 */
132063638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS)
132163638450STejun Heo 		return;
132263638450STejun Heo 
132363638450STejun Heo 	raw_spin_lock(&wci_lock);
132463638450STejun Heo 
132563638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS) {
132663638450STejun Heo 		raw_spin_unlock(&wci_lock);
132763638450STejun Heo 		return;
132863638450STejun Heo 	}
132963638450STejun Heo 
133063638450STejun Heo 	if (wci_find_ent(func)) {
133163638450STejun Heo 		raw_spin_unlock(&wci_lock);
133263638450STejun Heo 		goto restart;
133363638450STejun Heo 	}
133463638450STejun Heo 
133563638450STejun Heo 	ent = &wci_ents[wci_nr_ents++];
133663638450STejun Heo 	ent->func = func;
133763638450STejun Heo 	atomic64_set(&ent->cnt, 1);
133863638450STejun Heo 	hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
133963638450STejun Heo 
134063638450STejun Heo 	raw_spin_unlock(&wci_lock);
134163638450STejun Heo }
134263638450STejun Heo 
134363638450STejun Heo #else	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
134463638450STejun Heo static void wq_cpu_intensive_report(work_func_t func) {}
134563638450STejun Heo #endif	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
134663638450STejun Heo 
1347c54d5046STejun Heo /**
13481da177e4SLinus Torvalds  * wq_worker_running - a worker is running again
13491da177e4SLinus Torvalds  * @task: task waking up
13501da177e4SLinus Torvalds  *
13511da177e4SLinus Torvalds  * This function is called when a worker returns from schedule()
13521da177e4SLinus Torvalds  */
13531da177e4SLinus Torvalds void wq_worker_running(struct task_struct *task)
13541da177e4SLinus Torvalds {
13551da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
13561da177e4SLinus Torvalds 
1357c8f6219bSZqiang 	if (!READ_ONCE(worker->sleeping))
13581da177e4SLinus Torvalds 		return;
13591da177e4SLinus Torvalds 
13601da177e4SLinus Torvalds 	/*
13611da177e4SLinus Torvalds 	 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
13621da177e4SLinus Torvalds 	 * and the nr_running increment below, we may ruin the nr_running reset
13631da177e4SLinus Torvalds 	 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
13641da177e4SLinus Torvalds 	 * pool. Protect against such race.
13651da177e4SLinus Torvalds 	 */
13661da177e4SLinus Torvalds 	preempt_disable();
13671da177e4SLinus Torvalds 	if (!(worker->flags & WORKER_NOT_RUNNING))
13681da177e4SLinus Torvalds 		worker->pool->nr_running++;
13691da177e4SLinus Torvalds 	preempt_enable();
1370616db877STejun Heo 
1371616db877STejun Heo 	/*
1372616db877STejun Heo 	 * CPU intensive auto-detection cares about how long a work item hogged
1373616db877STejun Heo 	 * CPU without sleeping. Reset the starting timestamp on wakeup.
1374616db877STejun Heo 	 */
1375616db877STejun Heo 	worker->current_at = worker->task->se.sum_exec_runtime;
1376616db877STejun Heo 
1377c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 0);
13781da177e4SLinus Torvalds }
13791da177e4SLinus Torvalds 
13801da177e4SLinus Torvalds /**
13811da177e4SLinus Torvalds  * wq_worker_sleeping - a worker is going to sleep
13821da177e4SLinus Torvalds  * @task: task going to sleep
13831da177e4SLinus Torvalds  *
13841da177e4SLinus Torvalds  * This function is called from schedule() when a busy worker is
13851da177e4SLinus Torvalds  * going to sleep.
13861da177e4SLinus Torvalds  */
13871da177e4SLinus Torvalds void wq_worker_sleeping(struct task_struct *task)
13881da177e4SLinus Torvalds {
13891da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
13901da177e4SLinus Torvalds 	struct worker_pool *pool;
13911da177e4SLinus Torvalds 
13921da177e4SLinus Torvalds 	/*
13931da177e4SLinus Torvalds 	 * Rescuers, which may not have all the fields set up like normal
13941da177e4SLinus Torvalds 	 * workers, also reach here, let's not access anything before
13951da177e4SLinus Torvalds 	 * checking NOT_RUNNING.
13961da177e4SLinus Torvalds 	 */
13971da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING)
13981da177e4SLinus Torvalds 		return;
13991da177e4SLinus Torvalds 
14001da177e4SLinus Torvalds 	pool = worker->pool;
14011da177e4SLinus Torvalds 
14021da177e4SLinus Torvalds 	/* Return if preempted before wq_worker_running() was reached */
1403c8f6219bSZqiang 	if (READ_ONCE(worker->sleeping))
14041da177e4SLinus Torvalds 		return;
14051da177e4SLinus Torvalds 
1406c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 1);
14071da177e4SLinus Torvalds 	raw_spin_lock_irq(&pool->lock);
14081da177e4SLinus Torvalds 
14091da177e4SLinus Torvalds 	/*
14101da177e4SLinus Torvalds 	 * Recheck in case unbind_workers() preempted us. We don't
14111da177e4SLinus Torvalds 	 * want to decrement nr_running after the worker is unbound
14121da177e4SLinus Torvalds 	 * and nr_running has been reset.
14131da177e4SLinus Torvalds 	 */
14141da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING) {
14151da177e4SLinus Torvalds 		raw_spin_unlock_irq(&pool->lock);
14161da177e4SLinus Torvalds 		return;
14171da177e4SLinus Torvalds 	}
14181da177e4SLinus Torvalds 
14191da177e4SLinus Torvalds 	pool->nr_running--;
14200219a352STejun Heo 	if (kick_pool(pool))
1421725e8ec5STejun Heo 		worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
14220219a352STejun Heo 
14231da177e4SLinus Torvalds 	raw_spin_unlock_irq(&pool->lock);
14241da177e4SLinus Torvalds }
14251da177e4SLinus Torvalds 
14261da177e4SLinus Torvalds /**
1427616db877STejun Heo  * wq_worker_tick - a scheduler tick occurred while a kworker is running
1428616db877STejun Heo  * @task: task currently running
1429616db877STejun Heo  *
1430616db877STejun Heo  * Called from scheduler_tick(). We're in the IRQ context and the current
1431616db877STejun Heo  * worker's fields which follow the 'K' locking rule can be accessed safely.
1432616db877STejun Heo  */
1433616db877STejun Heo void wq_worker_tick(struct task_struct *task)
1434616db877STejun Heo {
1435616db877STejun Heo 	struct worker *worker = kthread_data(task);
1436616db877STejun Heo 	struct pool_workqueue *pwq = worker->current_pwq;
1437616db877STejun Heo 	struct worker_pool *pool = worker->pool;
1438616db877STejun Heo 
1439616db877STejun Heo 	if (!pwq)
1440616db877STejun Heo 		return;
1441616db877STejun Heo 
14428a1dd1e5STejun Heo 	pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
14438a1dd1e5STejun Heo 
144418c8ae81SZqiang 	if (!wq_cpu_intensive_thresh_us)
144518c8ae81SZqiang 		return;
144618c8ae81SZqiang 
1447616db877STejun Heo 	/*
1448616db877STejun Heo 	 * If the current worker is concurrency managed and hogged the CPU for
1449616db877STejun Heo 	 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1450616db877STejun Heo 	 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1451c8f6219bSZqiang 	 *
1452c8f6219bSZqiang 	 * Set @worker->sleeping means that @worker is in the process of
1453c8f6219bSZqiang 	 * switching out voluntarily and won't be contributing to
1454c8f6219bSZqiang 	 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1455c8f6219bSZqiang 	 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1456c8f6219bSZqiang 	 * double decrements. The task is releasing the CPU anyway. Let's skip.
1457c8f6219bSZqiang 	 * We probably want to make this prettier in the future.
1458616db877STejun Heo 	 */
1459c8f6219bSZqiang 	if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1460616db877STejun Heo 	    worker->task->se.sum_exec_runtime - worker->current_at <
1461616db877STejun Heo 	    wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1462616db877STejun Heo 		return;
1463616db877STejun Heo 
1464616db877STejun Heo 	raw_spin_lock(&pool->lock);
1465616db877STejun Heo 
1466616db877STejun Heo 	worker_set_flags(worker, WORKER_CPU_INTENSIVE);
146763638450STejun Heo 	wq_cpu_intensive_report(worker->current_func);
1468616db877STejun Heo 	pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1469616db877STejun Heo 
14700219a352STejun Heo 	if (kick_pool(pool))
1471616db877STejun Heo 		pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1472616db877STejun Heo 
1473616db877STejun Heo 	raw_spin_unlock(&pool->lock);
1474616db877STejun Heo }
1475616db877STejun Heo 
1476616db877STejun Heo /**
14771da177e4SLinus Torvalds  * wq_worker_last_func - retrieve worker's last work function
14781da177e4SLinus Torvalds  * @task: Task to retrieve last work function of.
14791da177e4SLinus Torvalds  *
14801da177e4SLinus Torvalds  * Determine the last function a worker executed. This is called from
14811da177e4SLinus Torvalds  * the scheduler to get a worker's last known identity.
14821da177e4SLinus Torvalds  *
14831da177e4SLinus Torvalds  * CONTEXT:
14849b41ea72SAndrew Morton  * raw_spin_lock_irq(rq->lock)
14851da177e4SLinus Torvalds  *
14861da177e4SLinus Torvalds  * This function is called during schedule() when a kworker is going
1487f756d5e2SNathan Lynch  * to sleep. It's used by psi to identify aggregation workers during
1488f756d5e2SNathan Lynch  * dequeuing, to allow periodic aggregation to shut-off when that
14891da177e4SLinus Torvalds  * worker is the last task in the system or cgroup to go to sleep.
14901da177e4SLinus Torvalds  *
14911da177e4SLinus Torvalds  * As this function doesn't involve any workqueue-related locking, it
14921da177e4SLinus Torvalds  * only returns stable values when called from inside the scheduler's
14931da177e4SLinus Torvalds  * queuing and dequeuing paths, when @task, which must be a kworker,
14941da177e4SLinus Torvalds  * is guaranteed to not be processing any works.
1495365970a1SDavid Howells  *
1496365970a1SDavid Howells  * Return:
1497365970a1SDavid Howells  * The last work function %current executed as a worker, NULL if it
1498365970a1SDavid Howells  * hasn't executed any work yet.
1499365970a1SDavid Howells  */
1500365970a1SDavid Howells work_func_t wq_worker_last_func(struct task_struct *task)
1501365970a1SDavid Howells {
1502365970a1SDavid Howells 	struct worker *worker = kthread_data(task);
1503365970a1SDavid Howells 
1504365970a1SDavid Howells 	return worker->last_func;
1505365970a1SDavid Howells }
1506365970a1SDavid Howells 
1507d302f017STejun Heo /**
150891ccc6e7STejun Heo  * wq_node_nr_active - Determine wq_node_nr_active to use
150991ccc6e7STejun Heo  * @wq: workqueue of interest
151091ccc6e7STejun Heo  * @node: NUMA node, can be %NUMA_NO_NODE
151191ccc6e7STejun Heo  *
151291ccc6e7STejun Heo  * Determine wq_node_nr_active to use for @wq on @node. Returns:
151391ccc6e7STejun Heo  *
151491ccc6e7STejun Heo  * - %NULL for per-cpu workqueues as they don't need to use shared nr_active.
151591ccc6e7STejun Heo  *
151691ccc6e7STejun Heo  * - node_nr_active[nr_node_ids] if @node is %NUMA_NO_NODE.
151791ccc6e7STejun Heo  *
151891ccc6e7STejun Heo  * - Otherwise, node_nr_active[@node].
151991ccc6e7STejun Heo  */
152091ccc6e7STejun Heo static struct wq_node_nr_active *wq_node_nr_active(struct workqueue_struct *wq,
152191ccc6e7STejun Heo 						   int node)
152291ccc6e7STejun Heo {
152391ccc6e7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
152491ccc6e7STejun Heo 		return NULL;
152591ccc6e7STejun Heo 
152691ccc6e7STejun Heo 	if (node == NUMA_NO_NODE)
152791ccc6e7STejun Heo 		node = nr_node_ids;
152891ccc6e7STejun Heo 
152991ccc6e7STejun Heo 	return wq->node_nr_active[node];
153091ccc6e7STejun Heo }
153191ccc6e7STejun Heo 
153291ccc6e7STejun Heo /**
15335797b1c1STejun Heo  * wq_update_node_max_active - Update per-node max_actives to use
15345797b1c1STejun Heo  * @wq: workqueue to update
15355797b1c1STejun Heo  * @off_cpu: CPU that's going down, -1 if a CPU is not going down
15365797b1c1STejun Heo  *
15375797b1c1STejun Heo  * Update @wq->node_nr_active[]->max. @wq must be unbound. max_active is
15385797b1c1STejun Heo  * distributed among nodes according to the proportions of numbers of online
15395797b1c1STejun Heo  * cpus. The result is always between @wq->min_active and max_active.
15405797b1c1STejun Heo  */
15415797b1c1STejun Heo static void wq_update_node_max_active(struct workqueue_struct *wq, int off_cpu)
15425797b1c1STejun Heo {
15435797b1c1STejun Heo 	struct cpumask *effective = unbound_effective_cpumask(wq);
15445797b1c1STejun Heo 	int min_active = READ_ONCE(wq->min_active);
15455797b1c1STejun Heo 	int max_active = READ_ONCE(wq->max_active);
15465797b1c1STejun Heo 	int total_cpus, node;
15475797b1c1STejun Heo 
15485797b1c1STejun Heo 	lockdep_assert_held(&wq->mutex);
15495797b1c1STejun Heo 
1550c5f8cd6cSTejun Heo 	if (!wq_topo_initialized)
1551c5f8cd6cSTejun Heo 		return;
1552c5f8cd6cSTejun Heo 
155315930da4STejun Heo 	if (off_cpu >= 0 && !cpumask_test_cpu(off_cpu, effective))
15545797b1c1STejun Heo 		off_cpu = -1;
15555797b1c1STejun Heo 
15565797b1c1STejun Heo 	total_cpus = cpumask_weight_and(effective, cpu_online_mask);
15575797b1c1STejun Heo 	if (off_cpu >= 0)
15585797b1c1STejun Heo 		total_cpus--;
15595797b1c1STejun Heo 
15605797b1c1STejun Heo 	for_each_node(node) {
15615797b1c1STejun Heo 		int node_cpus;
15625797b1c1STejun Heo 
15635797b1c1STejun Heo 		node_cpus = cpumask_weight_and(effective, cpumask_of_node(node));
15645797b1c1STejun Heo 		if (off_cpu >= 0 && cpu_to_node(off_cpu) == node)
15655797b1c1STejun Heo 			node_cpus--;
15665797b1c1STejun Heo 
15675797b1c1STejun Heo 		wq_node_nr_active(wq, node)->max =
15685797b1c1STejun Heo 			clamp(DIV_ROUND_UP(max_active * node_cpus, total_cpus),
15695797b1c1STejun Heo 			      min_active, max_active);
15705797b1c1STejun Heo 	}
15715797b1c1STejun Heo 
15725797b1c1STejun Heo 	wq_node_nr_active(wq, NUMA_NO_NODE)->max = min_active;
15735797b1c1STejun Heo }
15745797b1c1STejun Heo 
15755797b1c1STejun Heo /**
15768864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
15778864b4e5STejun Heo  * @pwq: pool_workqueue to get
15788864b4e5STejun Heo  *
15798864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
15808864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
15818864b4e5STejun Heo  */
15828864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
15838864b4e5STejun Heo {
15848864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
15858864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
15868864b4e5STejun Heo 	pwq->refcnt++;
15878864b4e5STejun Heo }
15888864b4e5STejun Heo 
15898864b4e5STejun Heo /**
15908864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
15918864b4e5STejun Heo  * @pwq: pool_workqueue to put
15928864b4e5STejun Heo  *
15938864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
15948864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
15958864b4e5STejun Heo  */
15968864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
15978864b4e5STejun Heo {
15988864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
15998864b4e5STejun Heo 	if (likely(--pwq->refcnt))
16008864b4e5STejun Heo 		return;
16018864b4e5STejun Heo 	/*
1602967b494eSTejun Heo 	 * @pwq can't be released under pool->lock, bounce to a dedicated
1603967b494eSTejun Heo 	 * kthread_worker to avoid A-A deadlocks.
16048864b4e5STejun Heo 	 */
1605687a9aa5STejun Heo 	kthread_queue_work(pwq_release_worker, &pwq->release_work);
16068864b4e5STejun Heo }
16078864b4e5STejun Heo 
1608dce90d47STejun Heo /**
1609dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1610dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1611dce90d47STejun Heo  *
1612dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1613dce90d47STejun Heo  */
1614dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1615dce90d47STejun Heo {
1616dce90d47STejun Heo 	if (pwq) {
1617dce90d47STejun Heo 		/*
161824acfb71SThomas Gleixner 		 * As both pwqs and pools are RCU protected, the
1619dce90d47STejun Heo 		 * following lock operations are safe.
1620dce90d47STejun Heo 		 */
1621a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
1622dce90d47STejun Heo 		put_pwq(pwq);
1623a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
1624dce90d47STejun Heo 	}
1625dce90d47STejun Heo }
1626dce90d47STejun Heo 
1627afa87ce8STejun Heo static bool pwq_is_empty(struct pool_workqueue *pwq)
1628afa87ce8STejun Heo {
1629afa87ce8STejun Heo 	return !pwq->nr_active && list_empty(&pwq->inactive_works);
1630afa87ce8STejun Heo }
1631afa87ce8STejun Heo 
16324c638030STejun Heo static void __pwq_activate_work(struct pool_workqueue *pwq,
16334c638030STejun Heo 				struct work_struct *work)
1634bf4ede01STejun Heo {
16351c270b79STejun Heo 	unsigned long *wdb = work_data_bits(work);
16361c270b79STejun Heo 
16371c270b79STejun Heo 	WARN_ON_ONCE(!(*wdb & WORK_STRUCT_INACTIVE));
1638bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
163982607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
164082607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1641112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
16421c270b79STejun Heo 	__clear_bit(WORK_STRUCT_INACTIVE_BIT, wdb);
16434c638030STejun Heo }
16444c638030STejun Heo 
16454c638030STejun Heo /**
16464c638030STejun Heo  * pwq_activate_work - Activate a work item if inactive
16474c638030STejun Heo  * @pwq: pool_workqueue @work belongs to
16484c638030STejun Heo  * @work: work item to activate
16494c638030STejun Heo  *
16504c638030STejun Heo  * Returns %true if activated. %false if already active.
16514c638030STejun Heo  */
16524c638030STejun Heo static bool pwq_activate_work(struct pool_workqueue *pwq,
16534c638030STejun Heo 			      struct work_struct *work)
16544c638030STejun Heo {
16554c638030STejun Heo 	struct worker_pool *pool = pwq->pool;
165691ccc6e7STejun Heo 	struct wq_node_nr_active *nna;
16574c638030STejun Heo 
16584c638030STejun Heo 	lockdep_assert_held(&pool->lock);
16594c638030STejun Heo 
16604c638030STejun Heo 	if (!(*work_data_bits(work) & WORK_STRUCT_INACTIVE))
16614c638030STejun Heo 		return false;
16624c638030STejun Heo 
166391ccc6e7STejun Heo 	nna = wq_node_nr_active(pwq->wq, pool->node);
166491ccc6e7STejun Heo 	if (nna)
166591ccc6e7STejun Heo 		atomic_inc(&nna->nr);
166691ccc6e7STejun Heo 
1667112202d9STejun Heo 	pwq->nr_active++;
16684c638030STejun Heo 	__pwq_activate_work(pwq, work);
16694c638030STejun Heo 	return true;
1670bf4ede01STejun Heo }
1671bf4ede01STejun Heo 
16725797b1c1STejun Heo static bool tryinc_node_nr_active(struct wq_node_nr_active *nna)
16735797b1c1STejun Heo {
16745797b1c1STejun Heo 	int max = READ_ONCE(nna->max);
16755797b1c1STejun Heo 
16765797b1c1STejun Heo 	while (true) {
16775797b1c1STejun Heo 		int old, tmp;
16785797b1c1STejun Heo 
16795797b1c1STejun Heo 		old = atomic_read(&nna->nr);
16805797b1c1STejun Heo 		if (old >= max)
16815797b1c1STejun Heo 			return false;
16825797b1c1STejun Heo 		tmp = atomic_cmpxchg_relaxed(&nna->nr, old, old + 1);
16835797b1c1STejun Heo 		if (tmp == old)
16845797b1c1STejun Heo 			return true;
16855797b1c1STejun Heo 	}
16865797b1c1STejun Heo }
16875797b1c1STejun Heo 
16881c270b79STejun Heo /**
16891c270b79STejun Heo  * pwq_tryinc_nr_active - Try to increment nr_active for a pwq
16901c270b79STejun Heo  * @pwq: pool_workqueue of interest
16915797b1c1STejun Heo  * @fill: max_active may have increased, try to increase concurrency level
16921c270b79STejun Heo  *
16931c270b79STejun Heo  * Try to increment nr_active for @pwq. Returns %true if an nr_active count is
16941c270b79STejun Heo  * successfully obtained. %false otherwise.
16951c270b79STejun Heo  */
16965797b1c1STejun Heo static bool pwq_tryinc_nr_active(struct pool_workqueue *pwq, bool fill)
16973aa62497SLai Jiangshan {
16981c270b79STejun Heo 	struct workqueue_struct *wq = pwq->wq;
16991c270b79STejun Heo 	struct worker_pool *pool = pwq->pool;
170091ccc6e7STejun Heo 	struct wq_node_nr_active *nna = wq_node_nr_active(wq, pool->node);
17015797b1c1STejun Heo 	bool obtained = false;
17021c270b79STejun Heo 
17031c270b79STejun Heo 	lockdep_assert_held(&pool->lock);
17041c270b79STejun Heo 
17055797b1c1STejun Heo 	if (!nna) {
17064cb1ef64STejun Heo 		/* BH or per-cpu workqueue, pwq->nr_active is sufficient */
17071c270b79STejun Heo 		obtained = pwq->nr_active < READ_ONCE(wq->max_active);
17085797b1c1STejun Heo 		goto out;
170991ccc6e7STejun Heo 	}
17105797b1c1STejun Heo 
17115797b1c1STejun Heo 	/*
17125797b1c1STejun Heo 	 * Unbound workqueue uses per-node shared nr_active $nna. If @pwq is
17135797b1c1STejun Heo 	 * already waiting on $nna, pwq_dec_nr_active() will maintain the
17145797b1c1STejun Heo 	 * concurrency level. Don't jump the line.
17155797b1c1STejun Heo 	 *
17165797b1c1STejun Heo 	 * We need to ignore the pending test after max_active has increased as
17175797b1c1STejun Heo 	 * pwq_dec_nr_active() can only maintain the concurrency level but not
17185797b1c1STejun Heo 	 * increase it. This is indicated by @fill.
17195797b1c1STejun Heo 	 */
17205797b1c1STejun Heo 	if (!list_empty(&pwq->pending_node) && likely(!fill))
17215797b1c1STejun Heo 		goto out;
17225797b1c1STejun Heo 
17235797b1c1STejun Heo 	obtained = tryinc_node_nr_active(nna);
17245797b1c1STejun Heo 	if (obtained)
17255797b1c1STejun Heo 		goto out;
17265797b1c1STejun Heo 
17275797b1c1STejun Heo 	/*
17285797b1c1STejun Heo 	 * Lockless acquisition failed. Lock, add ourself to $nna->pending_pwqs
17295797b1c1STejun Heo 	 * and try again. The smp_mb() is paired with the implied memory barrier
17305797b1c1STejun Heo 	 * of atomic_dec_return() in pwq_dec_nr_active() to ensure that either
17315797b1c1STejun Heo 	 * we see the decremented $nna->nr or they see non-empty
17325797b1c1STejun Heo 	 * $nna->pending_pwqs.
17335797b1c1STejun Heo 	 */
17345797b1c1STejun Heo 	raw_spin_lock(&nna->lock);
17355797b1c1STejun Heo 
17365797b1c1STejun Heo 	if (list_empty(&pwq->pending_node))
17375797b1c1STejun Heo 		list_add_tail(&pwq->pending_node, &nna->pending_pwqs);
17385797b1c1STejun Heo 	else if (likely(!fill))
17395797b1c1STejun Heo 		goto out_unlock;
17405797b1c1STejun Heo 
17415797b1c1STejun Heo 	smp_mb();
17425797b1c1STejun Heo 
17435797b1c1STejun Heo 	obtained = tryinc_node_nr_active(nna);
17445797b1c1STejun Heo 
17455797b1c1STejun Heo 	/*
17465797b1c1STejun Heo 	 * If @fill, @pwq might have already been pending. Being spuriously
17475797b1c1STejun Heo 	 * pending in cold paths doesn't affect anything. Let's leave it be.
17485797b1c1STejun Heo 	 */
17495797b1c1STejun Heo 	if (obtained && likely(!fill))
17505797b1c1STejun Heo 		list_del_init(&pwq->pending_node);
17515797b1c1STejun Heo 
17525797b1c1STejun Heo out_unlock:
17535797b1c1STejun Heo 	raw_spin_unlock(&nna->lock);
17545797b1c1STejun Heo out:
17555797b1c1STejun Heo 	if (obtained)
17565797b1c1STejun Heo 		pwq->nr_active++;
17571c270b79STejun Heo 	return obtained;
17581c270b79STejun Heo }
17591c270b79STejun Heo 
17601c270b79STejun Heo /**
17611c270b79STejun Heo  * pwq_activate_first_inactive - Activate the first inactive work item on a pwq
17621c270b79STejun Heo  * @pwq: pool_workqueue of interest
17635797b1c1STejun Heo  * @fill: max_active may have increased, try to increase concurrency level
17641c270b79STejun Heo  *
17651c270b79STejun Heo  * Activate the first inactive work item of @pwq if available and allowed by
17661c270b79STejun Heo  * max_active limit.
17671c270b79STejun Heo  *
17681c270b79STejun Heo  * Returns %true if an inactive work item has been activated. %false if no
17691c270b79STejun Heo  * inactive work item is found or max_active limit is reached.
17701c270b79STejun Heo  */
17715797b1c1STejun Heo static bool pwq_activate_first_inactive(struct pool_workqueue *pwq, bool fill)
17721c270b79STejun Heo {
17731c270b79STejun Heo 	struct work_struct *work =
17741c270b79STejun Heo 		list_first_entry_or_null(&pwq->inactive_works,
17753aa62497SLai Jiangshan 					 struct work_struct, entry);
17763aa62497SLai Jiangshan 
17775797b1c1STejun Heo 	if (work && pwq_tryinc_nr_active(pwq, fill)) {
17781c270b79STejun Heo 		__pwq_activate_work(pwq, work);
17791c270b79STejun Heo 		return true;
17801c270b79STejun Heo 	} else {
17811c270b79STejun Heo 		return false;
17821c270b79STejun Heo 	}
17831c270b79STejun Heo }
17841c270b79STejun Heo 
17851c270b79STejun Heo /**
17865797b1c1STejun Heo  * node_activate_pending_pwq - Activate a pending pwq on a wq_node_nr_active
17875797b1c1STejun Heo  * @nna: wq_node_nr_active to activate a pending pwq for
17885797b1c1STejun Heo  * @caller_pool: worker_pool the caller is locking
17895797b1c1STejun Heo  *
17905797b1c1STejun Heo  * Activate a pwq in @nna->pending_pwqs. Called with @caller_pool locked.
17915797b1c1STejun Heo  * @caller_pool may be unlocked and relocked to lock other worker_pools.
17925797b1c1STejun Heo  */
17935797b1c1STejun Heo static void node_activate_pending_pwq(struct wq_node_nr_active *nna,
17945797b1c1STejun Heo 				      struct worker_pool *caller_pool)
17955797b1c1STejun Heo {
17965797b1c1STejun Heo 	struct worker_pool *locked_pool = caller_pool;
17975797b1c1STejun Heo 	struct pool_workqueue *pwq;
17985797b1c1STejun Heo 	struct work_struct *work;
17995797b1c1STejun Heo 
18005797b1c1STejun Heo 	lockdep_assert_held(&caller_pool->lock);
18015797b1c1STejun Heo 
18025797b1c1STejun Heo 	raw_spin_lock(&nna->lock);
18035797b1c1STejun Heo retry:
18045797b1c1STejun Heo 	pwq = list_first_entry_or_null(&nna->pending_pwqs,
18055797b1c1STejun Heo 				       struct pool_workqueue, pending_node);
18065797b1c1STejun Heo 	if (!pwq)
18075797b1c1STejun Heo 		goto out_unlock;
18085797b1c1STejun Heo 
18095797b1c1STejun Heo 	/*
18105797b1c1STejun Heo 	 * If @pwq is for a different pool than @locked_pool, we need to lock
18115797b1c1STejun Heo 	 * @pwq->pool->lock. Let's trylock first. If unsuccessful, do the unlock
18125797b1c1STejun Heo 	 * / lock dance. For that, we also need to release @nna->lock as it's
18135797b1c1STejun Heo 	 * nested inside pool locks.
18145797b1c1STejun Heo 	 */
18155797b1c1STejun Heo 	if (pwq->pool != locked_pool) {
18165797b1c1STejun Heo 		raw_spin_unlock(&locked_pool->lock);
18175797b1c1STejun Heo 		locked_pool = pwq->pool;
18185797b1c1STejun Heo 		if (!raw_spin_trylock(&locked_pool->lock)) {
18195797b1c1STejun Heo 			raw_spin_unlock(&nna->lock);
18205797b1c1STejun Heo 			raw_spin_lock(&locked_pool->lock);
18215797b1c1STejun Heo 			raw_spin_lock(&nna->lock);
18225797b1c1STejun Heo 			goto retry;
18235797b1c1STejun Heo 		}
18245797b1c1STejun Heo 	}
18255797b1c1STejun Heo 
18265797b1c1STejun Heo 	/*
18275797b1c1STejun Heo 	 * $pwq may not have any inactive work items due to e.g. cancellations.
18285797b1c1STejun Heo 	 * Drop it from pending_pwqs and see if there's another one.
18295797b1c1STejun Heo 	 */
18305797b1c1STejun Heo 	work = list_first_entry_or_null(&pwq->inactive_works,
18315797b1c1STejun Heo 					struct work_struct, entry);
18325797b1c1STejun Heo 	if (!work) {
18335797b1c1STejun Heo 		list_del_init(&pwq->pending_node);
18345797b1c1STejun Heo 		goto retry;
18355797b1c1STejun Heo 	}
18365797b1c1STejun Heo 
18375797b1c1STejun Heo 	/*
18385797b1c1STejun Heo 	 * Acquire an nr_active count and activate the inactive work item. If
18395797b1c1STejun Heo 	 * $pwq still has inactive work items, rotate it to the end of the
18405797b1c1STejun Heo 	 * pending_pwqs so that we round-robin through them. This means that
18415797b1c1STejun Heo 	 * inactive work items are not activated in queueing order which is fine
18425797b1c1STejun Heo 	 * given that there has never been any ordering across different pwqs.
18435797b1c1STejun Heo 	 */
18445797b1c1STejun Heo 	if (likely(tryinc_node_nr_active(nna))) {
18455797b1c1STejun Heo 		pwq->nr_active++;
18465797b1c1STejun Heo 		__pwq_activate_work(pwq, work);
18475797b1c1STejun Heo 
18485797b1c1STejun Heo 		if (list_empty(&pwq->inactive_works))
18495797b1c1STejun Heo 			list_del_init(&pwq->pending_node);
18505797b1c1STejun Heo 		else
18515797b1c1STejun Heo 			list_move_tail(&pwq->pending_node, &nna->pending_pwqs);
18525797b1c1STejun Heo 
18535797b1c1STejun Heo 		/* if activating a foreign pool, make sure it's running */
18545797b1c1STejun Heo 		if (pwq->pool != caller_pool)
18555797b1c1STejun Heo 			kick_pool(pwq->pool);
18565797b1c1STejun Heo 	}
18575797b1c1STejun Heo 
18585797b1c1STejun Heo out_unlock:
18595797b1c1STejun Heo 	raw_spin_unlock(&nna->lock);
18605797b1c1STejun Heo 	if (locked_pool != caller_pool) {
18615797b1c1STejun Heo 		raw_spin_unlock(&locked_pool->lock);
18625797b1c1STejun Heo 		raw_spin_lock(&caller_pool->lock);
18635797b1c1STejun Heo 	}
18645797b1c1STejun Heo }
18655797b1c1STejun Heo 
18665797b1c1STejun Heo /**
18671c270b79STejun Heo  * pwq_dec_nr_active - Retire an active count
18681c270b79STejun Heo  * @pwq: pool_workqueue of interest
18691c270b79STejun Heo  *
18701c270b79STejun Heo  * Decrement @pwq's nr_active and try to activate the first inactive work item.
18715797b1c1STejun Heo  * For unbound workqueues, this function may temporarily drop @pwq->pool->lock.
18721c270b79STejun Heo  */
18731c270b79STejun Heo static void pwq_dec_nr_active(struct pool_workqueue *pwq)
18741c270b79STejun Heo {
18751c270b79STejun Heo 	struct worker_pool *pool = pwq->pool;
187691ccc6e7STejun Heo 	struct wq_node_nr_active *nna = wq_node_nr_active(pwq->wq, pool->node);
18771c270b79STejun Heo 
18781c270b79STejun Heo 	lockdep_assert_held(&pool->lock);
18791c270b79STejun Heo 
188091ccc6e7STejun Heo 	/*
188191ccc6e7STejun Heo 	 * @pwq->nr_active should be decremented for both percpu and unbound
188291ccc6e7STejun Heo 	 * workqueues.
188391ccc6e7STejun Heo 	 */
18841c270b79STejun Heo 	pwq->nr_active--;
188591ccc6e7STejun Heo 
188691ccc6e7STejun Heo 	/*
188791ccc6e7STejun Heo 	 * For a percpu workqueue, it's simple. Just need to kick the first
188891ccc6e7STejun Heo 	 * inactive work item on @pwq itself.
188991ccc6e7STejun Heo 	 */
189091ccc6e7STejun Heo 	if (!nna) {
18915797b1c1STejun Heo 		pwq_activate_first_inactive(pwq, false);
189291ccc6e7STejun Heo 		return;
189391ccc6e7STejun Heo 	}
189491ccc6e7STejun Heo 
18955797b1c1STejun Heo 	/*
18965797b1c1STejun Heo 	 * If @pwq is for an unbound workqueue, it's more complicated because
18975797b1c1STejun Heo 	 * multiple pwqs and pools may be sharing the nr_active count. When a
18985797b1c1STejun Heo 	 * pwq needs to wait for an nr_active count, it puts itself on
18995797b1c1STejun Heo 	 * $nna->pending_pwqs. The following atomic_dec_return()'s implied
19005797b1c1STejun Heo 	 * memory barrier is paired with smp_mb() in pwq_tryinc_nr_active() to
19015797b1c1STejun Heo 	 * guarantee that either we see non-empty pending_pwqs or they see
19025797b1c1STejun Heo 	 * decremented $nna->nr.
19035797b1c1STejun Heo 	 *
19045797b1c1STejun Heo 	 * $nna->max may change as CPUs come online/offline and @pwq->wq's
19055797b1c1STejun Heo 	 * max_active gets updated. However, it is guaranteed to be equal to or
19065797b1c1STejun Heo 	 * larger than @pwq->wq->min_active which is above zero unless freezing.
19075797b1c1STejun Heo 	 * This maintains the forward progress guarantee.
19085797b1c1STejun Heo 	 */
19095797b1c1STejun Heo 	if (atomic_dec_return(&nna->nr) >= READ_ONCE(nna->max))
19105797b1c1STejun Heo 		return;
19115797b1c1STejun Heo 
19125797b1c1STejun Heo 	if (!list_empty(&nna->pending_pwqs))
19135797b1c1STejun Heo 		node_activate_pending_pwq(nna, pool);
19143aa62497SLai Jiangshan }
19153aa62497SLai Jiangshan 
1916bf4ede01STejun Heo /**
1917112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1918112202d9STejun Heo  * @pwq: pwq of interest
1919c4560c2cSLai Jiangshan  * @work_data: work_data of work which left the queue
1920bf4ede01STejun Heo  *
1921bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
1922112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
1923bf4ede01STejun Heo  *
1924dd6c3c54STejun Heo  * NOTE:
1925dd6c3c54STejun Heo  * For unbound workqueues, this function may temporarily drop @pwq->pool->lock
1926dd6c3c54STejun Heo  * and thus should be called after all other state updates for the in-flight
1927dd6c3c54STejun Heo  * work item is complete.
1928dd6c3c54STejun Heo  *
1929bf4ede01STejun Heo  * CONTEXT:
1930a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
1931bf4ede01STejun Heo  */
1932c4560c2cSLai Jiangshan static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1933bf4ede01STejun Heo {
1934c4560c2cSLai Jiangshan 	int color = get_work_color(work_data);
1935c4560c2cSLai Jiangshan 
19361c270b79STejun Heo 	if (!(work_data & WORK_STRUCT_INACTIVE))
19371c270b79STejun Heo 		pwq_dec_nr_active(pwq);
1938018f3a13SLai Jiangshan 
1939018f3a13SLai Jiangshan 	pwq->nr_in_flight[color]--;
1940bf4ede01STejun Heo 
1941bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
1942112202d9STejun Heo 	if (likely(pwq->flush_color != color))
19438864b4e5STejun Heo 		goto out_put;
1944bf4ede01STejun Heo 
1945bf4ede01STejun Heo 	/* are there still in-flight works? */
1946112202d9STejun Heo 	if (pwq->nr_in_flight[color])
19478864b4e5STejun Heo 		goto out_put;
1948bf4ede01STejun Heo 
1949112202d9STejun Heo 	/* this pwq is done, clear flush_color */
1950112202d9STejun Heo 	pwq->flush_color = -1;
1951bf4ede01STejun Heo 
1952bf4ede01STejun Heo 	/*
1953112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
1954bf4ede01STejun Heo 	 * will handle the rest.
1955bf4ede01STejun Heo 	 */
1956112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1957112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
19588864b4e5STejun Heo out_put:
19598864b4e5STejun Heo 	put_pwq(pwq);
1960bf4ede01STejun Heo }
1961bf4ede01STejun Heo 
196236e227d2STejun Heo /**
1963bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
196436e227d2STejun Heo  * @work: work item to steal
196536e227d2STejun Heo  * @is_dwork: @work is a delayed_work
1966bbb68dfaSTejun Heo  * @flags: place to store irq state
196736e227d2STejun Heo  *
196836e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
1969d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
197036e227d2STejun Heo  *
1971d185af30SYacine Belkadi  * Return:
19723eb6b31bSMauro Carvalho Chehab  *
19733eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
197436e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
197536e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
197636e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
1977bbb68dfaSTejun Heo  *  -ENOENT	if someone else is canceling @work, this state may persist
1978bbb68dfaSTejun Heo  *		for arbitrarily long
19793eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
198036e227d2STejun Heo  *
1981d185af30SYacine Belkadi  * Note:
1982bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
1983e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
1984e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
1985e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1986bbb68dfaSTejun Heo  *
1987bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
1988bbb68dfaSTejun Heo  * responsible for releasing it using local_irq_restore(*@flags).
1989bbb68dfaSTejun Heo  *
1990e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
1991bf4ede01STejun Heo  */
1992bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1993bbb68dfaSTejun Heo 			       unsigned long *flags)
1994bf4ede01STejun Heo {
1995d565ed63STejun Heo 	struct worker_pool *pool;
1996112202d9STejun Heo 	struct pool_workqueue *pwq;
1997bf4ede01STejun Heo 
1998bbb68dfaSTejun Heo 	local_irq_save(*flags);
1999bbb68dfaSTejun Heo 
200036e227d2STejun Heo 	/* try to steal the timer if it exists */
200136e227d2STejun Heo 	if (is_dwork) {
200236e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
200336e227d2STejun Heo 
2004e0aecdd8STejun Heo 		/*
2005e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
2006e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
2007e0aecdd8STejun Heo 		 * running on the local CPU.
2008e0aecdd8STejun Heo 		 */
200936e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
201036e227d2STejun Heo 			return 1;
201136e227d2STejun Heo 	}
201236e227d2STejun Heo 
201336e227d2STejun Heo 	/* try to claim PENDING the normal way */
2014bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
2015bf4ede01STejun Heo 		return 0;
2016bf4ede01STejun Heo 
201724acfb71SThomas Gleixner 	rcu_read_lock();
2018bf4ede01STejun Heo 	/*
2019bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
2020bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
2021bf4ede01STejun Heo 	 */
2022d565ed63STejun Heo 	pool = get_work_pool(work);
2023d565ed63STejun Heo 	if (!pool)
2024bbb68dfaSTejun Heo 		goto fail;
2025bf4ede01STejun Heo 
2026a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&pool->lock);
2027bf4ede01STejun Heo 	/*
2028112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
2029112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
2030112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
2031112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
2032112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
20330b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
2034bf4ede01STejun Heo 	 */
2035112202d9STejun Heo 	pwq = get_work_pwq(work);
2036112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
2037c70e1779STejun Heo 		unsigned long work_data;
2038c70e1779STejun Heo 
2039bf4ede01STejun Heo 		debug_work_deactivate(work);
20403aa62497SLai Jiangshan 
20413aa62497SLai Jiangshan 		/*
2042018f3a13SLai Jiangshan 		 * A cancelable inactive work item must be in the
2043018f3a13SLai Jiangshan 		 * pwq->inactive_works since a queued barrier can't be
2044018f3a13SLai Jiangshan 		 * canceled (see the comments in insert_wq_barrier()).
2045018f3a13SLai Jiangshan 		 *
2046f97a4a1aSLai Jiangshan 		 * An inactive work item cannot be grabbed directly because
2047d812796eSLai Jiangshan 		 * it might have linked barrier work items which, if left
2048f97a4a1aSLai Jiangshan 		 * on the inactive_works list, will confuse pwq->nr_active
204916062836STejun Heo 		 * management later on and cause stall.  Make sure the work
205016062836STejun Heo 		 * item is activated before grabbing.
20513aa62497SLai Jiangshan 		 */
20524c638030STejun Heo 		pwq_activate_work(pwq, work);
20533aa62497SLai Jiangshan 
2054bf4ede01STejun Heo 		list_del_init(&work->entry);
205536e227d2STejun Heo 
2056c70e1779STejun Heo 		/*
2057c70e1779STejun Heo 		 * work->data points to pwq iff queued. Let's point to pool. As
2058c70e1779STejun Heo 		 * this destroys work->data needed by the next step, stash it.
2059c70e1779STejun Heo 		 */
2060c70e1779STejun Heo 		work_data = *work_data_bits(work);
20614468a00fSLai Jiangshan 		set_work_pool_and_keep_pending(work, pool->id);
20624468a00fSLai Jiangshan 
2063dd6c3c54STejun Heo 		/* must be the last step, see the function comment */
2064c70e1779STejun Heo 		pwq_dec_nr_in_flight(pwq, work_data);
2065dd6c3c54STejun Heo 
2066a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock(&pool->lock);
206724acfb71SThomas Gleixner 		rcu_read_unlock();
206836e227d2STejun Heo 		return 1;
2069bf4ede01STejun Heo 	}
2070a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pool->lock);
2071bbb68dfaSTejun Heo fail:
207224acfb71SThomas Gleixner 	rcu_read_unlock();
2073bbb68dfaSTejun Heo 	local_irq_restore(*flags);
2074bbb68dfaSTejun Heo 	if (work_is_canceling(work))
2075bbb68dfaSTejun Heo 		return -ENOENT;
2076bbb68dfaSTejun Heo 	cpu_relax();
207736e227d2STejun Heo 	return -EAGAIN;
2078bf4ede01STejun Heo }
2079bf4ede01STejun Heo 
2080bf4ede01STejun Heo /**
2081706026c2STejun Heo  * insert_work - insert a work into a pool
2082112202d9STejun Heo  * @pwq: pwq @work belongs to
20834690c4abSTejun Heo  * @work: work to insert
20844690c4abSTejun Heo  * @head: insertion point
20854690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
20864690c4abSTejun Heo  *
2087112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
2088706026c2STejun Heo  * work_struct flags.
20894690c4abSTejun Heo  *
20904690c4abSTejun Heo  * CONTEXT:
2091a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
2092365970a1SDavid Howells  */
2093112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
2094112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
2095b89deed3SOleg Nesterov {
2096fe089f87STejun Heo 	debug_work_activate(work);
2097e1d8aa9fSFrederic Weisbecker 
2098e89a85d6SWalter Wu 	/* record the work call stack in order to print it in KASAN reports */
2099f70da745SMarco Elver 	kasan_record_aux_stack_noalloc(work);
2100e89a85d6SWalter Wu 
21014690c4abSTejun Heo 	/* we own @work, set data and link */
2102112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
21031a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
21048864b4e5STejun Heo 	get_pwq(pwq);
2105b89deed3SOleg Nesterov }
2106b89deed3SOleg Nesterov 
2107c8efcc25STejun Heo /*
2108c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
21098d03ecfeSTejun Heo  * same workqueue.
2110c8efcc25STejun Heo  */
2111c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
2112c8efcc25STejun Heo {
2113c8efcc25STejun Heo 	struct worker *worker;
2114c8efcc25STejun Heo 
21158d03ecfeSTejun Heo 	worker = current_wq_worker();
2116c8efcc25STejun Heo 	/*
2117bf393fd4SBart Van Assche 	 * Return %true iff I'm a worker executing a work item on @wq.  If
21188d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
2119c8efcc25STejun Heo 	 */
2120112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
2121c8efcc25STejun Heo }
2122c8efcc25STejun Heo 
2123ef557180SMike Galbraith /*
2124ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
2125ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
2126ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
2127ef557180SMike Galbraith  */
2128ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
2129ef557180SMike Galbraith {
2130ef557180SMike Galbraith 	int new_cpu;
2131ef557180SMike Galbraith 
2132f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
2133ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
2134ef557180SMike Galbraith 			return cpu;
2135a8ec5880SAmmar Faizi 	} else {
2136a8ec5880SAmmar Faizi 		pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
2137f303fccbSTejun Heo 	}
2138f303fccbSTejun Heo 
2139ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
2140ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
2141ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
2142ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
2143ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
2144ef557180SMike Galbraith 			return cpu;
2145ef557180SMike Galbraith 	}
2146ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
2147ef557180SMike Galbraith 
2148ef557180SMike Galbraith 	return new_cpu;
2149ef557180SMike Galbraith }
2150ef557180SMike Galbraith 
2151d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
21521da177e4SLinus Torvalds 			 struct work_struct *work)
21531da177e4SLinus Torvalds {
2154112202d9STejun Heo 	struct pool_workqueue *pwq;
2155fe089f87STejun Heo 	struct worker_pool *last_pool, *pool;
21568a2e8e5dSTejun Heo 	unsigned int work_flags;
2157b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
21588930cabaSTejun Heo 
21598930cabaSTejun Heo 	/*
21608930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
21618930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
21628930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
21638930cabaSTejun Heo 	 * happen with IRQ disabled.
21648930cabaSTejun Heo 	 */
21658e8eb730SFrederic Weisbecker 	lockdep_assert_irqs_disabled();
21661da177e4SLinus Torvalds 
21671e19ffc6STejun Heo 
216833e3f0a3SRichard Clark 	/*
216933e3f0a3SRichard Clark 	 * For a draining wq, only works from the same workqueue are
217033e3f0a3SRichard Clark 	 * allowed. The __WQ_DESTROYING helps to spot the issue that
217133e3f0a3SRichard Clark 	 * queues a new work item to a wq after destroy_workqueue(wq).
217233e3f0a3SRichard Clark 	 */
217333e3f0a3SRichard Clark 	if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
217433e3f0a3SRichard Clark 		     WARN_ON_ONCE(!is_chained_work(wq))))
2175e41e704bSTejun Heo 		return;
217624acfb71SThomas Gleixner 	rcu_read_lock();
21779e8cd2f5STejun Heo retry:
2178aa202f1fSHillf Danton 	/* pwq which will be used unless @work is executing elsewhere */
2179636b927eSTejun Heo 	if (req_cpu == WORK_CPU_UNBOUND) {
2180636b927eSTejun Heo 		if (wq->flags & WQ_UNBOUND)
2181ef557180SMike Galbraith 			cpu = wq_select_unbound_cpu(raw_smp_processor_id());
2182636b927eSTejun Heo 		else
2183aa202f1fSHillf Danton 			cpu = raw_smp_processor_id();
2184aa202f1fSHillf Danton 	}
2185f3421797STejun Heo 
2186636b927eSTejun Heo 	pwq = rcu_dereference(*per_cpu_ptr(wq->cpu_pwq, cpu));
2187fe089f87STejun Heo 	pool = pwq->pool;
2188fe089f87STejun Heo 
218918aa9effSTejun Heo 	/*
2190c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
2191c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
2192c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
219318aa9effSTejun Heo 	 */
2194c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
2195fe089f87STejun Heo 	if (last_pool && last_pool != pool) {
219618aa9effSTejun Heo 		struct worker *worker;
219718aa9effSTejun Heo 
2198a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&last_pool->lock);
219918aa9effSTejun Heo 
2200c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
220118aa9effSTejun Heo 
2202112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
2203c9178087STejun Heo 			pwq = worker->current_pwq;
2204fe089f87STejun Heo 			pool = pwq->pool;
2205fe089f87STejun Heo 			WARN_ON_ONCE(pool != last_pool);
22068594fadeSLai Jiangshan 		} else {
220718aa9effSTejun Heo 			/* meh... not running there, queue here */
2208a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&last_pool->lock);
2209fe089f87STejun Heo 			raw_spin_lock(&pool->lock);
221018aa9effSTejun Heo 		}
22118930cabaSTejun Heo 	} else {
2212fe089f87STejun Heo 		raw_spin_lock(&pool->lock);
22138930cabaSTejun Heo 	}
2214502ca9d8STejun Heo 
22159e8cd2f5STejun Heo 	/*
2216636b927eSTejun Heo 	 * pwq is determined and locked. For unbound pools, we could have raced
2217636b927eSTejun Heo 	 * with pwq release and it could already be dead. If its refcnt is zero,
2218636b927eSTejun Heo 	 * repeat pwq selection. Note that unbound pwqs never die without
2219636b927eSTejun Heo 	 * another pwq replacing it in cpu_pwq or while work items are executing
2220636b927eSTejun Heo 	 * on it, so the retrying is guaranteed to make forward-progress.
22219e8cd2f5STejun Heo 	 */
22229e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
22239e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
2224fe089f87STejun Heo 			raw_spin_unlock(&pool->lock);
22259e8cd2f5STejun Heo 			cpu_relax();
22269e8cd2f5STejun Heo 			goto retry;
22279e8cd2f5STejun Heo 		}
22289e8cd2f5STejun Heo 		/* oops */
22299e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
22309e8cd2f5STejun Heo 			  wq->name, cpu);
22319e8cd2f5STejun Heo 	}
22329e8cd2f5STejun Heo 
2233112202d9STejun Heo 	/* pwq determined, queue */
2234112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
2235502ca9d8STejun Heo 
223624acfb71SThomas Gleixner 	if (WARN_ON(!list_empty(&work->entry)))
223724acfb71SThomas Gleixner 		goto out;
22381e19ffc6STejun Heo 
2239112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
2240112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
22411e19ffc6STejun Heo 
2242a045a272STejun Heo 	/*
2243a045a272STejun Heo 	 * Limit the number of concurrently active work items to max_active.
2244a045a272STejun Heo 	 * @work must also queue behind existing inactive work items to maintain
2245a045a272STejun Heo 	 * ordering when max_active changes. See wq_adjust_max_active().
2246a045a272STejun Heo 	 */
22475797b1c1STejun Heo 	if (list_empty(&pwq->inactive_works) && pwq_tryinc_nr_active(pwq, false)) {
2248fe089f87STejun Heo 		if (list_empty(&pool->worklist))
2249fe089f87STejun Heo 			pool->watchdog_ts = jiffies;
2250fe089f87STejun Heo 
2251cdadf009STejun Heo 		trace_workqueue_activate_work(work);
2252fe089f87STejun Heo 		insert_work(pwq, work, &pool->worklist, work_flags);
22530219a352STejun Heo 		kick_pool(pool);
22548a2e8e5dSTejun Heo 	} else {
2255f97a4a1aSLai Jiangshan 		work_flags |= WORK_STRUCT_INACTIVE;
2256fe089f87STejun Heo 		insert_work(pwq, work, &pwq->inactive_works, work_flags);
22578a2e8e5dSTejun Heo 	}
22581e19ffc6STejun Heo 
225924acfb71SThomas Gleixner out:
2260fe089f87STejun Heo 	raw_spin_unlock(&pool->lock);
226124acfb71SThomas Gleixner 	rcu_read_unlock();
22621da177e4SLinus Torvalds }
22631da177e4SLinus Torvalds 
22640fcb78c2SRolf Eike Beer /**
2265c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
2266c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
2267c1a220e7SZhang Rui  * @wq: workqueue to use
2268c1a220e7SZhang Rui  * @work: work to queue
2269c1a220e7SZhang Rui  *
2270c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
2271443378f0SPaul E. McKenney  * can't go away.  Callers that fail to ensure that the specified
2272443378f0SPaul E. McKenney  * CPU cannot go away will execute on a randomly chosen CPU.
2273854f5cc5SPaul E. McKenney  * But note well that callers specifying a CPU that never has been
2274854f5cc5SPaul E. McKenney  * online will get a splat.
2275d185af30SYacine Belkadi  *
2276d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
2277c1a220e7SZhang Rui  */
2278d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
2279d4283e93STejun Heo 		   struct work_struct *work)
2280c1a220e7SZhang Rui {
2281d4283e93STejun Heo 	bool ret = false;
22828930cabaSTejun Heo 	unsigned long flags;
22838930cabaSTejun Heo 
22848930cabaSTejun Heo 	local_irq_save(flags);
2285c1a220e7SZhang Rui 
228622df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
22874690c4abSTejun Heo 		__queue_work(cpu, wq, work);
2288d4283e93STejun Heo 		ret = true;
2289c1a220e7SZhang Rui 	}
22908930cabaSTejun Heo 
22918930cabaSTejun Heo 	local_irq_restore(flags);
2292c1a220e7SZhang Rui 	return ret;
2293c1a220e7SZhang Rui }
2294ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
2295c1a220e7SZhang Rui 
22968204e0c1SAlexander Duyck /**
2297fef59c9cSTejun Heo  * select_numa_node_cpu - Select a CPU based on NUMA node
22988204e0c1SAlexander Duyck  * @node: NUMA node ID that we want to select a CPU from
22998204e0c1SAlexander Duyck  *
23008204e0c1SAlexander Duyck  * This function will attempt to find a "random" cpu available on a given
23018204e0c1SAlexander Duyck  * node. If there are no CPUs available on the given node it will return
23028204e0c1SAlexander Duyck  * WORK_CPU_UNBOUND indicating that we should just schedule to any
23038204e0c1SAlexander Duyck  * available CPU if we need to schedule this work.
23048204e0c1SAlexander Duyck  */
2305fef59c9cSTejun Heo static int select_numa_node_cpu(int node)
23068204e0c1SAlexander Duyck {
23078204e0c1SAlexander Duyck 	int cpu;
23088204e0c1SAlexander Duyck 
23098204e0c1SAlexander Duyck 	/* Delay binding to CPU if node is not valid or online */
23108204e0c1SAlexander Duyck 	if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
23118204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
23128204e0c1SAlexander Duyck 
23138204e0c1SAlexander Duyck 	/* Use local node/cpu if we are already there */
23148204e0c1SAlexander Duyck 	cpu = raw_smp_processor_id();
23158204e0c1SAlexander Duyck 	if (node == cpu_to_node(cpu))
23168204e0c1SAlexander Duyck 		return cpu;
23178204e0c1SAlexander Duyck 
23188204e0c1SAlexander Duyck 	/* Use "random" otherwise know as "first" online CPU of node */
23198204e0c1SAlexander Duyck 	cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
23208204e0c1SAlexander Duyck 
23218204e0c1SAlexander Duyck 	/* If CPU is valid return that, otherwise just defer */
23228204e0c1SAlexander Duyck 	return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
23238204e0c1SAlexander Duyck }
23248204e0c1SAlexander Duyck 
23258204e0c1SAlexander Duyck /**
23268204e0c1SAlexander Duyck  * queue_work_node - queue work on a "random" cpu for a given NUMA node
23278204e0c1SAlexander Duyck  * @node: NUMA node that we are targeting the work for
23288204e0c1SAlexander Duyck  * @wq: workqueue to use
23298204e0c1SAlexander Duyck  * @work: work to queue
23308204e0c1SAlexander Duyck  *
23318204e0c1SAlexander Duyck  * We queue the work to a "random" CPU within a given NUMA node. The basic
23328204e0c1SAlexander Duyck  * idea here is to provide a way to somehow associate work with a given
23338204e0c1SAlexander Duyck  * NUMA node.
23348204e0c1SAlexander Duyck  *
23358204e0c1SAlexander Duyck  * This function will only make a best effort attempt at getting this onto
23368204e0c1SAlexander Duyck  * the right NUMA node. If no node is requested or the requested node is
23378204e0c1SAlexander Duyck  * offline then we just fall back to standard queue_work behavior.
23388204e0c1SAlexander Duyck  *
23398204e0c1SAlexander Duyck  * Currently the "random" CPU ends up being the first available CPU in the
23408204e0c1SAlexander Duyck  * intersection of cpu_online_mask and the cpumask of the node, unless we
23418204e0c1SAlexander Duyck  * are running on the node. In that case we just use the current CPU.
23428204e0c1SAlexander Duyck  *
23438204e0c1SAlexander Duyck  * Return: %false if @work was already on a queue, %true otherwise.
23448204e0c1SAlexander Duyck  */
23458204e0c1SAlexander Duyck bool queue_work_node(int node, struct workqueue_struct *wq,
23468204e0c1SAlexander Duyck 		     struct work_struct *work)
23478204e0c1SAlexander Duyck {
23488204e0c1SAlexander Duyck 	unsigned long flags;
23498204e0c1SAlexander Duyck 	bool ret = false;
23508204e0c1SAlexander Duyck 
23518204e0c1SAlexander Duyck 	/*
23528204e0c1SAlexander Duyck 	 * This current implementation is specific to unbound workqueues.
23538204e0c1SAlexander Duyck 	 * Specifically we only return the first available CPU for a given
23548204e0c1SAlexander Duyck 	 * node instead of cycling through individual CPUs within the node.
23558204e0c1SAlexander Duyck 	 *
23568204e0c1SAlexander Duyck 	 * If this is used with a per-cpu workqueue then the logic in
23578204e0c1SAlexander Duyck 	 * workqueue_select_cpu_near would need to be updated to allow for
23588204e0c1SAlexander Duyck 	 * some round robin type logic.
23598204e0c1SAlexander Duyck 	 */
23608204e0c1SAlexander Duyck 	WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
23618204e0c1SAlexander Duyck 
23628204e0c1SAlexander Duyck 	local_irq_save(flags);
23638204e0c1SAlexander Duyck 
23648204e0c1SAlexander Duyck 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
2365fef59c9cSTejun Heo 		int cpu = select_numa_node_cpu(node);
23668204e0c1SAlexander Duyck 
23678204e0c1SAlexander Duyck 		__queue_work(cpu, wq, work);
23688204e0c1SAlexander Duyck 		ret = true;
23698204e0c1SAlexander Duyck 	}
23708204e0c1SAlexander Duyck 
23718204e0c1SAlexander Duyck 	local_irq_restore(flags);
23728204e0c1SAlexander Duyck 	return ret;
23738204e0c1SAlexander Duyck }
23748204e0c1SAlexander Duyck EXPORT_SYMBOL_GPL(queue_work_node);
23758204e0c1SAlexander Duyck 
23768c20feb6SKees Cook void delayed_work_timer_fn(struct timer_list *t)
23771da177e4SLinus Torvalds {
23788c20feb6SKees Cook 	struct delayed_work *dwork = from_timer(dwork, t, timer);
23791da177e4SLinus Torvalds 
2380e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
238160c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
23821da177e4SLinus Torvalds }
23831438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
23841da177e4SLinus Torvalds 
23857beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
238652bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
23871da177e4SLinus Torvalds {
23887beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
23897beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
23901da177e4SLinus Torvalds 
2391637fdbaeSTejun Heo 	WARN_ON_ONCE(!wq);
23924b243563SSami Tolvanen 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
2393fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
2394fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
23957beb2edfSTejun Heo 
23968852aac2STejun Heo 	/*
23978852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
23988852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
23998852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
24008852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
24018852aac2STejun Heo 	 */
24028852aac2STejun Heo 	if (!delay) {
24038852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
24048852aac2STejun Heo 		return;
24058852aac2STejun Heo 	}
24068852aac2STejun Heo 
240760c057bcSLai Jiangshan 	dwork->wq = wq;
24081265057fSTejun Heo 	dwork->cpu = cpu;
24097beb2edfSTejun Heo 	timer->expires = jiffies + delay;
24107beb2edfSTejun Heo 
2411aae17ebbSLeonardo Bras 	if (housekeeping_enabled(HK_TYPE_TIMER)) {
2412aae17ebbSLeonardo Bras 		/* If the current cpu is a housekeeping cpu, use it. */
2413aae17ebbSLeonardo Bras 		cpu = smp_processor_id();
2414aae17ebbSLeonardo Bras 		if (!housekeeping_test_cpu(cpu, HK_TYPE_TIMER))
2415aae17ebbSLeonardo Bras 			cpu = housekeeping_any_cpu(HK_TYPE_TIMER);
24167beb2edfSTejun Heo 		add_timer_on(timer, cpu);
2417aae17ebbSLeonardo Bras 	} else {
2418aae17ebbSLeonardo Bras 		if (likely(cpu == WORK_CPU_UNBOUND))
2419041bd12eSTejun Heo 			add_timer(timer);
2420aae17ebbSLeonardo Bras 		else
2421aae17ebbSLeonardo Bras 			add_timer_on(timer, cpu);
2422aae17ebbSLeonardo Bras 	}
24237beb2edfSTejun Heo }
24241da177e4SLinus Torvalds 
24250fcb78c2SRolf Eike Beer /**
24260fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
24270fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
24280fcb78c2SRolf Eike Beer  * @wq: workqueue to use
2429af9997e4SRandy Dunlap  * @dwork: work to queue
24300fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
24310fcb78c2SRolf Eike Beer  *
2432d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
2433715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
2434715f1300STejun Heo  * execution.
24350fcb78c2SRolf Eike Beer  */
2436d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
243752bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
24387a6bc1cdSVenkatesh Pallipadi {
243952bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
2440d4283e93STejun Heo 	bool ret = false;
24418930cabaSTejun Heo 	unsigned long flags;
24428930cabaSTejun Heo 
24438930cabaSTejun Heo 	/* read the comment in __queue_work() */
24448930cabaSTejun Heo 	local_irq_save(flags);
24457a6bc1cdSVenkatesh Pallipadi 
244622df02bbSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
24477beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
2448d4283e93STejun Heo 		ret = true;
24497a6bc1cdSVenkatesh Pallipadi 	}
24508930cabaSTejun Heo 
24518930cabaSTejun Heo 	local_irq_restore(flags);
24527a6bc1cdSVenkatesh Pallipadi 	return ret;
24537a6bc1cdSVenkatesh Pallipadi }
2454ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
24551da177e4SLinus Torvalds 
2456c8e55f36STejun Heo /**
24578376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
24588376fe22STejun Heo  * @cpu: CPU number to execute work on
24598376fe22STejun Heo  * @wq: workqueue to use
24608376fe22STejun Heo  * @dwork: work to queue
24618376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
24628376fe22STejun Heo  *
24638376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
24648376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
24658376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
24668376fe22STejun Heo  * current state.
24678376fe22STejun Heo  *
2468d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
24698376fe22STejun Heo  * pending and its timer was modified.
24708376fe22STejun Heo  *
2471e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
24728376fe22STejun Heo  * See try_to_grab_pending() for details.
24738376fe22STejun Heo  */
24748376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
24758376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
24768376fe22STejun Heo {
24778376fe22STejun Heo 	unsigned long flags;
24788376fe22STejun Heo 	int ret;
24798376fe22STejun Heo 
24808376fe22STejun Heo 	do {
24818376fe22STejun Heo 		ret = try_to_grab_pending(&dwork->work, true, &flags);
24828376fe22STejun Heo 	} while (unlikely(ret == -EAGAIN));
24838376fe22STejun Heo 
24848376fe22STejun Heo 	if (likely(ret >= 0)) {
24858376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
24868376fe22STejun Heo 		local_irq_restore(flags);
24878376fe22STejun Heo 	}
24888376fe22STejun Heo 
24898376fe22STejun Heo 	/* -ENOENT from try_to_grab_pending() becomes %true */
24908376fe22STejun Heo 	return ret;
24918376fe22STejun Heo }
24928376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
24938376fe22STejun Heo 
249405f0fe6bSTejun Heo static void rcu_work_rcufn(struct rcu_head *rcu)
249505f0fe6bSTejun Heo {
249605f0fe6bSTejun Heo 	struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
249705f0fe6bSTejun Heo 
249805f0fe6bSTejun Heo 	/* read the comment in __queue_work() */
249905f0fe6bSTejun Heo 	local_irq_disable();
250005f0fe6bSTejun Heo 	__queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
250105f0fe6bSTejun Heo 	local_irq_enable();
250205f0fe6bSTejun Heo }
250305f0fe6bSTejun Heo 
250405f0fe6bSTejun Heo /**
250505f0fe6bSTejun Heo  * queue_rcu_work - queue work after a RCU grace period
250605f0fe6bSTejun Heo  * @wq: workqueue to use
250705f0fe6bSTejun Heo  * @rwork: work to queue
250805f0fe6bSTejun Heo  *
250905f0fe6bSTejun Heo  * Return: %false if @rwork was already pending, %true otherwise.  Note
251005f0fe6bSTejun Heo  * that a full RCU grace period is guaranteed only after a %true return.
2511bf393fd4SBart Van Assche  * While @rwork is guaranteed to be executed after a %false return, the
251205f0fe6bSTejun Heo  * execution may happen before a full RCU grace period has passed.
251305f0fe6bSTejun Heo  */
251405f0fe6bSTejun Heo bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
251505f0fe6bSTejun Heo {
251605f0fe6bSTejun Heo 	struct work_struct *work = &rwork->work;
251705f0fe6bSTejun Heo 
251805f0fe6bSTejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
251905f0fe6bSTejun Heo 		rwork->wq = wq;
2520a7e30c0eSUladzislau Rezki 		call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
252105f0fe6bSTejun Heo 		return true;
252205f0fe6bSTejun Heo 	}
252305f0fe6bSTejun Heo 
252405f0fe6bSTejun Heo 	return false;
252505f0fe6bSTejun Heo }
252605f0fe6bSTejun Heo EXPORT_SYMBOL(queue_rcu_work);
252705f0fe6bSTejun Heo 
2528f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
2529c34056a3STejun Heo {
2530c34056a3STejun Heo 	struct worker *worker;
2531c34056a3STejun Heo 
2532f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
2533c8e55f36STejun Heo 	if (worker) {
2534c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
2535affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
2536da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
2537e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
2538e22bee78STejun Heo 		worker->flags = WORKER_PREP;
2539c8e55f36STejun Heo 	}
2540c34056a3STejun Heo 	return worker;
2541c34056a3STejun Heo }
2542c34056a3STejun Heo 
25439546b29eSTejun Heo static cpumask_t *pool_allowed_cpus(struct worker_pool *pool)
25449546b29eSTejun Heo {
25458639ecebSTejun Heo 	if (pool->cpu < 0 && pool->attrs->affn_strict)
25469546b29eSTejun Heo 		return pool->attrs->__pod_cpumask;
25478639ecebSTejun Heo 	else
25488639ecebSTejun Heo 		return pool->attrs->cpumask;
25499546b29eSTejun Heo }
25509546b29eSTejun Heo 
2551c34056a3STejun Heo /**
25524736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
25534736cbf7SLai Jiangshan  * @worker: worker to be attached
25544736cbf7SLai Jiangshan  * @pool: the target pool
25554736cbf7SLai Jiangshan  *
25564736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
25574736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
25584736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
25594736cbf7SLai Jiangshan  */
25604736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
25614736cbf7SLai Jiangshan 				  struct worker_pool *pool)
25624736cbf7SLai Jiangshan {
25631258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
25644736cbf7SLai Jiangshan 
25654736cbf7SLai Jiangshan 	/*
25664cb1ef64STejun Heo 	 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains stable
25674cb1ef64STejun Heo 	 * across this function. See the comments above the flag definition for
25684cb1ef64STejun Heo 	 * details. BH workers are, while per-CPU, always DISASSOCIATED.
25694736cbf7SLai Jiangshan 	 */
25704cb1ef64STejun Heo 	if (pool->flags & POOL_DISASSOCIATED) {
25714736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
25724cb1ef64STejun Heo 	} else {
25734cb1ef64STejun Heo 		WARN_ON_ONCE(pool->flags & POOL_BH);
25745c25b5ffSPeter Zijlstra 		kthread_set_per_cpu(worker->task, pool->cpu);
25754cb1ef64STejun Heo 	}
25764736cbf7SLai Jiangshan 
2577640f17c8SPeter Zijlstra 	if (worker->rescue_wq)
25789546b29eSTejun Heo 		set_cpus_allowed_ptr(worker->task, pool_allowed_cpus(pool));
2579640f17c8SPeter Zijlstra 
25804736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
2581a2d812a2STejun Heo 	worker->pool = pool;
25824736cbf7SLai Jiangshan 
25831258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
25844736cbf7SLai Jiangshan }
25854736cbf7SLai Jiangshan 
25864736cbf7SLai Jiangshan /**
258760f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
258860f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
258960f5a4bcSLai Jiangshan  *
25904736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
25914736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
25924736cbf7SLai Jiangshan  * other reference to the pool.
259360f5a4bcSLai Jiangshan  */
2594a2d812a2STejun Heo static void worker_detach_from_pool(struct worker *worker)
259560f5a4bcSLai Jiangshan {
2596a2d812a2STejun Heo 	struct worker_pool *pool = worker->pool;
259760f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
259860f5a4bcSLai Jiangshan 
25994cb1ef64STejun Heo 	/* there is one permanent BH worker per CPU which should never detach */
26004cb1ef64STejun Heo 	WARN_ON_ONCE(pool->flags & POOL_BH);
26014cb1ef64STejun Heo 
26021258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2603a2d812a2STejun Heo 
26045c25b5ffSPeter Zijlstra 	kthread_set_per_cpu(worker->task, -1);
2605da028469SLai Jiangshan 	list_del(&worker->node);
2606a2d812a2STejun Heo 	worker->pool = NULL;
2607a2d812a2STejun Heo 
2608e02b9312SValentin Schneider 	if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
260960f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
26101258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
261160f5a4bcSLai Jiangshan 
2612b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
2613b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2614b62c0751SLai Jiangshan 
261560f5a4bcSLai Jiangshan 	if (detach_completion)
261660f5a4bcSLai Jiangshan 		complete(detach_completion);
261760f5a4bcSLai Jiangshan }
261860f5a4bcSLai Jiangshan 
261960f5a4bcSLai Jiangshan /**
2620c34056a3STejun Heo  * create_worker - create a new workqueue worker
262163d95a91STejun Heo  * @pool: pool the new worker will belong to
2622c34056a3STejun Heo  *
2623051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
2624c34056a3STejun Heo  *
2625c34056a3STejun Heo  * CONTEXT:
2626c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
2627c34056a3STejun Heo  *
2628d185af30SYacine Belkadi  * Return:
2629c34056a3STejun Heo  * Pointer to the newly created worker.
2630c34056a3STejun Heo  */
2631bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
2632c34056a3STejun Heo {
2633e441b56fSZhen Lei 	struct worker *worker;
2634e441b56fSZhen Lei 	int id;
26355d9c7a1eSLucy Mielke 	char id_buf[23];
2636c34056a3STejun Heo 
26377cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
2638e441b56fSZhen Lei 	id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
26393f0ea0b8SPetr Mladek 	if (id < 0) {
26403f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
26413f0ea0b8SPetr Mladek 			    ERR_PTR(id));
2642e441b56fSZhen Lei 		return NULL;
26433f0ea0b8SPetr Mladek 	}
2644c34056a3STejun Heo 
2645f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
26463f0ea0b8SPetr Mladek 	if (!worker) {
26473f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker\n");
2648c34056a3STejun Heo 		goto fail;
26493f0ea0b8SPetr Mladek 	}
2650c34056a3STejun Heo 
2651c34056a3STejun Heo 	worker->id = id;
2652c34056a3STejun Heo 
26534cb1ef64STejun Heo 	if (!(pool->flags & POOL_BH)) {
265429c91e99STejun Heo 		if (pool->cpu >= 0)
2655e3c916a4STejun Heo 			snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
2656e3c916a4STejun Heo 				 pool->attrs->nice < 0  ? "H" : "");
2657f3421797STejun Heo 		else
2658e3c916a4STejun Heo 			snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
2659e3c916a4STejun Heo 
26604cb1ef64STejun Heo 		worker->task = kthread_create_on_node(worker_thread, worker,
26614cb1ef64STejun Heo 					pool->node, "kworker/%s", id_buf);
26623f0ea0b8SPetr Mladek 		if (IS_ERR(worker->task)) {
266360f54038SPetr Mladek 			if (PTR_ERR(worker->task) == -EINTR) {
266460f54038SPetr Mladek 				pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n",
266560f54038SPetr Mladek 				       id_buf);
266660f54038SPetr Mladek 			} else {
26673f0ea0b8SPetr Mladek 				pr_err_once("workqueue: Failed to create a worker thread: %pe",
26683f0ea0b8SPetr Mladek 					    worker->task);
266960f54038SPetr Mladek 			}
2670c34056a3STejun Heo 			goto fail;
26713f0ea0b8SPetr Mladek 		}
2672c34056a3STejun Heo 
267391151228SOleg Nesterov 		set_user_nice(worker->task, pool->attrs->nice);
26749546b29eSTejun Heo 		kthread_bind_mask(worker->task, pool_allowed_cpus(pool));
26754cb1ef64STejun Heo 	}
267691151228SOleg Nesterov 
2677da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
26784736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
2679822d8405STejun Heo 
2680051e1850SLai Jiangshan 	/* start the newly created worker */
2681a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
26820219a352STejun Heo 
2683051e1850SLai Jiangshan 	worker->pool->nr_workers++;
2684051e1850SLai Jiangshan 	worker_enter_idle(worker);
26850219a352STejun Heo 
26860219a352STejun Heo 	/*
26870219a352STejun Heo 	 * @worker is waiting on a completion in kthread() and will trigger hung
26886a229b0eSTejun Heo 	 * check if not woken up soon. As kick_pool() is noop if @pool is empty,
26896a229b0eSTejun Heo 	 * wake it up explicitly.
26900219a352STejun Heo 	 */
26914cb1ef64STejun Heo 	if (worker->task)
2692051e1850SLai Jiangshan 		wake_up_process(worker->task);
26930219a352STejun Heo 
2694a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2695051e1850SLai Jiangshan 
2696c34056a3STejun Heo 	return worker;
2697822d8405STejun Heo 
2698c34056a3STejun Heo fail:
2699e441b56fSZhen Lei 	ida_free(&pool->worker_ida, id);
2700c34056a3STejun Heo 	kfree(worker);
2701c34056a3STejun Heo 	return NULL;
2702c34056a3STejun Heo }
2703c34056a3STejun Heo 
2704793777bcSValentin Schneider static void unbind_worker(struct worker *worker)
2705793777bcSValentin Schneider {
2706793777bcSValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2707793777bcSValentin Schneider 
2708793777bcSValentin Schneider 	kthread_set_per_cpu(worker->task, -1);
2709793777bcSValentin Schneider 	if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2710793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2711793777bcSValentin Schneider 	else
2712793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2713793777bcSValentin Schneider }
2714793777bcSValentin Schneider 
2715e02b9312SValentin Schneider static void wake_dying_workers(struct list_head *cull_list)
2716e02b9312SValentin Schneider {
2717e02b9312SValentin Schneider 	struct worker *worker, *tmp;
2718e02b9312SValentin Schneider 
2719e02b9312SValentin Schneider 	list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2720e02b9312SValentin Schneider 		list_del_init(&worker->entry);
2721e02b9312SValentin Schneider 		unbind_worker(worker);
2722e02b9312SValentin Schneider 		/*
2723e02b9312SValentin Schneider 		 * If the worker was somehow already running, then it had to be
2724e02b9312SValentin Schneider 		 * in pool->idle_list when set_worker_dying() happened or we
2725e02b9312SValentin Schneider 		 * wouldn't have gotten here.
2726c34056a3STejun Heo 		 *
2727e02b9312SValentin Schneider 		 * Thus, the worker must either have observed the WORKER_DIE
2728e02b9312SValentin Schneider 		 * flag, or have set its state to TASK_IDLE. Either way, the
2729e02b9312SValentin Schneider 		 * below will be observed by the worker and is safe to do
2730e02b9312SValentin Schneider 		 * outside of pool->lock.
2731e02b9312SValentin Schneider 		 */
2732e02b9312SValentin Schneider 		wake_up_process(worker->task);
2733e02b9312SValentin Schneider 	}
2734e02b9312SValentin Schneider }
2735e02b9312SValentin Schneider 
2736e02b9312SValentin Schneider /**
2737e02b9312SValentin Schneider  * set_worker_dying - Tag a worker for destruction
2738e02b9312SValentin Schneider  * @worker: worker to be destroyed
2739e02b9312SValentin Schneider  * @list: transfer worker away from its pool->idle_list and into list
2740e02b9312SValentin Schneider  *
2741e02b9312SValentin Schneider  * Tag @worker for destruction and adjust @pool stats accordingly.  The worker
2742e02b9312SValentin Schneider  * should be idle.
2743c8e55f36STejun Heo  *
2744c8e55f36STejun Heo  * CONTEXT:
2745a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
2746c34056a3STejun Heo  */
2747e02b9312SValentin Schneider static void set_worker_dying(struct worker *worker, struct list_head *list)
2748c34056a3STejun Heo {
2749bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2750c34056a3STejun Heo 
2751cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
2752e02b9312SValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2753cd549687STejun Heo 
2754c34056a3STejun Heo 	/* sanity check frenzy */
27556183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
275673eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
275773eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
27586183c009STejun Heo 		return;
2759c34056a3STejun Heo 
2760bd7bdd43STejun Heo 	pool->nr_workers--;
2761bd7bdd43STejun Heo 	pool->nr_idle--;
2762c8e55f36STejun Heo 
2763cb444766STejun Heo 	worker->flags |= WORKER_DIE;
2764e02b9312SValentin Schneider 
2765e02b9312SValentin Schneider 	list_move(&worker->entry, list);
2766e02b9312SValentin Schneider 	list_move(&worker->node, &pool->dying_workers);
2767c34056a3STejun Heo }
2768c34056a3STejun Heo 
27693f959aa3SValentin Schneider /**
27703f959aa3SValentin Schneider  * idle_worker_timeout - check if some idle workers can now be deleted.
27713f959aa3SValentin Schneider  * @t: The pool's idle_timer that just expired
27723f959aa3SValentin Schneider  *
27733f959aa3SValentin Schneider  * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
27743f959aa3SValentin Schneider  * worker_leave_idle(), as a worker flicking between idle and active while its
27753f959aa3SValentin Schneider  * pool is at the too_many_workers() tipping point would cause too much timer
27763f959aa3SValentin Schneider  * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
27773f959aa3SValentin Schneider  * it expire and re-evaluate things from there.
27783f959aa3SValentin Schneider  */
277932a6c723SKees Cook static void idle_worker_timeout(struct timer_list *t)
2780e22bee78STejun Heo {
278132a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, idle_timer);
27823f959aa3SValentin Schneider 	bool do_cull = false;
27833f959aa3SValentin Schneider 
27843f959aa3SValentin Schneider 	if (work_pending(&pool->idle_cull_work))
27853f959aa3SValentin Schneider 		return;
27863f959aa3SValentin Schneider 
27873f959aa3SValentin Schneider 	raw_spin_lock_irq(&pool->lock);
27883f959aa3SValentin Schneider 
27893f959aa3SValentin Schneider 	if (too_many_workers(pool)) {
27903f959aa3SValentin Schneider 		struct worker *worker;
27913f959aa3SValentin Schneider 		unsigned long expires;
27923f959aa3SValentin Schneider 
27933f959aa3SValentin Schneider 		/* idle_list is kept in LIFO order, check the last one */
27943f959aa3SValentin Schneider 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
27953f959aa3SValentin Schneider 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
27963f959aa3SValentin Schneider 		do_cull = !time_before(jiffies, expires);
27973f959aa3SValentin Schneider 
27983f959aa3SValentin Schneider 		if (!do_cull)
27993f959aa3SValentin Schneider 			mod_timer(&pool->idle_timer, expires);
28003f959aa3SValentin Schneider 	}
28013f959aa3SValentin Schneider 	raw_spin_unlock_irq(&pool->lock);
28023f959aa3SValentin Schneider 
28033f959aa3SValentin Schneider 	if (do_cull)
28043f959aa3SValentin Schneider 		queue_work(system_unbound_wq, &pool->idle_cull_work);
28053f959aa3SValentin Schneider }
28063f959aa3SValentin Schneider 
28073f959aa3SValentin Schneider /**
28083f959aa3SValentin Schneider  * idle_cull_fn - cull workers that have been idle for too long.
28093f959aa3SValentin Schneider  * @work: the pool's work for handling these idle workers
28103f959aa3SValentin Schneider  *
28113f959aa3SValentin Schneider  * This goes through a pool's idle workers and gets rid of those that have been
28123f959aa3SValentin Schneider  * idle for at least IDLE_WORKER_TIMEOUT seconds.
2813e02b9312SValentin Schneider  *
2814e02b9312SValentin Schneider  * We don't want to disturb isolated CPUs because of a pcpu kworker being
2815e02b9312SValentin Schneider  * culled, so this also resets worker affinity. This requires a sleepable
2816e02b9312SValentin Schneider  * context, hence the split between timer callback and work item.
28173f959aa3SValentin Schneider  */
28183f959aa3SValentin Schneider static void idle_cull_fn(struct work_struct *work)
28193f959aa3SValentin Schneider {
28203f959aa3SValentin Schneider 	struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
28219680540cSYang Yingliang 	LIST_HEAD(cull_list);
2822e22bee78STejun Heo 
2823e02b9312SValentin Schneider 	/*
2824e02b9312SValentin Schneider 	 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2825e02b9312SValentin Schneider 	 * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2826e02b9312SValentin Schneider 	 * path. This is required as a previously-preempted worker could run after
2827e02b9312SValentin Schneider 	 * set_worker_dying() has happened but before wake_dying_workers() did.
2828e02b9312SValentin Schneider 	 */
2829e02b9312SValentin Schneider 	mutex_lock(&wq_pool_attach_mutex);
2830a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2831e22bee78STejun Heo 
28323347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
2833e22bee78STejun Heo 		struct worker *worker;
2834e22bee78STejun Heo 		unsigned long expires;
2835e22bee78STejun Heo 
283663d95a91STejun Heo 		worker = list_entry(pool->idle_list.prev, struct worker, entry);
2837e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2838e22bee78STejun Heo 
28393347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
284063d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
28413347fc9fSLai Jiangshan 			break;
2842e22bee78STejun Heo 		}
28433347fc9fSLai Jiangshan 
2844e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
2845e22bee78STejun Heo 	}
2846e22bee78STejun Heo 
2847a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2848e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
2849e02b9312SValentin Schneider 	mutex_unlock(&wq_pool_attach_mutex);
2850e22bee78STejun Heo }
2851e22bee78STejun Heo 
2852493a1724STejun Heo static void send_mayday(struct work_struct *work)
2853e22bee78STejun Heo {
2854112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2855112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
2856493a1724STejun Heo 
28572e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
2858e22bee78STejun Heo 
2859493008a8STejun Heo 	if (!wq->rescuer)
2860493a1724STejun Heo 		return;
2861e22bee78STejun Heo 
2862e22bee78STejun Heo 	/* mayday mayday mayday */
2863493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
286477668c8bSLai Jiangshan 		/*
286577668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
286677668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
286777668c8bSLai Jiangshan 		 * rescuer is done with it.
286877668c8bSLai Jiangshan 		 */
286977668c8bSLai Jiangshan 		get_pwq(pwq);
2870493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
2871e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
2872725e8ec5STejun Heo 		pwq->stats[PWQ_STAT_MAYDAY]++;
2873493a1724STejun Heo 	}
2874e22bee78STejun Heo }
2875e22bee78STejun Heo 
287632a6c723SKees Cook static void pool_mayday_timeout(struct timer_list *t)
2877e22bee78STejun Heo {
287832a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2879e22bee78STejun Heo 	struct work_struct *work;
2880e22bee78STejun Heo 
2881a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2882a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&wq_mayday_lock);		/* for wq->maydays */
2883e22bee78STejun Heo 
288463d95a91STejun Heo 	if (need_to_create_worker(pool)) {
2885e22bee78STejun Heo 		/*
2886e22bee78STejun Heo 		 * We've been trying to create a new worker but
2887e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
2888e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
2889e22bee78STejun Heo 		 * rescuers.
2890e22bee78STejun Heo 		 */
289163d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
2892e22bee78STejun Heo 			send_mayday(work);
2893e22bee78STejun Heo 	}
2894e22bee78STejun Heo 
2895a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&wq_mayday_lock);
2896a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2897e22bee78STejun Heo 
289863d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2899e22bee78STejun Heo }
2900e22bee78STejun Heo 
2901e22bee78STejun Heo /**
2902e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
290363d95a91STejun Heo  * @pool: pool to create a new worker for
2904e22bee78STejun Heo  *
290563d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
2906e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
2907e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
290863d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
2909e22bee78STejun Heo  * possible allocation deadlock.
2910e22bee78STejun Heo  *
2911c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
2912c5aa87bbSTejun Heo  * may_start_working() %true.
2913e22bee78STejun Heo  *
2914e22bee78STejun Heo  * LOCKING:
2915a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2916e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
2917e22bee78STejun Heo  * manager.
2918e22bee78STejun Heo  */
291929187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
2920d565ed63STejun Heo __releases(&pool->lock)
2921d565ed63STejun Heo __acquires(&pool->lock)
2922e22bee78STejun Heo {
2923e22bee78STejun Heo restart:
2924a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
29259f9c2364STejun Heo 
2926e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
292763d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2928e22bee78STejun Heo 
2929e22bee78STejun Heo 	while (true) {
2930051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
2931e22bee78STejun Heo 			break;
2932e22bee78STejun Heo 
2933e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
29349f9c2364STejun Heo 
293563d95a91STejun Heo 		if (!need_to_create_worker(pool))
2936e22bee78STejun Heo 			break;
2937e22bee78STejun Heo 	}
2938e22bee78STejun Heo 
293963d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
2940a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2941051e1850SLai Jiangshan 	/*
2942051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
2943051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
2944051e1850SLai Jiangshan 	 * already become busy.
2945051e1850SLai Jiangshan 	 */
294663d95a91STejun Heo 	if (need_to_create_worker(pool))
2947e22bee78STejun Heo 		goto restart;
2948e22bee78STejun Heo }
2949e22bee78STejun Heo 
2950e22bee78STejun Heo /**
2951e22bee78STejun Heo  * manage_workers - manage worker pool
2952e22bee78STejun Heo  * @worker: self
2953e22bee78STejun Heo  *
2954706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
2955e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
2956706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
2957e22bee78STejun Heo  *
2958e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
2959e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
2960e22bee78STejun Heo  * and may_start_working() is true.
2961e22bee78STejun Heo  *
2962e22bee78STejun Heo  * CONTEXT:
2963a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2964e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
2965e22bee78STejun Heo  *
2966d185af30SYacine Belkadi  * Return:
296729187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
296829187a9eSTejun Heo  * start processing works, %true if management function was performed and
296929187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
297029187a9eSTejun Heo  * no longer be true.
2971e22bee78STejun Heo  */
2972e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2973e22bee78STejun Heo {
297463d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
2975e22bee78STejun Heo 
2976692b4825STejun Heo 	if (pool->flags & POOL_MANAGER_ACTIVE)
297729187a9eSTejun Heo 		return false;
2978692b4825STejun Heo 
2979692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
29802607d7a6STejun Heo 	pool->manager = worker;
2981e22bee78STejun Heo 
298229187a9eSTejun Heo 	maybe_create_worker(pool);
2983e22bee78STejun Heo 
29842607d7a6STejun Heo 	pool->manager = NULL;
2985692b4825STejun Heo 	pool->flags &= ~POOL_MANAGER_ACTIVE;
2986d8bb65abSSebastian Andrzej Siewior 	rcuwait_wake_up(&manager_wait);
298729187a9eSTejun Heo 	return true;
2988e22bee78STejun Heo }
2989e22bee78STejun Heo 
2990a62428c0STejun Heo /**
2991a62428c0STejun Heo  * process_one_work - process single work
2992c34056a3STejun Heo  * @worker: self
2993a62428c0STejun Heo  * @work: work to process
2994a62428c0STejun Heo  *
2995a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
2996a62428c0STejun Heo  * process a single work including synchronization against and
2997a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
2998a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
2999a62428c0STejun Heo  * call this function to process a work.
3000a62428c0STejun Heo  *
3001a62428c0STejun Heo  * CONTEXT:
3002a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
3003a62428c0STejun Heo  */
3004c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
3005d565ed63STejun Heo __releases(&pool->lock)
3006d565ed63STejun Heo __acquires(&pool->lock)
30071da177e4SLinus Torvalds {
3008112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
3009bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
3010c4560c2cSLai Jiangshan 	unsigned long work_data;
3011c35aea39STejun Heo 	int lockdep_start_depth, rcu_start_depth;
30124e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
30134e6045f1SJohannes Berg 	/*
3014a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
3015a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
3016a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
3017a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
3018a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
30194e6045f1SJohannes Berg 	 */
30204d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
30214d82a1deSPeter Zijlstra 
30224d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
30234e6045f1SJohannes Berg #endif
3024807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
302585327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
3026ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
302725511a47STejun Heo 
30288930cabaSTejun Heo 	/* claim and dequeue */
3029dc186ad7SThomas Gleixner 	debug_work_deactivate(work);
3030c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
3031c34056a3STejun Heo 	worker->current_work = work;
3032a2c1c57bSTejun Heo 	worker->current_func = work->func;
3033112202d9STejun Heo 	worker->current_pwq = pwq;
30344cb1ef64STejun Heo 	if (worker->task)
3035616db877STejun Heo 		worker->current_at = worker->task->se.sum_exec_runtime;
3036c4560c2cSLai Jiangshan 	work_data = *work_data_bits(work);
3037d812796eSLai Jiangshan 	worker->current_color = get_work_color(work_data);
30387a22ad75STejun Heo 
30398bf89593STejun Heo 	/*
30408bf89593STejun Heo 	 * Record wq name for cmdline and debug reporting, may get
30418bf89593STejun Heo 	 * overridden through set_worker_desc().
30428bf89593STejun Heo 	 */
30438bf89593STejun Heo 	strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
30448bf89593STejun Heo 
3045a62428c0STejun Heo 	list_del_init(&work->entry);
3046a62428c0STejun Heo 
3047649027d7STejun Heo 	/*
3048228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
3049228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
3050228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
3051228f1d00SLai Jiangshan 	 * execution of the pending work items.
3052fb0e7bebSTejun Heo 	 */
3053616db877STejun Heo 	if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
3054228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
3055fb0e7bebSTejun Heo 
3056974271c4STejun Heo 	/*
30570219a352STejun Heo 	 * Kick @pool if necessary. It's always noop for per-cpu worker pools
30580219a352STejun Heo 	 * since nr_running would always be >= 1 at this point. This is used to
30590219a352STejun Heo 	 * chain execution of the pending work items for WORKER_NOT_RUNNING
30600219a352STejun Heo 	 * workers such as the UNBOUND and CPU_INTENSIVE ones.
3061974271c4STejun Heo 	 */
30620219a352STejun Heo 	kick_pool(pool);
3063974271c4STejun Heo 
30648930cabaSTejun Heo 	/*
30657c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
3066d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
306723657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
306823657bb1STejun Heo 	 * disabled.
30698930cabaSTejun Heo 	 */
30707c3eed5cSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id);
30711da177e4SLinus Torvalds 
3072fe48ba7dSMirsad Goran Todorovac 	pwq->stats[PWQ_STAT_STARTED]++;
3073a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
3074365970a1SDavid Howells 
3075c35aea39STejun Heo 	rcu_start_depth = rcu_preempt_depth();
3076c35aea39STejun Heo 	lockdep_start_depth = lockdep_depth(current);
3077a1d14934SPeter Zijlstra 	lock_map_acquire(&pwq->wq->lockdep_map);
30783295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
3079e6f3faa7SPeter Zijlstra 	/*
3080f52be570SPeter Zijlstra 	 * Strictly speaking we should mark the invariant state without holding
3081f52be570SPeter Zijlstra 	 * any locks, that is, before these two lock_map_acquire()'s.
3082e6f3faa7SPeter Zijlstra 	 *
3083e6f3faa7SPeter Zijlstra 	 * However, that would result in:
3084e6f3faa7SPeter Zijlstra 	 *
3085e6f3faa7SPeter Zijlstra 	 *   A(W1)
3086e6f3faa7SPeter Zijlstra 	 *   WFC(C)
3087e6f3faa7SPeter Zijlstra 	 *		A(W1)
3088e6f3faa7SPeter Zijlstra 	 *		C(C)
3089e6f3faa7SPeter Zijlstra 	 *
3090e6f3faa7SPeter Zijlstra 	 * Which would create W1->C->W1 dependencies, even though there is no
3091e6f3faa7SPeter Zijlstra 	 * actual deadlock possible. There are two solutions, using a
3092e6f3faa7SPeter Zijlstra 	 * read-recursive acquire on the work(queue) 'locks', but this will then
3093f52be570SPeter Zijlstra 	 * hit the lockdep limitation on recursive locks, or simply discard
3094e6f3faa7SPeter Zijlstra 	 * these locks.
3095e6f3faa7SPeter Zijlstra 	 *
3096e6f3faa7SPeter Zijlstra 	 * AFAICT there is no possible deadlock scenario between the
3097e6f3faa7SPeter Zijlstra 	 * flush_work() and complete() primitives (except for single-threaded
3098e6f3faa7SPeter Zijlstra 	 * workqueues), so hiding them isn't a problem.
3099e6f3faa7SPeter Zijlstra 	 */
3100f52be570SPeter Zijlstra 	lockdep_invariant_state(true);
3101e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
3102a2c1c57bSTejun Heo 	worker->current_func(work);
3103e36c886aSArjan van de Ven 	/*
3104e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
3105e36c886aSArjan van de Ven 	 * point will only record its address.
3106e36c886aSArjan van de Ven 	 */
31071c5da0ecSDaniel Jordan 	trace_workqueue_execute_end(work, worker->current_func);
3108725e8ec5STejun Heo 	pwq->stats[PWQ_STAT_COMPLETED]++;
31093295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
3110112202d9STejun Heo 	lock_map_release(&pwq->wq->lockdep_map);
31111da177e4SLinus Torvalds 
3112c35aea39STejun Heo 	if (unlikely((worker->task && in_atomic()) ||
3113c35aea39STejun Heo 		     lockdep_depth(current) != lockdep_start_depth ||
3114c35aea39STejun Heo 		     rcu_preempt_depth() != rcu_start_depth)) {
3115c35aea39STejun Heo 		pr_err("BUG: workqueue leaked atomic, lock or RCU: %s[%d]\n"
3116c35aea39STejun Heo 		       "     preempt=0x%08x lock=%d->%d RCU=%d->%d workfn=%ps\n",
3117c35aea39STejun Heo 		       current->comm, task_pid_nr(current), preempt_count(),
3118c35aea39STejun Heo 		       lockdep_start_depth, lockdep_depth(current),
3119c35aea39STejun Heo 		       rcu_start_depth, rcu_preempt_depth(),
3120c35aea39STejun Heo 		       worker->current_func);
3121d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
3122d5abe669SPeter Zijlstra 		dump_stack();
3123d5abe669SPeter Zijlstra 	}
3124d5abe669SPeter Zijlstra 
3125b22ce278STejun Heo 	/*
3126025f50f3SSebastian Andrzej Siewior 	 * The following prevents a kworker from hogging CPU on !PREEMPTION
3127b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
3128b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
3129b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
3130789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
3131789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
3132b22ce278STejun Heo 	 */
31334cb1ef64STejun Heo 	if (worker->task)
3134a7e6425eSPaul E. McKenney 		cond_resched();
3135b22ce278STejun Heo 
3136a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
3137a62428c0STejun Heo 
3138616db877STejun Heo 	/*
3139616db877STejun Heo 	 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
3140616db877STejun Heo 	 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
3141616db877STejun Heo 	 * wq_cpu_intensive_thresh_us. Clear it.
3142616db877STejun Heo 	 */
3143fb0e7bebSTejun Heo 	worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
3144fb0e7bebSTejun Heo 
31451b69ac6bSJohannes Weiner 	/* tag the worker for identification in schedule() */
31461b69ac6bSJohannes Weiner 	worker->last_func = worker->current_func;
31471b69ac6bSJohannes Weiner 
3148a62428c0STejun Heo 	/* we're done with it, release */
314942f8570fSSasha Levin 	hash_del(&worker->hentry);
3150c34056a3STejun Heo 	worker->current_work = NULL;
3151a2c1c57bSTejun Heo 	worker->current_func = NULL;
3152112202d9STejun Heo 	worker->current_pwq = NULL;
3153d812796eSLai Jiangshan 	worker->current_color = INT_MAX;
3154dd6c3c54STejun Heo 
3155dd6c3c54STejun Heo 	/* must be the last step, see the function comment */
3156c4560c2cSLai Jiangshan 	pwq_dec_nr_in_flight(pwq, work_data);
31571da177e4SLinus Torvalds }
31581da177e4SLinus Torvalds 
3159affee4b2STejun Heo /**
3160affee4b2STejun Heo  * process_scheduled_works - process scheduled works
3161affee4b2STejun Heo  * @worker: self
3162affee4b2STejun Heo  *
3163affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
3164affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
3165affee4b2STejun Heo  * fetches a work from the top and executes it.
3166affee4b2STejun Heo  *
3167affee4b2STejun Heo  * CONTEXT:
3168a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3169affee4b2STejun Heo  * multiple times.
3170affee4b2STejun Heo  */
3171affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
31721da177e4SLinus Torvalds {
3173c0ab017dSTejun Heo 	struct work_struct *work;
3174c0ab017dSTejun Heo 	bool first = true;
3175c0ab017dSTejun Heo 
3176c0ab017dSTejun Heo 	while ((work = list_first_entry_or_null(&worker->scheduled,
3177c0ab017dSTejun Heo 						struct work_struct, entry))) {
3178c0ab017dSTejun Heo 		if (first) {
3179c0ab017dSTejun Heo 			worker->pool->watchdog_ts = jiffies;
3180c0ab017dSTejun Heo 			first = false;
3181c0ab017dSTejun Heo 		}
3182c34056a3STejun Heo 		process_one_work(worker, work);
3183a62428c0STejun Heo 	}
31841da177e4SLinus Torvalds }
31851da177e4SLinus Torvalds 
3186197f6accSTejun Heo static void set_pf_worker(bool val)
3187197f6accSTejun Heo {
3188197f6accSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
3189197f6accSTejun Heo 	if (val)
3190197f6accSTejun Heo 		current->flags |= PF_WQ_WORKER;
3191197f6accSTejun Heo 	else
3192197f6accSTejun Heo 		current->flags &= ~PF_WQ_WORKER;
3193197f6accSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
3194197f6accSTejun Heo }
3195197f6accSTejun Heo 
31964690c4abSTejun Heo /**
31974690c4abSTejun Heo  * worker_thread - the worker thread function
3198c34056a3STejun Heo  * @__worker: self
31994690c4abSTejun Heo  *
3200c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
3201c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
3202c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
3203c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
3204c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
3205d185af30SYacine Belkadi  *
3206d185af30SYacine Belkadi  * Return: 0
32074690c4abSTejun Heo  */
3208c34056a3STejun Heo static int worker_thread(void *__worker)
32091da177e4SLinus Torvalds {
3210c34056a3STejun Heo 	struct worker *worker = __worker;
3211bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
32121da177e4SLinus Torvalds 
3213e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
3214197f6accSTejun Heo 	set_pf_worker(true);
3215c8e55f36STejun Heo woke_up:
3216a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
3217affee4b2STejun Heo 
3218a9ab775bSTejun Heo 	/* am I supposed to die? */
3219a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
3220a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
3221197f6accSTejun Heo 		set_pf_worker(false);
322260f5a4bcSLai Jiangshan 
322360f5a4bcSLai Jiangshan 		set_task_comm(worker->task, "kworker/dying");
3224e441b56fSZhen Lei 		ida_free(&pool->worker_ida, worker->id);
3225a2d812a2STejun Heo 		worker_detach_from_pool(worker);
3226e02b9312SValentin Schneider 		WARN_ON_ONCE(!list_empty(&worker->entry));
322760f5a4bcSLai Jiangshan 		kfree(worker);
3228c8e55f36STejun Heo 		return 0;
3229c8e55f36STejun Heo 	}
3230c8e55f36STejun Heo 
3231c8e55f36STejun Heo 	worker_leave_idle(worker);
3232db7bccf4STejun Heo recheck:
3233e22bee78STejun Heo 	/* no more worker necessary? */
323463d95a91STejun Heo 	if (!need_more_worker(pool))
3235e22bee78STejun Heo 		goto sleep;
3236e22bee78STejun Heo 
3237e22bee78STejun Heo 	/* do we need to manage? */
323863d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
3239e22bee78STejun Heo 		goto recheck;
3240e22bee78STejun Heo 
3241c8e55f36STejun Heo 	/*
3242c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
3243c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
3244c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
3245c8e55f36STejun Heo 	 */
32466183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
3247c8e55f36STejun Heo 
3248e22bee78STejun Heo 	/*
3249a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
3250a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
3251a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
3252a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
3253a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
3254e22bee78STejun Heo 	 */
3255a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
3256e22bee78STejun Heo 
3257e22bee78STejun Heo 	do {
3258affee4b2STejun Heo 		struct work_struct *work =
3259bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
3260affee4b2STejun Heo 					 struct work_struct, entry);
3261affee4b2STejun Heo 
3262873eaca6STejun Heo 		if (assign_work(work, worker, NULL))
3263affee4b2STejun Heo 			process_scheduled_works(worker);
326463d95a91STejun Heo 	} while (keep_working(pool));
3265affee4b2STejun Heo 
3266228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
3267d313dd85STejun Heo sleep:
3268c8e55f36STejun Heo 	/*
3269d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
3270d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
3271d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
3272d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
3273d565ed63STejun Heo 	 * event.
3274c8e55f36STejun Heo 	 */
3275c8e55f36STejun Heo 	worker_enter_idle(worker);
3276c5a94a61SPeter Zijlstra 	__set_current_state(TASK_IDLE);
3277a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
32781da177e4SLinus Torvalds 	schedule();
3279c8e55f36STejun Heo 	goto woke_up;
32801da177e4SLinus Torvalds }
32811da177e4SLinus Torvalds 
3282e22bee78STejun Heo /**
3283e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
3284111c225aSTejun Heo  * @__rescuer: self
3285e22bee78STejun Heo  *
3286e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
3287493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
3288e22bee78STejun Heo  *
3289706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
3290e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
3291e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
3292e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
3293e22bee78STejun Heo  * the problem rescuer solves.
3294e22bee78STejun Heo  *
3295706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
3296706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
3297e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
3298e22bee78STejun Heo  *
3299e22bee78STejun Heo  * This should happen rarely.
3300d185af30SYacine Belkadi  *
3301d185af30SYacine Belkadi  * Return: 0
3302e22bee78STejun Heo  */
3303111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
3304e22bee78STejun Heo {
3305111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
3306111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
33074d595b86SLai Jiangshan 	bool should_stop;
3308e22bee78STejun Heo 
3309e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
3310111c225aSTejun Heo 
3311111c225aSTejun Heo 	/*
3312111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
3313111c225aSTejun Heo 	 * doesn't participate in concurrency management.
3314111c225aSTejun Heo 	 */
3315197f6accSTejun Heo 	set_pf_worker(true);
3316e22bee78STejun Heo repeat:
3317c5a94a61SPeter Zijlstra 	set_current_state(TASK_IDLE);
33181da177e4SLinus Torvalds 
33194d595b86SLai Jiangshan 	/*
33204d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
33214d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
33224d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
33234d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
33244d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
33254d595b86SLai Jiangshan 	 * list is always empty on exit.
33264d595b86SLai Jiangshan 	 */
33274d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
33281da177e4SLinus Torvalds 
3329493a1724STejun Heo 	/* see whether any pwq is asking for help */
3330a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq_mayday_lock);
3331493a1724STejun Heo 
3332493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
3333493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
3334493a1724STejun Heo 					struct pool_workqueue, mayday_node);
3335112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
3336e22bee78STejun Heo 		struct work_struct *work, *n;
3337e22bee78STejun Heo 
3338e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
3339493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
3340493a1724STejun Heo 
3341a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
3342e22bee78STejun Heo 
334351697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
334451697d39SLai Jiangshan 
3345a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
3346e22bee78STejun Heo 
3347e22bee78STejun Heo 		/*
3348e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
3349e22bee78STejun Heo 		 * process'em.
3350e22bee78STejun Heo 		 */
3351873eaca6STejun Heo 		WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
335282607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
3353873eaca6STejun Heo 			if (get_work_pwq(work) == pwq &&
3354873eaca6STejun Heo 			    assign_work(work, rescuer, &n))
3355725e8ec5STejun Heo 				pwq->stats[PWQ_STAT_RESCUED]++;
335682607adcSTejun Heo 		}
3357e22bee78STejun Heo 
3358873eaca6STejun Heo 		if (!list_empty(&rescuer->scheduled)) {
3359e22bee78STejun Heo 			process_scheduled_works(rescuer);
33607576958aSTejun Heo 
33617576958aSTejun Heo 			/*
3362008847f6SNeilBrown 			 * The above execution of rescued work items could
3363008847f6SNeilBrown 			 * have created more to rescue through
3364f97a4a1aSLai Jiangshan 			 * pwq_activate_first_inactive() or chained
3365008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
3366008847f6SNeilBrown 			 * that such back-to-back work items, which may be
3367008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
3368008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
3369008847f6SNeilBrown 			 */
33704f3f4cf3SLai Jiangshan 			if (pwq->nr_active && need_to_create_worker(pool)) {
3371a9b8a985SSebastian Andrzej Siewior 				raw_spin_lock(&wq_mayday_lock);
3372e66b39afSTejun Heo 				/*
3373e66b39afSTejun Heo 				 * Queue iff we aren't racing destruction
3374e66b39afSTejun Heo 				 * and somebody else hasn't queued it already.
3375e66b39afSTejun Heo 				 */
3376e66b39afSTejun Heo 				if (wq->rescuer && list_empty(&pwq->mayday_node)) {
3377008847f6SNeilBrown 					get_pwq(pwq);
3378e66b39afSTejun Heo 					list_add_tail(&pwq->mayday_node, &wq->maydays);
3379e66b39afSTejun Heo 				}
3380a9b8a985SSebastian Andrzej Siewior 				raw_spin_unlock(&wq_mayday_lock);
3381008847f6SNeilBrown 			}
3382008847f6SNeilBrown 		}
3383008847f6SNeilBrown 
3384008847f6SNeilBrown 		/*
338577668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
338613b1d625SLai Jiangshan 		 * go away while we're still attached to it.
338777668c8bSLai Jiangshan 		 */
338877668c8bSLai Jiangshan 		put_pwq(pwq);
338977668c8bSLai Jiangshan 
339077668c8bSLai Jiangshan 		/*
33910219a352STejun Heo 		 * Leave this pool. Notify regular workers; otherwise, we end up
33920219a352STejun Heo 		 * with 0 concurrency and stalling the execution.
33937576958aSTejun Heo 		 */
33940219a352STejun Heo 		kick_pool(pool);
33957576958aSTejun Heo 
3396a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
339713b1d625SLai Jiangshan 
3398a2d812a2STejun Heo 		worker_detach_from_pool(rescuer);
339913b1d625SLai Jiangshan 
3400a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
34011da177e4SLinus Torvalds 	}
34021da177e4SLinus Torvalds 
3403a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq_mayday_lock);
3404493a1724STejun Heo 
34054d595b86SLai Jiangshan 	if (should_stop) {
34064d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
3407197f6accSTejun Heo 		set_pf_worker(false);
34084d595b86SLai Jiangshan 		return 0;
34094d595b86SLai Jiangshan 	}
34104d595b86SLai Jiangshan 
3411111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
3412111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
3413e22bee78STejun Heo 	schedule();
3414e22bee78STejun Heo 	goto repeat;
34151da177e4SLinus Torvalds }
34161da177e4SLinus Torvalds 
34174cb1ef64STejun Heo static void bh_worker(struct worker *worker)
34184cb1ef64STejun Heo {
34194cb1ef64STejun Heo 	struct worker_pool *pool = worker->pool;
34204cb1ef64STejun Heo 	int nr_restarts = BH_WORKER_RESTARTS;
34214cb1ef64STejun Heo 	unsigned long end = jiffies + BH_WORKER_JIFFIES;
34224cb1ef64STejun Heo 
34234cb1ef64STejun Heo 	raw_spin_lock_irq(&pool->lock);
34244cb1ef64STejun Heo 	worker_leave_idle(worker);
34254cb1ef64STejun Heo 
34264cb1ef64STejun Heo 	/*
34274cb1ef64STejun Heo 	 * This function follows the structure of worker_thread(). See there for
34284cb1ef64STejun Heo 	 * explanations on each step.
34294cb1ef64STejun Heo 	 */
34304cb1ef64STejun Heo 	if (!need_more_worker(pool))
34314cb1ef64STejun Heo 		goto done;
34324cb1ef64STejun Heo 
34334cb1ef64STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
34344cb1ef64STejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
34354cb1ef64STejun Heo 
34364cb1ef64STejun Heo 	do {
34374cb1ef64STejun Heo 		struct work_struct *work =
34384cb1ef64STejun Heo 			list_first_entry(&pool->worklist,
34394cb1ef64STejun Heo 					 struct work_struct, entry);
34404cb1ef64STejun Heo 
34414cb1ef64STejun Heo 		if (assign_work(work, worker, NULL))
34424cb1ef64STejun Heo 			process_scheduled_works(worker);
34434cb1ef64STejun Heo 	} while (keep_working(pool) &&
34444cb1ef64STejun Heo 		 --nr_restarts && time_before(jiffies, end));
34454cb1ef64STejun Heo 
34464cb1ef64STejun Heo 	worker_set_flags(worker, WORKER_PREP);
34474cb1ef64STejun Heo done:
34484cb1ef64STejun Heo 	worker_enter_idle(worker);
34494cb1ef64STejun Heo 	kick_pool(pool);
34504cb1ef64STejun Heo 	raw_spin_unlock_irq(&pool->lock);
34514cb1ef64STejun Heo }
34524cb1ef64STejun Heo 
34534cb1ef64STejun Heo /*
34544cb1ef64STejun Heo  * TODO: Convert all tasklet users to workqueue and use softirq directly.
34554cb1ef64STejun Heo  *
34564cb1ef64STejun Heo  * This is currently called from tasklet[_hi]action() and thus is also called
34574cb1ef64STejun Heo  * whenever there are tasklets to run. Let's do an early exit if there's nothing
34584cb1ef64STejun Heo  * queued. Once conversion from tasklet is complete, the need_more_worker() test
34594cb1ef64STejun Heo  * can be dropped.
34604cb1ef64STejun Heo  *
34614cb1ef64STejun Heo  * After full conversion, we'll add worker->softirq_action, directly use the
34624cb1ef64STejun Heo  * softirq action and obtain the worker pointer from the softirq_action pointer.
34634cb1ef64STejun Heo  */
34644cb1ef64STejun Heo void workqueue_softirq_action(bool highpri)
34654cb1ef64STejun Heo {
34664cb1ef64STejun Heo 	struct worker_pool *pool =
34674cb1ef64STejun Heo 		&per_cpu(bh_worker_pools, smp_processor_id())[highpri];
34684cb1ef64STejun Heo 	if (need_more_worker(pool))
34694cb1ef64STejun Heo 		bh_worker(list_first_entry(&pool->workers, struct worker, node));
34704cb1ef64STejun Heo }
34714cb1ef64STejun Heo 
3472fca839c0STejun Heo /**
3473fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
3474fca839c0STejun Heo  * @target_wq: workqueue being flushed
3475fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
3476fca839c0STejun Heo  *
3477fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
3478fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
3479fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
3480fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
3481fca839c0STejun Heo  * a deadlock.
3482fca839c0STejun Heo  */
3483fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
3484fca839c0STejun Heo 				   struct work_struct *target_work)
3485fca839c0STejun Heo {
3486fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
3487fca839c0STejun Heo 	struct worker *worker;
3488fca839c0STejun Heo 
3489fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
3490fca839c0STejun Heo 		return;
3491fca839c0STejun Heo 
3492fca839c0STejun Heo 	worker = current_wq_worker();
3493fca839c0STejun Heo 
3494fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
3495d75f773cSSakari Ailus 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
3496fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
349723d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
349823d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
3499d75f773cSSakari Ailus 		  "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
3500fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
3501fca839c0STejun Heo 		  target_wq->name, target_func);
3502fca839c0STejun Heo }
3503fca839c0STejun Heo 
3504fc2e4d70SOleg Nesterov struct wq_barrier {
3505fc2e4d70SOleg Nesterov 	struct work_struct	work;
3506fc2e4d70SOleg Nesterov 	struct completion	done;
35072607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
3508fc2e4d70SOleg Nesterov };
3509fc2e4d70SOleg Nesterov 
3510fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
3511fc2e4d70SOleg Nesterov {
3512fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
3513fc2e4d70SOleg Nesterov 	complete(&barr->done);
3514fc2e4d70SOleg Nesterov }
3515fc2e4d70SOleg Nesterov 
35164690c4abSTejun Heo /**
35174690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
3518112202d9STejun Heo  * @pwq: pwq to insert barrier into
35194690c4abSTejun Heo  * @barr: wq_barrier to insert
3520affee4b2STejun Heo  * @target: target work to attach @barr to
3521affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
35224690c4abSTejun Heo  *
3523affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
3524affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
3525affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
3526affee4b2STejun Heo  * cpu.
3527affee4b2STejun Heo  *
3528affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
3529affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
3530affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
3531affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
3532affee4b2STejun Heo  * after a work with LINKED flag set.
3533affee4b2STejun Heo  *
3534affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
3535112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
35364690c4abSTejun Heo  *
35374690c4abSTejun Heo  * CONTEXT:
3538a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
35394690c4abSTejun Heo  */
3540112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
3541affee4b2STejun Heo 			      struct wq_barrier *barr,
3542affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
3543fc2e4d70SOleg Nesterov {
35444cb1ef64STejun Heo 	static __maybe_unused struct lock_class_key bh_key, thr_key;
3545d812796eSLai Jiangshan 	unsigned int work_flags = 0;
3546d812796eSLai Jiangshan 	unsigned int work_color;
3547affee4b2STejun Heo 	struct list_head *head;
3548affee4b2STejun Heo 
3549dc186ad7SThomas Gleixner 	/*
3550d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
3551dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
3552dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
3553dc186ad7SThomas Gleixner 	 * might deadlock.
35544cb1ef64STejun Heo 	 *
35554cb1ef64STejun Heo 	 * BH and threaded workqueues need separate lockdep keys to avoid
35564cb1ef64STejun Heo 	 * spuriously triggering "inconsistent {SOFTIRQ-ON-W} -> {IN-SOFTIRQ-W}
35574cb1ef64STejun Heo 	 * usage".
3558dc186ad7SThomas Gleixner 	 */
35594cb1ef64STejun Heo 	INIT_WORK_ONSTACK_KEY(&barr->work, wq_barrier_func,
35604cb1ef64STejun Heo 			      (pwq->wq->flags & WQ_BH) ? &bh_key : &thr_key);
356122df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
356252fa5bc5SBoqun Feng 
3563fd1a5b04SByungchul Park 	init_completion_map(&barr->done, &target->lockdep_map);
3564fd1a5b04SByungchul Park 
35652607d7a6STejun Heo 	barr->task = current;
356683c22520SOleg Nesterov 
35675797b1c1STejun Heo 	/* The barrier work item does not participate in nr_active. */
3568018f3a13SLai Jiangshan 	work_flags |= WORK_STRUCT_INACTIVE;
3569018f3a13SLai Jiangshan 
3570affee4b2STejun Heo 	/*
3571affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
3572affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
3573affee4b2STejun Heo 	 */
3574d812796eSLai Jiangshan 	if (worker) {
3575affee4b2STejun Heo 		head = worker->scheduled.next;
3576d812796eSLai Jiangshan 		work_color = worker->current_color;
3577d812796eSLai Jiangshan 	} else {
3578affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
3579affee4b2STejun Heo 
3580affee4b2STejun Heo 		head = target->entry.next;
3581affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
3582d21cece0SLai Jiangshan 		work_flags |= *bits & WORK_STRUCT_LINKED;
3583d812796eSLai Jiangshan 		work_color = get_work_color(*bits);
3584affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
3585affee4b2STejun Heo 	}
3586affee4b2STejun Heo 
3587d812796eSLai Jiangshan 	pwq->nr_in_flight[work_color]++;
3588d812796eSLai Jiangshan 	work_flags |= work_color_to_flags(work_color);
3589d812796eSLai Jiangshan 
3590d21cece0SLai Jiangshan 	insert_work(pwq, &barr->work, head, work_flags);
3591fc2e4d70SOleg Nesterov }
3592fc2e4d70SOleg Nesterov 
359373f53c4aSTejun Heo /**
3594112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
359573f53c4aSTejun Heo  * @wq: workqueue being flushed
359673f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
359773f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
359873f53c4aSTejun Heo  *
3599112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
360073f53c4aSTejun Heo  *
3601112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
3602112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
3603112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
3604112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
3605112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
360673f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
360773f53c4aSTejun Heo  *
360873f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
360973f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
361073f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
361173f53c4aSTejun Heo  * is returned.
361273f53c4aSTejun Heo  *
3613112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
361473f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
361573f53c4aSTejun Heo  * advanced to @work_color.
361673f53c4aSTejun Heo  *
361773f53c4aSTejun Heo  * CONTEXT:
36183c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
361973f53c4aSTejun Heo  *
3620d185af30SYacine Belkadi  * Return:
362173f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
362273f53c4aSTejun Heo  * otherwise.
362373f53c4aSTejun Heo  */
3624112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
362573f53c4aSTejun Heo 				      int flush_color, int work_color)
36261da177e4SLinus Torvalds {
362773f53c4aSTejun Heo 	bool wait = false;
362849e3cf44STejun Heo 	struct pool_workqueue *pwq;
36291da177e4SLinus Torvalds 
363073f53c4aSTejun Heo 	if (flush_color >= 0) {
36316183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
3632112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
3633dc186ad7SThomas Gleixner 	}
363414441960SOleg Nesterov 
363549e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3636112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
36371da177e4SLinus Torvalds 
3638a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
363973f53c4aSTejun Heo 
364073f53c4aSTejun Heo 		if (flush_color >= 0) {
36416183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
364273f53c4aSTejun Heo 
3643112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
3644112202d9STejun Heo 				pwq->flush_color = flush_color;
3645112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
364673f53c4aSTejun Heo 				wait = true;
36471da177e4SLinus Torvalds 			}
364873f53c4aSTejun Heo 		}
364973f53c4aSTejun Heo 
365073f53c4aSTejun Heo 		if (work_color >= 0) {
36516183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
3652112202d9STejun Heo 			pwq->work_color = work_color;
365373f53c4aSTejun Heo 		}
365473f53c4aSTejun Heo 
3655a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
36561da177e4SLinus Torvalds 	}
36571da177e4SLinus Torvalds 
3658112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
365973f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
366073f53c4aSTejun Heo 
366173f53c4aSTejun Heo 	return wait;
366283c22520SOleg Nesterov }
36631da177e4SLinus Torvalds 
3664c35aea39STejun Heo static void touch_wq_lockdep_map(struct workqueue_struct *wq)
3665c35aea39STejun Heo {
36664cb1ef64STejun Heo #ifdef CONFIG_LOCKDEP
36674cb1ef64STejun Heo 	if (wq->flags & WQ_BH)
36684cb1ef64STejun Heo 		local_bh_disable();
36694cb1ef64STejun Heo 
3670c35aea39STejun Heo 	lock_map_acquire(&wq->lockdep_map);
3671c35aea39STejun Heo 	lock_map_release(&wq->lockdep_map);
36724cb1ef64STejun Heo 
36734cb1ef64STejun Heo 	if (wq->flags & WQ_BH)
36744cb1ef64STejun Heo 		local_bh_enable();
36754cb1ef64STejun Heo #endif
3676c35aea39STejun Heo }
3677c35aea39STejun Heo 
3678c35aea39STejun Heo static void touch_work_lockdep_map(struct work_struct *work,
3679c35aea39STejun Heo 				   struct workqueue_struct *wq)
3680c35aea39STejun Heo {
36814cb1ef64STejun Heo #ifdef CONFIG_LOCKDEP
36824cb1ef64STejun Heo 	if (wq->flags & WQ_BH)
36834cb1ef64STejun Heo 		local_bh_disable();
36844cb1ef64STejun Heo 
3685c35aea39STejun Heo 	lock_map_acquire(&work->lockdep_map);
3686c35aea39STejun Heo 	lock_map_release(&work->lockdep_map);
36874cb1ef64STejun Heo 
36884cb1ef64STejun Heo 	if (wq->flags & WQ_BH)
36894cb1ef64STejun Heo 		local_bh_enable();
36904cb1ef64STejun Heo #endif
3691c35aea39STejun Heo }
3692c35aea39STejun Heo 
36930fcb78c2SRolf Eike Beer /**
3694c4f135d6STetsuo Handa  * __flush_workqueue - ensure that any scheduled work has run to completion.
36950fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
36961da177e4SLinus Torvalds  *
3697c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
3698c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
36991da177e4SLinus Torvalds  */
3700c4f135d6STetsuo Handa void __flush_workqueue(struct workqueue_struct *wq)
37011da177e4SLinus Torvalds {
370273f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
370373f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
370473f53c4aSTejun Heo 		.flush_color = -1,
3705fd1a5b04SByungchul Park 		.done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
370673f53c4aSTejun Heo 	};
370773f53c4aSTejun Heo 	int next_color;
3708b1f4ec17SOleg Nesterov 
37093347fa09STejun Heo 	if (WARN_ON(!wq_online))
37103347fa09STejun Heo 		return;
37113347fa09STejun Heo 
3712c35aea39STejun Heo 	touch_wq_lockdep_map(wq);
371387915adcSJohannes Berg 
37143c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
371573f53c4aSTejun Heo 
371673f53c4aSTejun Heo 	/*
371773f53c4aSTejun Heo 	 * Start-to-wait phase
371873f53c4aSTejun Heo 	 */
371973f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
372073f53c4aSTejun Heo 
372173f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
372273f53c4aSTejun Heo 		/*
372373f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
372473f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
372573f53c4aSTejun Heo 		 * by one.
372673f53c4aSTejun Heo 		 */
37276183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
372873f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
372973f53c4aSTejun Heo 		wq->work_color = next_color;
373073f53c4aSTejun Heo 
373173f53c4aSTejun Heo 		if (!wq->first_flusher) {
373273f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
37336183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
373473f53c4aSTejun Heo 
373573f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
373673f53c4aSTejun Heo 
3737112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
373873f53c4aSTejun Heo 						       wq->work_color)) {
373973f53c4aSTejun Heo 				/* nothing to flush, done */
374073f53c4aSTejun Heo 				wq->flush_color = next_color;
374173f53c4aSTejun Heo 				wq->first_flusher = NULL;
374273f53c4aSTejun Heo 				goto out_unlock;
374373f53c4aSTejun Heo 			}
374473f53c4aSTejun Heo 		} else {
374573f53c4aSTejun Heo 			/* wait in queue */
37466183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
374773f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
3748112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
374973f53c4aSTejun Heo 		}
375073f53c4aSTejun Heo 	} else {
375173f53c4aSTejun Heo 		/*
375273f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
375373f53c4aSTejun Heo 		 * The next flush completion will assign us
375473f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
375573f53c4aSTejun Heo 		 */
375673f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
375773f53c4aSTejun Heo 	}
375873f53c4aSTejun Heo 
3759fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
3760fca839c0STejun Heo 
37613c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
376273f53c4aSTejun Heo 
376373f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
376473f53c4aSTejun Heo 
376573f53c4aSTejun Heo 	/*
376673f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
376773f53c4aSTejun Heo 	 *
376873f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
376973f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
377073f53c4aSTejun Heo 	 */
377100d5d15bSChris Wilson 	if (READ_ONCE(wq->first_flusher) != &this_flusher)
377273f53c4aSTejun Heo 		return;
377373f53c4aSTejun Heo 
37743c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
377573f53c4aSTejun Heo 
37764ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
37774ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
37784ce48b37STejun Heo 		goto out_unlock;
37794ce48b37STejun Heo 
378000d5d15bSChris Wilson 	WRITE_ONCE(wq->first_flusher, NULL);
378173f53c4aSTejun Heo 
37826183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
37836183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
378473f53c4aSTejun Heo 
378573f53c4aSTejun Heo 	while (true) {
378673f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
378773f53c4aSTejun Heo 
378873f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
378973f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
379073f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
379173f53c4aSTejun Heo 				break;
379273f53c4aSTejun Heo 			list_del_init(&next->list);
379373f53c4aSTejun Heo 			complete(&next->done);
379473f53c4aSTejun Heo 		}
379573f53c4aSTejun Heo 
37966183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
379773f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
379873f53c4aSTejun Heo 
379973f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
380073f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
380173f53c4aSTejun Heo 
380273f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
380373f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
380473f53c4aSTejun Heo 			/*
380573f53c4aSTejun Heo 			 * Assign the same color to all overflowed
380673f53c4aSTejun Heo 			 * flushers, advance work_color and append to
380773f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
380873f53c4aSTejun Heo 			 * phase for these overflowed flushers.
380973f53c4aSTejun Heo 			 */
381073f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
381173f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
381273f53c4aSTejun Heo 
381373f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
381473f53c4aSTejun Heo 
381573f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
381673f53c4aSTejun Heo 					      &wq->flusher_queue);
3817112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
381873f53c4aSTejun Heo 		}
381973f53c4aSTejun Heo 
382073f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
38216183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
382273f53c4aSTejun Heo 			break;
382373f53c4aSTejun Heo 		}
382473f53c4aSTejun Heo 
382573f53c4aSTejun Heo 		/*
382673f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
3827112202d9STejun Heo 		 * the new first flusher and arm pwqs.
382873f53c4aSTejun Heo 		 */
38296183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
38306183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
383173f53c4aSTejun Heo 
383273f53c4aSTejun Heo 		list_del_init(&next->list);
383373f53c4aSTejun Heo 		wq->first_flusher = next;
383473f53c4aSTejun Heo 
3835112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
383673f53c4aSTejun Heo 			break;
383773f53c4aSTejun Heo 
383873f53c4aSTejun Heo 		/*
383973f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
384073f53c4aSTejun Heo 		 * flusher and repeat cascading.
384173f53c4aSTejun Heo 		 */
384273f53c4aSTejun Heo 		wq->first_flusher = NULL;
384373f53c4aSTejun Heo 	}
384473f53c4aSTejun Heo 
384573f53c4aSTejun Heo out_unlock:
38463c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
38471da177e4SLinus Torvalds }
3848c4f135d6STetsuo Handa EXPORT_SYMBOL(__flush_workqueue);
38491da177e4SLinus Torvalds 
38509c5a2ba7STejun Heo /**
38519c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
38529c5a2ba7STejun Heo  * @wq: workqueue to drain
38539c5a2ba7STejun Heo  *
38549c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
38559c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
38569c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
3857b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
38589c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
38599c5a2ba7STejun Heo  * takes too long.
38609c5a2ba7STejun Heo  */
38619c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
38629c5a2ba7STejun Heo {
38639c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
386449e3cf44STejun Heo 	struct pool_workqueue *pwq;
38659c5a2ba7STejun Heo 
38669c5a2ba7STejun Heo 	/*
38679c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
38689c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
3869618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
38709c5a2ba7STejun Heo 	 */
387187fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
38729c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
3873618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
387487fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
38759c5a2ba7STejun Heo reflush:
3876c4f135d6STetsuo Handa 	__flush_workqueue(wq);
38779c5a2ba7STejun Heo 
3878b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
387976af4d93STejun Heo 
388049e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3881fa2563e4SThomas Tuttle 		bool drained;
38829c5a2ba7STejun Heo 
3883a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
3884afa87ce8STejun Heo 		drained = pwq_is_empty(pwq);
3885a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
3886fa2563e4SThomas Tuttle 
3887fa2563e4SThomas Tuttle 		if (drained)
38889c5a2ba7STejun Heo 			continue;
38899c5a2ba7STejun Heo 
38909c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
38919c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
3892e9ad2eb3SStephen Zhang 			pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3893e9ad2eb3SStephen Zhang 				wq->name, __func__, flush_cnt);
389476af4d93STejun Heo 
3895b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
38969c5a2ba7STejun Heo 		goto reflush;
38979c5a2ba7STejun Heo 	}
38989c5a2ba7STejun Heo 
38999c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
3900618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
390187fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
39029c5a2ba7STejun Heo }
39039c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
39049c5a2ba7STejun Heo 
3905d6e89786SJohannes Berg static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3906d6e89786SJohannes Berg 			     bool from_cancel)
3907baf59022STejun Heo {
3908baf59022STejun Heo 	struct worker *worker = NULL;
3909c9e7cf27STejun Heo 	struct worker_pool *pool;
3910112202d9STejun Heo 	struct pool_workqueue *pwq;
3911c35aea39STejun Heo 	struct workqueue_struct *wq;
3912baf59022STejun Heo 
3913baf59022STejun Heo 	might_sleep();
3914baf59022STejun Heo 
391524acfb71SThomas Gleixner 	rcu_read_lock();
3916fa1b54e6STejun Heo 	pool = get_work_pool(work);
3917fa1b54e6STejun Heo 	if (!pool) {
391824acfb71SThomas Gleixner 		rcu_read_unlock();
3919fa1b54e6STejun Heo 		return false;
3920fa1b54e6STejun Heo 	}
3921fa1b54e6STejun Heo 
3922a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
39230b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
3924112202d9STejun Heo 	pwq = get_work_pwq(work);
3925112202d9STejun Heo 	if (pwq) {
3926112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
3927baf59022STejun Heo 			goto already_gone;
3928606a5020STejun Heo 	} else {
3929c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
3930baf59022STejun Heo 		if (!worker)
3931baf59022STejun Heo 			goto already_gone;
3932112202d9STejun Heo 		pwq = worker->current_pwq;
3933606a5020STejun Heo 	}
3934baf59022STejun Heo 
3935c35aea39STejun Heo 	wq = pwq->wq;
3936c35aea39STejun Heo 	check_flush_dependency(wq, work);
3937fca839c0STejun Heo 
3938112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
3939a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
3940baf59022STejun Heo 
3941c35aea39STejun Heo 	touch_work_lockdep_map(work, wq);
3942c35aea39STejun Heo 
3943e159489bSTejun Heo 	/*
3944a1d14934SPeter Zijlstra 	 * Force a lock recursion deadlock when using flush_work() inside a
3945a1d14934SPeter Zijlstra 	 * single-threaded or rescuer equipped workqueue.
3946a1d14934SPeter Zijlstra 	 *
3947a1d14934SPeter Zijlstra 	 * For single threaded workqueues the deadlock happens when the work
3948a1d14934SPeter Zijlstra 	 * is after the work issuing the flush_work(). For rescuer equipped
3949a1d14934SPeter Zijlstra 	 * workqueues the deadlock happens when the rescuer stalls, blocking
3950a1d14934SPeter Zijlstra 	 * forward progress.
3951e159489bSTejun Heo 	 */
3952c35aea39STejun Heo 	if (!from_cancel && (wq->saved_max_active == 1 || wq->rescuer))
3953c35aea39STejun Heo 		touch_wq_lockdep_map(wq);
3954c35aea39STejun Heo 
395524acfb71SThomas Gleixner 	rcu_read_unlock();
3956baf59022STejun Heo 	return true;
3957baf59022STejun Heo already_gone:
3958a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
395924acfb71SThomas Gleixner 	rcu_read_unlock();
3960baf59022STejun Heo 	return false;
3961baf59022STejun Heo }
3962baf59022STejun Heo 
3963d6e89786SJohannes Berg static bool __flush_work(struct work_struct *work, bool from_cancel)
3964d6e89786SJohannes Berg {
3965d6e89786SJohannes Berg 	struct wq_barrier barr;
3966d6e89786SJohannes Berg 
3967d6e89786SJohannes Berg 	if (WARN_ON(!wq_online))
3968d6e89786SJohannes Berg 		return false;
3969d6e89786SJohannes Berg 
39704d43d395STetsuo Handa 	if (WARN_ON(!work->func))
39714d43d395STetsuo Handa 		return false;
39724d43d395STetsuo Handa 
3973d6e89786SJohannes Berg 	if (start_flush_work(work, &barr, from_cancel)) {
3974d6e89786SJohannes Berg 		wait_for_completion(&barr.done);
3975d6e89786SJohannes Berg 		destroy_work_on_stack(&barr.work);
3976d6e89786SJohannes Berg 		return true;
3977d6e89786SJohannes Berg 	} else {
3978d6e89786SJohannes Berg 		return false;
3979d6e89786SJohannes Berg 	}
3980d6e89786SJohannes Berg }
3981d6e89786SJohannes Berg 
3982db700897SOleg Nesterov /**
3983401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
3984401a8d04STejun Heo  * @work: the work to flush
3985db700897SOleg Nesterov  *
3986606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
3987606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
3988401a8d04STejun Heo  *
3989d185af30SYacine Belkadi  * Return:
3990401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
3991401a8d04STejun Heo  * %false if it was already idle.
3992db700897SOleg Nesterov  */
3993401a8d04STejun Heo bool flush_work(struct work_struct *work)
3994db700897SOleg Nesterov {
3995d6e89786SJohannes Berg 	return __flush_work(work, false);
3996606a5020STejun Heo }
3997db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
3998db700897SOleg Nesterov 
39998603e1b3STejun Heo struct cwt_wait {
4000ac6424b9SIngo Molnar 	wait_queue_entry_t		wait;
40018603e1b3STejun Heo 	struct work_struct	*work;
40028603e1b3STejun Heo };
40038603e1b3STejun Heo 
4004ac6424b9SIngo Molnar static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
40058603e1b3STejun Heo {
40068603e1b3STejun Heo 	struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
40078603e1b3STejun Heo 
40088603e1b3STejun Heo 	if (cwait->work != key)
40098603e1b3STejun Heo 		return 0;
40108603e1b3STejun Heo 	return autoremove_wake_function(wait, mode, sync, key);
40118603e1b3STejun Heo }
40128603e1b3STejun Heo 
401336e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
4014401a8d04STejun Heo {
40158603e1b3STejun Heo 	static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
4016bbb68dfaSTejun Heo 	unsigned long flags;
40171f1f642eSOleg Nesterov 	int ret;
40181f1f642eSOleg Nesterov 
40191f1f642eSOleg Nesterov 	do {
4020bbb68dfaSTejun Heo 		ret = try_to_grab_pending(work, is_dwork, &flags);
4021bbb68dfaSTejun Heo 		/*
40228603e1b3STejun Heo 		 * If someone else is already canceling, wait for it to
40238603e1b3STejun Heo 		 * finish.  flush_work() doesn't work for PREEMPT_NONE
40248603e1b3STejun Heo 		 * because we may get scheduled between @work's completion
40258603e1b3STejun Heo 		 * and the other canceling task resuming and clearing
40268603e1b3STejun Heo 		 * CANCELING - flush_work() will return false immediately
40278603e1b3STejun Heo 		 * as @work is no longer busy, try_to_grab_pending() will
40288603e1b3STejun Heo 		 * return -ENOENT as @work is still being canceled and the
40298603e1b3STejun Heo 		 * other canceling task won't be able to clear CANCELING as
40308603e1b3STejun Heo 		 * we're hogging the CPU.
40318603e1b3STejun Heo 		 *
40328603e1b3STejun Heo 		 * Let's wait for completion using a waitqueue.  As this
40338603e1b3STejun Heo 		 * may lead to the thundering herd problem, use a custom
40348603e1b3STejun Heo 		 * wake function which matches @work along with exclusive
40358603e1b3STejun Heo 		 * wait and wakeup.
4036bbb68dfaSTejun Heo 		 */
40378603e1b3STejun Heo 		if (unlikely(ret == -ENOENT)) {
40388603e1b3STejun Heo 			struct cwt_wait cwait;
40398603e1b3STejun Heo 
40408603e1b3STejun Heo 			init_wait(&cwait.wait);
40418603e1b3STejun Heo 			cwait.wait.func = cwt_wakefn;
40428603e1b3STejun Heo 			cwait.work = work;
40438603e1b3STejun Heo 
40448603e1b3STejun Heo 			prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
40458603e1b3STejun Heo 						  TASK_UNINTERRUPTIBLE);
40468603e1b3STejun Heo 			if (work_is_canceling(work))
40478603e1b3STejun Heo 				schedule();
40488603e1b3STejun Heo 			finish_wait(&cancel_waitq, &cwait.wait);
40498603e1b3STejun Heo 		}
40501f1f642eSOleg Nesterov 	} while (unlikely(ret < 0));
40511f1f642eSOleg Nesterov 
4052bbb68dfaSTejun Heo 	/* tell other tasks trying to grab @work to back off */
4053bbb68dfaSTejun Heo 	mark_work_canceling(work);
4054bbb68dfaSTejun Heo 	local_irq_restore(flags);
4055bbb68dfaSTejun Heo 
40563347fa09STejun Heo 	/*
40573347fa09STejun Heo 	 * This allows canceling during early boot.  We know that @work
40583347fa09STejun Heo 	 * isn't executing.
40593347fa09STejun Heo 	 */
40603347fa09STejun Heo 	if (wq_online)
4061d6e89786SJohannes Berg 		__flush_work(work, true);
40623347fa09STejun Heo 
40637a22ad75STejun Heo 	clear_work_data(work);
40648603e1b3STejun Heo 
40658603e1b3STejun Heo 	/*
40668603e1b3STejun Heo 	 * Paired with prepare_to_wait() above so that either
40678603e1b3STejun Heo 	 * waitqueue_active() is visible here or !work_is_canceling() is
40688603e1b3STejun Heo 	 * visible there.
40698603e1b3STejun Heo 	 */
40708603e1b3STejun Heo 	smp_mb();
40718603e1b3STejun Heo 	if (waitqueue_active(&cancel_waitq))
40728603e1b3STejun Heo 		__wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
40738603e1b3STejun Heo 
40741f1f642eSOleg Nesterov 	return ret;
40751f1f642eSOleg Nesterov }
40761f1f642eSOleg Nesterov 
40776e84d644SOleg Nesterov /**
4078401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
4079401a8d04STejun Heo  * @work: the work to cancel
40806e84d644SOleg Nesterov  *
4081401a8d04STejun Heo  * Cancel @work and wait for its execution to finish.  This function
4082401a8d04STejun Heo  * can be used even if the work re-queues itself or migrates to
4083401a8d04STejun Heo  * another workqueue.  On return from this function, @work is
4084401a8d04STejun Heo  * guaranteed to be not pending or executing on any CPU.
40851f1f642eSOleg Nesterov  *
4086401a8d04STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for
4087401a8d04STejun Heo  * delayed_work's.  Use cancel_delayed_work_sync() instead.
40886e84d644SOleg Nesterov  *
4089401a8d04STejun Heo  * The caller must ensure that the workqueue on which @work was last
40906e84d644SOleg Nesterov  * queued can't be destroyed before this function returns.
4091401a8d04STejun Heo  *
4092d185af30SYacine Belkadi  * Return:
4093401a8d04STejun Heo  * %true if @work was pending, %false otherwise.
40946e84d644SOleg Nesterov  */
4095401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
40966e84d644SOleg Nesterov {
409736e227d2STejun Heo 	return __cancel_work_timer(work, false);
4098b89deed3SOleg Nesterov }
409928e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
4100b89deed3SOleg Nesterov 
41016e84d644SOleg Nesterov /**
4102401a8d04STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
4103401a8d04STejun Heo  * @dwork: the delayed work to flush
41046e84d644SOleg Nesterov  *
4105401a8d04STejun Heo  * Delayed timer is cancelled and the pending work is queued for
4106401a8d04STejun Heo  * immediate execution.  Like flush_work(), this function only
4107401a8d04STejun Heo  * considers the last queueing instance of @dwork.
41081f1f642eSOleg Nesterov  *
4109d185af30SYacine Belkadi  * Return:
4110401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
4111401a8d04STejun Heo  * %false if it was already idle.
41126e84d644SOleg Nesterov  */
4113401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
4114401a8d04STejun Heo {
41158930cabaSTejun Heo 	local_irq_disable();
4116401a8d04STejun Heo 	if (del_timer_sync(&dwork->timer))
411760c057bcSLai Jiangshan 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
41188930cabaSTejun Heo 	local_irq_enable();
4119401a8d04STejun Heo 	return flush_work(&dwork->work);
4120401a8d04STejun Heo }
4121401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
4122401a8d04STejun Heo 
412305f0fe6bSTejun Heo /**
412405f0fe6bSTejun Heo  * flush_rcu_work - wait for a rwork to finish executing the last queueing
412505f0fe6bSTejun Heo  * @rwork: the rcu work to flush
412605f0fe6bSTejun Heo  *
412705f0fe6bSTejun Heo  * Return:
412805f0fe6bSTejun Heo  * %true if flush_rcu_work() waited for the work to finish execution,
412905f0fe6bSTejun Heo  * %false if it was already idle.
413005f0fe6bSTejun Heo  */
413105f0fe6bSTejun Heo bool flush_rcu_work(struct rcu_work *rwork)
413205f0fe6bSTejun Heo {
413305f0fe6bSTejun Heo 	if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
413405f0fe6bSTejun Heo 		rcu_barrier();
413505f0fe6bSTejun Heo 		flush_work(&rwork->work);
413605f0fe6bSTejun Heo 		return true;
413705f0fe6bSTejun Heo 	} else {
413805f0fe6bSTejun Heo 		return flush_work(&rwork->work);
413905f0fe6bSTejun Heo 	}
414005f0fe6bSTejun Heo }
414105f0fe6bSTejun Heo EXPORT_SYMBOL(flush_rcu_work);
414205f0fe6bSTejun Heo 
4143f72b8792SJens Axboe static bool __cancel_work(struct work_struct *work, bool is_dwork)
4144f72b8792SJens Axboe {
4145f72b8792SJens Axboe 	unsigned long flags;
4146f72b8792SJens Axboe 	int ret;
4147f72b8792SJens Axboe 
4148f72b8792SJens Axboe 	do {
4149f72b8792SJens Axboe 		ret = try_to_grab_pending(work, is_dwork, &flags);
4150f72b8792SJens Axboe 	} while (unlikely(ret == -EAGAIN));
4151f72b8792SJens Axboe 
4152f72b8792SJens Axboe 	if (unlikely(ret < 0))
4153f72b8792SJens Axboe 		return false;
4154f72b8792SJens Axboe 
4155f72b8792SJens Axboe 	set_work_pool_and_clear_pending(work, get_work_pool_id(work));
4156f72b8792SJens Axboe 	local_irq_restore(flags);
4157f72b8792SJens Axboe 	return ret;
4158f72b8792SJens Axboe }
4159f72b8792SJens Axboe 
416073b4b532SAndrey Grodzovsky /*
416173b4b532SAndrey Grodzovsky  * See cancel_delayed_work()
416273b4b532SAndrey Grodzovsky  */
416373b4b532SAndrey Grodzovsky bool cancel_work(struct work_struct *work)
416473b4b532SAndrey Grodzovsky {
416573b4b532SAndrey Grodzovsky 	return __cancel_work(work, false);
416673b4b532SAndrey Grodzovsky }
416773b4b532SAndrey Grodzovsky EXPORT_SYMBOL(cancel_work);
416873b4b532SAndrey Grodzovsky 
4169401a8d04STejun Heo /**
417057b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
417157b30ae7STejun Heo  * @dwork: delayed_work to cancel
417209383498STejun Heo  *
4173d185af30SYacine Belkadi  * Kill off a pending delayed_work.
4174d185af30SYacine Belkadi  *
4175d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
4176d185af30SYacine Belkadi  * pending.
4177d185af30SYacine Belkadi  *
4178d185af30SYacine Belkadi  * Note:
4179d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
4180d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
4181d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
418209383498STejun Heo  *
418357b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
418409383498STejun Heo  */
418557b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
418609383498STejun Heo {
4187f72b8792SJens Axboe 	return __cancel_work(&dwork->work, true);
418809383498STejun Heo }
418957b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
419009383498STejun Heo 
419109383498STejun Heo /**
4192401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
4193401a8d04STejun Heo  * @dwork: the delayed work cancel
4194401a8d04STejun Heo  *
4195401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
4196401a8d04STejun Heo  *
4197d185af30SYacine Belkadi  * Return:
4198401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
4199401a8d04STejun Heo  */
4200401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
42016e84d644SOleg Nesterov {
420236e227d2STejun Heo 	return __cancel_work_timer(&dwork->work, true);
42036e84d644SOleg Nesterov }
4204f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
42051da177e4SLinus Torvalds 
42060fcb78c2SRolf Eike Beer /**
420731ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
4208b6136773SAndrew Morton  * @func: the function to call
4209b6136773SAndrew Morton  *
421031ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
421131ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
4212b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
421331ddd871STejun Heo  *
4214d185af30SYacine Belkadi  * Return:
421531ddd871STejun Heo  * 0 on success, -errno on failure.
4216b6136773SAndrew Morton  */
421765f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
421815316ba8SChristoph Lameter {
421915316ba8SChristoph Lameter 	int cpu;
422038f51568SNamhyung Kim 	struct work_struct __percpu *works;
422115316ba8SChristoph Lameter 
4222b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
4223b6136773SAndrew Morton 	if (!works)
422415316ba8SChristoph Lameter 		return -ENOMEM;
4225b6136773SAndrew Morton 
4226ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
422793981800STejun Heo 
422815316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
42299bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
42309bfb1839SIngo Molnar 
42319bfb1839SIngo Molnar 		INIT_WORK(work, func);
42328de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
423315316ba8SChristoph Lameter 	}
423493981800STejun Heo 
423593981800STejun Heo 	for_each_online_cpu(cpu)
42368616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
423793981800STejun Heo 
4238ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4239b6136773SAndrew Morton 	free_percpu(works);
424015316ba8SChristoph Lameter 	return 0;
424115316ba8SChristoph Lameter }
424215316ba8SChristoph Lameter 
4243eef6a7d5SAlan Stern /**
42441fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
42451fa44ecaSJames Bottomley  * @fn:		the function to execute
42461fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
42471fa44ecaSJames Bottomley  *		be available when the work executes)
42481fa44ecaSJames Bottomley  *
42491fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
42501fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
42511fa44ecaSJames Bottomley  *
4252d185af30SYacine Belkadi  * Return:	0 - function was executed
42531fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
42541fa44ecaSJames Bottomley  */
425565f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
42561fa44ecaSJames Bottomley {
42571fa44ecaSJames Bottomley 	if (!in_interrupt()) {
425865f27f38SDavid Howells 		fn(&ew->work);
42591fa44ecaSJames Bottomley 		return 0;
42601fa44ecaSJames Bottomley 	}
42611fa44ecaSJames Bottomley 
426265f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
42631fa44ecaSJames Bottomley 	schedule_work(&ew->work);
42641fa44ecaSJames Bottomley 
42651fa44ecaSJames Bottomley 	return 1;
42661fa44ecaSJames Bottomley }
42671fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
42681fa44ecaSJames Bottomley 
42697a4e344cSTejun Heo /**
42707a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
42717a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
42727a4e344cSTejun Heo  *
42737a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
42747a4e344cSTejun Heo  */
4275513c98d0SDaniel Jordan void free_workqueue_attrs(struct workqueue_attrs *attrs)
42767a4e344cSTejun Heo {
42777a4e344cSTejun Heo 	if (attrs) {
42787a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
42799546b29eSTejun Heo 		free_cpumask_var(attrs->__pod_cpumask);
42807a4e344cSTejun Heo 		kfree(attrs);
42817a4e344cSTejun Heo 	}
42827a4e344cSTejun Heo }
42837a4e344cSTejun Heo 
42847a4e344cSTejun Heo /**
42857a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
42867a4e344cSTejun Heo  *
42877a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
4288d185af30SYacine Belkadi  * return it.
4289d185af30SYacine Belkadi  *
4290d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
42917a4e344cSTejun Heo  */
4292513c98d0SDaniel Jordan struct workqueue_attrs *alloc_workqueue_attrs(void)
42937a4e344cSTejun Heo {
42947a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
42957a4e344cSTejun Heo 
4296be69d00dSThomas Gleixner 	attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
42977a4e344cSTejun Heo 	if (!attrs)
42987a4e344cSTejun Heo 		goto fail;
4299be69d00dSThomas Gleixner 	if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
43007a4e344cSTejun Heo 		goto fail;
43019546b29eSTejun Heo 	if (!alloc_cpumask_var(&attrs->__pod_cpumask, GFP_KERNEL))
43029546b29eSTejun Heo 		goto fail;
43037a4e344cSTejun Heo 
430413e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
4305523a301eSTejun Heo 	attrs->affn_scope = WQ_AFFN_DFL;
43067a4e344cSTejun Heo 	return attrs;
43077a4e344cSTejun Heo fail:
43087a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
43097a4e344cSTejun Heo 	return NULL;
43107a4e344cSTejun Heo }
43117a4e344cSTejun Heo 
431229c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
431329c91e99STejun Heo 				 const struct workqueue_attrs *from)
431429c91e99STejun Heo {
431529c91e99STejun Heo 	to->nice = from->nice;
431629c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
43179546b29eSTejun Heo 	cpumask_copy(to->__pod_cpumask, from->__pod_cpumask);
43188639ecebSTejun Heo 	to->affn_strict = from->affn_strict;
431984193c07STejun Heo 
43202865a8fbSShaohua Li 	/*
432184193c07STejun Heo 	 * Unlike hash and equality test, copying shouldn't ignore wq-only
432284193c07STejun Heo 	 * fields as copying is used for both pool and wq attrs. Instead,
432384193c07STejun Heo 	 * get_unbound_pool() explicitly clears the fields.
43242865a8fbSShaohua Li 	 */
432584193c07STejun Heo 	to->affn_scope = from->affn_scope;
4326af73f5c9STejun Heo 	to->ordered = from->ordered;
432729c91e99STejun Heo }
432829c91e99STejun Heo 
43295de7a03cSTejun Heo /*
43305de7a03cSTejun Heo  * Some attrs fields are workqueue-only. Clear them for worker_pool's. See the
43315de7a03cSTejun Heo  * comments in 'struct workqueue_attrs' definition.
43325de7a03cSTejun Heo  */
43335de7a03cSTejun Heo static void wqattrs_clear_for_pool(struct workqueue_attrs *attrs)
43345de7a03cSTejun Heo {
433584193c07STejun Heo 	attrs->affn_scope = WQ_AFFN_NR_TYPES;
43365de7a03cSTejun Heo 	attrs->ordered = false;
43375de7a03cSTejun Heo }
43385de7a03cSTejun Heo 
433929c91e99STejun Heo /* hash value of the content of @attr */
434029c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
434129c91e99STejun Heo {
434229c91e99STejun Heo 	u32 hash = 0;
434329c91e99STejun Heo 
434429c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
434513e2e556STejun Heo 	hash = jhash(cpumask_bits(attrs->cpumask),
434613e2e556STejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
43479546b29eSTejun Heo 	hash = jhash(cpumask_bits(attrs->__pod_cpumask),
43489546b29eSTejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
43498639ecebSTejun Heo 	hash = jhash_1word(attrs->affn_strict, hash);
435029c91e99STejun Heo 	return hash;
435129c91e99STejun Heo }
435229c91e99STejun Heo 
435329c91e99STejun Heo /* content equality test */
435429c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
435529c91e99STejun Heo 			  const struct workqueue_attrs *b)
435629c91e99STejun Heo {
435729c91e99STejun Heo 	if (a->nice != b->nice)
435829c91e99STejun Heo 		return false;
435929c91e99STejun Heo 	if (!cpumask_equal(a->cpumask, b->cpumask))
436029c91e99STejun Heo 		return false;
43619546b29eSTejun Heo 	if (!cpumask_equal(a->__pod_cpumask, b->__pod_cpumask))
43629546b29eSTejun Heo 		return false;
43638639ecebSTejun Heo 	if (a->affn_strict != b->affn_strict)
43648639ecebSTejun Heo 		return false;
436529c91e99STejun Heo 	return true;
436629c91e99STejun Heo }
436729c91e99STejun Heo 
43680f36ee24STejun Heo /* Update @attrs with actually available CPUs */
43690f36ee24STejun Heo static void wqattrs_actualize_cpumask(struct workqueue_attrs *attrs,
43700f36ee24STejun Heo 				      const cpumask_t *unbound_cpumask)
43710f36ee24STejun Heo {
43720f36ee24STejun Heo 	/*
43730f36ee24STejun Heo 	 * Calculate the effective CPU mask of @attrs given @unbound_cpumask. If
43740f36ee24STejun Heo 	 * @attrs->cpumask doesn't overlap with @unbound_cpumask, we fallback to
43750f36ee24STejun Heo 	 * @unbound_cpumask.
43760f36ee24STejun Heo 	 */
43770f36ee24STejun Heo 	cpumask_and(attrs->cpumask, attrs->cpumask, unbound_cpumask);
43780f36ee24STejun Heo 	if (unlikely(cpumask_empty(attrs->cpumask)))
43790f36ee24STejun Heo 		cpumask_copy(attrs->cpumask, unbound_cpumask);
43800f36ee24STejun Heo }
43810f36ee24STejun Heo 
438284193c07STejun Heo /* find wq_pod_type to use for @attrs */
438384193c07STejun Heo static const struct wq_pod_type *
438484193c07STejun Heo wqattrs_pod_type(const struct workqueue_attrs *attrs)
438584193c07STejun Heo {
4386523a301eSTejun Heo 	enum wq_affn_scope scope;
4387523a301eSTejun Heo 	struct wq_pod_type *pt;
4388523a301eSTejun Heo 
4389523a301eSTejun Heo 	/* to synchronize access to wq_affn_dfl */
4390523a301eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
4391523a301eSTejun Heo 
4392523a301eSTejun Heo 	if (attrs->affn_scope == WQ_AFFN_DFL)
4393523a301eSTejun Heo 		scope = wq_affn_dfl;
4394523a301eSTejun Heo 	else
4395523a301eSTejun Heo 		scope = attrs->affn_scope;
4396523a301eSTejun Heo 
4397523a301eSTejun Heo 	pt = &wq_pod_types[scope];
439884193c07STejun Heo 
439984193c07STejun Heo 	if (!WARN_ON_ONCE(attrs->affn_scope == WQ_AFFN_NR_TYPES) &&
440084193c07STejun Heo 	    likely(pt->nr_pods))
440184193c07STejun Heo 		return pt;
440284193c07STejun Heo 
440384193c07STejun Heo 	/*
440484193c07STejun Heo 	 * Before workqueue_init_topology(), only SYSTEM is available which is
440584193c07STejun Heo 	 * initialized in workqueue_init_early().
440684193c07STejun Heo 	 */
440784193c07STejun Heo 	pt = &wq_pod_types[WQ_AFFN_SYSTEM];
440884193c07STejun Heo 	BUG_ON(!pt->nr_pods);
440984193c07STejun Heo 	return pt;
441084193c07STejun Heo }
441184193c07STejun Heo 
44127a4e344cSTejun Heo /**
44137a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
44147a4e344cSTejun Heo  * @pool: worker_pool to initialize
44157a4e344cSTejun Heo  *
4416402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
4417d185af30SYacine Belkadi  *
4418d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
441929c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
442029c91e99STejun Heo  * on @pool safely to release it.
44217a4e344cSTejun Heo  */
44227a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
44234e1a1f9aSTejun Heo {
4424a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_init(&pool->lock);
442529c91e99STejun Heo 	pool->id = -1;
442629c91e99STejun Heo 	pool->cpu = -1;
4427f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
44284e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
442982607adcSTejun Heo 	pool->watchdog_ts = jiffies;
44304e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
44314e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
44324e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
44334e1a1f9aSTejun Heo 
443432a6c723SKees Cook 	timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
44353f959aa3SValentin Schneider 	INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
44364e1a1f9aSTejun Heo 
443732a6c723SKees Cook 	timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
44384e1a1f9aSTejun Heo 
4439da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
4440e02b9312SValentin Schneider 	INIT_LIST_HEAD(&pool->dying_workers);
44417a4e344cSTejun Heo 
44427cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
444329c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
444429c91e99STejun Heo 	pool->refcnt = 1;
444529c91e99STejun Heo 
444629c91e99STejun Heo 	/* shouldn't fail above this point */
4447be69d00dSThomas Gleixner 	pool->attrs = alloc_workqueue_attrs();
44487a4e344cSTejun Heo 	if (!pool->attrs)
44497a4e344cSTejun Heo 		return -ENOMEM;
44505de7a03cSTejun Heo 
44515de7a03cSTejun Heo 	wqattrs_clear_for_pool(pool->attrs);
44525de7a03cSTejun Heo 
44537a4e344cSTejun Heo 	return 0;
44544e1a1f9aSTejun Heo }
44554e1a1f9aSTejun Heo 
4456669de8bdSBart Van Assche #ifdef CONFIG_LOCKDEP
4457669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
4458669de8bdSBart Van Assche {
4459669de8bdSBart Van Assche 	char *lock_name;
4460669de8bdSBart Van Assche 
4461669de8bdSBart Van Assche 	lockdep_register_key(&wq->key);
4462669de8bdSBart Van Assche 	lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
4463669de8bdSBart Van Assche 	if (!lock_name)
4464669de8bdSBart Van Assche 		lock_name = wq->name;
446569a106c0SQian Cai 
446669a106c0SQian Cai 	wq->lock_name = lock_name;
4467669de8bdSBart Van Assche 	lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
4468669de8bdSBart Van Assche }
4469669de8bdSBart Van Assche 
4470669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
4471669de8bdSBart Van Assche {
4472669de8bdSBart Van Assche 	lockdep_unregister_key(&wq->key);
4473669de8bdSBart Van Assche }
4474669de8bdSBart Van Assche 
4475669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
4476669de8bdSBart Van Assche {
4477669de8bdSBart Van Assche 	if (wq->lock_name != wq->name)
4478669de8bdSBart Van Assche 		kfree(wq->lock_name);
4479669de8bdSBart Van Assche }
4480669de8bdSBart Van Assche #else
4481669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
4482669de8bdSBart Van Assche {
4483669de8bdSBart Van Assche }
4484669de8bdSBart Van Assche 
4485669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
4486669de8bdSBart Van Assche {
4487669de8bdSBart Van Assche }
4488669de8bdSBart Van Assche 
4489669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
4490669de8bdSBart Van Assche {
4491669de8bdSBart Van Assche }
4492669de8bdSBart Van Assche #endif
4493669de8bdSBart Van Assche 
449491ccc6e7STejun Heo static void free_node_nr_active(struct wq_node_nr_active **nna_ar)
449591ccc6e7STejun Heo {
449691ccc6e7STejun Heo 	int node;
449791ccc6e7STejun Heo 
449891ccc6e7STejun Heo 	for_each_node(node) {
449991ccc6e7STejun Heo 		kfree(nna_ar[node]);
450091ccc6e7STejun Heo 		nna_ar[node] = NULL;
450191ccc6e7STejun Heo 	}
450291ccc6e7STejun Heo 
450391ccc6e7STejun Heo 	kfree(nna_ar[nr_node_ids]);
450491ccc6e7STejun Heo 	nna_ar[nr_node_ids] = NULL;
450591ccc6e7STejun Heo }
450691ccc6e7STejun Heo 
450791ccc6e7STejun Heo static void init_node_nr_active(struct wq_node_nr_active *nna)
450891ccc6e7STejun Heo {
4509c5f8cd6cSTejun Heo 	nna->max = WQ_DFL_MIN_ACTIVE;
451091ccc6e7STejun Heo 	atomic_set(&nna->nr, 0);
45115797b1c1STejun Heo 	raw_spin_lock_init(&nna->lock);
45125797b1c1STejun Heo 	INIT_LIST_HEAD(&nna->pending_pwqs);
451391ccc6e7STejun Heo }
451491ccc6e7STejun Heo 
451591ccc6e7STejun Heo /*
451691ccc6e7STejun Heo  * Each node's nr_active counter will be accessed mostly from its own node and
451791ccc6e7STejun Heo  * should be allocated in the node.
451891ccc6e7STejun Heo  */
451991ccc6e7STejun Heo static int alloc_node_nr_active(struct wq_node_nr_active **nna_ar)
452091ccc6e7STejun Heo {
452191ccc6e7STejun Heo 	struct wq_node_nr_active *nna;
452291ccc6e7STejun Heo 	int node;
452391ccc6e7STejun Heo 
452491ccc6e7STejun Heo 	for_each_node(node) {
452591ccc6e7STejun Heo 		nna = kzalloc_node(sizeof(*nna), GFP_KERNEL, node);
452691ccc6e7STejun Heo 		if (!nna)
452791ccc6e7STejun Heo 			goto err_free;
452891ccc6e7STejun Heo 		init_node_nr_active(nna);
452991ccc6e7STejun Heo 		nna_ar[node] = nna;
453091ccc6e7STejun Heo 	}
453191ccc6e7STejun Heo 
453291ccc6e7STejun Heo 	/* [nr_node_ids] is used as the fallback */
453391ccc6e7STejun Heo 	nna = kzalloc_node(sizeof(*nna), GFP_KERNEL, NUMA_NO_NODE);
453491ccc6e7STejun Heo 	if (!nna)
453591ccc6e7STejun Heo 		goto err_free;
453691ccc6e7STejun Heo 	init_node_nr_active(nna);
453791ccc6e7STejun Heo 	nna_ar[nr_node_ids] = nna;
453891ccc6e7STejun Heo 
453991ccc6e7STejun Heo 	return 0;
454091ccc6e7STejun Heo 
454191ccc6e7STejun Heo err_free:
454291ccc6e7STejun Heo 	free_node_nr_active(nna_ar);
454391ccc6e7STejun Heo 	return -ENOMEM;
454491ccc6e7STejun Heo }
454591ccc6e7STejun Heo 
4546e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
4547e2dca7adSTejun Heo {
4548e2dca7adSTejun Heo 	struct workqueue_struct *wq =
4549e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
4550e2dca7adSTejun Heo 
455191ccc6e7STejun Heo 	if (wq->flags & WQ_UNBOUND)
455291ccc6e7STejun Heo 		free_node_nr_active(wq->node_nr_active);
455391ccc6e7STejun Heo 
4554669de8bdSBart Van Assche 	wq_free_lockdep(wq);
4555ee1ceef7STejun Heo 	free_percpu(wq->cpu_pwq);
4556e2dca7adSTejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
4557e2dca7adSTejun Heo 	kfree(wq);
4558e2dca7adSTejun Heo }
4559e2dca7adSTejun Heo 
456029c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
456129c91e99STejun Heo {
456229c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
456329c91e99STejun Heo 
45647cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
456529c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
456629c91e99STejun Heo 	kfree(pool);
456729c91e99STejun Heo }
456829c91e99STejun Heo 
456929c91e99STejun Heo /**
457029c91e99STejun Heo  * put_unbound_pool - put a worker_pool
457129c91e99STejun Heo  * @pool: worker_pool to put
457229c91e99STejun Heo  *
457324acfb71SThomas Gleixner  * Put @pool.  If its refcnt reaches zero, it gets destroyed in RCU
4574c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
4575c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
4576c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
4577a892caccSTejun Heo  *
4578a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
457929c91e99STejun Heo  */
458029c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
458129c91e99STejun Heo {
458260f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
458329c91e99STejun Heo 	struct worker *worker;
45849680540cSYang Yingliang 	LIST_HEAD(cull_list);
4585e02b9312SValentin Schneider 
4586a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
4587a892caccSTejun Heo 
4588a892caccSTejun Heo 	if (--pool->refcnt)
458929c91e99STejun Heo 		return;
459029c91e99STejun Heo 
459129c91e99STejun Heo 	/* sanity checks */
459261d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
4593a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
459429c91e99STejun Heo 		return;
459529c91e99STejun Heo 
459629c91e99STejun Heo 	/* release id and unhash */
459729c91e99STejun Heo 	if (pool->id >= 0)
459829c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
459929c91e99STejun Heo 	hash_del(&pool->hash_node);
460029c91e99STejun Heo 
4601c5aa87bbSTejun Heo 	/*
4602692b4825STejun Heo 	 * Become the manager and destroy all workers.  This prevents
4603692b4825STejun Heo 	 * @pool's workers from blocking on attach_mutex.  We're the last
4604692b4825STejun Heo 	 * manager and @pool gets freed with the flag set.
46059ab03be4SValentin Schneider 	 *
46069ab03be4SValentin Schneider 	 * Having a concurrent manager is quite unlikely to happen as we can
46079ab03be4SValentin Schneider 	 * only get here with
46089ab03be4SValentin Schneider 	 *   pwq->refcnt == pool->refcnt == 0
46099ab03be4SValentin Schneider 	 * which implies no work queued to the pool, which implies no worker can
46109ab03be4SValentin Schneider 	 * become the manager. However a worker could have taken the role of
46119ab03be4SValentin Schneider 	 * manager before the refcnts dropped to 0, since maybe_create_worker()
46129ab03be4SValentin Schneider 	 * drops pool->lock
4613c5aa87bbSTejun Heo 	 */
46149ab03be4SValentin Schneider 	while (true) {
46159ab03be4SValentin Schneider 		rcuwait_wait_event(&manager_wait,
46169ab03be4SValentin Schneider 				   !(pool->flags & POOL_MANAGER_ACTIVE),
4617d8bb65abSSebastian Andrzej Siewior 				   TASK_UNINTERRUPTIBLE);
4618e02b9312SValentin Schneider 
4619e02b9312SValentin Schneider 		mutex_lock(&wq_pool_attach_mutex);
46209ab03be4SValentin Schneider 		raw_spin_lock_irq(&pool->lock);
46219ab03be4SValentin Schneider 		if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
4622692b4825STejun Heo 			pool->flags |= POOL_MANAGER_ACTIVE;
46239ab03be4SValentin Schneider 			break;
46249ab03be4SValentin Schneider 		}
46259ab03be4SValentin Schneider 		raw_spin_unlock_irq(&pool->lock);
4626e02b9312SValentin Schneider 		mutex_unlock(&wq_pool_attach_mutex);
46279ab03be4SValentin Schneider 	}
4628692b4825STejun Heo 
46291037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
4630e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
463129c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
4632a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
463360f5a4bcSLai Jiangshan 
4634e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
4635e02b9312SValentin Schneider 
4636e02b9312SValentin Schneider 	if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
463760f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
46381258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
463960f5a4bcSLai Jiangshan 
464060f5a4bcSLai Jiangshan 	if (pool->detach_completion)
464160f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
464260f5a4bcSLai Jiangshan 
464329c91e99STejun Heo 	/* shut down the timers */
464429c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
46453f959aa3SValentin Schneider 	cancel_work_sync(&pool->idle_cull_work);
464629c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
464729c91e99STejun Heo 
464824acfb71SThomas Gleixner 	/* RCU protected to allow dereferences from get_work_pool() */
464925b00775SPaul E. McKenney 	call_rcu(&pool->rcu, rcu_free_pool);
465029c91e99STejun Heo }
465129c91e99STejun Heo 
465229c91e99STejun Heo /**
465329c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
465429c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
465529c91e99STejun Heo  *
465629c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
465729c91e99STejun Heo  * reference count and return it.  If there already is a matching
465829c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
4659d185af30SYacine Belkadi  * create a new one.
4660a892caccSTejun Heo  *
4661a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
4662d185af30SYacine Belkadi  *
4663d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
4664d185af30SYacine Belkadi  * On failure, %NULL.
466529c91e99STejun Heo  */
466629c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
466729c91e99STejun Heo {
466884193c07STejun Heo 	struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_NUMA];
466929c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
467029c91e99STejun Heo 	struct worker_pool *pool;
467184193c07STejun Heo 	int pod, node = NUMA_NO_NODE;
467229c91e99STejun Heo 
4673a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
467429c91e99STejun Heo 
467529c91e99STejun Heo 	/* do we already have a matching pool? */
467629c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
467729c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
467829c91e99STejun Heo 			pool->refcnt++;
46793fb1823cSLai Jiangshan 			return pool;
468029c91e99STejun Heo 		}
468129c91e99STejun Heo 	}
468229c91e99STejun Heo 
46839546b29eSTejun Heo 	/* If __pod_cpumask is contained inside a NUMA pod, that's our node */
468484193c07STejun Heo 	for (pod = 0; pod < pt->nr_pods; pod++) {
46859546b29eSTejun Heo 		if (cpumask_subset(attrs->__pod_cpumask, pt->pod_cpus[pod])) {
468684193c07STejun Heo 			node = pt->pod_node[pod];
4687e2273584SXunlei Pang 			break;
4688e2273584SXunlei Pang 		}
4689e2273584SXunlei Pang 	}
4690e2273584SXunlei Pang 
469129c91e99STejun Heo 	/* nope, create a new one */
469284193c07STejun Heo 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, node);
469329c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
469429c91e99STejun Heo 		goto fail;
469529c91e99STejun Heo 
469684193c07STejun Heo 	pool->node = node;
46975de7a03cSTejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
46985de7a03cSTejun Heo 	wqattrs_clear_for_pool(pool->attrs);
46992865a8fbSShaohua Li 
470029c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
470129c91e99STejun Heo 		goto fail;
470229c91e99STejun Heo 
470329c91e99STejun Heo 	/* create and start the initial worker */
47043347fa09STejun Heo 	if (wq_online && !create_worker(pool))
470529c91e99STejun Heo 		goto fail;
470629c91e99STejun Heo 
470729c91e99STejun Heo 	/* install */
470829c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
47093fb1823cSLai Jiangshan 
471029c91e99STejun Heo 	return pool;
471129c91e99STejun Heo fail:
471229c91e99STejun Heo 	if (pool)
471329c91e99STejun Heo 		put_unbound_pool(pool);
471429c91e99STejun Heo 	return NULL;
471529c91e99STejun Heo }
471629c91e99STejun Heo 
47178864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
47188864b4e5STejun Heo {
47198864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
47208864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
47218864b4e5STejun Heo }
47228864b4e5STejun Heo 
47238864b4e5STejun Heo /*
4724967b494eSTejun Heo  * Scheduled on pwq_release_worker by put_pwq() when an unbound pwq hits zero
4725967b494eSTejun Heo  * refcnt and needs to be destroyed.
47268864b4e5STejun Heo  */
4727687a9aa5STejun Heo static void pwq_release_workfn(struct kthread_work *work)
47288864b4e5STejun Heo {
47298864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
4730687a9aa5STejun Heo 						  release_work);
47318864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
47328864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
4733b42b0bddSYang Yingliang 	bool is_last = false;
47348864b4e5STejun Heo 
4735b42b0bddSYang Yingliang 	/*
4736687a9aa5STejun Heo 	 * When @pwq is not linked, it doesn't hold any reference to the
4737b42b0bddSYang Yingliang 	 * @wq, and @wq is invalid to access.
4738b42b0bddSYang Yingliang 	 */
4739b42b0bddSYang Yingliang 	if (!list_empty(&pwq->pwqs_node)) {
47403c25a55dSLai Jiangshan 		mutex_lock(&wq->mutex);
47418864b4e5STejun Heo 		list_del_rcu(&pwq->pwqs_node);
4742bc0caf09STejun Heo 		is_last = list_empty(&wq->pwqs);
47433c25a55dSLai Jiangshan 		mutex_unlock(&wq->mutex);
4744b42b0bddSYang Yingliang 	}
47458864b4e5STejun Heo 
4746687a9aa5STejun Heo 	if (wq->flags & WQ_UNBOUND) {
4747a892caccSTejun Heo 		mutex_lock(&wq_pool_mutex);
47488864b4e5STejun Heo 		put_unbound_pool(pool);
4749a892caccSTejun Heo 		mutex_unlock(&wq_pool_mutex);
4750687a9aa5STejun Heo 	}
4751a892caccSTejun Heo 
47525797b1c1STejun Heo 	if (!list_empty(&pwq->pending_node)) {
47535797b1c1STejun Heo 		struct wq_node_nr_active *nna =
47545797b1c1STejun Heo 			wq_node_nr_active(pwq->wq, pwq->pool->node);
47555797b1c1STejun Heo 
47565797b1c1STejun Heo 		raw_spin_lock_irq(&nna->lock);
47575797b1c1STejun Heo 		list_del_init(&pwq->pending_node);
47585797b1c1STejun Heo 		raw_spin_unlock_irq(&nna->lock);
47595797b1c1STejun Heo 	}
47605797b1c1STejun Heo 
476125b00775SPaul E. McKenney 	call_rcu(&pwq->rcu, rcu_free_pwq);
47628864b4e5STejun Heo 
47638864b4e5STejun Heo 	/*
47648864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
4765e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
47668864b4e5STejun Heo 	 */
4767669de8bdSBart Van Assche 	if (is_last) {
4768669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
476925b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
47706029a918STejun Heo 	}
4771669de8bdSBart Van Assche }
47728864b4e5STejun Heo 
477367dc8325SCai Huoqing /* initialize newly allocated @pwq which is associated with @wq and @pool */
4774f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
4775f147f29eSTejun Heo 		     struct worker_pool *pool)
4776d2c1d404STejun Heo {
4777d2c1d404STejun Heo 	BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
4778d2c1d404STejun Heo 
4779e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
4780e50aba9aSTejun Heo 
4781d2c1d404STejun Heo 	pwq->pool = pool;
4782d2c1d404STejun Heo 	pwq->wq = wq;
4783d2c1d404STejun Heo 	pwq->flush_color = -1;
47848864b4e5STejun Heo 	pwq->refcnt = 1;
4785f97a4a1aSLai Jiangshan 	INIT_LIST_HEAD(&pwq->inactive_works);
47865797b1c1STejun Heo 	INIT_LIST_HEAD(&pwq->pending_node);
47871befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
4788d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
4789687a9aa5STejun Heo 	kthread_init_work(&pwq->release_work, pwq_release_workfn);
4790f147f29eSTejun Heo }
4791d2c1d404STejun Heo 
4792f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
47931befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
4794f147f29eSTejun Heo {
4795f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
4796f147f29eSTejun Heo 
4797f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
479875ccf595STejun Heo 
47991befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
48001befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
48011befcf30STejun Heo 		return;
48021befcf30STejun Heo 
480329b1cb41SLai Jiangshan 	/* set the matching work_color */
480475ccf595STejun Heo 	pwq->work_color = wq->work_color;
4805983ca25eSTejun Heo 
4806983ca25eSTejun Heo 	/* link in @pwq */
48079e8cd2f5STejun Heo 	list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
4808df2d5ae4STejun Heo }
48096029a918STejun Heo 
4810f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
4811f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
4812f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
4813f147f29eSTejun Heo {
4814f147f29eSTejun Heo 	struct worker_pool *pool;
4815f147f29eSTejun Heo 	struct pool_workqueue *pwq;
4816f147f29eSTejun Heo 
4817f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
4818f147f29eSTejun Heo 
4819f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
4820f147f29eSTejun Heo 	if (!pool)
4821f147f29eSTejun Heo 		return NULL;
4822f147f29eSTejun Heo 
4823e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
4824f147f29eSTejun Heo 	if (!pwq) {
4825f147f29eSTejun Heo 		put_unbound_pool(pool);
4826f147f29eSTejun Heo 		return NULL;
4827f147f29eSTejun Heo 	}
4828f147f29eSTejun Heo 
4829f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
4830f147f29eSTejun Heo 	return pwq;
4831d2c1d404STejun Heo }
4832d2c1d404STejun Heo 
48334c16bd32STejun Heo /**
4834fef59c9cSTejun Heo  * wq_calc_pod_cpumask - calculate a wq_attrs' cpumask for a pod
4835042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
483684193c07STejun Heo  * @cpu: the target CPU
48374c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
48384c16bd32STejun Heo  *
4839fef59c9cSTejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @pod. If
4840fef59c9cSTejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during calculation.
48419546b29eSTejun Heo  * The result is stored in @attrs->__pod_cpumask.
48424c16bd32STejun Heo  *
4843fef59c9cSTejun Heo  * If pod affinity is not enabled, @attrs->cpumask is always used. If enabled
4844fef59c9cSTejun Heo  * and @pod has online CPUs requested by @attrs, the returned cpumask is the
4845fef59c9cSTejun Heo  * intersection of the possible CPUs of @pod and @attrs->cpumask.
48464c16bd32STejun Heo  *
4847fef59c9cSTejun Heo  * The caller is responsible for ensuring that the cpumask of @pod stays stable.
48484c16bd32STejun Heo  */
48499546b29eSTejun Heo static void wq_calc_pod_cpumask(struct workqueue_attrs *attrs, int cpu,
48509546b29eSTejun Heo 				int cpu_going_down)
48514c16bd32STejun Heo {
485284193c07STejun Heo 	const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
485384193c07STejun Heo 	int pod = pt->cpu_pod[cpu];
48544c16bd32STejun Heo 
4855fef59c9cSTejun Heo 	/* does @pod have any online CPUs @attrs wants? */
48569546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, pt->pod_cpus[pod], attrs->cpumask);
48579546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, attrs->__pod_cpumask, cpu_online_mask);
48584c16bd32STejun Heo 	if (cpu_going_down >= 0)
48599546b29eSTejun Heo 		cpumask_clear_cpu(cpu_going_down, attrs->__pod_cpumask);
48604c16bd32STejun Heo 
48619546b29eSTejun Heo 	if (cpumask_empty(attrs->__pod_cpumask)) {
48629546b29eSTejun Heo 		cpumask_copy(attrs->__pod_cpumask, attrs->cpumask);
486384193c07STejun Heo 		return;
486484193c07STejun Heo 	}
48654c16bd32STejun Heo 
4866fef59c9cSTejun Heo 	/* yeap, return possible CPUs in @pod that @attrs wants */
48679546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, attrs->cpumask, pt->pod_cpus[pod]);
48681ad0f0a7SMichael Bringmann 
48699546b29eSTejun Heo 	if (cpumask_empty(attrs->__pod_cpumask))
48701ad0f0a7SMichael Bringmann 		pr_warn_once("WARNING: workqueue cpumask: online intersect > "
48711ad0f0a7SMichael Bringmann 				"possible intersect\n");
48724c16bd32STejun Heo }
48734c16bd32STejun Heo 
48749f66cff2STejun Heo /* install @pwq into @wq and return the old pwq, @cpu < 0 for dfl_pwq */
4875636b927eSTejun Heo static struct pool_workqueue *install_unbound_pwq(struct workqueue_struct *wq,
4876636b927eSTejun Heo 					int cpu, struct pool_workqueue *pwq)
48771befcf30STejun Heo {
48789f66cff2STejun Heo 	struct pool_workqueue __rcu **slot = unbound_pwq_slot(wq, cpu);
48791befcf30STejun Heo 	struct pool_workqueue *old_pwq;
48801befcf30STejun Heo 
48815b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
48821befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
48831befcf30STejun Heo 
48841befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
48851befcf30STejun Heo 	link_pwq(pwq);
48861befcf30STejun Heo 
48879f66cff2STejun Heo 	old_pwq = rcu_access_pointer(*slot);
48889f66cff2STejun Heo 	rcu_assign_pointer(*slot, pwq);
48891befcf30STejun Heo 	return old_pwq;
48901befcf30STejun Heo }
48911befcf30STejun Heo 
48922d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
48932d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
48942d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
48952d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
4896042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
48972d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
48982d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
48992d5f0764SLai Jiangshan };
49002d5f0764SLai Jiangshan 
49012d5f0764SLai Jiangshan /* free the resources after success or abort */
49022d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
49032d5f0764SLai Jiangshan {
49042d5f0764SLai Jiangshan 	if (ctx) {
4905636b927eSTejun Heo 		int cpu;
49062d5f0764SLai Jiangshan 
4907636b927eSTejun Heo 		for_each_possible_cpu(cpu)
4908636b927eSTejun Heo 			put_pwq_unlocked(ctx->pwq_tbl[cpu]);
49092d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
49102d5f0764SLai Jiangshan 
49112d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
49122d5f0764SLai Jiangshan 
49132d5f0764SLai Jiangshan 		kfree(ctx);
49142d5f0764SLai Jiangshan 	}
49152d5f0764SLai Jiangshan }
49162d5f0764SLai Jiangshan 
49172d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
49182d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
49192d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
492099c621efSLai Jiangshan 		      const struct workqueue_attrs *attrs,
492199c621efSLai Jiangshan 		      const cpumask_var_t unbound_cpumask)
49222d5f0764SLai Jiangshan {
49232d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
49249546b29eSTejun Heo 	struct workqueue_attrs *new_attrs;
4925636b927eSTejun Heo 	int cpu;
49262d5f0764SLai Jiangshan 
49272d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
49282d5f0764SLai Jiangshan 
492984193c07STejun Heo 	if (WARN_ON(attrs->affn_scope < 0 ||
493084193c07STejun Heo 		    attrs->affn_scope >= WQ_AFFN_NR_TYPES))
493184193c07STejun Heo 		return ERR_PTR(-EINVAL);
493284193c07STejun Heo 
4933636b927eSTejun Heo 	ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_cpu_ids), GFP_KERNEL);
49342d5f0764SLai Jiangshan 
4935be69d00dSThomas Gleixner 	new_attrs = alloc_workqueue_attrs();
49369546b29eSTejun Heo 	if (!ctx || !new_attrs)
49372d5f0764SLai Jiangshan 		goto out_free;
49382d5f0764SLai Jiangshan 
4939042f7df1SLai Jiangshan 	/*
49402d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
49412d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
49422d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
49432d5f0764SLai Jiangshan 	 */
49440f36ee24STejun Heo 	copy_workqueue_attrs(new_attrs, attrs);
49450f36ee24STejun Heo 	wqattrs_actualize_cpumask(new_attrs, unbound_cpumask);
49469546b29eSTejun Heo 	cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
49472d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
49482d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
49492d5f0764SLai Jiangshan 		goto out_free;
49502d5f0764SLai Jiangshan 
4951636b927eSTejun Heo 	for_each_possible_cpu(cpu) {
4952af73f5c9STejun Heo 		if (new_attrs->ordered) {
49532d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
4954636b927eSTejun Heo 			ctx->pwq_tbl[cpu] = ctx->dfl_pwq;
4955636b927eSTejun Heo 		} else {
49569546b29eSTejun Heo 			wq_calc_pod_cpumask(new_attrs, cpu, -1);
49579546b29eSTejun Heo 			ctx->pwq_tbl[cpu] = alloc_unbound_pwq(wq, new_attrs);
4958636b927eSTejun Heo 			if (!ctx->pwq_tbl[cpu])
4959636b927eSTejun Heo 				goto out_free;
49602d5f0764SLai Jiangshan 		}
49612d5f0764SLai Jiangshan 	}
49622d5f0764SLai Jiangshan 
4963042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
4964042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
4965042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
49669546b29eSTejun Heo 	cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
49672d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
4968042f7df1SLai Jiangshan 
49692d5f0764SLai Jiangshan 	ctx->wq = wq;
49702d5f0764SLai Jiangshan 	return ctx;
49712d5f0764SLai Jiangshan 
49722d5f0764SLai Jiangshan out_free:
49732d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
49742d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
497584193c07STejun Heo 	return ERR_PTR(-ENOMEM);
49762d5f0764SLai Jiangshan }
49772d5f0764SLai Jiangshan 
49782d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
49792d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
49802d5f0764SLai Jiangshan {
4981636b927eSTejun Heo 	int cpu;
49822d5f0764SLai Jiangshan 
49832d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
49842d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
49852d5f0764SLai Jiangshan 
49862d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
49872d5f0764SLai Jiangshan 
49889f66cff2STejun Heo 	/* save the previous pwqs and install the new ones */
4989636b927eSTejun Heo 	for_each_possible_cpu(cpu)
4990636b927eSTejun Heo 		ctx->pwq_tbl[cpu] = install_unbound_pwq(ctx->wq, cpu,
4991636b927eSTejun Heo 							ctx->pwq_tbl[cpu]);
49929f66cff2STejun Heo 	ctx->dfl_pwq = install_unbound_pwq(ctx->wq, -1, ctx->dfl_pwq);
49932d5f0764SLai Jiangshan 
49945797b1c1STejun Heo 	/* update node_nr_active->max */
49955797b1c1STejun Heo 	wq_update_node_max_active(ctx->wq, -1);
49965797b1c1STejun Heo 
49972d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
49982d5f0764SLai Jiangshan }
49992d5f0764SLai Jiangshan 
5000a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
5001a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
5002a0111cf6SLai Jiangshan {
5003a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
5004a0111cf6SLai Jiangshan 
5005a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
5006a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
5007a0111cf6SLai Jiangshan 		return -EINVAL;
5008a0111cf6SLai Jiangshan 
5009a0111cf6SLai Jiangshan 	/* creating multiple pwqs breaks ordering guarantee */
50100a94efb5STejun Heo 	if (!list_empty(&wq->pwqs)) {
50110a94efb5STejun Heo 		if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
5012a0111cf6SLai Jiangshan 			return -EINVAL;
5013a0111cf6SLai Jiangshan 
50140a94efb5STejun Heo 		wq->flags &= ~__WQ_ORDERED;
50150a94efb5STejun Heo 	}
50160a94efb5STejun Heo 
501799c621efSLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
501884193c07STejun Heo 	if (IS_ERR(ctx))
501984193c07STejun Heo 		return PTR_ERR(ctx);
5020a0111cf6SLai Jiangshan 
5021a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
5022a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
5023a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
5024a0111cf6SLai Jiangshan 
50256201171eSwanghaibin 	return 0;
5026a0111cf6SLai Jiangshan }
5027a0111cf6SLai Jiangshan 
50289e8cd2f5STejun Heo /**
50299e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
50309e8cd2f5STejun Heo  * @wq: the target workqueue
50319e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
50329e8cd2f5STejun Heo  *
5033fef59c9cSTejun Heo  * Apply @attrs to an unbound workqueue @wq. Unless disabled, this function maps
5034fef59c9cSTejun Heo  * a separate pwq to each CPU pod with possibles CPUs in @attrs->cpumask so that
5035fef59c9cSTejun Heo  * work items are affine to the pod it was issued on. Older pwqs are released as
5036fef59c9cSTejun Heo  * in-flight work items finish. Note that a work item which repeatedly requeues
5037fef59c9cSTejun Heo  * itself back-to-back will stay on its current pwq.
50389e8cd2f5STejun Heo  *
5039d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
5040d185af30SYacine Belkadi  *
5041ffd8bea8SSebastian Andrzej Siewior  * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
5042509b3204SDaniel Jordan  *
5043d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
50449e8cd2f5STejun Heo  */
5045513c98d0SDaniel Jordan int apply_workqueue_attrs(struct workqueue_struct *wq,
50469e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
50479e8cd2f5STejun Heo {
5048a0111cf6SLai Jiangshan 	int ret;
50499e8cd2f5STejun Heo 
5050509b3204SDaniel Jordan 	lockdep_assert_cpus_held();
5051509b3204SDaniel Jordan 
5052509b3204SDaniel Jordan 	mutex_lock(&wq_pool_mutex);
5053a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
5054509b3204SDaniel Jordan 	mutex_unlock(&wq_pool_mutex);
50552d5f0764SLai Jiangshan 
50562d5f0764SLai Jiangshan 	return ret;
50579e8cd2f5STejun Heo }
50589e8cd2f5STejun Heo 
50594c16bd32STejun Heo /**
5060fef59c9cSTejun Heo  * wq_update_pod - update pod affinity of a wq for CPU hot[un]plug
50614c16bd32STejun Heo  * @wq: the target workqueue
50624cbfd3deSTejun Heo  * @cpu: the CPU to update pool association for
50634cbfd3deSTejun Heo  * @hotplug_cpu: the CPU coming up or going down
50644c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
50654c16bd32STejun Heo  *
50664c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
5067fef59c9cSTejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update pod affinity of
50684c16bd32STejun Heo  * @wq accordingly.
50694c16bd32STejun Heo  *
50704c16bd32STejun Heo  *
5071fef59c9cSTejun Heo  * If pod affinity can't be adjusted due to memory allocation failure, it falls
5072fef59c9cSTejun Heo  * back to @wq->dfl_pwq which may not be optimal but is always correct.
5073fef59c9cSTejun Heo  *
5074fef59c9cSTejun Heo  * Note that when the last allowed CPU of a pod goes offline for a workqueue
5075fef59c9cSTejun Heo  * with a cpumask spanning multiple pods, the workers which were already
5076fef59c9cSTejun Heo  * executing the work items for the workqueue will lose their CPU affinity and
5077fef59c9cSTejun Heo  * may execute on any CPU. This is similar to how per-cpu workqueues behave on
5078fef59c9cSTejun Heo  * CPU_DOWN. If a workqueue user wants strict affinity, it's the user's
5079fef59c9cSTejun Heo  * responsibility to flush the work item from CPU_DOWN_PREPARE.
50804c16bd32STejun Heo  */
5081fef59c9cSTejun Heo static void wq_update_pod(struct workqueue_struct *wq, int cpu,
50824cbfd3deSTejun Heo 			  int hotplug_cpu, bool online)
50834c16bd32STejun Heo {
50844cbfd3deSTejun Heo 	int off_cpu = online ? -1 : hotplug_cpu;
50854c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
50864c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
50874c16bd32STejun Heo 
50884c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
50894c16bd32STejun Heo 
509084193c07STejun Heo 	if (!(wq->flags & WQ_UNBOUND) || wq->unbound_attrs->ordered)
50914c16bd32STejun Heo 		return;
50924c16bd32STejun Heo 
50934c16bd32STejun Heo 	/*
50944c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
50954c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
50964c16bd32STejun Heo 	 * CPU hotplug exclusion.
50974c16bd32STejun Heo 	 */
5098fef59c9cSTejun Heo 	target_attrs = wq_update_pod_attrs_buf;
50994c16bd32STejun Heo 
51004c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
51010f36ee24STejun Heo 	wqattrs_actualize_cpumask(target_attrs, wq_unbound_cpumask);
51024c16bd32STejun Heo 
5103636b927eSTejun Heo 	/* nothing to do if the target cpumask matches the current pwq */
51049546b29eSTejun Heo 	wq_calc_pod_cpumask(target_attrs, cpu, off_cpu);
51059f66cff2STejun Heo 	if (wqattrs_equal(target_attrs, unbound_pwq(wq, cpu)->pool->attrs))
5106f7142ed4SLai Jiangshan 		return;
51074c16bd32STejun Heo 
51084c16bd32STejun Heo 	/* create a new pwq */
51094c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
51104c16bd32STejun Heo 	if (!pwq) {
5111fef59c9cSTejun Heo 		pr_warn("workqueue: allocation failed while updating CPU pod affinity of \"%s\"\n",
51124c16bd32STejun Heo 			wq->name);
511377f300b1SDaeseok Youn 		goto use_dfl_pwq;
51144c16bd32STejun Heo 	}
51154c16bd32STejun Heo 
5116f7142ed4SLai Jiangshan 	/* Install the new pwq. */
51174c16bd32STejun Heo 	mutex_lock(&wq->mutex);
5118636b927eSTejun Heo 	old_pwq = install_unbound_pwq(wq, cpu, pwq);
51194c16bd32STejun Heo 	goto out_unlock;
51204c16bd32STejun Heo 
51214c16bd32STejun Heo use_dfl_pwq:
5122f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
51239f66cff2STejun Heo 	pwq = unbound_pwq(wq, -1);
51249f66cff2STejun Heo 	raw_spin_lock_irq(&pwq->pool->lock);
51259f66cff2STejun Heo 	get_pwq(pwq);
51269f66cff2STejun Heo 	raw_spin_unlock_irq(&pwq->pool->lock);
51279f66cff2STejun Heo 	old_pwq = install_unbound_pwq(wq, cpu, pwq);
51284c16bd32STejun Heo out_unlock:
51294c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
51304c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
51314c16bd32STejun Heo }
51324c16bd32STejun Heo 
513330cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
51341da177e4SLinus Torvalds {
513549e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
51368a2b7538STejun Heo 	int cpu, ret;
5137e1d8aa9fSFrederic Weisbecker 
5138687a9aa5STejun Heo 	wq->cpu_pwq = alloc_percpu(struct pool_workqueue *);
5139ee1ceef7STejun Heo 	if (!wq->cpu_pwq)
5140687a9aa5STejun Heo 		goto enomem;
514130cdf249STejun Heo 
5142636b927eSTejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
514330cdf249STejun Heo 		for_each_possible_cpu(cpu) {
51444cb1ef64STejun Heo 			struct pool_workqueue **pwq_p;
51454cb1ef64STejun Heo 			struct worker_pool __percpu *pools;
51464cb1ef64STejun Heo 			struct worker_pool *pool;
51474cb1ef64STejun Heo 
51484cb1ef64STejun Heo 			if (wq->flags & WQ_BH)
51494cb1ef64STejun Heo 				pools = bh_worker_pools;
51504cb1ef64STejun Heo 			else
51514cb1ef64STejun Heo 				pools = cpu_worker_pools;
51524cb1ef64STejun Heo 
51534cb1ef64STejun Heo 			pool = &(per_cpu_ptr(pools, cpu)[highpri]);
51544cb1ef64STejun Heo 			pwq_p = per_cpu_ptr(wq->cpu_pwq, cpu);
515530cdf249STejun Heo 
5156687a9aa5STejun Heo 			*pwq_p = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL,
5157687a9aa5STejun Heo 						       pool->node);
5158687a9aa5STejun Heo 			if (!*pwq_p)
5159687a9aa5STejun Heo 				goto enomem;
5160687a9aa5STejun Heo 
5161687a9aa5STejun Heo 			init_pwq(*pwq_p, wq, pool);
5162f147f29eSTejun Heo 
5163f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
5164687a9aa5STejun Heo 			link_pwq(*pwq_p);
5165f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
516630cdf249STejun Heo 		}
516730cdf249STejun Heo 		return 0;
5168509b3204SDaniel Jordan 	}
5169509b3204SDaniel Jordan 
5170ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
5171509b3204SDaniel Jordan 	if (wq->flags & __WQ_ORDERED) {
51729f66cff2STejun Heo 		struct pool_workqueue *dfl_pwq;
51739f66cff2STejun Heo 
51748a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
51758a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
51769f66cff2STejun Heo 		dfl_pwq = rcu_access_pointer(wq->dfl_pwq);
51779f66cff2STejun Heo 		WARN(!ret && (wq->pwqs.next != &dfl_pwq->pwqs_node ||
51789f66cff2STejun Heo 			      wq->pwqs.prev != &dfl_pwq->pwqs_node),
51798a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
51809e8cd2f5STejun Heo 	} else {
5181509b3204SDaniel Jordan 		ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
51829e8cd2f5STejun Heo 	}
5183ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
5184509b3204SDaniel Jordan 
518564344553SZqiang 	/* for unbound pwq, flush the pwq_release_worker ensures that the
518664344553SZqiang 	 * pwq_release_workfn() completes before calling kfree(wq).
518764344553SZqiang 	 */
518864344553SZqiang 	if (ret)
518964344553SZqiang 		kthread_flush_worker(pwq_release_worker);
519064344553SZqiang 
5191509b3204SDaniel Jordan 	return ret;
5192687a9aa5STejun Heo 
5193687a9aa5STejun Heo enomem:
5194687a9aa5STejun Heo 	if (wq->cpu_pwq) {
51957b42f401SZqiang 		for_each_possible_cpu(cpu) {
51967b42f401SZqiang 			struct pool_workqueue *pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
51977b42f401SZqiang 
51987b42f401SZqiang 			if (pwq)
51997b42f401SZqiang 				kmem_cache_free(pwq_cache, pwq);
52007b42f401SZqiang 		}
5201687a9aa5STejun Heo 		free_percpu(wq->cpu_pwq);
5202687a9aa5STejun Heo 		wq->cpu_pwq = NULL;
5203687a9aa5STejun Heo 	}
5204687a9aa5STejun Heo 	return -ENOMEM;
52050f900049STejun Heo }
52060f900049STejun Heo 
5207f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
5208f3421797STejun Heo 			       const char *name)
5209b71ab8c2STejun Heo {
5210636b927eSTejun Heo 	if (max_active < 1 || max_active > WQ_MAX_ACTIVE)
5211044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
5212636b927eSTejun Heo 			max_active, name, 1, WQ_MAX_ACTIVE);
5213b71ab8c2STejun Heo 
5214636b927eSTejun Heo 	return clamp_val(max_active, 1, WQ_MAX_ACTIVE);
5215b71ab8c2STejun Heo }
5216b71ab8c2STejun Heo 
5217983c7515STejun Heo /*
5218983c7515STejun Heo  * Workqueues which may be used during memory reclaim should have a rescuer
5219983c7515STejun Heo  * to guarantee forward progress.
5220983c7515STejun Heo  */
5221983c7515STejun Heo static int init_rescuer(struct workqueue_struct *wq)
5222983c7515STejun Heo {
5223983c7515STejun Heo 	struct worker *rescuer;
5224b92b36eaSDan Carpenter 	int ret;
5225983c7515STejun Heo 
5226983c7515STejun Heo 	if (!(wq->flags & WQ_MEM_RECLAIM))
5227983c7515STejun Heo 		return 0;
5228983c7515STejun Heo 
5229983c7515STejun Heo 	rescuer = alloc_worker(NUMA_NO_NODE);
52304c0736a7SPetr Mladek 	if (!rescuer) {
52314c0736a7SPetr Mladek 		pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
52324c0736a7SPetr Mladek 		       wq->name);
5233983c7515STejun Heo 		return -ENOMEM;
52344c0736a7SPetr Mladek 	}
5235983c7515STejun Heo 
5236983c7515STejun Heo 	rescuer->rescue_wq = wq;
5237b6a46f72SAaron Tomlin 	rescuer->task = kthread_create(rescuer_thread, rescuer, "kworker/R-%s", wq->name);
5238f187b697SSean Fu 	if (IS_ERR(rescuer->task)) {
5239b92b36eaSDan Carpenter 		ret = PTR_ERR(rescuer->task);
52404c0736a7SPetr Mladek 		pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
52414c0736a7SPetr Mladek 		       wq->name, ERR_PTR(ret));
5242983c7515STejun Heo 		kfree(rescuer);
5243b92b36eaSDan Carpenter 		return ret;
5244983c7515STejun Heo 	}
5245983c7515STejun Heo 
5246983c7515STejun Heo 	wq->rescuer = rescuer;
524785f0ab43SJuri Lelli 	if (wq->flags & WQ_UNBOUND)
524885f0ab43SJuri Lelli 		kthread_bind_mask(rescuer->task, wq->unbound_attrs->cpumask);
524985f0ab43SJuri Lelli 	else
5250983c7515STejun Heo 		kthread_bind_mask(rescuer->task, cpu_possible_mask);
5251983c7515STejun Heo 	wake_up_process(rescuer->task);
5252983c7515STejun Heo 
5253983c7515STejun Heo 	return 0;
5254983c7515STejun Heo }
5255983c7515STejun Heo 
5256a045a272STejun Heo /**
5257a045a272STejun Heo  * wq_adjust_max_active - update a wq's max_active to the current setting
5258a045a272STejun Heo  * @wq: target workqueue
5259a045a272STejun Heo  *
5260a045a272STejun Heo  * If @wq isn't freezing, set @wq->max_active to the saved_max_active and
5261a045a272STejun Heo  * activate inactive work items accordingly. If @wq is freezing, clear
5262a045a272STejun Heo  * @wq->max_active to zero.
5263a045a272STejun Heo  */
5264a045a272STejun Heo static void wq_adjust_max_active(struct workqueue_struct *wq)
5265a045a272STejun Heo {
5266c5404d4eSTejun Heo 	bool activated;
52675797b1c1STejun Heo 	int new_max, new_min;
5268a045a272STejun Heo 
5269a045a272STejun Heo 	lockdep_assert_held(&wq->mutex);
5270a045a272STejun Heo 
5271a045a272STejun Heo 	if ((wq->flags & WQ_FREEZABLE) && workqueue_freezing) {
52725797b1c1STejun Heo 		new_max = 0;
52735797b1c1STejun Heo 		new_min = 0;
52745797b1c1STejun Heo 	} else {
52755797b1c1STejun Heo 		new_max = wq->saved_max_active;
52765797b1c1STejun Heo 		new_min = wq->saved_min_active;
5277a045a272STejun Heo 	}
5278a045a272STejun Heo 
52795797b1c1STejun Heo 	if (wq->max_active == new_max && wq->min_active == new_min)
5280a045a272STejun Heo 		return;
5281a045a272STejun Heo 
5282a045a272STejun Heo 	/*
52835797b1c1STejun Heo 	 * Update @wq->max/min_active and then kick inactive work items if more
5284a045a272STejun Heo 	 * active work items are allowed. This doesn't break work item ordering
5285a045a272STejun Heo 	 * because new work items are always queued behind existing inactive
5286a045a272STejun Heo 	 * work items if there are any.
5287a045a272STejun Heo 	 */
52885797b1c1STejun Heo 	WRITE_ONCE(wq->max_active, new_max);
52895797b1c1STejun Heo 	WRITE_ONCE(wq->min_active, new_min);
52905797b1c1STejun Heo 
52915797b1c1STejun Heo 	if (wq->flags & WQ_UNBOUND)
52925797b1c1STejun Heo 		wq_update_node_max_active(wq, -1);
52935797b1c1STejun Heo 
52945797b1c1STejun Heo 	if (new_max == 0)
52955797b1c1STejun Heo 		return;
5296a045a272STejun Heo 
5297c5404d4eSTejun Heo 	/*
5298c5404d4eSTejun Heo 	 * Round-robin through pwq's activating the first inactive work item
5299c5404d4eSTejun Heo 	 * until max_active is filled.
5300c5404d4eSTejun Heo 	 */
5301c5404d4eSTejun Heo 	do {
5302c5404d4eSTejun Heo 		struct pool_workqueue *pwq;
5303c5404d4eSTejun Heo 
5304c5404d4eSTejun Heo 		activated = false;
5305a045a272STejun Heo 		for_each_pwq(pwq, wq) {
5306a045a272STejun Heo 			unsigned long flags;
5307a045a272STejun Heo 
5308c5404d4eSTejun Heo 			/* can be called during early boot w/ irq disabled */
5309a045a272STejun Heo 			raw_spin_lock_irqsave(&pwq->pool->lock, flags);
53105797b1c1STejun Heo 			if (pwq_activate_first_inactive(pwq, true)) {
5311c5404d4eSTejun Heo 				activated = true;
5312a045a272STejun Heo 				kick_pool(pwq->pool);
5313c5404d4eSTejun Heo 			}
5314a045a272STejun Heo 			raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
5315a045a272STejun Heo 		}
5316c5404d4eSTejun Heo 	} while (activated);
5317a045a272STejun Heo }
5318a045a272STejun Heo 
5319a2775bbcSMathieu Malaterre __printf(1, 4)
5320669de8bdSBart Van Assche struct workqueue_struct *alloc_workqueue(const char *fmt,
532197e37d7bSTejun Heo 					 unsigned int flags,
5322669de8bdSBart Van Assche 					 int max_active, ...)
53233af24433SOleg Nesterov {
5324ecf6881fSTejun Heo 	va_list args;
53253af24433SOleg Nesterov 	struct workqueue_struct *wq;
532691ccc6e7STejun Heo 	size_t wq_size;
532791ccc6e7STejun Heo 	int name_len;
5328b196be89STejun Heo 
53294cb1ef64STejun Heo 	if (flags & WQ_BH) {
53304cb1ef64STejun Heo 		if (WARN_ON_ONCE(flags & ~__WQ_BH_ALLOWS))
53314cb1ef64STejun Heo 			return NULL;
53324cb1ef64STejun Heo 		if (WARN_ON_ONCE(max_active))
53334cb1ef64STejun Heo 			return NULL;
53344cb1ef64STejun Heo 	}
53354cb1ef64STejun Heo 
53365c0338c6STejun Heo 	/*
5337fef59c9cSTejun Heo 	 * Unbound && max_active == 1 used to imply ordered, which is no longer
5338fef59c9cSTejun Heo 	 * the case on many machines due to per-pod pools. While
53395c0338c6STejun Heo 	 * alloc_ordered_workqueue() is the right way to create an ordered
5340fef59c9cSTejun Heo 	 * workqueue, keep the previous behavior to avoid subtle breakages.
53415c0338c6STejun Heo 	 */
53425c0338c6STejun Heo 	if ((flags & WQ_UNBOUND) && max_active == 1)
53435c0338c6STejun Heo 		flags |= __WQ_ORDERED;
53445c0338c6STejun Heo 
5345cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
5346cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
5347cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
5348cee22a15SViresh Kumar 
5349ecf6881fSTejun Heo 	/* allocate wq and format name */
535091ccc6e7STejun Heo 	if (flags & WQ_UNBOUND)
535191ccc6e7STejun Heo 		wq_size = struct_size(wq, node_nr_active, nr_node_ids + 1);
535291ccc6e7STejun Heo 	else
535391ccc6e7STejun Heo 		wq_size = sizeof(*wq);
535491ccc6e7STejun Heo 
535591ccc6e7STejun Heo 	wq = kzalloc(wq_size, GFP_KERNEL);
5356b196be89STejun Heo 	if (!wq)
5357d2c1d404STejun Heo 		return NULL;
5358b196be89STejun Heo 
53596029a918STejun Heo 	if (flags & WQ_UNBOUND) {
5360be69d00dSThomas Gleixner 		wq->unbound_attrs = alloc_workqueue_attrs();
53616029a918STejun Heo 		if (!wq->unbound_attrs)
53626029a918STejun Heo 			goto err_free_wq;
53636029a918STejun Heo 	}
53646029a918STejun Heo 
5365669de8bdSBart Van Assche 	va_start(args, max_active);
536691ccc6e7STejun Heo 	name_len = vsnprintf(wq->name, sizeof(wq->name), fmt, args);
5367b196be89STejun Heo 	va_end(args);
53683af24433SOleg Nesterov 
536991ccc6e7STejun Heo 	if (name_len >= WQ_NAME_LEN)
537091ccc6e7STejun Heo 		pr_warn_once("workqueue: name exceeds WQ_NAME_LEN. Truncating to: %s\n",
537191ccc6e7STejun Heo 			     wq->name);
537231c89007SAudra Mitchell 
53734cb1ef64STejun Heo 	if (flags & WQ_BH) {
53744cb1ef64STejun Heo 		/*
53754cb1ef64STejun Heo 		 * BH workqueues always share a single execution context per CPU
53764cb1ef64STejun Heo 		 * and don't impose any max_active limit.
53774cb1ef64STejun Heo 		 */
53784cb1ef64STejun Heo 		max_active = INT_MAX;
53794cb1ef64STejun Heo 	} else {
5380d320c038STejun Heo 		max_active = max_active ?: WQ_DFL_ACTIVE;
5381b196be89STejun Heo 		max_active = wq_clamp_max_active(max_active, flags, wq->name);
53824cb1ef64STejun Heo 	}
53833af24433SOleg Nesterov 
5384b196be89STejun Heo 	/* init wq */
538597e37d7bSTejun Heo 	wq->flags = flags;
5386a045a272STejun Heo 	wq->max_active = max_active;
53875797b1c1STejun Heo 	wq->min_active = min(max_active, WQ_DFL_MIN_ACTIVE);
53885797b1c1STejun Heo 	wq->saved_max_active = wq->max_active;
53895797b1c1STejun Heo 	wq->saved_min_active = wq->min_active;
53903c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
5391112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
539230cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
539373f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
539473f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
5395493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
53963af24433SOleg Nesterov 
5397669de8bdSBart Van Assche 	wq_init_lockdep(wq);
5398cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
53993af24433SOleg Nesterov 
540091ccc6e7STejun Heo 	if (flags & WQ_UNBOUND) {
540191ccc6e7STejun Heo 		if (alloc_node_nr_active(wq->node_nr_active) < 0)
540282efcab3SBart Van Assche 			goto err_unreg_lockdep;
540391ccc6e7STejun Heo 	}
540491ccc6e7STejun Heo 
540591ccc6e7STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
540691ccc6e7STejun Heo 		goto err_free_node_nr_active;
54071537663fSTejun Heo 
540840c17f75STejun Heo 	if (wq_online && init_rescuer(wq) < 0)
5409d2c1d404STejun Heo 		goto err_destroy;
5410e22bee78STejun Heo 
5411226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
5412226223abSTejun Heo 		goto err_destroy;
5413226223abSTejun Heo 
54146af8bf3dSOleg Nesterov 	/*
541568e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
541668e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
541768e13a67SLai Jiangshan 	 * list.
54186af8bf3dSOleg Nesterov 	 */
541968e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5420a0a1a5fdSTejun Heo 
5421a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
5422a045a272STejun Heo 	wq_adjust_max_active(wq);
5423a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
5424a0a1a5fdSTejun Heo 
5425e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
5426a0a1a5fdSTejun Heo 
542768e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
54283af24433SOleg Nesterov 
54293af24433SOleg Nesterov 	return wq;
5430d2c1d404STejun Heo 
543191ccc6e7STejun Heo err_free_node_nr_active:
543291ccc6e7STejun Heo 	if (wq->flags & WQ_UNBOUND)
543391ccc6e7STejun Heo 		free_node_nr_active(wq->node_nr_active);
543482efcab3SBart Van Assche err_unreg_lockdep:
5435009bb421SBart Van Assche 	wq_unregister_lockdep(wq);
5436009bb421SBart Van Assche 	wq_free_lockdep(wq);
543782efcab3SBart Van Assche err_free_wq:
54386029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
54394690c4abSTejun Heo 	kfree(wq);
5440d2c1d404STejun Heo 	return NULL;
5441d2c1d404STejun Heo err_destroy:
5442d2c1d404STejun Heo 	destroy_workqueue(wq);
54434690c4abSTejun Heo 	return NULL;
54441da177e4SLinus Torvalds }
5445669de8bdSBart Van Assche EXPORT_SYMBOL_GPL(alloc_workqueue);
54461da177e4SLinus Torvalds 
5447c29eb853STejun Heo static bool pwq_busy(struct pool_workqueue *pwq)
5448c29eb853STejun Heo {
5449c29eb853STejun Heo 	int i;
5450c29eb853STejun Heo 
5451c29eb853STejun Heo 	for (i = 0; i < WORK_NR_COLORS; i++)
5452c29eb853STejun Heo 		if (pwq->nr_in_flight[i])
5453c29eb853STejun Heo 			return true;
5454c29eb853STejun Heo 
54559f66cff2STejun Heo 	if ((pwq != rcu_access_pointer(pwq->wq->dfl_pwq)) && (pwq->refcnt > 1))
5456c29eb853STejun Heo 		return true;
5457afa87ce8STejun Heo 	if (!pwq_is_empty(pwq))
5458c29eb853STejun Heo 		return true;
5459c29eb853STejun Heo 
5460c29eb853STejun Heo 	return false;
5461c29eb853STejun Heo }
5462c29eb853STejun Heo 
54633af24433SOleg Nesterov /**
54643af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
54653af24433SOleg Nesterov  * @wq: target workqueue
54663af24433SOleg Nesterov  *
54673af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
54683af24433SOleg Nesterov  */
54693af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
54703af24433SOleg Nesterov {
547149e3cf44STejun Heo 	struct pool_workqueue *pwq;
5472636b927eSTejun Heo 	int cpu;
54733af24433SOleg Nesterov 
5474def98c84STejun Heo 	/*
5475def98c84STejun Heo 	 * Remove it from sysfs first so that sanity check failure doesn't
5476def98c84STejun Heo 	 * lead to sysfs name conflicts.
5477def98c84STejun Heo 	 */
5478def98c84STejun Heo 	workqueue_sysfs_unregister(wq);
5479def98c84STejun Heo 
548033e3f0a3SRichard Clark 	/* mark the workqueue destruction is in progress */
548133e3f0a3SRichard Clark 	mutex_lock(&wq->mutex);
548233e3f0a3SRichard Clark 	wq->flags |= __WQ_DESTROYING;
548333e3f0a3SRichard Clark 	mutex_unlock(&wq->mutex);
548433e3f0a3SRichard Clark 
54859c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
54869c5a2ba7STejun Heo 	drain_workqueue(wq);
5487c8efcc25STejun Heo 
5488def98c84STejun Heo 	/* kill rescuer, if sanity checks fail, leave it w/o rescuer */
5489def98c84STejun Heo 	if (wq->rescuer) {
5490def98c84STejun Heo 		struct worker *rescuer = wq->rescuer;
5491def98c84STejun Heo 
5492def98c84STejun Heo 		/* this prevents new queueing */
5493a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
5494def98c84STejun Heo 		wq->rescuer = NULL;
5495a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
5496def98c84STejun Heo 
5497def98c84STejun Heo 		/* rescuer will empty maydays list before exiting */
5498def98c84STejun Heo 		kthread_stop(rescuer->task);
54998efe1223STejun Heo 		kfree(rescuer);
5500def98c84STejun Heo 	}
5501def98c84STejun Heo 
5502c29eb853STejun Heo 	/*
5503c29eb853STejun Heo 	 * Sanity checks - grab all the locks so that we wait for all
5504c29eb853STejun Heo 	 * in-flight operations which may do put_pwq().
5505c29eb853STejun Heo 	 */
5506c29eb853STejun Heo 	mutex_lock(&wq_pool_mutex);
5507b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
550849e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
5509a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
5510c29eb853STejun Heo 		if (WARN_ON(pwq_busy(pwq))) {
55111d9a6159SKefeng Wang 			pr_warn("%s: %s has the following busy pwq\n",
5512e66b39afSTejun Heo 				__func__, wq->name);
5513c29eb853STejun Heo 			show_pwq(pwq);
5514a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pwq->pool->lock);
5515b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
5516c29eb853STejun Heo 			mutex_unlock(&wq_pool_mutex);
551755df0933SImran Khan 			show_one_workqueue(wq);
55186183c009STejun Heo 			return;
551976af4d93STejun Heo 		}
5520a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
552176af4d93STejun Heo 	}
5522b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
55236183c009STejun Heo 
5524a0a1a5fdSTejun Heo 	/*
5525a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
5526a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
5527a0a1a5fdSTejun Heo 	 */
5528e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
552968e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
55303af24433SOleg Nesterov 
55318864b4e5STejun Heo 	/*
5532636b927eSTejun Heo 	 * We're the sole accessor of @wq. Directly access cpu_pwq and dfl_pwq
5533636b927eSTejun Heo 	 * to put the base refs. @wq will be auto-destroyed from the last
5534636b927eSTejun Heo 	 * pwq_put. RCU read lock prevents @wq from going away from under us.
55358864b4e5STejun Heo 	 */
5536636b927eSTejun Heo 	rcu_read_lock();
5537636b927eSTejun Heo 
5538636b927eSTejun Heo 	for_each_possible_cpu(cpu) {
55399f66cff2STejun Heo 		put_pwq_unlocked(unbound_pwq(wq, cpu));
55409f66cff2STejun Heo 		RCU_INIT_POINTER(*unbound_pwq_slot(wq, cpu), NULL);
55414c16bd32STejun Heo 	}
55424c16bd32STejun Heo 
55439f66cff2STejun Heo 	put_pwq_unlocked(unbound_pwq(wq, -1));
55449f66cff2STejun Heo 	RCU_INIT_POINTER(*unbound_pwq_slot(wq, -1), NULL);
5545636b927eSTejun Heo 
5546636b927eSTejun Heo 	rcu_read_unlock();
55473af24433SOleg Nesterov }
55483af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
55493af24433SOleg Nesterov 
5550dcd989cbSTejun Heo /**
5551dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
5552dcd989cbSTejun Heo  * @wq: target workqueue
5553dcd989cbSTejun Heo  * @max_active: new max_active value.
5554dcd989cbSTejun Heo  *
55555797b1c1STejun Heo  * Set max_active of @wq to @max_active. See the alloc_workqueue() function
55565797b1c1STejun Heo  * comment.
5557dcd989cbSTejun Heo  *
5558dcd989cbSTejun Heo  * CONTEXT:
5559dcd989cbSTejun Heo  * Don't call from IRQ context.
5560dcd989cbSTejun Heo  */
5561dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
5562dcd989cbSTejun Heo {
55634cb1ef64STejun Heo 	/* max_active doesn't mean anything for BH workqueues */
55644cb1ef64STejun Heo 	if (WARN_ON(wq->flags & WQ_BH))
55654cb1ef64STejun Heo 		return;
55668719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
55670a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
55688719dceaSTejun Heo 		return;
55698719dceaSTejun Heo 
5570f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
5571dcd989cbSTejun Heo 
5572a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
5573dcd989cbSTejun Heo 
55740a94efb5STejun Heo 	wq->flags &= ~__WQ_ORDERED;
5575dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
55765797b1c1STejun Heo 	if (wq->flags & WQ_UNBOUND)
55775797b1c1STejun Heo 		wq->saved_min_active = min(wq->saved_min_active, max_active);
55785797b1c1STejun Heo 
5579a045a272STejun Heo 	wq_adjust_max_active(wq);
5580dcd989cbSTejun Heo 
5581a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
5582dcd989cbSTejun Heo }
5583dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
5584dcd989cbSTejun Heo 
5585dcd989cbSTejun Heo /**
558627d4ee03SLukas Wunner  * current_work - retrieve %current task's work struct
558727d4ee03SLukas Wunner  *
558827d4ee03SLukas Wunner  * Determine if %current task is a workqueue worker and what it's working on.
558927d4ee03SLukas Wunner  * Useful to find out the context that the %current task is running in.
559027d4ee03SLukas Wunner  *
559127d4ee03SLukas Wunner  * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
559227d4ee03SLukas Wunner  */
559327d4ee03SLukas Wunner struct work_struct *current_work(void)
559427d4ee03SLukas Wunner {
559527d4ee03SLukas Wunner 	struct worker *worker = current_wq_worker();
559627d4ee03SLukas Wunner 
559727d4ee03SLukas Wunner 	return worker ? worker->current_work : NULL;
559827d4ee03SLukas Wunner }
559927d4ee03SLukas Wunner EXPORT_SYMBOL(current_work);
560027d4ee03SLukas Wunner 
560127d4ee03SLukas Wunner /**
5602e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
5603e6267616STejun Heo  *
5604e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
5605e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
5606d185af30SYacine Belkadi  *
5607d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
5608e6267616STejun Heo  */
5609e6267616STejun Heo bool current_is_workqueue_rescuer(void)
5610e6267616STejun Heo {
5611e6267616STejun Heo 	struct worker *worker = current_wq_worker();
5612e6267616STejun Heo 
56136a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
5614e6267616STejun Heo }
5615e6267616STejun Heo 
5616e6267616STejun Heo /**
5617dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
5618dcd989cbSTejun Heo  * @cpu: CPU in question
5619dcd989cbSTejun Heo  * @wq: target workqueue
5620dcd989cbSTejun Heo  *
5621dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
5622dcd989cbSTejun Heo  * no synchronization around this function and the test result is
5623dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
5624dcd989cbSTejun Heo  *
5625d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
5626636b927eSTejun Heo  *
5627636b927eSTejun Heo  * With the exception of ordered workqueues, all workqueues have per-cpu
5628636b927eSTejun Heo  * pool_workqueues, each with its own congested state. A workqueue being
5629636b927eSTejun Heo  * congested on one CPU doesn't mean that the workqueue is contested on any
5630636b927eSTejun Heo  * other CPUs.
5631d3251859STejun Heo  *
5632d185af30SYacine Belkadi  * Return:
5633dcd989cbSTejun Heo  * %true if congested, %false otherwise.
5634dcd989cbSTejun Heo  */
5635d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
5636dcd989cbSTejun Heo {
56377fb98ea7STejun Heo 	struct pool_workqueue *pwq;
563876af4d93STejun Heo 	bool ret;
563976af4d93STejun Heo 
564024acfb71SThomas Gleixner 	rcu_read_lock();
564124acfb71SThomas Gleixner 	preempt_disable();
56427fb98ea7STejun Heo 
5643d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
5644d3251859STejun Heo 		cpu = smp_processor_id();
5645d3251859STejun Heo 
5646687a9aa5STejun Heo 	pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
5647f97a4a1aSLai Jiangshan 	ret = !list_empty(&pwq->inactive_works);
5648636b927eSTejun Heo 
564924acfb71SThomas Gleixner 	preempt_enable();
565024acfb71SThomas Gleixner 	rcu_read_unlock();
565176af4d93STejun Heo 
565276af4d93STejun Heo 	return ret;
5653dcd989cbSTejun Heo }
5654dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
5655dcd989cbSTejun Heo 
5656dcd989cbSTejun Heo /**
5657dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
5658dcd989cbSTejun Heo  * @work: the work to be tested
5659dcd989cbSTejun Heo  *
5660dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
5661dcd989cbSTejun Heo  * synchronization around this function and the test result is
5662dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
5663dcd989cbSTejun Heo  *
5664d185af30SYacine Belkadi  * Return:
5665dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
5666dcd989cbSTejun Heo  */
5667dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
5668dcd989cbSTejun Heo {
5669fa1b54e6STejun Heo 	struct worker_pool *pool;
5670dcd989cbSTejun Heo 	unsigned long flags;
5671dcd989cbSTejun Heo 	unsigned int ret = 0;
5672dcd989cbSTejun Heo 
5673dcd989cbSTejun Heo 	if (work_pending(work))
5674dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
5675038366c5SLai Jiangshan 
567624acfb71SThomas Gleixner 	rcu_read_lock();
5677fa1b54e6STejun Heo 	pool = get_work_pool(work);
5678038366c5SLai Jiangshan 	if (pool) {
5679a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pool->lock, flags);
5680c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
5681dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
5682a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pool->lock, flags);
5683038366c5SLai Jiangshan 	}
568424acfb71SThomas Gleixner 	rcu_read_unlock();
5685dcd989cbSTejun Heo 
5686dcd989cbSTejun Heo 	return ret;
5687dcd989cbSTejun Heo }
5688dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
5689dcd989cbSTejun Heo 
56903d1cb205STejun Heo /**
56913d1cb205STejun Heo  * set_worker_desc - set description for the current work item
56923d1cb205STejun Heo  * @fmt: printf-style format string
56933d1cb205STejun Heo  * @...: arguments for the format string
56943d1cb205STejun Heo  *
56953d1cb205STejun Heo  * This function can be called by a running work function to describe what
56963d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
56973d1cb205STejun Heo  * information will be printed out together to help debugging.  The
56983d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
56993d1cb205STejun Heo  */
57003d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
57013d1cb205STejun Heo {
57023d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
57033d1cb205STejun Heo 	va_list args;
57043d1cb205STejun Heo 
57053d1cb205STejun Heo 	if (worker) {
57063d1cb205STejun Heo 		va_start(args, fmt);
57073d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
57083d1cb205STejun Heo 		va_end(args);
57093d1cb205STejun Heo 	}
57103d1cb205STejun Heo }
57115c750d58SSteffen Maier EXPORT_SYMBOL_GPL(set_worker_desc);
57123d1cb205STejun Heo 
57133d1cb205STejun Heo /**
57143d1cb205STejun Heo  * print_worker_info - print out worker information and description
57153d1cb205STejun Heo  * @log_lvl: the log level to use when printing
57163d1cb205STejun Heo  * @task: target task
57173d1cb205STejun Heo  *
57183d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
57193d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
57203d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
57213d1cb205STejun Heo  *
57223d1cb205STejun Heo  * This function can be safely called on any task as long as the
57233d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
57243d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
57253d1cb205STejun Heo  */
57263d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
57273d1cb205STejun Heo {
57283d1cb205STejun Heo 	work_func_t *fn = NULL;
57293d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
57303d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
57313d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
57323d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
57333d1cb205STejun Heo 	struct worker *worker;
57343d1cb205STejun Heo 
57353d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
57363d1cb205STejun Heo 		return;
57373d1cb205STejun Heo 
57383d1cb205STejun Heo 	/*
57393d1cb205STejun Heo 	 * This function is called without any synchronization and @task
57403d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
57413d1cb205STejun Heo 	 */
5742e700591aSPetr Mladek 	worker = kthread_probe_data(task);
57433d1cb205STejun Heo 
57443d1cb205STejun Heo 	/*
57458bf89593STejun Heo 	 * Carefully copy the associated workqueue's workfn, name and desc.
57468bf89593STejun Heo 	 * Keep the original last '\0' in case the original is garbage.
57473d1cb205STejun Heo 	 */
5748fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
5749fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
5750fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
5751fe557319SChristoph Hellwig 	copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
5752fe557319SChristoph Hellwig 	copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
57533d1cb205STejun Heo 
57543d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
5755d75f773cSSakari Ailus 		printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
57568bf89593STejun Heo 		if (strcmp(name, desc))
57573d1cb205STejun Heo 			pr_cont(" (%s)", desc);
57583d1cb205STejun Heo 		pr_cont("\n");
57593d1cb205STejun Heo 	}
57603d1cb205STejun Heo }
57613d1cb205STejun Heo 
57623494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
57633494fc30STejun Heo {
57643494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
57653494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
57663494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
57674cb1ef64STejun Heo 	pr_cont(" flags=0x%x", pool->flags);
57684cb1ef64STejun Heo 	if (pool->flags & POOL_BH)
57694cb1ef64STejun Heo 		pr_cont(" bh%s",
57704cb1ef64STejun Heo 			pool->attrs->nice == HIGHPRI_NICE_LEVEL ? "-hi" : "");
57714cb1ef64STejun Heo 	else
57724cb1ef64STejun Heo 		pr_cont(" nice=%d", pool->attrs->nice);
57734cb1ef64STejun Heo }
57744cb1ef64STejun Heo 
57754cb1ef64STejun Heo static void pr_cont_worker_id(struct worker *worker)
57764cb1ef64STejun Heo {
57774cb1ef64STejun Heo 	struct worker_pool *pool = worker->pool;
57784cb1ef64STejun Heo 
57794cb1ef64STejun Heo 	if (pool->flags & WQ_BH)
57804cb1ef64STejun Heo 		pr_cont("bh%s",
57814cb1ef64STejun Heo 			pool->attrs->nice == HIGHPRI_NICE_LEVEL ? "-hi" : "");
57824cb1ef64STejun Heo 	else
57834cb1ef64STejun Heo 		pr_cont("%d%s", task_pid_nr(worker->task),
57844cb1ef64STejun Heo 			worker->rescue_wq ? "(RESCUER)" : "");
57853494fc30STejun Heo }
57863494fc30STejun Heo 
5787c76feb0dSPaul E. McKenney struct pr_cont_work_struct {
5788c76feb0dSPaul E. McKenney 	bool comma;
5789c76feb0dSPaul E. McKenney 	work_func_t func;
5790c76feb0dSPaul E. McKenney 	long ctr;
5791c76feb0dSPaul E. McKenney };
5792c76feb0dSPaul E. McKenney 
5793c76feb0dSPaul E. McKenney static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
5794c76feb0dSPaul E. McKenney {
5795c76feb0dSPaul E. McKenney 	if (!pcwsp->ctr)
5796c76feb0dSPaul E. McKenney 		goto out_record;
5797c76feb0dSPaul E. McKenney 	if (func == pcwsp->func) {
5798c76feb0dSPaul E. McKenney 		pcwsp->ctr++;
5799c76feb0dSPaul E. McKenney 		return;
5800c76feb0dSPaul E. McKenney 	}
5801c76feb0dSPaul E. McKenney 	if (pcwsp->ctr == 1)
5802c76feb0dSPaul E. McKenney 		pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
5803c76feb0dSPaul E. McKenney 	else
5804c76feb0dSPaul E. McKenney 		pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
5805c76feb0dSPaul E. McKenney 	pcwsp->ctr = 0;
5806c76feb0dSPaul E. McKenney out_record:
5807c76feb0dSPaul E. McKenney 	if ((long)func == -1L)
5808c76feb0dSPaul E. McKenney 		return;
5809c76feb0dSPaul E. McKenney 	pcwsp->comma = comma;
5810c76feb0dSPaul E. McKenney 	pcwsp->func = func;
5811c76feb0dSPaul E. McKenney 	pcwsp->ctr = 1;
5812c76feb0dSPaul E. McKenney }
5813c76feb0dSPaul E. McKenney 
5814c76feb0dSPaul E. McKenney static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
58153494fc30STejun Heo {
58163494fc30STejun Heo 	if (work->func == wq_barrier_func) {
58173494fc30STejun Heo 		struct wq_barrier *barr;
58183494fc30STejun Heo 
58193494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
58203494fc30STejun Heo 
5821c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
58223494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
58233494fc30STejun Heo 			task_pid_nr(barr->task));
58243494fc30STejun Heo 	} else {
5825c76feb0dSPaul E. McKenney 		if (!comma)
5826c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5827c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, work->func, pcwsp);
58283494fc30STejun Heo 	}
58293494fc30STejun Heo }
58303494fc30STejun Heo 
58313494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
58323494fc30STejun Heo {
5833c76feb0dSPaul E. McKenney 	struct pr_cont_work_struct pcws = { .ctr = 0, };
58343494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
58353494fc30STejun Heo 	struct work_struct *work;
58363494fc30STejun Heo 	struct worker *worker;
58373494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
58383494fc30STejun Heo 	int bkt;
58393494fc30STejun Heo 
58403494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
58413494fc30STejun Heo 	pr_cont_pool_info(pool);
58423494fc30STejun Heo 
5843a045a272STejun Heo 	pr_cont(" active=%d refcnt=%d%s\n",
5844a045a272STejun Heo 		pwq->nr_active, pwq->refcnt,
58453494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
58463494fc30STejun Heo 
58473494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
58483494fc30STejun Heo 		if (worker->current_pwq == pwq) {
58493494fc30STejun Heo 			has_in_flight = true;
58503494fc30STejun Heo 			break;
58513494fc30STejun Heo 		}
58523494fc30STejun Heo 	}
58533494fc30STejun Heo 	if (has_in_flight) {
58543494fc30STejun Heo 		bool comma = false;
58553494fc30STejun Heo 
58563494fc30STejun Heo 		pr_info("    in-flight:");
58573494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
58583494fc30STejun Heo 			if (worker->current_pwq != pwq)
58593494fc30STejun Heo 				continue;
58603494fc30STejun Heo 
58614cb1ef64STejun Heo 			pr_cont(" %s", comma ? "," : "");
58624cb1ef64STejun Heo 			pr_cont_worker_id(worker);
58634cb1ef64STejun Heo 			pr_cont(":%ps", worker->current_func);
58643494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
5865c76feb0dSPaul E. McKenney 				pr_cont_work(false, work, &pcws);
5866c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
58673494fc30STejun Heo 			comma = true;
58683494fc30STejun Heo 		}
58693494fc30STejun Heo 		pr_cont("\n");
58703494fc30STejun Heo 	}
58713494fc30STejun Heo 
58723494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
58733494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
58743494fc30STejun Heo 			has_pending = true;
58753494fc30STejun Heo 			break;
58763494fc30STejun Heo 		}
58773494fc30STejun Heo 	}
58783494fc30STejun Heo 	if (has_pending) {
58793494fc30STejun Heo 		bool comma = false;
58803494fc30STejun Heo 
58813494fc30STejun Heo 		pr_info("    pending:");
58823494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
58833494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
58843494fc30STejun Heo 				continue;
58853494fc30STejun Heo 
5886c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
58873494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
58883494fc30STejun Heo 		}
5889c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
58903494fc30STejun Heo 		pr_cont("\n");
58913494fc30STejun Heo 	}
58923494fc30STejun Heo 
5893f97a4a1aSLai Jiangshan 	if (!list_empty(&pwq->inactive_works)) {
58943494fc30STejun Heo 		bool comma = false;
58953494fc30STejun Heo 
5896f97a4a1aSLai Jiangshan 		pr_info("    inactive:");
5897f97a4a1aSLai Jiangshan 		list_for_each_entry(work, &pwq->inactive_works, entry) {
5898c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
58993494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
59003494fc30STejun Heo 		}
5901c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
59023494fc30STejun Heo 		pr_cont("\n");
59033494fc30STejun Heo 	}
59043494fc30STejun Heo }
59053494fc30STejun Heo 
59063494fc30STejun Heo /**
590755df0933SImran Khan  * show_one_workqueue - dump state of specified workqueue
590855df0933SImran Khan  * @wq: workqueue whose state will be printed
59093494fc30STejun Heo  */
591055df0933SImran Khan void show_one_workqueue(struct workqueue_struct *wq)
59113494fc30STejun Heo {
59123494fc30STejun Heo 	struct pool_workqueue *pwq;
59133494fc30STejun Heo 	bool idle = true;
591455df0933SImran Khan 	unsigned long flags;
59153494fc30STejun Heo 
59163494fc30STejun Heo 	for_each_pwq(pwq, wq) {
5917afa87ce8STejun Heo 		if (!pwq_is_empty(pwq)) {
59183494fc30STejun Heo 			idle = false;
59193494fc30STejun Heo 			break;
59203494fc30STejun Heo 		}
59213494fc30STejun Heo 	}
592255df0933SImran Khan 	if (idle) /* Nothing to print for idle workqueue */
592355df0933SImran Khan 		return;
59243494fc30STejun Heo 
59253494fc30STejun Heo 	pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
59263494fc30STejun Heo 
59273494fc30STejun Heo 	for_each_pwq(pwq, wq) {
5928a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irqsave(&pwq->pool->lock, flags);
5929afa87ce8STejun Heo 		if (!pwq_is_empty(pwq)) {
593057116ce1SJohan Hovold 			/*
593157116ce1SJohan Hovold 			 * Defer printing to avoid deadlocks in console
593257116ce1SJohan Hovold 			 * drivers that queue work while holding locks
593357116ce1SJohan Hovold 			 * also taken in their write paths.
593457116ce1SJohan Hovold 			 */
593557116ce1SJohan Hovold 			printk_deferred_enter();
59363494fc30STejun Heo 			show_pwq(pwq);
593757116ce1SJohan Hovold 			printk_deferred_exit();
593857116ce1SJohan Hovold 		}
5939a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
594062635ea8SSergey Senozhatsky 		/*
594162635ea8SSergey Senozhatsky 		 * We could be printing a lot from atomic context, e.g.
594255df0933SImran Khan 		 * sysrq-t -> show_all_workqueues(). Avoid triggering
594362635ea8SSergey Senozhatsky 		 * hard lockup.
594462635ea8SSergey Senozhatsky 		 */
594562635ea8SSergey Senozhatsky 		touch_nmi_watchdog();
59463494fc30STejun Heo 	}
594755df0933SImran Khan 
59483494fc30STejun Heo }
59493494fc30STejun Heo 
595055df0933SImran Khan /**
595155df0933SImran Khan  * show_one_worker_pool - dump state of specified worker pool
595255df0933SImran Khan  * @pool: worker pool whose state will be printed
595355df0933SImran Khan  */
595455df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool)
595555df0933SImran Khan {
59563494fc30STejun Heo 	struct worker *worker;
59573494fc30STejun Heo 	bool first = true;
595855df0933SImran Khan 	unsigned long flags;
5959335a42ebSPetr Mladek 	unsigned long hung = 0;
59603494fc30STejun Heo 
5961a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irqsave(&pool->lock, flags);
59623494fc30STejun Heo 	if (pool->nr_workers == pool->nr_idle)
59633494fc30STejun Heo 		goto next_pool;
5964335a42ebSPetr Mladek 
5965335a42ebSPetr Mladek 	/* How long the first pending work is waiting for a worker. */
5966335a42ebSPetr Mladek 	if (!list_empty(&pool->worklist))
5967335a42ebSPetr Mladek 		hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
5968335a42ebSPetr Mladek 
596957116ce1SJohan Hovold 	/*
597057116ce1SJohan Hovold 	 * Defer printing to avoid deadlocks in console drivers that
597157116ce1SJohan Hovold 	 * queue work while holding locks also taken in their write
597257116ce1SJohan Hovold 	 * paths.
597357116ce1SJohan Hovold 	 */
597457116ce1SJohan Hovold 	printk_deferred_enter();
59753494fc30STejun Heo 	pr_info("pool %d:", pool->id);
59763494fc30STejun Heo 	pr_cont_pool_info(pool);
5977335a42ebSPetr Mladek 	pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
59783494fc30STejun Heo 	if (pool->manager)
59793494fc30STejun Heo 		pr_cont(" manager: %d",
59803494fc30STejun Heo 			task_pid_nr(pool->manager->task));
59813494fc30STejun Heo 	list_for_each_entry(worker, &pool->idle_list, entry) {
59824cb1ef64STejun Heo 		pr_cont(" %s", first ? "idle: " : "");
59834cb1ef64STejun Heo 		pr_cont_worker_id(worker);
59843494fc30STejun Heo 		first = false;
59853494fc30STejun Heo 	}
59863494fc30STejun Heo 	pr_cont("\n");
598757116ce1SJohan Hovold 	printk_deferred_exit();
59883494fc30STejun Heo next_pool:
5989a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&pool->lock, flags);
599062635ea8SSergey Senozhatsky 	/*
599162635ea8SSergey Senozhatsky 	 * We could be printing a lot from atomic context, e.g.
599255df0933SImran Khan 	 * sysrq-t -> show_all_workqueues(). Avoid triggering
599362635ea8SSergey Senozhatsky 	 * hard lockup.
599462635ea8SSergey Senozhatsky 	 */
599562635ea8SSergey Senozhatsky 	touch_nmi_watchdog();
599655df0933SImran Khan 
59973494fc30STejun Heo }
59983494fc30STejun Heo 
599955df0933SImran Khan /**
600055df0933SImran Khan  * show_all_workqueues - dump workqueue state
600155df0933SImran Khan  *
6002704bc669SJungseung Lee  * Called from a sysrq handler and prints out all busy workqueues and pools.
600355df0933SImran Khan  */
600455df0933SImran Khan void show_all_workqueues(void)
600555df0933SImran Khan {
600655df0933SImran Khan 	struct workqueue_struct *wq;
600755df0933SImran Khan 	struct worker_pool *pool;
600855df0933SImran Khan 	int pi;
600955df0933SImran Khan 
601055df0933SImran Khan 	rcu_read_lock();
601155df0933SImran Khan 
601255df0933SImran Khan 	pr_info("Showing busy workqueues and worker pools:\n");
601355df0933SImran Khan 
601455df0933SImran Khan 	list_for_each_entry_rcu(wq, &workqueues, list)
601555df0933SImran Khan 		show_one_workqueue(wq);
601655df0933SImran Khan 
601755df0933SImran Khan 	for_each_pool(pool, pi)
601855df0933SImran Khan 		show_one_worker_pool(pool);
601955df0933SImran Khan 
602024acfb71SThomas Gleixner 	rcu_read_unlock();
60213494fc30STejun Heo }
60223494fc30STejun Heo 
6023704bc669SJungseung Lee /**
6024704bc669SJungseung Lee  * show_freezable_workqueues - dump freezable workqueue state
6025704bc669SJungseung Lee  *
6026704bc669SJungseung Lee  * Called from try_to_freeze_tasks() and prints out all freezable workqueues
6027704bc669SJungseung Lee  * still busy.
6028704bc669SJungseung Lee  */
6029704bc669SJungseung Lee void show_freezable_workqueues(void)
6030704bc669SJungseung Lee {
6031704bc669SJungseung Lee 	struct workqueue_struct *wq;
6032704bc669SJungseung Lee 
6033704bc669SJungseung Lee 	rcu_read_lock();
6034704bc669SJungseung Lee 
6035704bc669SJungseung Lee 	pr_info("Showing freezable workqueues that are still busy:\n");
6036704bc669SJungseung Lee 
6037704bc669SJungseung Lee 	list_for_each_entry_rcu(wq, &workqueues, list) {
6038704bc669SJungseung Lee 		if (!(wq->flags & WQ_FREEZABLE))
6039704bc669SJungseung Lee 			continue;
6040704bc669SJungseung Lee 		show_one_workqueue(wq);
6041704bc669SJungseung Lee 	}
6042704bc669SJungseung Lee 
6043704bc669SJungseung Lee 	rcu_read_unlock();
6044704bc669SJungseung Lee }
6045704bc669SJungseung Lee 
60466b59808bSTejun Heo /* used to show worker information through /proc/PID/{comm,stat,status} */
60476b59808bSTejun Heo void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
60486b59808bSTejun Heo {
60496b59808bSTejun Heo 	int off;
60506b59808bSTejun Heo 
60516b59808bSTejun Heo 	/* always show the actual comm */
60526b59808bSTejun Heo 	off = strscpy(buf, task->comm, size);
60536b59808bSTejun Heo 	if (off < 0)
60546b59808bSTejun Heo 		return;
60556b59808bSTejun Heo 
6056197f6accSTejun Heo 	/* stabilize PF_WQ_WORKER and worker pool association */
60576b59808bSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
60586b59808bSTejun Heo 
6059197f6accSTejun Heo 	if (task->flags & PF_WQ_WORKER) {
6060197f6accSTejun Heo 		struct worker *worker = kthread_data(task);
6061197f6accSTejun Heo 		struct worker_pool *pool = worker->pool;
60626b59808bSTejun Heo 
60636b59808bSTejun Heo 		if (pool) {
6064a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock_irq(&pool->lock);
60656b59808bSTejun Heo 			/*
6066197f6accSTejun Heo 			 * ->desc tracks information (wq name or
6067197f6accSTejun Heo 			 * set_worker_desc()) for the latest execution.  If
6068197f6accSTejun Heo 			 * current, prepend '+', otherwise '-'.
60696b59808bSTejun Heo 			 */
60706b59808bSTejun Heo 			if (worker->desc[0] != '\0') {
60716b59808bSTejun Heo 				if (worker->current_work)
60726b59808bSTejun Heo 					scnprintf(buf + off, size - off, "+%s",
60736b59808bSTejun Heo 						  worker->desc);
60746b59808bSTejun Heo 				else
60756b59808bSTejun Heo 					scnprintf(buf + off, size - off, "-%s",
60766b59808bSTejun Heo 						  worker->desc);
60776b59808bSTejun Heo 			}
6078a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pool->lock);
60796b59808bSTejun Heo 		}
6080197f6accSTejun Heo 	}
60816b59808bSTejun Heo 
60826b59808bSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
60836b59808bSTejun Heo }
60846b59808bSTejun Heo 
608566448bc2SMathieu Malaterre #ifdef CONFIG_SMP
608666448bc2SMathieu Malaterre 
6087db7bccf4STejun Heo /*
6088db7bccf4STejun Heo  * CPU hotplug.
6089db7bccf4STejun Heo  *
6090e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
6091112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
6092706026c2STejun Heo  * pool which make migrating pending and scheduled works very
6093e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
609494cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
6095e22bee78STejun Heo  * blocked draining impractical.
6096e22bee78STejun Heo  *
609724647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
6098628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
6099628c78e7STejun Heo  * cpu comes back online.
6100db7bccf4STejun Heo  */
6101db7bccf4STejun Heo 
6102e8b3f8dbSLai Jiangshan static void unbind_workers(int cpu)
6103db7bccf4STejun Heo {
61044ce62e9eSTejun Heo 	struct worker_pool *pool;
6105db7bccf4STejun Heo 	struct worker *worker;
6106db7bccf4STejun Heo 
6107f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
61081258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
6109a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
6110e22bee78STejun Heo 
6111f2d5a0eeSTejun Heo 		/*
611292f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
611394cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
611411b45b0bSLai Jiangshan 		 * must be on the cpu.  After this, they may become diasporas.
6115b4ac9384SLai Jiangshan 		 * And the preemption disabled section in their sched callbacks
6116b4ac9384SLai Jiangshan 		 * are guaranteed to see WORKER_UNBOUND since the code here
6117b4ac9384SLai Jiangshan 		 * is on the same cpu.
6118f2d5a0eeSTejun Heo 		 */
6119da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
6120403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
6121db7bccf4STejun Heo 
612224647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
6123f2d5a0eeSTejun Heo 
6124e22bee78STejun Heo 		/*
6125989442d7SLai Jiangshan 		 * The handling of nr_running in sched callbacks are disabled
6126989442d7SLai Jiangshan 		 * now.  Zap nr_running.  After this, nr_running stays zero and
6127989442d7SLai Jiangshan 		 * need_more_worker() and keep_working() are always true as
6128989442d7SLai Jiangshan 		 * long as the worklist is not empty.  This pool now behaves as
6129989442d7SLai Jiangshan 		 * an unbound (in terms of concurrency management) pool which
6130eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
6131e22bee78STejun Heo 		 */
6132bc35f7efSLai Jiangshan 		pool->nr_running = 0;
6133eb283428SLai Jiangshan 
6134eb283428SLai Jiangshan 		/*
6135eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
6136eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
6137eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
6138eb283428SLai Jiangshan 		 */
61390219a352STejun Heo 		kick_pool(pool);
6140989442d7SLai Jiangshan 
6141a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
6142989442d7SLai Jiangshan 
6143793777bcSValentin Schneider 		for_each_pool_worker(worker, pool)
6144793777bcSValentin Schneider 			unbind_worker(worker);
6145989442d7SLai Jiangshan 
6146989442d7SLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
6147eb283428SLai Jiangshan 	}
6148db7bccf4STejun Heo }
6149db7bccf4STejun Heo 
6150bd7c089eSTejun Heo /**
6151bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
6152bd7c089eSTejun Heo  * @pool: pool of interest
6153bd7c089eSTejun Heo  *
6154a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
6155bd7c089eSTejun Heo  */
6156bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
6157bd7c089eSTejun Heo {
6158a9ab775bSTejun Heo 	struct worker *worker;
6159bd7c089eSTejun Heo 
61601258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
6161bd7c089eSTejun Heo 
6162bd7c089eSTejun Heo 	/*
6163a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
6164a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
6165402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
6166a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
6167a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
6168bd7c089eSTejun Heo 	 */
6169c63a2e52SValentin Schneider 	for_each_pool_worker(worker, pool) {
6170c63a2e52SValentin Schneider 		kthread_set_per_cpu(worker->task, pool->cpu);
6171c63a2e52SValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
61729546b29eSTejun Heo 						  pool_allowed_cpus(pool)) < 0);
6173c63a2e52SValentin Schneider 	}
6174a9ab775bSTejun Heo 
6175a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
6176f7c17d26SWanpeng Li 
61773de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
6178a9ab775bSTejun Heo 
6179da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
6180a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
6181a9ab775bSTejun Heo 
6182a9ab775bSTejun Heo 		/*
6183a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
6184a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
6185a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
6186a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
6187a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
6188a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
6189a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
6190a9ab775bSTejun Heo 		 *
6191c95491edSMark Rutland 		 * WRITE_ONCE() is necessary because @worker->flags may be
6192a9ab775bSTejun Heo 		 * tested without holding any lock in
61936d25be57SThomas Gleixner 		 * wq_worker_running().  Without it, NOT_RUNNING test may
6194a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
6195a9ab775bSTejun Heo 		 * management operations.
6196bd7c089eSTejun Heo 		 */
6197a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
6198a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
6199a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
6200c95491edSMark Rutland 		WRITE_ONCE(worker->flags, worker_flags);
6201bd7c089eSTejun Heo 	}
6202a9ab775bSTejun Heo 
6203a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
6204bd7c089eSTejun Heo }
6205bd7c089eSTejun Heo 
62067dbc725eSTejun Heo /**
62077dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
62087dbc725eSTejun Heo  * @pool: unbound pool of interest
62097dbc725eSTejun Heo  * @cpu: the CPU which is coming up
62107dbc725eSTejun Heo  *
62117dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
62127dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
62137dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
62147dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
62157dbc725eSTejun Heo  */
62167dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
62177dbc725eSTejun Heo {
62187dbc725eSTejun Heo 	static cpumask_t cpumask;
62197dbc725eSTejun Heo 	struct worker *worker;
62207dbc725eSTejun Heo 
62211258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
62227dbc725eSTejun Heo 
62237dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
62247dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
62257dbc725eSTejun Heo 		return;
62267dbc725eSTejun Heo 
62277dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
62287dbc725eSTejun Heo 
62297dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
6230da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
6231d945b5e9SPeter Zijlstra 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
62327dbc725eSTejun Heo }
62337dbc725eSTejun Heo 
62347ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
62351da177e4SLinus Torvalds {
62364ce62e9eSTejun Heo 	struct worker_pool *pool;
62371da177e4SLinus Torvalds 
6238f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
62393ce63377STejun Heo 		if (pool->nr_workers)
62403ce63377STejun Heo 			continue;
6241051e1850SLai Jiangshan 		if (!create_worker(pool))
62427ee681b2SThomas Gleixner 			return -ENOMEM;
62433af24433SOleg Nesterov 	}
62447ee681b2SThomas Gleixner 	return 0;
62457ee681b2SThomas Gleixner }
62461da177e4SLinus Torvalds 
62477ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
62487ee681b2SThomas Gleixner {
62497ee681b2SThomas Gleixner 	struct worker_pool *pool;
62507ee681b2SThomas Gleixner 	struct workqueue_struct *wq;
62517ee681b2SThomas Gleixner 	int pi;
62527ee681b2SThomas Gleixner 
625368e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
62547dbc725eSTejun Heo 
62557dbc725eSTejun Heo 	for_each_pool(pool, pi) {
62564cb1ef64STejun Heo 		/* BH pools aren't affected by hotplug */
62574cb1ef64STejun Heo 		if (pool->flags & POOL_BH)
62584cb1ef64STejun Heo 			continue;
625994cf58bbSTejun Heo 
62604cb1ef64STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
6261f05b558dSLai Jiangshan 		if (pool->cpu == cpu)
626294cf58bbSTejun Heo 			rebind_workers(pool);
6263f05b558dSLai Jiangshan 		else if (pool->cpu < 0)
62647dbc725eSTejun Heo 			restore_unbound_workers_cpumask(pool, cpu);
62651258fae7STejun Heo 		mutex_unlock(&wq_pool_attach_mutex);
626694cf58bbSTejun Heo 	}
62677dbc725eSTejun Heo 
6268fef59c9cSTejun Heo 	/* update pod affinity of unbound workqueues */
62694cbfd3deSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
627084193c07STejun Heo 		struct workqueue_attrs *attrs = wq->unbound_attrs;
627184193c07STejun Heo 
627284193c07STejun Heo 		if (attrs) {
627384193c07STejun Heo 			const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
62744cbfd3deSTejun Heo 			int tcpu;
62754cbfd3deSTejun Heo 
627684193c07STejun Heo 			for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
6277fef59c9cSTejun Heo 				wq_update_pod(wq, tcpu, cpu, true);
62785797b1c1STejun Heo 
62795797b1c1STejun Heo 			mutex_lock(&wq->mutex);
62805797b1c1STejun Heo 			wq_update_node_max_active(wq, -1);
62815797b1c1STejun Heo 			mutex_unlock(&wq->mutex);
62824cbfd3deSTejun Heo 		}
62834cbfd3deSTejun Heo 	}
62844c16bd32STejun Heo 
628568e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
62867ee681b2SThomas Gleixner 	return 0;
628765758202STejun Heo }
628865758202STejun Heo 
62897ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
629065758202STejun Heo {
62914c16bd32STejun Heo 	struct workqueue_struct *wq;
62928db25e78STejun Heo 
62934c16bd32STejun Heo 	/* unbinding per-cpu workers should happen on the local CPU */
6294e8b3f8dbSLai Jiangshan 	if (WARN_ON(cpu != smp_processor_id()))
6295e8b3f8dbSLai Jiangshan 		return -1;
6296e8b3f8dbSLai Jiangshan 
6297e8b3f8dbSLai Jiangshan 	unbind_workers(cpu);
62984c16bd32STejun Heo 
6299fef59c9cSTejun Heo 	/* update pod affinity of unbound workqueues */
63004c16bd32STejun Heo 	mutex_lock(&wq_pool_mutex);
63014cbfd3deSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
630284193c07STejun Heo 		struct workqueue_attrs *attrs = wq->unbound_attrs;
630384193c07STejun Heo 
630484193c07STejun Heo 		if (attrs) {
630584193c07STejun Heo 			const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
63064cbfd3deSTejun Heo 			int tcpu;
63074cbfd3deSTejun Heo 
630884193c07STejun Heo 			for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
6309fef59c9cSTejun Heo 				wq_update_pod(wq, tcpu, cpu, false);
63105797b1c1STejun Heo 
63115797b1c1STejun Heo 			mutex_lock(&wq->mutex);
63125797b1c1STejun Heo 			wq_update_node_max_active(wq, cpu);
63135797b1c1STejun Heo 			mutex_unlock(&wq->mutex);
63144cbfd3deSTejun Heo 		}
63154cbfd3deSTejun Heo 	}
63164c16bd32STejun Heo 	mutex_unlock(&wq_pool_mutex);
63174c16bd32STejun Heo 
63187ee681b2SThomas Gleixner 	return 0;
631965758202STejun Heo }
632065758202STejun Heo 
63212d3854a3SRusty Russell struct work_for_cpu {
6322ed48ece2STejun Heo 	struct work_struct work;
63232d3854a3SRusty Russell 	long (*fn)(void *);
63242d3854a3SRusty Russell 	void *arg;
63252d3854a3SRusty Russell 	long ret;
63262d3854a3SRusty Russell };
63272d3854a3SRusty Russell 
6328ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
63292d3854a3SRusty Russell {
6330ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
6331ed48ece2STejun Heo 
63322d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
63332d3854a3SRusty Russell }
63342d3854a3SRusty Russell 
63352d3854a3SRusty Russell /**
6336265f3ed0SFrederic Weisbecker  * work_on_cpu_key - run a function in thread context on a particular cpu
63372d3854a3SRusty Russell  * @cpu: the cpu to run on
63382d3854a3SRusty Russell  * @fn: the function to run
63392d3854a3SRusty Russell  * @arg: the function arg
6340265f3ed0SFrederic Weisbecker  * @key: The lock class key for lock debugging purposes
63412d3854a3SRusty Russell  *
634231ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
63436b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
6344d185af30SYacine Belkadi  *
6345d185af30SYacine Belkadi  * Return: The value @fn returns.
63462d3854a3SRusty Russell  */
6347265f3ed0SFrederic Weisbecker long work_on_cpu_key(int cpu, long (*fn)(void *),
6348265f3ed0SFrederic Weisbecker 		     void *arg, struct lock_class_key *key)
63492d3854a3SRusty Russell {
6350ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
63512d3854a3SRusty Russell 
6352265f3ed0SFrederic Weisbecker 	INIT_WORK_ONSTACK_KEY(&wfc.work, work_for_cpu_fn, key);
6353ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
635412997d1aSBjorn Helgaas 	flush_work(&wfc.work);
6355440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
63562d3854a3SRusty Russell 	return wfc.ret;
63572d3854a3SRusty Russell }
6358265f3ed0SFrederic Weisbecker EXPORT_SYMBOL_GPL(work_on_cpu_key);
63590e8d6a93SThomas Gleixner 
63600e8d6a93SThomas Gleixner /**
6361265f3ed0SFrederic Weisbecker  * work_on_cpu_safe_key - run a function in thread context on a particular cpu
63620e8d6a93SThomas Gleixner  * @cpu: the cpu to run on
63630e8d6a93SThomas Gleixner  * @fn:  the function to run
63640e8d6a93SThomas Gleixner  * @arg: the function argument
6365265f3ed0SFrederic Weisbecker  * @key: The lock class key for lock debugging purposes
63660e8d6a93SThomas Gleixner  *
63670e8d6a93SThomas Gleixner  * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
63680e8d6a93SThomas Gleixner  * any locks which would prevent @fn from completing.
63690e8d6a93SThomas Gleixner  *
63700e8d6a93SThomas Gleixner  * Return: The value @fn returns.
63710e8d6a93SThomas Gleixner  */
6372265f3ed0SFrederic Weisbecker long work_on_cpu_safe_key(int cpu, long (*fn)(void *),
6373265f3ed0SFrederic Weisbecker 			  void *arg, struct lock_class_key *key)
63740e8d6a93SThomas Gleixner {
63750e8d6a93SThomas Gleixner 	long ret = -ENODEV;
63760e8d6a93SThomas Gleixner 
6377ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
63780e8d6a93SThomas Gleixner 	if (cpu_online(cpu))
6379265f3ed0SFrederic Weisbecker 		ret = work_on_cpu_key(cpu, fn, arg, key);
6380ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
63810e8d6a93SThomas Gleixner 	return ret;
63820e8d6a93SThomas Gleixner }
6383265f3ed0SFrederic Weisbecker EXPORT_SYMBOL_GPL(work_on_cpu_safe_key);
63842d3854a3SRusty Russell #endif /* CONFIG_SMP */
63852d3854a3SRusty Russell 
6386a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
6387e7577c50SRusty Russell 
6388a0a1a5fdSTejun Heo /**
6389a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
6390a0a1a5fdSTejun Heo  *
639158a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
6392f97a4a1aSLai Jiangshan  * workqueues will queue new works to their inactive_works list instead of
6393706026c2STejun Heo  * pool->worklist.
6394a0a1a5fdSTejun Heo  *
6395a0a1a5fdSTejun Heo  * CONTEXT:
6396a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
6397a0a1a5fdSTejun Heo  */
6398a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
6399a0a1a5fdSTejun Heo {
640024b8a847STejun Heo 	struct workqueue_struct *wq;
6401a0a1a5fdSTejun Heo 
640268e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
6403a0a1a5fdSTejun Heo 
64046183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
6405a0a1a5fdSTejun Heo 	workqueue_freezing = true;
6406a0a1a5fdSTejun Heo 
640724b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
6408a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
6409a045a272STejun Heo 		wq_adjust_max_active(wq);
6410a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
6411a1056305STejun Heo 	}
64125bcab335STejun Heo 
641368e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
6414a0a1a5fdSTejun Heo }
6415a0a1a5fdSTejun Heo 
6416a0a1a5fdSTejun Heo /**
641758a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
6418a0a1a5fdSTejun Heo  *
6419a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
6420a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
6421a0a1a5fdSTejun Heo  *
6422a0a1a5fdSTejun Heo  * CONTEXT:
642368e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
6424a0a1a5fdSTejun Heo  *
6425d185af30SYacine Belkadi  * Return:
642658a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
642758a69cb4STejun Heo  * is complete.
6428a0a1a5fdSTejun Heo  */
6429a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
6430a0a1a5fdSTejun Heo {
6431a0a1a5fdSTejun Heo 	bool busy = false;
643224b8a847STejun Heo 	struct workqueue_struct *wq;
643324b8a847STejun Heo 	struct pool_workqueue *pwq;
6434a0a1a5fdSTejun Heo 
643568e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
6436a0a1a5fdSTejun Heo 
64376183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
6438a0a1a5fdSTejun Heo 
643924b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
644024b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
644124b8a847STejun Heo 			continue;
6442a0a1a5fdSTejun Heo 		/*
6443a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
6444a0a1a5fdSTejun Heo 		 * to peek without lock.
6445a0a1a5fdSTejun Heo 		 */
644624acfb71SThomas Gleixner 		rcu_read_lock();
644724b8a847STejun Heo 		for_each_pwq(pwq, wq) {
64486183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
6449112202d9STejun Heo 			if (pwq->nr_active) {
6450a0a1a5fdSTejun Heo 				busy = true;
645124acfb71SThomas Gleixner 				rcu_read_unlock();
6452a0a1a5fdSTejun Heo 				goto out_unlock;
6453a0a1a5fdSTejun Heo 			}
6454a0a1a5fdSTejun Heo 		}
645524acfb71SThomas Gleixner 		rcu_read_unlock();
6456a0a1a5fdSTejun Heo 	}
6457a0a1a5fdSTejun Heo out_unlock:
645868e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
6459a0a1a5fdSTejun Heo 	return busy;
6460a0a1a5fdSTejun Heo }
6461a0a1a5fdSTejun Heo 
6462a0a1a5fdSTejun Heo /**
6463a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
6464a0a1a5fdSTejun Heo  *
6465a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
6466706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
6467a0a1a5fdSTejun Heo  *
6468a0a1a5fdSTejun Heo  * CONTEXT:
6469a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
6470a0a1a5fdSTejun Heo  */
6471a0a1a5fdSTejun Heo void thaw_workqueues(void)
6472a0a1a5fdSTejun Heo {
647324b8a847STejun Heo 	struct workqueue_struct *wq;
6474a0a1a5fdSTejun Heo 
647568e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
6476a0a1a5fdSTejun Heo 
6477a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
6478a0a1a5fdSTejun Heo 		goto out_unlock;
6479a0a1a5fdSTejun Heo 
648074b414eaSLai Jiangshan 	workqueue_freezing = false;
648124b8a847STejun Heo 
648224b8a847STejun Heo 	/* restore max_active and repopulate worklist */
648324b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
6484a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
6485a045a272STejun Heo 		wq_adjust_max_active(wq);
6486a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
648724b8a847STejun Heo 	}
648824b8a847STejun Heo 
6489a0a1a5fdSTejun Heo out_unlock:
649068e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
6491a0a1a5fdSTejun Heo }
6492a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
6493a0a1a5fdSTejun Heo 
649499c621efSLai Jiangshan static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
6495042f7df1SLai Jiangshan {
6496042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
6497042f7df1SLai Jiangshan 	int ret = 0;
6498042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
6499042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
6500042f7df1SLai Jiangshan 
6501042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
6502042f7df1SLai Jiangshan 
6503042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
6504042f7df1SLai Jiangshan 		if (!(wq->flags & WQ_UNBOUND))
6505042f7df1SLai Jiangshan 			continue;
6506ca10d851SWaiman Long 
6507042f7df1SLai Jiangshan 		/* creating multiple pwqs breaks ordering guarantee */
6508ca10d851SWaiman Long 		if (!list_empty(&wq->pwqs)) {
6509ca10d851SWaiman Long 			if (wq->flags & __WQ_ORDERED_EXPLICIT)
6510042f7df1SLai Jiangshan 				continue;
6511ca10d851SWaiman Long 			wq->flags &= ~__WQ_ORDERED;
6512ca10d851SWaiman Long 		}
6513042f7df1SLai Jiangshan 
651499c621efSLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
651584193c07STejun Heo 		if (IS_ERR(ctx)) {
651684193c07STejun Heo 			ret = PTR_ERR(ctx);
6517042f7df1SLai Jiangshan 			break;
6518042f7df1SLai Jiangshan 		}
6519042f7df1SLai Jiangshan 
6520042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
6521042f7df1SLai Jiangshan 	}
6522042f7df1SLai Jiangshan 
6523042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
6524042f7df1SLai Jiangshan 		if (!ret)
6525042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
6526042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
6527042f7df1SLai Jiangshan 	}
6528042f7df1SLai Jiangshan 
652999c621efSLai Jiangshan 	if (!ret) {
653099c621efSLai Jiangshan 		mutex_lock(&wq_pool_attach_mutex);
653199c621efSLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
653299c621efSLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
653399c621efSLai Jiangshan 	}
6534042f7df1SLai Jiangshan 	return ret;
6535042f7df1SLai Jiangshan }
6536042f7df1SLai Jiangshan 
6537042f7df1SLai Jiangshan /**
6538fe28f631SWaiman Long  * workqueue_unbound_exclude_cpumask - Exclude given CPUs from unbound cpumask
6539fe28f631SWaiman Long  * @exclude_cpumask: the cpumask to be excluded from wq_unbound_cpumask
6540fe28f631SWaiman Long  *
6541fe28f631SWaiman Long  * This function can be called from cpuset code to provide a set of isolated
6542fe28f631SWaiman Long  * CPUs that should be excluded from wq_unbound_cpumask. The caller must hold
6543fe28f631SWaiman Long  * either cpus_read_lock or cpus_write_lock.
6544fe28f631SWaiman Long  */
6545fe28f631SWaiman Long int workqueue_unbound_exclude_cpumask(cpumask_var_t exclude_cpumask)
6546fe28f631SWaiman Long {
6547fe28f631SWaiman Long 	cpumask_var_t cpumask;
6548fe28f631SWaiman Long 	int ret = 0;
6549fe28f631SWaiman Long 
6550fe28f631SWaiman Long 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
6551fe28f631SWaiman Long 		return -ENOMEM;
6552fe28f631SWaiman Long 
6553fe28f631SWaiman Long 	lockdep_assert_cpus_held();
6554fe28f631SWaiman Long 	mutex_lock(&wq_pool_mutex);
6555fe28f631SWaiman Long 
6556fe28f631SWaiman Long 	/* Save the current isolated cpumask & export it via sysfs */
6557fe28f631SWaiman Long 	cpumask_copy(wq_isolated_cpumask, exclude_cpumask);
6558fe28f631SWaiman Long 
6559fe28f631SWaiman Long 	/*
6560fe28f631SWaiman Long 	 * If the operation fails, it will fall back to
6561fe28f631SWaiman Long 	 * wq_requested_unbound_cpumask which is initially set to
6562fe28f631SWaiman Long 	 * (HK_TYPE_WQ ∩ HK_TYPE_DOMAIN) house keeping mask and rewritten
6563fe28f631SWaiman Long 	 * by any subsequent write to workqueue/cpumask sysfs file.
6564fe28f631SWaiman Long 	 */
6565fe28f631SWaiman Long 	if (!cpumask_andnot(cpumask, wq_requested_unbound_cpumask, exclude_cpumask))
6566fe28f631SWaiman Long 		cpumask_copy(cpumask, wq_requested_unbound_cpumask);
6567fe28f631SWaiman Long 	if (!cpumask_equal(cpumask, wq_unbound_cpumask))
6568fe28f631SWaiman Long 		ret = workqueue_apply_unbound_cpumask(cpumask);
6569fe28f631SWaiman Long 
6570fe28f631SWaiman Long 	mutex_unlock(&wq_pool_mutex);
6571fe28f631SWaiman Long 	free_cpumask_var(cpumask);
6572fe28f631SWaiman Long 	return ret;
6573fe28f631SWaiman Long }
6574fe28f631SWaiman Long 
657563c5484eSTejun Heo static int parse_affn_scope(const char *val)
657663c5484eSTejun Heo {
657763c5484eSTejun Heo 	int i;
657863c5484eSTejun Heo 
657963c5484eSTejun Heo 	for (i = 0; i < ARRAY_SIZE(wq_affn_names); i++) {
658063c5484eSTejun Heo 		if (!strncasecmp(val, wq_affn_names[i], strlen(wq_affn_names[i])))
658163c5484eSTejun Heo 			return i;
658263c5484eSTejun Heo 	}
658363c5484eSTejun Heo 	return -EINVAL;
658463c5484eSTejun Heo }
658563c5484eSTejun Heo 
658663c5484eSTejun Heo static int wq_affn_dfl_set(const char *val, const struct kernel_param *kp)
658763c5484eSTejun Heo {
6588523a301eSTejun Heo 	struct workqueue_struct *wq;
6589523a301eSTejun Heo 	int affn, cpu;
659063c5484eSTejun Heo 
659163c5484eSTejun Heo 	affn = parse_affn_scope(val);
659263c5484eSTejun Heo 	if (affn < 0)
659363c5484eSTejun Heo 		return affn;
6594523a301eSTejun Heo 	if (affn == WQ_AFFN_DFL)
6595523a301eSTejun Heo 		return -EINVAL;
6596523a301eSTejun Heo 
6597523a301eSTejun Heo 	cpus_read_lock();
6598523a301eSTejun Heo 	mutex_lock(&wq_pool_mutex);
659963c5484eSTejun Heo 
660063c5484eSTejun Heo 	wq_affn_dfl = affn;
6601523a301eSTejun Heo 
6602523a301eSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
6603523a301eSTejun Heo 		for_each_online_cpu(cpu) {
6604523a301eSTejun Heo 			wq_update_pod(wq, cpu, cpu, true);
6605523a301eSTejun Heo 		}
6606523a301eSTejun Heo 	}
6607523a301eSTejun Heo 
6608523a301eSTejun Heo 	mutex_unlock(&wq_pool_mutex);
6609523a301eSTejun Heo 	cpus_read_unlock();
6610523a301eSTejun Heo 
661163c5484eSTejun Heo 	return 0;
661263c5484eSTejun Heo }
661363c5484eSTejun Heo 
661463c5484eSTejun Heo static int wq_affn_dfl_get(char *buffer, const struct kernel_param *kp)
661563c5484eSTejun Heo {
661663c5484eSTejun Heo 	return scnprintf(buffer, PAGE_SIZE, "%s\n", wq_affn_names[wq_affn_dfl]);
661763c5484eSTejun Heo }
661863c5484eSTejun Heo 
661963c5484eSTejun Heo static const struct kernel_param_ops wq_affn_dfl_ops = {
662063c5484eSTejun Heo 	.set	= wq_affn_dfl_set,
662163c5484eSTejun Heo 	.get	= wq_affn_dfl_get,
662263c5484eSTejun Heo };
662363c5484eSTejun Heo 
662463c5484eSTejun Heo module_param_cb(default_affinity_scope, &wq_affn_dfl_ops, NULL, 0644);
662563c5484eSTejun Heo 
66266ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
66276ba94429SFrederic Weisbecker /*
66286ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
66296ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
66306ba94429SFrederic Weisbecker  * following attributes.
66316ba94429SFrederic Weisbecker  *
66326ba94429SFrederic Weisbecker  *  per_cpu		RO bool	: whether the workqueue is per-cpu or unbound
66336ba94429SFrederic Weisbecker  *  max_active		RW int	: maximum number of in-flight work items
66346ba94429SFrederic Weisbecker  *
66356ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
66366ba94429SFrederic Weisbecker  *
66376ba94429SFrederic Weisbecker  *  nice		RW int	: nice value of the workers
66386ba94429SFrederic Weisbecker  *  cpumask		RW mask	: bitmask of allowed CPUs for the workers
663963c5484eSTejun Heo  *  affinity_scope	RW str  : worker CPU affinity scope (cache, numa, none)
66408639ecebSTejun Heo  *  affinity_strict	RW bool : worker CPU affinity is strict
66416ba94429SFrederic Weisbecker  */
66426ba94429SFrederic Weisbecker struct wq_device {
66436ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
66446ba94429SFrederic Weisbecker 	struct device			dev;
66456ba94429SFrederic Weisbecker };
66466ba94429SFrederic Weisbecker 
66476ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
66486ba94429SFrederic Weisbecker {
66496ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
66506ba94429SFrederic Weisbecker 
66516ba94429SFrederic Weisbecker 	return wq_dev->wq;
66526ba94429SFrederic Weisbecker }
66536ba94429SFrederic Weisbecker 
66546ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
66556ba94429SFrederic Weisbecker 			    char *buf)
66566ba94429SFrederic Weisbecker {
66576ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
66586ba94429SFrederic Weisbecker 
66596ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
66606ba94429SFrederic Weisbecker }
66616ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
66626ba94429SFrederic Weisbecker 
66636ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
66646ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
66656ba94429SFrederic Weisbecker {
66666ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
66676ba94429SFrederic Weisbecker 
66686ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
66696ba94429SFrederic Weisbecker }
66706ba94429SFrederic Weisbecker 
66716ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
66726ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
66736ba94429SFrederic Weisbecker 				size_t count)
66746ba94429SFrederic Weisbecker {
66756ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
66766ba94429SFrederic Weisbecker 	int val;
66776ba94429SFrederic Weisbecker 
66786ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
66796ba94429SFrederic Weisbecker 		return -EINVAL;
66806ba94429SFrederic Weisbecker 
66816ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
66826ba94429SFrederic Weisbecker 	return count;
66836ba94429SFrederic Weisbecker }
66846ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
66856ba94429SFrederic Weisbecker 
66866ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
66876ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
66886ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
66896ba94429SFrederic Weisbecker 	NULL,
66906ba94429SFrederic Weisbecker };
66916ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
66926ba94429SFrederic Weisbecker 
669349277a5bSWaiman Long static void apply_wqattrs_lock(void)
669449277a5bSWaiman Long {
669549277a5bSWaiman Long 	/* CPUs should stay stable across pwq creations and installations */
669649277a5bSWaiman Long 	cpus_read_lock();
669749277a5bSWaiman Long 	mutex_lock(&wq_pool_mutex);
669849277a5bSWaiman Long }
669949277a5bSWaiman Long 
670049277a5bSWaiman Long static void apply_wqattrs_unlock(void)
670149277a5bSWaiman Long {
670249277a5bSWaiman Long 	mutex_unlock(&wq_pool_mutex);
670349277a5bSWaiman Long 	cpus_read_unlock();
670449277a5bSWaiman Long }
670549277a5bSWaiman Long 
67066ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
67076ba94429SFrederic Weisbecker 			    char *buf)
67086ba94429SFrederic Weisbecker {
67096ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
67106ba94429SFrederic Weisbecker 	int written;
67116ba94429SFrederic Weisbecker 
67126ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
67136ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
67146ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
67156ba94429SFrederic Weisbecker 
67166ba94429SFrederic Weisbecker 	return written;
67176ba94429SFrederic Weisbecker }
67186ba94429SFrederic Weisbecker 
67196ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
67206ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
67216ba94429SFrederic Weisbecker {
67226ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
67236ba94429SFrederic Weisbecker 
6724899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
6725899a94feSLai Jiangshan 
6726be69d00dSThomas Gleixner 	attrs = alloc_workqueue_attrs();
67276ba94429SFrederic Weisbecker 	if (!attrs)
67286ba94429SFrederic Weisbecker 		return NULL;
67296ba94429SFrederic Weisbecker 
67306ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
67316ba94429SFrederic Weisbecker 	return attrs;
67326ba94429SFrederic Weisbecker }
67336ba94429SFrederic Weisbecker 
67346ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
67356ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
67366ba94429SFrederic Weisbecker {
67376ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
67386ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
6739d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
6740d4d3e257SLai Jiangshan 
6741d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
67426ba94429SFrederic Weisbecker 
67436ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
67446ba94429SFrederic Weisbecker 	if (!attrs)
6745d4d3e257SLai Jiangshan 		goto out_unlock;
67466ba94429SFrederic Weisbecker 
67476ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
67486ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
6749d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
67506ba94429SFrederic Weisbecker 	else
67516ba94429SFrederic Weisbecker 		ret = -EINVAL;
67526ba94429SFrederic Weisbecker 
6753d4d3e257SLai Jiangshan out_unlock:
6754d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
67556ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
67566ba94429SFrederic Weisbecker 	return ret ?: count;
67576ba94429SFrederic Weisbecker }
67586ba94429SFrederic Weisbecker 
67596ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
67606ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
67616ba94429SFrederic Weisbecker {
67626ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
67636ba94429SFrederic Weisbecker 	int written;
67646ba94429SFrederic Weisbecker 
67656ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
67666ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
67676ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
67686ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
67696ba94429SFrederic Weisbecker 	return written;
67706ba94429SFrederic Weisbecker }
67716ba94429SFrederic Weisbecker 
67726ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
67736ba94429SFrederic Weisbecker 				struct device_attribute *attr,
67746ba94429SFrederic Weisbecker 				const char *buf, size_t count)
67756ba94429SFrederic Weisbecker {
67766ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
67776ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
6778d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
6779d4d3e257SLai Jiangshan 
6780d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
67816ba94429SFrederic Weisbecker 
67826ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
67836ba94429SFrederic Weisbecker 	if (!attrs)
6784d4d3e257SLai Jiangshan 		goto out_unlock;
67856ba94429SFrederic Weisbecker 
67866ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
67876ba94429SFrederic Weisbecker 	if (!ret)
6788d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
67896ba94429SFrederic Weisbecker 
6790d4d3e257SLai Jiangshan out_unlock:
6791d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
67926ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
67936ba94429SFrederic Weisbecker 	return ret ?: count;
67946ba94429SFrederic Weisbecker }
67956ba94429SFrederic Weisbecker 
679663c5484eSTejun Heo static ssize_t wq_affn_scope_show(struct device *dev,
679763c5484eSTejun Heo 				  struct device_attribute *attr, char *buf)
679863c5484eSTejun Heo {
679963c5484eSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
680063c5484eSTejun Heo 	int written;
680163c5484eSTejun Heo 
680263c5484eSTejun Heo 	mutex_lock(&wq->mutex);
6803523a301eSTejun Heo 	if (wq->unbound_attrs->affn_scope == WQ_AFFN_DFL)
6804523a301eSTejun Heo 		written = scnprintf(buf, PAGE_SIZE, "%s (%s)\n",
6805523a301eSTejun Heo 				    wq_affn_names[WQ_AFFN_DFL],
6806523a301eSTejun Heo 				    wq_affn_names[wq_affn_dfl]);
6807523a301eSTejun Heo 	else
680863c5484eSTejun Heo 		written = scnprintf(buf, PAGE_SIZE, "%s\n",
680963c5484eSTejun Heo 				    wq_affn_names[wq->unbound_attrs->affn_scope]);
681063c5484eSTejun Heo 	mutex_unlock(&wq->mutex);
681163c5484eSTejun Heo 
681263c5484eSTejun Heo 	return written;
681363c5484eSTejun Heo }
681463c5484eSTejun Heo 
681563c5484eSTejun Heo static ssize_t wq_affn_scope_store(struct device *dev,
681663c5484eSTejun Heo 				   struct device_attribute *attr,
681763c5484eSTejun Heo 				   const char *buf, size_t count)
681863c5484eSTejun Heo {
681963c5484eSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
682063c5484eSTejun Heo 	struct workqueue_attrs *attrs;
682163c5484eSTejun Heo 	int affn, ret = -ENOMEM;
682263c5484eSTejun Heo 
682363c5484eSTejun Heo 	affn = parse_affn_scope(buf);
682463c5484eSTejun Heo 	if (affn < 0)
682563c5484eSTejun Heo 		return affn;
682663c5484eSTejun Heo 
682763c5484eSTejun Heo 	apply_wqattrs_lock();
682863c5484eSTejun Heo 	attrs = wq_sysfs_prep_attrs(wq);
682963c5484eSTejun Heo 	if (attrs) {
683063c5484eSTejun Heo 		attrs->affn_scope = affn;
683163c5484eSTejun Heo 		ret = apply_workqueue_attrs_locked(wq, attrs);
683263c5484eSTejun Heo 	}
683363c5484eSTejun Heo 	apply_wqattrs_unlock();
683463c5484eSTejun Heo 	free_workqueue_attrs(attrs);
683563c5484eSTejun Heo 	return ret ?: count;
683663c5484eSTejun Heo }
683763c5484eSTejun Heo 
68388639ecebSTejun Heo static ssize_t wq_affinity_strict_show(struct device *dev,
68398639ecebSTejun Heo 				       struct device_attribute *attr, char *buf)
68408639ecebSTejun Heo {
68418639ecebSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
68428639ecebSTejun Heo 
68438639ecebSTejun Heo 	return scnprintf(buf, PAGE_SIZE, "%d\n",
68448639ecebSTejun Heo 			 wq->unbound_attrs->affn_strict);
68458639ecebSTejun Heo }
68468639ecebSTejun Heo 
68478639ecebSTejun Heo static ssize_t wq_affinity_strict_store(struct device *dev,
68488639ecebSTejun Heo 					struct device_attribute *attr,
68498639ecebSTejun Heo 					const char *buf, size_t count)
68508639ecebSTejun Heo {
68518639ecebSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
68528639ecebSTejun Heo 	struct workqueue_attrs *attrs;
68538639ecebSTejun Heo 	int v, ret = -ENOMEM;
68548639ecebSTejun Heo 
68558639ecebSTejun Heo 	if (sscanf(buf, "%d", &v) != 1)
68568639ecebSTejun Heo 		return -EINVAL;
68578639ecebSTejun Heo 
68588639ecebSTejun Heo 	apply_wqattrs_lock();
68598639ecebSTejun Heo 	attrs = wq_sysfs_prep_attrs(wq);
68608639ecebSTejun Heo 	if (attrs) {
68618639ecebSTejun Heo 		attrs->affn_strict = (bool)v;
68628639ecebSTejun Heo 		ret = apply_workqueue_attrs_locked(wq, attrs);
68638639ecebSTejun Heo 	}
68648639ecebSTejun Heo 	apply_wqattrs_unlock();
68658639ecebSTejun Heo 	free_workqueue_attrs(attrs);
68668639ecebSTejun Heo 	return ret ?: count;
68678639ecebSTejun Heo }
68688639ecebSTejun Heo 
68696ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
68706ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
68716ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
687263c5484eSTejun Heo 	__ATTR(affinity_scope, 0644, wq_affn_scope_show, wq_affn_scope_store),
68738639ecebSTejun Heo 	__ATTR(affinity_strict, 0644, wq_affinity_strict_show, wq_affinity_strict_store),
68746ba94429SFrederic Weisbecker 	__ATTR_NULL,
68756ba94429SFrederic Weisbecker };
68766ba94429SFrederic Weisbecker 
68774f19b8e0STejun Heo static struct bus_type wq_subsys = {
68786ba94429SFrederic Weisbecker 	.name				= "workqueue",
68796ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
68806ba94429SFrederic Weisbecker };
68816ba94429SFrederic Weisbecker 
688249277a5bSWaiman Long /**
688349277a5bSWaiman Long  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
688449277a5bSWaiman Long  *  @cpumask: the cpumask to set
688549277a5bSWaiman Long  *
688649277a5bSWaiman Long  *  The low-level workqueues cpumask is a global cpumask that limits
688749277a5bSWaiman Long  *  the affinity of all unbound workqueues.  This function check the @cpumask
688849277a5bSWaiman Long  *  and apply it to all unbound workqueues and updates all pwqs of them.
688949277a5bSWaiman Long  *
689049277a5bSWaiman Long  *  Return:	0	- Success
689149277a5bSWaiman Long  *		-EINVAL	- Invalid @cpumask
689249277a5bSWaiman Long  *		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
689349277a5bSWaiman Long  */
689449277a5bSWaiman Long static int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
689549277a5bSWaiman Long {
689649277a5bSWaiman Long 	int ret = -EINVAL;
689749277a5bSWaiman Long 
689849277a5bSWaiman Long 	/*
689949277a5bSWaiman Long 	 * Not excluding isolated cpus on purpose.
690049277a5bSWaiman Long 	 * If the user wishes to include them, we allow that.
690149277a5bSWaiman Long 	 */
690249277a5bSWaiman Long 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
690349277a5bSWaiman Long 	if (!cpumask_empty(cpumask)) {
690449277a5bSWaiman Long 		apply_wqattrs_lock();
690549277a5bSWaiman Long 		cpumask_copy(wq_requested_unbound_cpumask, cpumask);
690649277a5bSWaiman Long 		if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
690749277a5bSWaiman Long 			ret = 0;
690849277a5bSWaiman Long 			goto out_unlock;
690949277a5bSWaiman Long 		}
691049277a5bSWaiman Long 
691149277a5bSWaiman Long 		ret = workqueue_apply_unbound_cpumask(cpumask);
691249277a5bSWaiman Long 
691349277a5bSWaiman Long out_unlock:
691449277a5bSWaiman Long 		apply_wqattrs_unlock();
691549277a5bSWaiman Long 	}
691649277a5bSWaiman Long 
691749277a5bSWaiman Long 	return ret;
691849277a5bSWaiman Long }
691949277a5bSWaiman Long 
6920fe28f631SWaiman Long static ssize_t __wq_cpumask_show(struct device *dev,
6921fe28f631SWaiman Long 		struct device_attribute *attr, char *buf, cpumask_var_t mask)
6922b05a7928SFrederic Weisbecker {
6923b05a7928SFrederic Weisbecker 	int written;
6924b05a7928SFrederic Weisbecker 
6925042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
6926fe28f631SWaiman Long 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n", cpumask_pr_args(mask));
6927042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
6928b05a7928SFrederic Weisbecker 
6929b05a7928SFrederic Weisbecker 	return written;
6930b05a7928SFrederic Weisbecker }
6931b05a7928SFrederic Weisbecker 
6932fe28f631SWaiman Long static ssize_t wq_unbound_cpumask_show(struct device *dev,
6933fe28f631SWaiman Long 		struct device_attribute *attr, char *buf)
6934fe28f631SWaiman Long {
6935fe28f631SWaiman Long 	return __wq_cpumask_show(dev, attr, buf, wq_unbound_cpumask);
6936fe28f631SWaiman Long }
6937fe28f631SWaiman Long 
6938fe28f631SWaiman Long static ssize_t wq_requested_cpumask_show(struct device *dev,
6939fe28f631SWaiman Long 		struct device_attribute *attr, char *buf)
6940fe28f631SWaiman Long {
6941fe28f631SWaiman Long 	return __wq_cpumask_show(dev, attr, buf, wq_requested_unbound_cpumask);
6942fe28f631SWaiman Long }
6943fe28f631SWaiman Long 
6944fe28f631SWaiman Long static ssize_t wq_isolated_cpumask_show(struct device *dev,
6945fe28f631SWaiman Long 		struct device_attribute *attr, char *buf)
6946fe28f631SWaiman Long {
6947fe28f631SWaiman Long 	return __wq_cpumask_show(dev, attr, buf, wq_isolated_cpumask);
6948fe28f631SWaiman Long }
6949fe28f631SWaiman Long 
6950042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
6951042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
6952042f7df1SLai Jiangshan {
6953042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
6954042f7df1SLai Jiangshan 	int ret;
6955042f7df1SLai Jiangshan 
6956042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
6957042f7df1SLai Jiangshan 		return -ENOMEM;
6958042f7df1SLai Jiangshan 
6959042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
6960042f7df1SLai Jiangshan 	if (!ret)
6961042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
6962042f7df1SLai Jiangshan 
6963042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
6964042f7df1SLai Jiangshan 	return ret ? ret : count;
6965042f7df1SLai Jiangshan }
6966042f7df1SLai Jiangshan 
6967fe28f631SWaiman Long static struct device_attribute wq_sysfs_cpumask_attrs[] = {
6968042f7df1SLai Jiangshan 	__ATTR(cpumask, 0644, wq_unbound_cpumask_show,
6969fe28f631SWaiman Long 	       wq_unbound_cpumask_store),
6970fe28f631SWaiman Long 	__ATTR(cpumask_requested, 0444, wq_requested_cpumask_show, NULL),
6971fe28f631SWaiman Long 	__ATTR(cpumask_isolated, 0444, wq_isolated_cpumask_show, NULL),
6972fe28f631SWaiman Long 	__ATTR_NULL,
6973fe28f631SWaiman Long };
6974b05a7928SFrederic Weisbecker 
69756ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
69766ba94429SFrederic Weisbecker {
6977686f6697SGreg Kroah-Hartman 	struct device *dev_root;
6978b05a7928SFrederic Weisbecker 	int err;
6979b05a7928SFrederic Weisbecker 
6980b05a7928SFrederic Weisbecker 	err = subsys_virtual_register(&wq_subsys, NULL);
6981b05a7928SFrederic Weisbecker 	if (err)
6982b05a7928SFrederic Weisbecker 		return err;
6983b05a7928SFrederic Weisbecker 
6984686f6697SGreg Kroah-Hartman 	dev_root = bus_get_dev_root(&wq_subsys);
6985686f6697SGreg Kroah-Hartman 	if (dev_root) {
6986fe28f631SWaiman Long 		struct device_attribute *attr;
6987fe28f631SWaiman Long 
6988fe28f631SWaiman Long 		for (attr = wq_sysfs_cpumask_attrs; attr->attr.name; attr++) {
6989fe28f631SWaiman Long 			err = device_create_file(dev_root, attr);
6990fe28f631SWaiman Long 			if (err)
6991fe28f631SWaiman Long 				break;
6992fe28f631SWaiman Long 		}
6993686f6697SGreg Kroah-Hartman 		put_device(dev_root);
6994686f6697SGreg Kroah-Hartman 	}
6995686f6697SGreg Kroah-Hartman 	return err;
69966ba94429SFrederic Weisbecker }
69976ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
69986ba94429SFrederic Weisbecker 
69996ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
70006ba94429SFrederic Weisbecker {
70016ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
70026ba94429SFrederic Weisbecker 
70036ba94429SFrederic Weisbecker 	kfree(wq_dev);
70046ba94429SFrederic Weisbecker }
70056ba94429SFrederic Weisbecker 
70066ba94429SFrederic Weisbecker /**
70076ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
70086ba94429SFrederic Weisbecker  * @wq: the workqueue to register
70096ba94429SFrederic Weisbecker  *
70106ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
70116ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
70126ba94429SFrederic Weisbecker  * which is the preferred method.
70136ba94429SFrederic Weisbecker  *
70146ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
70156ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
70166ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
70176ba94429SFrederic Weisbecker  * attributes.
70186ba94429SFrederic Weisbecker  *
70196ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
70206ba94429SFrederic Weisbecker  */
70216ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
70226ba94429SFrederic Weisbecker {
70236ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
70246ba94429SFrederic Weisbecker 	int ret;
70256ba94429SFrederic Weisbecker 
70266ba94429SFrederic Weisbecker 	/*
7027402dd89dSShailendra Verma 	 * Adjusting max_active or creating new pwqs by applying
70286ba94429SFrederic Weisbecker 	 * attributes breaks ordering guarantee.  Disallow exposing ordered
70296ba94429SFrederic Weisbecker 	 * workqueues.
70306ba94429SFrederic Weisbecker 	 */
70310a94efb5STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
70326ba94429SFrederic Weisbecker 		return -EINVAL;
70336ba94429SFrederic Weisbecker 
70346ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
70356ba94429SFrederic Weisbecker 	if (!wq_dev)
70366ba94429SFrederic Weisbecker 		return -ENOMEM;
70376ba94429SFrederic Weisbecker 
70386ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
70396ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
70406ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
704123217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
70426ba94429SFrederic Weisbecker 
70436ba94429SFrederic Weisbecker 	/*
70446ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
70456ba94429SFrederic Weisbecker 	 * everything is ready.
70466ba94429SFrederic Weisbecker 	 */
70476ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
70486ba94429SFrederic Weisbecker 
70496ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
70506ba94429SFrederic Weisbecker 	if (ret) {
7051537f4146SArvind Yadav 		put_device(&wq_dev->dev);
70526ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
70536ba94429SFrederic Weisbecker 		return ret;
70546ba94429SFrederic Weisbecker 	}
70556ba94429SFrederic Weisbecker 
70566ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
70576ba94429SFrederic Weisbecker 		struct device_attribute *attr;
70586ba94429SFrederic Weisbecker 
70596ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
70606ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
70616ba94429SFrederic Weisbecker 			if (ret) {
70626ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
70636ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
70646ba94429SFrederic Weisbecker 				return ret;
70656ba94429SFrederic Weisbecker 			}
70666ba94429SFrederic Weisbecker 		}
70676ba94429SFrederic Weisbecker 	}
70686ba94429SFrederic Weisbecker 
70696ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
70706ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
70716ba94429SFrederic Weisbecker 	return 0;
70726ba94429SFrederic Weisbecker }
70736ba94429SFrederic Weisbecker 
70746ba94429SFrederic Weisbecker /**
70756ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
70766ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
70776ba94429SFrederic Weisbecker  *
70786ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
70796ba94429SFrederic Weisbecker  */
70806ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
70816ba94429SFrederic Weisbecker {
70826ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
70836ba94429SFrederic Weisbecker 
70846ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
70856ba94429SFrederic Weisbecker 		return;
70866ba94429SFrederic Weisbecker 
70876ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
70886ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
70896ba94429SFrederic Weisbecker }
70906ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
70916ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
70926ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
70936ba94429SFrederic Weisbecker 
709482607adcSTejun Heo /*
709582607adcSTejun Heo  * Workqueue watchdog.
709682607adcSTejun Heo  *
709782607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
709882607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
709982607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
710082607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
710182607adcSTejun Heo  * largely opaque.
710282607adcSTejun Heo  *
710382607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
710482607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
710582607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
710682607adcSTejun Heo  *
710782607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
710882607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
710982607adcSTejun Heo  * corresponding sysfs parameter file.
711082607adcSTejun Heo  */
711182607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
711282607adcSTejun Heo 
711382607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
71145cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
711582607adcSTejun Heo 
711682607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
711782607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
711882607adcSTejun Heo 
7119cd2440d6SPetr Mladek /*
7120cd2440d6SPetr Mladek  * Show workers that might prevent the processing of pending work items.
7121cd2440d6SPetr Mladek  * The only candidates are CPU-bound workers in the running state.
7122cd2440d6SPetr Mladek  * Pending work items should be handled by another idle worker
7123cd2440d6SPetr Mladek  * in all other situations.
7124cd2440d6SPetr Mladek  */
7125cd2440d6SPetr Mladek static void show_cpu_pool_hog(struct worker_pool *pool)
7126cd2440d6SPetr Mladek {
7127cd2440d6SPetr Mladek 	struct worker *worker;
7128cd2440d6SPetr Mladek 	unsigned long flags;
7129cd2440d6SPetr Mladek 	int bkt;
7130cd2440d6SPetr Mladek 
7131cd2440d6SPetr Mladek 	raw_spin_lock_irqsave(&pool->lock, flags);
7132cd2440d6SPetr Mladek 
7133cd2440d6SPetr Mladek 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
7134cd2440d6SPetr Mladek 		if (task_is_running(worker->task)) {
7135cd2440d6SPetr Mladek 			/*
7136cd2440d6SPetr Mladek 			 * Defer printing to avoid deadlocks in console
7137cd2440d6SPetr Mladek 			 * drivers that queue work while holding locks
7138cd2440d6SPetr Mladek 			 * also taken in their write paths.
7139cd2440d6SPetr Mladek 			 */
7140cd2440d6SPetr Mladek 			printk_deferred_enter();
7141cd2440d6SPetr Mladek 
7142cd2440d6SPetr Mladek 			pr_info("pool %d:\n", pool->id);
7143cd2440d6SPetr Mladek 			sched_show_task(worker->task);
7144cd2440d6SPetr Mladek 
7145cd2440d6SPetr Mladek 			printk_deferred_exit();
7146cd2440d6SPetr Mladek 		}
7147cd2440d6SPetr Mladek 	}
7148cd2440d6SPetr Mladek 
7149cd2440d6SPetr Mladek 	raw_spin_unlock_irqrestore(&pool->lock, flags);
7150cd2440d6SPetr Mladek }
7151cd2440d6SPetr Mladek 
7152cd2440d6SPetr Mladek static void show_cpu_pools_hogs(void)
7153cd2440d6SPetr Mladek {
7154cd2440d6SPetr Mladek 	struct worker_pool *pool;
7155cd2440d6SPetr Mladek 	int pi;
7156cd2440d6SPetr Mladek 
7157cd2440d6SPetr Mladek 	pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
7158cd2440d6SPetr Mladek 
7159cd2440d6SPetr Mladek 	rcu_read_lock();
7160cd2440d6SPetr Mladek 
7161cd2440d6SPetr Mladek 	for_each_pool(pool, pi) {
7162cd2440d6SPetr Mladek 		if (pool->cpu_stall)
7163cd2440d6SPetr Mladek 			show_cpu_pool_hog(pool);
7164cd2440d6SPetr Mladek 
7165cd2440d6SPetr Mladek 	}
7166cd2440d6SPetr Mladek 
7167cd2440d6SPetr Mladek 	rcu_read_unlock();
7168cd2440d6SPetr Mladek }
7169cd2440d6SPetr Mladek 
717082607adcSTejun Heo static void wq_watchdog_reset_touched(void)
717182607adcSTejun Heo {
717282607adcSTejun Heo 	int cpu;
717382607adcSTejun Heo 
717482607adcSTejun Heo 	wq_watchdog_touched = jiffies;
717582607adcSTejun Heo 	for_each_possible_cpu(cpu)
717682607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
717782607adcSTejun Heo }
717882607adcSTejun Heo 
71795cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
718082607adcSTejun Heo {
718182607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
718282607adcSTejun Heo 	bool lockup_detected = false;
7183cd2440d6SPetr Mladek 	bool cpu_pool_stall = false;
7184940d71c6SSergey Senozhatsky 	unsigned long now = jiffies;
718582607adcSTejun Heo 	struct worker_pool *pool;
718682607adcSTejun Heo 	int pi;
718782607adcSTejun Heo 
718882607adcSTejun Heo 	if (!thresh)
718982607adcSTejun Heo 		return;
719082607adcSTejun Heo 
719182607adcSTejun Heo 	rcu_read_lock();
719282607adcSTejun Heo 
719382607adcSTejun Heo 	for_each_pool(pool, pi) {
719482607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
719582607adcSTejun Heo 
7196cd2440d6SPetr Mladek 		pool->cpu_stall = false;
719782607adcSTejun Heo 		if (list_empty(&pool->worklist))
719882607adcSTejun Heo 			continue;
719982607adcSTejun Heo 
7200940d71c6SSergey Senozhatsky 		/*
7201940d71c6SSergey Senozhatsky 		 * If a virtual machine is stopped by the host it can look to
7202940d71c6SSergey Senozhatsky 		 * the watchdog like a stall.
7203940d71c6SSergey Senozhatsky 		 */
7204940d71c6SSergey Senozhatsky 		kvm_check_and_clear_guest_paused();
7205940d71c6SSergey Senozhatsky 
720682607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
720789e28ce6SWang Qing 		if (pool->cpu >= 0)
720889e28ce6SWang Qing 			touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
720989e28ce6SWang Qing 		else
721082607adcSTejun Heo 			touched = READ_ONCE(wq_watchdog_touched);
721189e28ce6SWang Qing 		pool_ts = READ_ONCE(pool->watchdog_ts);
721282607adcSTejun Heo 
721382607adcSTejun Heo 		if (time_after(pool_ts, touched))
721482607adcSTejun Heo 			ts = pool_ts;
721582607adcSTejun Heo 		else
721682607adcSTejun Heo 			ts = touched;
721782607adcSTejun Heo 
721882607adcSTejun Heo 		/* did we stall? */
7219940d71c6SSergey Senozhatsky 		if (time_after(now, ts + thresh)) {
722082607adcSTejun Heo 			lockup_detected = true;
72214cb1ef64STejun Heo 			if (pool->cpu >= 0 && !(pool->flags & POOL_BH)) {
7222cd2440d6SPetr Mladek 				pool->cpu_stall = true;
7223cd2440d6SPetr Mladek 				cpu_pool_stall = true;
7224cd2440d6SPetr Mladek 			}
722582607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
722682607adcSTejun Heo 			pr_cont_pool_info(pool);
722782607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
7228940d71c6SSergey Senozhatsky 				jiffies_to_msecs(now - pool_ts) / 1000);
722982607adcSTejun Heo 		}
7230cd2440d6SPetr Mladek 
7231cd2440d6SPetr Mladek 
723282607adcSTejun Heo 	}
723382607adcSTejun Heo 
723482607adcSTejun Heo 	rcu_read_unlock();
723582607adcSTejun Heo 
723682607adcSTejun Heo 	if (lockup_detected)
723755df0933SImran Khan 		show_all_workqueues();
723882607adcSTejun Heo 
7239cd2440d6SPetr Mladek 	if (cpu_pool_stall)
7240cd2440d6SPetr Mladek 		show_cpu_pools_hogs();
7241cd2440d6SPetr Mladek 
724282607adcSTejun Heo 	wq_watchdog_reset_touched();
724382607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
724482607adcSTejun Heo }
724582607adcSTejun Heo 
7246cb9d7fd5SVincent Whitchurch notrace void wq_watchdog_touch(int cpu)
724782607adcSTejun Heo {
724882607adcSTejun Heo 	if (cpu >= 0)
724982607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
725089e28ce6SWang Qing 
725182607adcSTejun Heo 	wq_watchdog_touched = jiffies;
725282607adcSTejun Heo }
725382607adcSTejun Heo 
725482607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
725582607adcSTejun Heo {
725682607adcSTejun Heo 	wq_watchdog_thresh = 0;
725782607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
725882607adcSTejun Heo 
725982607adcSTejun Heo 	if (thresh) {
726082607adcSTejun Heo 		wq_watchdog_thresh = thresh;
726182607adcSTejun Heo 		wq_watchdog_reset_touched();
726282607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
726382607adcSTejun Heo 	}
726482607adcSTejun Heo }
726582607adcSTejun Heo 
726682607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
726782607adcSTejun Heo 					const struct kernel_param *kp)
726882607adcSTejun Heo {
726982607adcSTejun Heo 	unsigned long thresh;
727082607adcSTejun Heo 	int ret;
727182607adcSTejun Heo 
727282607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
727382607adcSTejun Heo 	if (ret)
727482607adcSTejun Heo 		return ret;
727582607adcSTejun Heo 
727682607adcSTejun Heo 	if (system_wq)
727782607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
727882607adcSTejun Heo 	else
727982607adcSTejun Heo 		wq_watchdog_thresh = thresh;
728082607adcSTejun Heo 
728182607adcSTejun Heo 	return 0;
728282607adcSTejun Heo }
728382607adcSTejun Heo 
728482607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
728582607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
728682607adcSTejun Heo 	.get	= param_get_ulong,
728782607adcSTejun Heo };
728882607adcSTejun Heo 
728982607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
729082607adcSTejun Heo 		0644);
729182607adcSTejun Heo 
729282607adcSTejun Heo static void wq_watchdog_init(void)
729382607adcSTejun Heo {
72945cd79d6aSKees Cook 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
729582607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
729682607adcSTejun Heo }
729782607adcSTejun Heo 
729882607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
729982607adcSTejun Heo 
730082607adcSTejun Heo static inline void wq_watchdog_init(void) { }
730182607adcSTejun Heo 
730282607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
730382607adcSTejun Heo 
73044a6c5607STejun Heo static void __init restrict_unbound_cpumask(const char *name, const struct cpumask *mask)
73054a6c5607STejun Heo {
73064a6c5607STejun Heo 	if (!cpumask_intersects(wq_unbound_cpumask, mask)) {
73074a6c5607STejun Heo 		pr_warn("workqueue: Restricting unbound_cpumask (%*pb) with %s (%*pb) leaves no CPU, ignoring\n",
73084a6c5607STejun Heo 			cpumask_pr_args(wq_unbound_cpumask), name, cpumask_pr_args(mask));
73094a6c5607STejun Heo 		return;
73104a6c5607STejun Heo 	}
73114a6c5607STejun Heo 
73124a6c5607STejun Heo 	cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, mask);
73134a6c5607STejun Heo }
73144a6c5607STejun Heo 
73152fcdb1b4STejun Heo static void __init init_cpu_worker_pool(struct worker_pool *pool, int cpu, int nice)
73162fcdb1b4STejun Heo {
73172fcdb1b4STejun Heo 	BUG_ON(init_worker_pool(pool));
73182fcdb1b4STejun Heo 	pool->cpu = cpu;
73192fcdb1b4STejun Heo 	cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
73202fcdb1b4STejun Heo 	cpumask_copy(pool->attrs->__pod_cpumask, cpumask_of(cpu));
73212fcdb1b4STejun Heo 	pool->attrs->nice = nice;
73222fcdb1b4STejun Heo 	pool->attrs->affn_strict = true;
73232fcdb1b4STejun Heo 	pool->node = cpu_to_node(cpu);
73242fcdb1b4STejun Heo 
73252fcdb1b4STejun Heo 	/* alloc pool ID */
73262fcdb1b4STejun Heo 	mutex_lock(&wq_pool_mutex);
73272fcdb1b4STejun Heo 	BUG_ON(worker_pool_assign_id(pool));
73282fcdb1b4STejun Heo 	mutex_unlock(&wq_pool_mutex);
73292fcdb1b4STejun Heo }
73302fcdb1b4STejun Heo 
73313347fa09STejun Heo /**
73323347fa09STejun Heo  * workqueue_init_early - early init for workqueue subsystem
73333347fa09STejun Heo  *
73342930155bSTejun Heo  * This is the first step of three-staged workqueue subsystem initialization and
73352930155bSTejun Heo  * invoked as soon as the bare basics - memory allocation, cpumasks and idr are
73362930155bSTejun Heo  * up. It sets up all the data structures and system workqueues and allows early
73372930155bSTejun Heo  * boot code to create workqueues and queue/cancel work items. Actual work item
73382930155bSTejun Heo  * execution starts only after kthreads can be created and scheduled right
73392930155bSTejun Heo  * before early initcalls.
73403347fa09STejun Heo  */
73412333e829SYu Chen void __init workqueue_init_early(void)
73421da177e4SLinus Torvalds {
734384193c07STejun Heo 	struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_SYSTEM];
73447a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
73457a4e344cSTejun Heo 	int i, cpu;
7346c34056a3STejun Heo 
734710cdb157SLai Jiangshan 	BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
7348e904e6c2STejun Heo 
7349b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
7350fe28f631SWaiman Long 	BUG_ON(!alloc_cpumask_var(&wq_requested_unbound_cpumask, GFP_KERNEL));
7351fe28f631SWaiman Long 	BUG_ON(!zalloc_cpumask_var(&wq_isolated_cpumask, GFP_KERNEL));
7352b05a7928SFrederic Weisbecker 
73534a6c5607STejun Heo 	cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
73544a6c5607STejun Heo 	restrict_unbound_cpumask("HK_TYPE_WQ", housekeeping_cpumask(HK_TYPE_WQ));
73554a6c5607STejun Heo 	restrict_unbound_cpumask("HK_TYPE_DOMAIN", housekeeping_cpumask(HK_TYPE_DOMAIN));
7356ace3c549Stiozhang 	if (!cpumask_empty(&wq_cmdline_cpumask))
73574a6c5607STejun Heo 		restrict_unbound_cpumask("workqueue.unbound_cpus", &wq_cmdline_cpumask);
7358ace3c549Stiozhang 
7359fe28f631SWaiman Long 	cpumask_copy(wq_requested_unbound_cpumask, wq_unbound_cpumask);
73608b03ae3cSTejun Heo 
73618b03ae3cSTejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
7362e22bee78STejun Heo 
73632930155bSTejun Heo 	wq_update_pod_attrs_buf = alloc_workqueue_attrs();
73642930155bSTejun Heo 	BUG_ON(!wq_update_pod_attrs_buf);
73652930155bSTejun Heo 
73667bd20b6bSMarcelo Tosatti 	/*
73677bd20b6bSMarcelo Tosatti 	 * If nohz_full is enabled, set power efficient workqueue as unbound.
73687bd20b6bSMarcelo Tosatti 	 * This allows workqueue items to be moved to HK CPUs.
73697bd20b6bSMarcelo Tosatti 	 */
73707bd20b6bSMarcelo Tosatti 	if (housekeeping_enabled(HK_TYPE_TICK))
73717bd20b6bSMarcelo Tosatti 		wq_power_efficient = true;
73727bd20b6bSMarcelo Tosatti 
737384193c07STejun Heo 	/* initialize WQ_AFFN_SYSTEM pods */
737484193c07STejun Heo 	pt->pod_cpus = kcalloc(1, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
737584193c07STejun Heo 	pt->pod_node = kcalloc(1, sizeof(pt->pod_node[0]), GFP_KERNEL);
737684193c07STejun Heo 	pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
737784193c07STejun Heo 	BUG_ON(!pt->pod_cpus || !pt->pod_node || !pt->cpu_pod);
737884193c07STejun Heo 
737984193c07STejun Heo 	BUG_ON(!zalloc_cpumask_var_node(&pt->pod_cpus[0], GFP_KERNEL, NUMA_NO_NODE));
738084193c07STejun Heo 
738184193c07STejun Heo 	pt->nr_pods = 1;
738284193c07STejun Heo 	cpumask_copy(pt->pod_cpus[0], cpu_possible_mask);
738384193c07STejun Heo 	pt->pod_node[0] = NUMA_NO_NODE;
738484193c07STejun Heo 	pt->cpu_pod[0] = 0;
738584193c07STejun Heo 
73864cb1ef64STejun Heo 	/* initialize BH and CPU pools */
73871da177e4SLinus Torvalds 	for_each_possible_cpu(cpu) {
73881da177e4SLinus Torvalds 		struct worker_pool *pool;
73891da177e4SLinus Torvalds 
73901da177e4SLinus Torvalds 		i = 0;
73914cb1ef64STejun Heo 		for_each_bh_worker_pool(pool, cpu) {
73924cb1ef64STejun Heo 			init_cpu_worker_pool(pool, cpu, std_nice[i++]);
73934cb1ef64STejun Heo 			pool->flags |= POOL_BH;
73944cb1ef64STejun Heo 		}
73954cb1ef64STejun Heo 
73964cb1ef64STejun Heo 		i = 0;
73972fcdb1b4STejun Heo 		for_each_cpu_worker_pool(pool, cpu)
73982fcdb1b4STejun Heo 			init_cpu_worker_pool(pool, cpu, std_nice[i++]);
73991da177e4SLinus Torvalds 	}
74001da177e4SLinus Torvalds 
74018a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
740229c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
740329c91e99STejun Heo 		struct workqueue_attrs *attrs;
740429c91e99STejun Heo 
7405be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
740629c91e99STejun Heo 		attrs->nice = std_nice[i];
740729c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
74088a2b7538STejun Heo 
74098a2b7538STejun Heo 		/*
74108a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
74118a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
74128a2b7538STejun Heo 		 */
7413be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
74148a2b7538STejun Heo 		attrs->nice = std_nice[i];
7415af73f5c9STejun Heo 		attrs->ordered = true;
74168a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
741729c91e99STejun Heo 	}
741829c91e99STejun Heo 
7419d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
74201aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
7421d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
7422f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
7423636b927eSTejun Heo 					    WQ_MAX_ACTIVE);
742424d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
742524d51addSTejun Heo 					      WQ_FREEZABLE, 0);
74260668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
74270668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
74288318d6a6SAudra Mitchell 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_pwr_efficient",
74290668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
74300668106cSViresh Kumar 					      0);
74314cb1ef64STejun Heo 	system_bh_wq = alloc_workqueue("events_bh", WQ_BH, 0);
74324cb1ef64STejun Heo 	system_bh_highpri_wq = alloc_workqueue("events_bh_highpri",
74334cb1ef64STejun Heo 					       WQ_BH | WQ_HIGHPRI, 0);
74341aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
74350668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
74360668106cSViresh Kumar 	       !system_power_efficient_wq ||
74374cb1ef64STejun Heo 	       !system_freezable_power_efficient_wq ||
74384cb1ef64STejun Heo 	       !system_bh_wq || !system_bh_highpri_wq);
74393347fa09STejun Heo }
74403347fa09STejun Heo 
7441aa6fde93STejun Heo static void __init wq_cpu_intensive_thresh_init(void)
7442aa6fde93STejun Heo {
7443aa6fde93STejun Heo 	unsigned long thresh;
7444aa6fde93STejun Heo 	unsigned long bogo;
7445aa6fde93STejun Heo 
7446dd64c873SZqiang 	pwq_release_worker = kthread_create_worker(0, "pool_workqueue_release");
7447dd64c873SZqiang 	BUG_ON(IS_ERR(pwq_release_worker));
7448dd64c873SZqiang 
7449aa6fde93STejun Heo 	/* if the user set it to a specific value, keep it */
7450aa6fde93STejun Heo 	if (wq_cpu_intensive_thresh_us != ULONG_MAX)
7451aa6fde93STejun Heo 		return;
7452aa6fde93STejun Heo 
7453aa6fde93STejun Heo 	/*
7454aa6fde93STejun Heo 	 * The default of 10ms is derived from the fact that most modern (as of
7455aa6fde93STejun Heo 	 * 2023) processors can do a lot in 10ms and that it's just below what
7456aa6fde93STejun Heo 	 * most consider human-perceivable. However, the kernel also runs on a
7457aa6fde93STejun Heo 	 * lot slower CPUs including microcontrollers where the threshold is way
7458aa6fde93STejun Heo 	 * too low.
7459aa6fde93STejun Heo 	 *
7460aa6fde93STejun Heo 	 * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
7461aa6fde93STejun Heo 	 * This is by no means accurate but it doesn't have to be. The mechanism
7462aa6fde93STejun Heo 	 * is still useful even when the threshold is fully scaled up. Also, as
7463aa6fde93STejun Heo 	 * the reports would usually be applicable to everyone, some machines
7464aa6fde93STejun Heo 	 * operating on longer thresholds won't significantly diminish their
7465aa6fde93STejun Heo 	 * usefulness.
7466aa6fde93STejun Heo 	 */
7467aa6fde93STejun Heo 	thresh = 10 * USEC_PER_MSEC;
7468aa6fde93STejun Heo 
7469aa6fde93STejun Heo 	/* see init/calibrate.c for lpj -> BogoMIPS calculation */
7470aa6fde93STejun Heo 	bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
7471aa6fde93STejun Heo 	if (bogo < 4000)
7472aa6fde93STejun Heo 		thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
7473aa6fde93STejun Heo 
7474aa6fde93STejun Heo 	pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
7475aa6fde93STejun Heo 		 loops_per_jiffy, bogo, thresh);
7476aa6fde93STejun Heo 
7477aa6fde93STejun Heo 	wq_cpu_intensive_thresh_us = thresh;
7478aa6fde93STejun Heo }
7479aa6fde93STejun Heo 
74803347fa09STejun Heo /**
74813347fa09STejun Heo  * workqueue_init - bring workqueue subsystem fully online
74823347fa09STejun Heo  *
74832930155bSTejun Heo  * This is the second step of three-staged workqueue subsystem initialization
74842930155bSTejun Heo  * and invoked as soon as kthreads can be created and scheduled. Workqueues have
74852930155bSTejun Heo  * been created and work items queued on them, but there are no kworkers
74862930155bSTejun Heo  * executing the work items yet. Populate the worker pools with the initial
74872930155bSTejun Heo  * workers and enable future kworker creations.
74883347fa09STejun Heo  */
74892333e829SYu Chen void __init workqueue_init(void)
74903347fa09STejun Heo {
74912186d9f9STejun Heo 	struct workqueue_struct *wq;
74923347fa09STejun Heo 	struct worker_pool *pool;
74933347fa09STejun Heo 	int cpu, bkt;
74943347fa09STejun Heo 
7495aa6fde93STejun Heo 	wq_cpu_intensive_thresh_init();
7496aa6fde93STejun Heo 
74972186d9f9STejun Heo 	mutex_lock(&wq_pool_mutex);
74982186d9f9STejun Heo 
74992930155bSTejun Heo 	/*
75002930155bSTejun Heo 	 * Per-cpu pools created earlier could be missing node hint. Fix them
75012930155bSTejun Heo 	 * up. Also, create a rescuer for workqueues that requested it.
75022930155bSTejun Heo 	 */
75032186d9f9STejun Heo 	for_each_possible_cpu(cpu) {
75044cb1ef64STejun Heo 		for_each_bh_worker_pool(pool, cpu)
75052186d9f9STejun Heo 			pool->node = cpu_to_node(cpu);
75064cb1ef64STejun Heo 		for_each_cpu_worker_pool(pool, cpu)
75074cb1ef64STejun Heo 			pool->node = cpu_to_node(cpu);
75082186d9f9STejun Heo 	}
75092186d9f9STejun Heo 
751040c17f75STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
751140c17f75STejun Heo 		WARN(init_rescuer(wq),
751240c17f75STejun Heo 		     "workqueue: failed to create early rescuer for %s",
751340c17f75STejun Heo 		     wq->name);
751440c17f75STejun Heo 	}
75152186d9f9STejun Heo 
75162186d9f9STejun Heo 	mutex_unlock(&wq_pool_mutex);
75172186d9f9STejun Heo 
75184cb1ef64STejun Heo 	/*
75194cb1ef64STejun Heo 	 * Create the initial workers. A BH pool has one pseudo worker that
75204cb1ef64STejun Heo 	 * represents the shared BH execution context and thus doesn't get
75214cb1ef64STejun Heo 	 * affected by hotplug events. Create the BH pseudo workers for all
75224cb1ef64STejun Heo 	 * possible CPUs here.
75234cb1ef64STejun Heo 	 */
75244cb1ef64STejun Heo 	for_each_possible_cpu(cpu)
75254cb1ef64STejun Heo 		for_each_bh_worker_pool(pool, cpu)
75264cb1ef64STejun Heo 			BUG_ON(!create_worker(pool));
75274cb1ef64STejun Heo 
75283347fa09STejun Heo 	for_each_online_cpu(cpu) {
75293347fa09STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
75303347fa09STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
75313347fa09STejun Heo 			BUG_ON(!create_worker(pool));
75323347fa09STejun Heo 		}
75333347fa09STejun Heo 	}
75343347fa09STejun Heo 
75353347fa09STejun Heo 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
75363347fa09STejun Heo 		BUG_ON(!create_worker(pool));
75373347fa09STejun Heo 
75383347fa09STejun Heo 	wq_online = true;
753982607adcSTejun Heo 	wq_watchdog_init();
75401da177e4SLinus Torvalds }
7541c4f135d6STetsuo Handa 
7542025e1684STejun Heo /*
7543025e1684STejun Heo  * Initialize @pt by first initializing @pt->cpu_pod[] with pod IDs according to
7544025e1684STejun Heo  * @cpu_shares_pod(). Each subset of CPUs that share a pod is assigned a unique
7545025e1684STejun Heo  * and consecutive pod ID. The rest of @pt is initialized accordingly.
7546025e1684STejun Heo  */
7547025e1684STejun Heo static void __init init_pod_type(struct wq_pod_type *pt,
7548025e1684STejun Heo 				 bool (*cpus_share_pod)(int, int))
7549025e1684STejun Heo {
7550025e1684STejun Heo 	int cur, pre, cpu, pod;
7551025e1684STejun Heo 
7552025e1684STejun Heo 	pt->nr_pods = 0;
7553025e1684STejun Heo 
7554025e1684STejun Heo 	/* init @pt->cpu_pod[] according to @cpus_share_pod() */
7555025e1684STejun Heo 	pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
7556025e1684STejun Heo 	BUG_ON(!pt->cpu_pod);
7557025e1684STejun Heo 
7558025e1684STejun Heo 	for_each_possible_cpu(cur) {
7559025e1684STejun Heo 		for_each_possible_cpu(pre) {
7560025e1684STejun Heo 			if (pre >= cur) {
7561025e1684STejun Heo 				pt->cpu_pod[cur] = pt->nr_pods++;
7562025e1684STejun Heo 				break;
7563025e1684STejun Heo 			}
7564025e1684STejun Heo 			if (cpus_share_pod(cur, pre)) {
7565025e1684STejun Heo 				pt->cpu_pod[cur] = pt->cpu_pod[pre];
7566025e1684STejun Heo 				break;
7567025e1684STejun Heo 			}
7568025e1684STejun Heo 		}
7569025e1684STejun Heo 	}
7570025e1684STejun Heo 
7571025e1684STejun Heo 	/* init the rest to match @pt->cpu_pod[] */
7572025e1684STejun Heo 	pt->pod_cpus = kcalloc(pt->nr_pods, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
7573025e1684STejun Heo 	pt->pod_node = kcalloc(pt->nr_pods, sizeof(pt->pod_node[0]), GFP_KERNEL);
7574025e1684STejun Heo 	BUG_ON(!pt->pod_cpus || !pt->pod_node);
7575025e1684STejun Heo 
7576025e1684STejun Heo 	for (pod = 0; pod < pt->nr_pods; pod++)
7577025e1684STejun Heo 		BUG_ON(!zalloc_cpumask_var(&pt->pod_cpus[pod], GFP_KERNEL));
7578025e1684STejun Heo 
7579025e1684STejun Heo 	for_each_possible_cpu(cpu) {
7580025e1684STejun Heo 		cpumask_set_cpu(cpu, pt->pod_cpus[pt->cpu_pod[cpu]]);
7581025e1684STejun Heo 		pt->pod_node[pt->cpu_pod[cpu]] = cpu_to_node(cpu);
7582025e1684STejun Heo 	}
7583025e1684STejun Heo }
7584025e1684STejun Heo 
758563c5484eSTejun Heo static bool __init cpus_dont_share(int cpu0, int cpu1)
758663c5484eSTejun Heo {
758763c5484eSTejun Heo 	return false;
758863c5484eSTejun Heo }
758963c5484eSTejun Heo 
759063c5484eSTejun Heo static bool __init cpus_share_smt(int cpu0, int cpu1)
759163c5484eSTejun Heo {
759263c5484eSTejun Heo #ifdef CONFIG_SCHED_SMT
759363c5484eSTejun Heo 	return cpumask_test_cpu(cpu0, cpu_smt_mask(cpu1));
759463c5484eSTejun Heo #else
759563c5484eSTejun Heo 	return false;
759663c5484eSTejun Heo #endif
759763c5484eSTejun Heo }
759863c5484eSTejun Heo 
7599025e1684STejun Heo static bool __init cpus_share_numa(int cpu0, int cpu1)
7600025e1684STejun Heo {
7601025e1684STejun Heo 	return cpu_to_node(cpu0) == cpu_to_node(cpu1);
7602025e1684STejun Heo }
7603025e1684STejun Heo 
76042930155bSTejun Heo /**
76052930155bSTejun Heo  * workqueue_init_topology - initialize CPU pods for unbound workqueues
76062930155bSTejun Heo  *
7607*96068b60SWang Jinchao  * This is the third step of three-staged workqueue subsystem initialization and
76082930155bSTejun Heo  * invoked after SMP and topology information are fully initialized. It
76092930155bSTejun Heo  * initializes the unbound CPU pods accordingly.
76102930155bSTejun Heo  */
76112930155bSTejun Heo void __init workqueue_init_topology(void)
7612a86feae6STejun Heo {
76132930155bSTejun Heo 	struct workqueue_struct *wq;
7614025e1684STejun Heo 	int cpu;
7615a86feae6STejun Heo 
761663c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_CPU], cpus_dont_share);
761763c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_SMT], cpus_share_smt);
761863c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_CACHE], cpus_share_cache);
7619025e1684STejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_NUMA], cpus_share_numa);
7620a86feae6STejun Heo 
7621c5f8cd6cSTejun Heo 	wq_topo_initialized = true;
7622c5f8cd6cSTejun Heo 
76232930155bSTejun Heo 	mutex_lock(&wq_pool_mutex);
7624a86feae6STejun Heo 
7625a86feae6STejun Heo 	/*
76262930155bSTejun Heo 	 * Workqueues allocated earlier would have all CPUs sharing the default
76272930155bSTejun Heo 	 * worker pool. Explicitly call wq_update_pod() on all workqueue and CPU
76282930155bSTejun Heo 	 * combinations to apply per-pod sharing.
76292930155bSTejun Heo 	 */
76302930155bSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
76315797b1c1STejun Heo 		for_each_online_cpu(cpu)
76322930155bSTejun Heo 			wq_update_pod(wq, cpu, cpu, true);
76335797b1c1STejun Heo 		if (wq->flags & WQ_UNBOUND) {
76345797b1c1STejun Heo 			mutex_lock(&wq->mutex);
76355797b1c1STejun Heo 			wq_update_node_max_active(wq, -1);
76365797b1c1STejun Heo 			mutex_unlock(&wq->mutex);
76372930155bSTejun Heo 		}
76382930155bSTejun Heo 	}
76392930155bSTejun Heo 
76402930155bSTejun Heo 	mutex_unlock(&wq_pool_mutex);
7641a86feae6STejun Heo }
7642a86feae6STejun Heo 
764320bdedafSTetsuo Handa void __warn_flushing_systemwide_wq(void)
764420bdedafSTetsuo Handa {
764520bdedafSTetsuo Handa 	pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
764620bdedafSTetsuo Handa 	dump_stack();
764720bdedafSTetsuo Handa }
7648c4f135d6STetsuo Handa EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
7649ace3c549Stiozhang 
7650ace3c549Stiozhang static int __init workqueue_unbound_cpus_setup(char *str)
7651ace3c549Stiozhang {
7652ace3c549Stiozhang 	if (cpulist_parse(str, &wq_cmdline_cpumask) < 0) {
7653ace3c549Stiozhang 		cpumask_clear(&wq_cmdline_cpumask);
7654ace3c549Stiozhang 		pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
7655ace3c549Stiozhang 	}
7656ace3c549Stiozhang 
7657ace3c549Stiozhang 	return 1;
7658ace3c549Stiozhang }
7659ace3c549Stiozhang __setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup);
7660