xref: /linux-6.15/kernel/workqueue.c (revision 2a1b02bc)
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>
572f34d733STejun Heo #include <linux/irq_work.h>
58e22bee78STejun Heo 
59ea138446STejun Heo #include "workqueue_internal.h"
601da177e4SLinus Torvalds 
61e563d0a7STejun Heo enum worker_pool_flags {
62bc2ae0f5STejun Heo 	/*
6324647570STejun Heo 	 * worker_pool flags
64bc2ae0f5STejun Heo 	 *
6524647570STejun Heo 	 * A bound pool is either associated or disassociated with its CPU.
66bc2ae0f5STejun Heo 	 * While associated (!DISASSOCIATED), all workers are bound to the
67bc2ae0f5STejun Heo 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
68bc2ae0f5STejun Heo 	 * is in effect.
69bc2ae0f5STejun Heo 	 *
70bc2ae0f5STejun Heo 	 * While DISASSOCIATED, the cpu may be offline and all workers have
71bc2ae0f5STejun Heo 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
7224647570STejun Heo 	 * be executing on any CPU.  The pool behaves as an unbound one.
73bc2ae0f5STejun Heo 	 *
74bc3a1afcSTejun Heo 	 * Note that DISASSOCIATED should be flipped only while holding
751258fae7STejun Heo 	 * wq_pool_attach_mutex to avoid changing binding state while
764736cbf7SLai Jiangshan 	 * worker_attach_to_pool() is in progress.
774cb1ef64STejun Heo 	 *
784cb1ef64STejun Heo 	 * As there can only be one concurrent BH execution context per CPU, a
794cb1ef64STejun Heo 	 * BH pool is per-CPU and always DISASSOCIATED.
80bc2ae0f5STejun Heo 	 */
814cb1ef64STejun Heo 	POOL_BH			= 1 << 0,	/* is a BH pool */
824cb1ef64STejun Heo 	POOL_MANAGER_ACTIVE	= 1 << 1,	/* being managed */
8324647570STejun Heo 	POOL_DISASSOCIATED	= 1 << 2,	/* cpu can't serve workers */
841acd92d9STejun Heo 	POOL_BH_DRAINING	= 1 << 3,	/* draining after CPU offline */
85e563d0a7STejun Heo };
86db7bccf4STejun Heo 
87e563d0a7STejun Heo enum worker_flags {
88c8e55f36STejun Heo 	/* worker flags */
89c8e55f36STejun Heo 	WORKER_DIE		= 1 << 1,	/* die die die */
90c8e55f36STejun Heo 	WORKER_IDLE		= 1 << 2,	/* is idle */
91e22bee78STejun Heo 	WORKER_PREP		= 1 << 3,	/* preparing to run works */
92fb0e7bebSTejun Heo 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
93f3421797STejun Heo 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
94a9ab775bSTejun Heo 	WORKER_REBOUND		= 1 << 8,	/* worker was rebound */
95e22bee78STejun Heo 
96a9ab775bSTejun Heo 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_CPU_INTENSIVE |
97a9ab775bSTejun Heo 				  WORKER_UNBOUND | WORKER_REBOUND,
98e563d0a7STejun Heo };
99db7bccf4STejun Heo 
100c5f5b942STejun Heo enum work_cancel_flags {
101c5f5b942STejun Heo 	WORK_CANCEL_DELAYED	= 1 << 0,	/* canceling a delayed_work */
10286898fa6STejun Heo 	WORK_CANCEL_DISABLE	= 1 << 1,	/* canceling to disable */
103c5f5b942STejun Heo };
104c5f5b942STejun Heo 
105e563d0a7STejun Heo enum wq_internal_consts {
106e34cdddbSTejun Heo 	NR_STD_WORKER_POOLS	= 2,		/* # standard pools per cpu */
1074ce62e9eSTejun Heo 
10829c91e99STejun Heo 	UNBOUND_POOL_HASH_ORDER	= 6,		/* hashed by pool->attrs */
109c8e55f36STejun Heo 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
110db7bccf4STejun Heo 
111e22bee78STejun Heo 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
112e22bee78STejun Heo 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
113e22bee78STejun Heo 
1143233cdbdSTejun Heo 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
1153233cdbdSTejun Heo 						/* call for help after 10ms
1163233cdbdSTejun Heo 						   (min two ticks) */
117e22bee78STejun Heo 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
118e22bee78STejun Heo 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
1191da177e4SLinus Torvalds 
1201da177e4SLinus Torvalds 	/*
121e22bee78STejun Heo 	 * Rescue workers are used only on emergencies and shared by
1228698a745SDongsheng Yang 	 * all cpus.  Give MIN_NICE.
123e22bee78STejun Heo 	 */
1248698a745SDongsheng Yang 	RESCUER_NICE_LEVEL	= MIN_NICE,
1258698a745SDongsheng Yang 	HIGHPRI_NICE_LEVEL	= MIN_NICE,
126ecf6881fSTejun Heo 
12731c89007SAudra Mitchell 	WQ_NAME_LEN		= 32,
128*2a1b02bcSTejun Heo 	WORKER_ID_LEN		= 10 + WQ_NAME_LEN, /* "kworker/R-" + WQ_NAME_LEN */
129c8e55f36STejun Heo };
130c8e55f36STejun Heo 
1311da177e4SLinus Torvalds /*
1324cb1ef64STejun Heo  * We don't want to trap softirq for too long. See MAX_SOFTIRQ_TIME and
1334cb1ef64STejun Heo  * MAX_SOFTIRQ_RESTART in kernel/softirq.c. These are macros because
1344cb1ef64STejun Heo  * msecs_to_jiffies() can't be an initializer.
1354cb1ef64STejun Heo  */
1364cb1ef64STejun Heo #define BH_WORKER_JIFFIES	msecs_to_jiffies(2)
1374cb1ef64STejun Heo #define BH_WORKER_RESTARTS	10
1384cb1ef64STejun Heo 
1394cb1ef64STejun Heo /*
1404690c4abSTejun Heo  * Structure fields follow one of the following exclusion rules.
1414690c4abSTejun Heo  *
142e41e704bSTejun Heo  * I: Modifiable by initialization/destruction paths and read-only for
143e41e704bSTejun Heo  *    everyone else.
1444690c4abSTejun Heo  *
145e22bee78STejun Heo  * P: Preemption protected.  Disabling preemption is enough and should
146e22bee78STejun Heo  *    only be modified and accessed from the local cpu.
147e22bee78STejun Heo  *
148d565ed63STejun Heo  * L: pool->lock protected.  Access with pool->lock held.
1494690c4abSTejun Heo  *
1505797b1c1STejun Heo  * LN: pool->lock and wq_node_nr_active->lock protected for writes. Either for
1515797b1c1STejun Heo  *     reads.
1525797b1c1STejun Heo  *
153bdf8b9bfSTejun Heo  * K: Only modified by worker while holding pool->lock. Can be safely read by
154bdf8b9bfSTejun Heo  *    self, while holding pool->lock or from IRQ context if %current is the
155bdf8b9bfSTejun Heo  *    kworker.
156bdf8b9bfSTejun Heo  *
157bdf8b9bfSTejun Heo  * S: Only modified by worker self.
158bdf8b9bfSTejun Heo  *
1591258fae7STejun Heo  * A: wq_pool_attach_mutex protected.
160822d8405STejun Heo  *
16168e13a67SLai Jiangshan  * PL: wq_pool_mutex protected.
16276af4d93STejun Heo  *
16324acfb71SThomas Gleixner  * PR: wq_pool_mutex protected for writes.  RCU protected for reads.
1645bcab335STejun Heo  *
1655b95e1afSLai Jiangshan  * PW: wq_pool_mutex and wq->mutex protected for writes.  Either for reads.
1665b95e1afSLai Jiangshan  *
1675b95e1afSLai Jiangshan  * PWR: wq_pool_mutex and wq->mutex protected for writes.  Either or
16824acfb71SThomas Gleixner  *      RCU for reads.
1695b95e1afSLai Jiangshan  *
1703c25a55dSLai Jiangshan  * WQ: wq->mutex protected.
1713c25a55dSLai Jiangshan  *
17224acfb71SThomas Gleixner  * WR: wq->mutex protected for writes.  RCU protected for reads.
1732e109a28STejun Heo  *
174a045a272STejun Heo  * WO: wq->mutex protected for writes. Updated with WRITE_ONCE() and can be read
175a045a272STejun Heo  *     with READ_ONCE() without locking.
176a045a272STejun Heo  *
1772e109a28STejun Heo  * MD: wq_mayday_lock protected.
178cd2440d6SPetr Mladek  *
179cd2440d6SPetr Mladek  * WD: Used internally by the watchdog.
1804690c4abSTejun Heo  */
1814690c4abSTejun Heo 
1822eaebdb3STejun Heo /* struct worker is defined in workqueue_internal.h */
183c34056a3STejun Heo 
184bd7bdd43STejun Heo struct worker_pool {
185a9b8a985SSebastian Andrzej Siewior 	raw_spinlock_t		lock;		/* the pool lock */
186d84ff051STejun Heo 	int			cpu;		/* I: the associated cpu */
187f3f90ad4STejun Heo 	int			node;		/* I: the associated node ID */
1889daf9e67STejun Heo 	int			id;		/* I: pool ID */
189bc8b50c2STejun Heo 	unsigned int		flags;		/* L: flags */
190bd7bdd43STejun Heo 
19182607adcSTejun Heo 	unsigned long		watchdog_ts;	/* L: watchdog timestamp */
192cd2440d6SPetr Mladek 	bool			cpu_stall;	/* WD: stalled cpu bound pool */
19382607adcSTejun Heo 
194bc35f7efSLai Jiangshan 	/*
195bc35f7efSLai Jiangshan 	 * The counter is incremented in a process context on the associated CPU
196bc35f7efSLai Jiangshan 	 * w/ preemption disabled, and decremented or reset in the same context
197bc35f7efSLai Jiangshan 	 * but w/ pool->lock held. The readers grab pool->lock and are
198bc35f7efSLai Jiangshan 	 * guaranteed to see if the counter reached zero.
199bc35f7efSLai Jiangshan 	 */
200bc35f7efSLai Jiangshan 	int			nr_running;
20184f91c62SLai Jiangshan 
202bd7bdd43STejun Heo 	struct list_head	worklist;	/* L: list of pending works */
203ea1abd61SLai Jiangshan 
2045826cc8fSLai Jiangshan 	int			nr_workers;	/* L: total number of workers */
2055826cc8fSLai Jiangshan 	int			nr_idle;	/* L: currently idle workers */
206bd7bdd43STejun Heo 
2072c1f1a91SLai Jiangshan 	struct list_head	idle_list;	/* L: list of idle workers */
208bd7bdd43STejun Heo 	struct timer_list	idle_timer;	/* L: worker idle timeout */
2093f959aa3SValentin Schneider 	struct work_struct      idle_cull_work; /* L: worker idle cleanup */
2103f959aa3SValentin Schneider 
211bd7bdd43STejun Heo 	struct timer_list	mayday_timer;	  /* L: SOS timer for workers */
212bd7bdd43STejun Heo 
213c5aa87bbSTejun Heo 	/* a workers is either on busy_hash or idle_list, or the manager */
214c9e7cf27STejun Heo 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
215c9e7cf27STejun Heo 						/* L: hash of busy workers */
216c9e7cf27STejun Heo 
2172607d7a6STejun Heo 	struct worker		*manager;	/* L: purely informational */
21892f9c5c4SLai Jiangshan 	struct list_head	workers;	/* A: attached workers */
219e02b9312SValentin Schneider 	struct list_head        dying_workers;  /* A: workers about to die */
22060f5a4bcSLai Jiangshan 	struct completion	*detach_completion; /* all workers detached */
221e19e397aSTejun Heo 
2227cda9aaeSLai Jiangshan 	struct ida		worker_ida;	/* worker IDs for task name */
223e19e397aSTejun Heo 
2247a4e344cSTejun Heo 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
22568e13a67SLai Jiangshan 	struct hlist_node	hash_node;	/* PL: unbound_pool_hash node */
22668e13a67SLai Jiangshan 	int			refcnt;		/* PL: refcnt for unbound pools */
2277a4e344cSTejun Heo 
228e19e397aSTejun Heo 	/*
22924acfb71SThomas Gleixner 	 * Destruction of pool is RCU protected to allow dereferences
23029c91e99STejun Heo 	 * from get_work_pool().
23129c91e99STejun Heo 	 */
23229c91e99STejun Heo 	struct rcu_head		rcu;
23384f91c62SLai Jiangshan };
2348b03ae3cSTejun Heo 
2358b03ae3cSTejun Heo /*
236725e8ec5STejun Heo  * Per-pool_workqueue statistics. These can be monitored using
237725e8ec5STejun Heo  * tools/workqueue/wq_monitor.py.
238725e8ec5STejun Heo  */
239725e8ec5STejun Heo enum pool_workqueue_stats {
240725e8ec5STejun Heo 	PWQ_STAT_STARTED,	/* work items started execution */
241725e8ec5STejun Heo 	PWQ_STAT_COMPLETED,	/* work items completed execution */
2428a1dd1e5STejun Heo 	PWQ_STAT_CPU_TIME,	/* total CPU time consumed */
243616db877STejun Heo 	PWQ_STAT_CPU_INTENSIVE,	/* wq_cpu_intensive_thresh_us violations */
244725e8ec5STejun Heo 	PWQ_STAT_CM_WAKEUP,	/* concurrency-management worker wakeups */
2458639ecebSTejun Heo 	PWQ_STAT_REPATRIATED,	/* unbound workers brought back into scope */
246725e8ec5STejun Heo 	PWQ_STAT_MAYDAY,	/* maydays to rescuer */
247725e8ec5STejun Heo 	PWQ_STAT_RESCUED,	/* linked work items executed by rescuer */
248725e8ec5STejun Heo 
249725e8ec5STejun Heo 	PWQ_NR_STATS,
250725e8ec5STejun Heo };
251725e8ec5STejun Heo 
252725e8ec5STejun Heo /*
253e9a8e01fSTejun Heo  * The per-pool workqueue.  While queued, bits below WORK_PWQ_SHIFT
254112202d9STejun Heo  * of work_struct->data are used for flags and the remaining high bits
255112202d9STejun Heo  * point to the pwq; thus, pwqs need to be aligned at two's power of the
256112202d9STejun Heo  * number of flag bits.
2571da177e4SLinus Torvalds  */
258112202d9STejun Heo struct pool_workqueue {
259bd7bdd43STejun Heo 	struct worker_pool	*pool;		/* I: the associated pool */
2604690c4abSTejun Heo 	struct workqueue_struct *wq;		/* I: the owning workqueue */
26173f53c4aSTejun Heo 	int			work_color;	/* L: current color */
26273f53c4aSTejun Heo 	int			flush_color;	/* L: flushing color */
2638864b4e5STejun Heo 	int			refcnt;		/* L: reference count */
26473f53c4aSTejun Heo 	int			nr_in_flight[WORK_NR_COLORS];
26573f53c4aSTejun Heo 						/* L: nr of in_flight works */
2664c065dbcSWaiman Long 	bool			plugged;	/* L: execution suspended */
267018f3a13SLai Jiangshan 
268018f3a13SLai Jiangshan 	/*
269018f3a13SLai Jiangshan 	 * nr_active management and WORK_STRUCT_INACTIVE:
270018f3a13SLai Jiangshan 	 *
271018f3a13SLai Jiangshan 	 * When pwq->nr_active >= max_active, new work item is queued to
272018f3a13SLai Jiangshan 	 * pwq->inactive_works instead of pool->worklist and marked with
273018f3a13SLai Jiangshan 	 * WORK_STRUCT_INACTIVE.
274018f3a13SLai Jiangshan 	 *
2755797b1c1STejun Heo 	 * All work items marked with WORK_STRUCT_INACTIVE do not participate in
2765797b1c1STejun Heo 	 * nr_active and all work items in pwq->inactive_works are marked with
2775797b1c1STejun Heo 	 * WORK_STRUCT_INACTIVE. But not all WORK_STRUCT_INACTIVE work items are
2785797b1c1STejun Heo 	 * in pwq->inactive_works. Some of them are ready to run in
2795797b1c1STejun Heo 	 * pool->worklist or worker->scheduled. Those work itmes are only struct
2805797b1c1STejun Heo 	 * wq_barrier which is used for flush_work() and should not participate
2815797b1c1STejun Heo 	 * in nr_active. For non-barrier work item, it is marked with
2825797b1c1STejun Heo 	 * WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
283018f3a13SLai Jiangshan 	 */
2841e19ffc6STejun Heo 	int			nr_active;	/* L: nr of active works */
285f97a4a1aSLai Jiangshan 	struct list_head	inactive_works;	/* L: inactive works */
2865797b1c1STejun Heo 	struct list_head	pending_node;	/* LN: node on wq_node_nr_active->pending_pwqs */
2873c25a55dSLai Jiangshan 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
2882e109a28STejun Heo 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
2898864b4e5STejun Heo 
290725e8ec5STejun Heo 	u64			stats[PWQ_NR_STATS];
291725e8ec5STejun Heo 
2928864b4e5STejun Heo 	/*
293967b494eSTejun Heo 	 * Release of unbound pwq is punted to a kthread_worker. See put_pwq()
294687a9aa5STejun Heo 	 * and pwq_release_workfn() for details. pool_workqueue itself is also
295687a9aa5STejun Heo 	 * RCU protected so that the first pwq can be determined without
296967b494eSTejun Heo 	 * grabbing wq->mutex.
2978864b4e5STejun Heo 	 */
298687a9aa5STejun Heo 	struct kthread_work	release_work;
2998864b4e5STejun Heo 	struct rcu_head		rcu;
300e9a8e01fSTejun Heo } __aligned(1 << WORK_STRUCT_PWQ_SHIFT);
3011da177e4SLinus Torvalds 
3021da177e4SLinus Torvalds /*
30373f53c4aSTejun Heo  * Structure used to wait for workqueue flush.
30473f53c4aSTejun Heo  */
30573f53c4aSTejun Heo struct wq_flusher {
3063c25a55dSLai Jiangshan 	struct list_head	list;		/* WQ: list of flushers */
3073c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: flush color waiting for */
30873f53c4aSTejun Heo 	struct completion	done;		/* flush completion */
30973f53c4aSTejun Heo };
3101da177e4SLinus Torvalds 
311226223abSTejun Heo struct wq_device;
312226223abSTejun Heo 
31373f53c4aSTejun Heo /*
31491ccc6e7STejun Heo  * Unlike in a per-cpu workqueue where max_active limits its concurrency level
31591ccc6e7STejun Heo  * on each CPU, in an unbound workqueue, max_active applies to the whole system.
31691ccc6e7STejun Heo  * As sharing a single nr_active across multiple sockets can be very expensive,
31791ccc6e7STejun Heo  * the counting and enforcement is per NUMA node.
3185797b1c1STejun Heo  *
3195797b1c1STejun Heo  * The following struct is used to enforce per-node max_active. When a pwq wants
3205797b1c1STejun Heo  * to start executing a work item, it should increment ->nr using
3215797b1c1STejun Heo  * tryinc_node_nr_active(). If acquisition fails due to ->nr already being over
3225797b1c1STejun Heo  * ->max, the pwq is queued on ->pending_pwqs. As in-flight work items finish
3235797b1c1STejun Heo  * and decrement ->nr, node_activate_pending_pwq() activates the pending pwqs in
3245797b1c1STejun Heo  * round-robin order.
32591ccc6e7STejun Heo  */
32691ccc6e7STejun Heo struct wq_node_nr_active {
3275797b1c1STejun Heo 	int			max;		/* per-node max_active */
3285797b1c1STejun Heo 	atomic_t		nr;		/* per-node nr_active */
3295797b1c1STejun Heo 	raw_spinlock_t		lock;		/* nests inside pool locks */
3305797b1c1STejun Heo 	struct list_head	pending_pwqs;	/* LN: pwqs with inactive works */
33191ccc6e7STejun Heo };
33291ccc6e7STejun Heo 
33391ccc6e7STejun Heo /*
334c5aa87bbSTejun Heo  * The externally visible workqueue.  It relays the issued work items to
335c5aa87bbSTejun Heo  * the appropriate worker_pool through its pool_workqueues.
3361da177e4SLinus Torvalds  */
3371da177e4SLinus Torvalds struct workqueue_struct {
3383c25a55dSLai Jiangshan 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
339e2dca7adSTejun Heo 	struct list_head	list;		/* PR: list of all workqueues */
34073f53c4aSTejun Heo 
3413c25a55dSLai Jiangshan 	struct mutex		mutex;		/* protects this wq */
3423c25a55dSLai Jiangshan 	int			work_color;	/* WQ: current work color */
3433c25a55dSLai Jiangshan 	int			flush_color;	/* WQ: current flush color */
344112202d9STejun Heo 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
3453c25a55dSLai Jiangshan 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
3463c25a55dSLai Jiangshan 	struct list_head	flusher_queue;	/* WQ: flush waiters */
3473c25a55dSLai Jiangshan 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
34873f53c4aSTejun Heo 
3492e109a28STejun Heo 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
35030ae2fc0STejun Heo 	struct worker		*rescuer;	/* MD: rescue worker */
351e22bee78STejun Heo 
35287fc741eSLai Jiangshan 	int			nr_drainers;	/* WQ: drain in progress */
3535797b1c1STejun Heo 
3545797b1c1STejun Heo 	/* See alloc_workqueue() function comment for info on min/max_active */
355a045a272STejun Heo 	int			max_active;	/* WO: max active works */
3565797b1c1STejun Heo 	int			min_active;	/* WO: min active works */
357a045a272STejun Heo 	int			saved_max_active; /* WQ: saved max_active */
3585797b1c1STejun Heo 	int			saved_min_active; /* WQ: saved min_active */
359226223abSTejun Heo 
3605b95e1afSLai Jiangshan 	struct workqueue_attrs	*unbound_attrs;	/* PW: only for unbound wqs */
3619f66cff2STejun Heo 	struct pool_workqueue __rcu *dfl_pwq;   /* PW: only for unbound wqs */
3626029a918STejun Heo 
363226223abSTejun Heo #ifdef CONFIG_SYSFS
364226223abSTejun Heo 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
365226223abSTejun Heo #endif
3664e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
367669de8bdSBart Van Assche 	char			*lock_name;
368669de8bdSBart Van Assche 	struct lock_class_key	key;
3694e6045f1SJohannes Berg 	struct lockdep_map	lockdep_map;
3704e6045f1SJohannes Berg #endif
371ecf6881fSTejun Heo 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
3722728fd2fSTejun Heo 
373e2dca7adSTejun Heo 	/*
37424acfb71SThomas Gleixner 	 * Destruction of workqueue_struct is RCU protected to allow walking
37524acfb71SThomas Gleixner 	 * the workqueues list without grabbing wq_pool_mutex.
376e2dca7adSTejun Heo 	 * This is used to dump all workqueues from sysrq.
377e2dca7adSTejun Heo 	 */
378e2dca7adSTejun Heo 	struct rcu_head		rcu;
379e2dca7adSTejun Heo 
3802728fd2fSTejun Heo 	/* hot fields used during command issue, aligned to cacheline */
3812728fd2fSTejun Heo 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
382636b927eSTejun Heo 	struct pool_workqueue __percpu __rcu **cpu_pwq; /* I: per-cpu pwqs */
38391ccc6e7STejun Heo 	struct wq_node_nr_active *node_nr_active[]; /* I: per-node nr_active */
3841da177e4SLinus Torvalds };
3851da177e4SLinus Torvalds 
38684193c07STejun Heo /*
38784193c07STejun Heo  * Each pod type describes how CPUs should be grouped for unbound workqueues.
38884193c07STejun Heo  * See the comment above workqueue_attrs->affn_scope.
38984193c07STejun Heo  */
39084193c07STejun Heo struct wq_pod_type {
39184193c07STejun Heo 	int			nr_pods;	/* number of pods */
39284193c07STejun Heo 	cpumask_var_t		*pod_cpus;	/* pod -> cpus */
39384193c07STejun Heo 	int			*pod_node;	/* pod -> node */
39484193c07STejun Heo 	int			*cpu_pod;	/* cpu -> pod */
39584193c07STejun Heo };
39684193c07STejun Heo 
3971211f3b2STejun Heo struct work_offq_data {
3981211f3b2STejun Heo 	u32			pool_id;
39986898fa6STejun Heo 	u32			disable;
4001211f3b2STejun Heo 	u32			flags;
4011211f3b2STejun Heo };
4021211f3b2STejun Heo 
40363c5484eSTejun Heo static const char *wq_affn_names[WQ_AFFN_NR_TYPES] = {
404523a301eSTejun Heo 	[WQ_AFFN_DFL]		= "default",
40563c5484eSTejun Heo 	[WQ_AFFN_CPU]		= "cpu",
40663c5484eSTejun Heo 	[WQ_AFFN_SMT]		= "smt",
40763c5484eSTejun Heo 	[WQ_AFFN_CACHE]		= "cache",
40863c5484eSTejun Heo 	[WQ_AFFN_NUMA]		= "numa",
40963c5484eSTejun Heo 	[WQ_AFFN_SYSTEM]	= "system",
41063c5484eSTejun Heo };
411bce90380STejun Heo 
412616db877STejun Heo /*
413616db877STejun Heo  * Per-cpu work items which run for longer than the following threshold are
414616db877STejun Heo  * automatically considered CPU intensive and excluded from concurrency
415616db877STejun Heo  * management to prevent them from noticeably delaying other per-cpu work items.
416aa6fde93STejun Heo  * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
417aa6fde93STejun Heo  * The actual value is initialized in wq_cpu_intensive_thresh_init().
418616db877STejun Heo  */
419aa6fde93STejun Heo static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
420616db877STejun Heo module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
421ccdec921SXuewen Yan #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
422ccdec921SXuewen Yan static unsigned int wq_cpu_intensive_warning_thresh = 4;
423ccdec921SXuewen Yan module_param_named(cpu_intensive_warning_thresh, wq_cpu_intensive_warning_thresh, uint, 0644);
424ccdec921SXuewen Yan #endif
425616db877STejun Heo 
426cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
427552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
428cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
429cee22a15SViresh Kumar 
430863b710bSTejun Heo static bool wq_online;			/* can kworkers be created yet? */
431c7a40c49STejun Heo static bool wq_topo_initialized __read_mostly = false;
432c7a40c49STejun Heo 
433c7a40c49STejun Heo static struct kmem_cache *pwq_cache;
434c7a40c49STejun Heo 
435c7a40c49STejun Heo static struct wq_pod_type wq_pod_types[WQ_AFFN_NR_TYPES];
436c7a40c49STejun Heo static enum wq_affn_scope wq_affn_dfl = WQ_AFFN_CACHE;
4373347fa09STejun Heo 
438fef59c9cSTejun Heo /* buf for wq_update_unbound_pod_attrs(), protected by CPU hotplug exclusion */
439fef59c9cSTejun Heo static struct workqueue_attrs *wq_update_pod_attrs_buf;
4404c16bd32STejun Heo 
44168e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
4421258fae7STejun Heo static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
443a9b8a985SSebastian Andrzej Siewior static DEFINE_RAW_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
444d8bb65abSSebastian Andrzej Siewior /* wait for manager to go away */
445d8bb65abSSebastian Andrzej Siewior static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
4465bcab335STejun Heo 
447e2dca7adSTejun Heo static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
44868e13a67SLai Jiangshan static bool workqueue_freezing;		/* PL: have wqs started freezing? */
4497d19c5ceSTejun Heo 
45099c621efSLai Jiangshan /* PL&A: allowable cpus for unbound wqs and work items */
451ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
452ef557180SMike Galbraith 
453fe28f631SWaiman Long /* PL: user requested unbound cpumask via sysfs */
454fe28f631SWaiman Long static cpumask_var_t wq_requested_unbound_cpumask;
455fe28f631SWaiman Long 
456fe28f631SWaiman Long /* PL: isolated cpumask to be excluded from unbound cpumask */
457fe28f631SWaiman Long static cpumask_var_t wq_isolated_cpumask;
458fe28f631SWaiman Long 
459ace3c549Stiozhang /* for further constrain wq_unbound_cpumask by cmdline parameter*/
460ace3c549Stiozhang static struct cpumask wq_cmdline_cpumask __initdata;
461ace3c549Stiozhang 
462ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
463ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
464b05a7928SFrederic Weisbecker 
465f303fccbSTejun Heo /*
466f303fccbSTejun Heo  * Local execution of unbound work items is no longer guaranteed.  The
467f303fccbSTejun Heo  * following always forces round-robin CPU selection on unbound work items
468f303fccbSTejun Heo  * to uncover usages which depend on it.
469f303fccbSTejun Heo  */
470f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
471f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
472f303fccbSTejun Heo #else
473f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
474f303fccbSTejun Heo #endif
475f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
476f303fccbSTejun Heo 
4772f34d733STejun Heo /* to raise softirq for the BH worker pools on other CPUs */
4782f34d733STejun Heo static DEFINE_PER_CPU_SHARED_ALIGNED(struct irq_work [NR_STD_WORKER_POOLS],
4792f34d733STejun Heo 				     bh_pool_irq_works);
4802f34d733STejun Heo 
4814cb1ef64STejun Heo /* the BH worker pools */
4824cb1ef64STejun Heo static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
4834cb1ef64STejun Heo 				     bh_worker_pools);
4844cb1ef64STejun Heo 
4857d19c5ceSTejun Heo /* the per-cpu worker pools */
4864cb1ef64STejun Heo static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS],
4874cb1ef64STejun Heo 				     cpu_worker_pools);
4887d19c5ceSTejun Heo 
48968e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
4907d19c5ceSTejun Heo 
49168e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
49229c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
49329c91e99STejun Heo 
494c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
49529c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
49629c91e99STejun Heo 
4978a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
4988a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
4998a2b7538STejun Heo 
500967b494eSTejun Heo /*
501967b494eSTejun Heo  * I: kthread_worker to release pwq's. pwq release needs to be bounced to a
502967b494eSTejun Heo  * process context while holding a pool lock. Bounce to a dedicated kthread
503967b494eSTejun Heo  * worker to avoid A-A deadlocks.
504967b494eSTejun Heo  */
50568279f9cSAlexey Dobriyan static struct kthread_worker *pwq_release_worker __ro_after_init;
506967b494eSTejun Heo 
50768279f9cSAlexey Dobriyan struct workqueue_struct *system_wq __ro_after_init;
508ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
50968279f9cSAlexey Dobriyan struct workqueue_struct *system_highpri_wq __ro_after_init;
5101aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
51168279f9cSAlexey Dobriyan struct workqueue_struct *system_long_wq __ro_after_init;
512d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
51368279f9cSAlexey Dobriyan struct workqueue_struct *system_unbound_wq __ro_after_init;
514f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
51568279f9cSAlexey Dobriyan struct workqueue_struct *system_freezable_wq __ro_after_init;
51624d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
51768279f9cSAlexey Dobriyan struct workqueue_struct *system_power_efficient_wq __ro_after_init;
5180668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
51968279f9cSAlexey Dobriyan struct workqueue_struct *system_freezable_power_efficient_wq __ro_after_init;
5200668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
5214cb1ef64STejun Heo struct workqueue_struct *system_bh_wq;
5224cb1ef64STejun Heo EXPORT_SYMBOL_GPL(system_bh_wq);
5234cb1ef64STejun Heo struct workqueue_struct *system_bh_highpri_wq;
5244cb1ef64STejun Heo EXPORT_SYMBOL_GPL(system_bh_highpri_wq);
525d320c038STejun Heo 
5267d19c5ceSTejun Heo static int worker_thread(void *__worker);
5276ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
528c29eb853STejun Heo static void show_pwq(struct pool_workqueue *pwq);
52955df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool);
5307d19c5ceSTejun Heo 
53197bd2347STejun Heo #define CREATE_TRACE_POINTS
53297bd2347STejun Heo #include <trace/events/workqueue.h>
53397bd2347STejun Heo 
53468e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex()					\
535d355001fSTejun Heo 	RCU_LOCKDEP_WARN(!rcu_read_lock_any_held() &&			\
536f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
53724acfb71SThomas Gleixner 			 "RCU or wq_pool_mutex should be held")
5385bcab335STejun Heo 
5395b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq)			\
540d355001fSTejun Heo 	RCU_LOCKDEP_WARN(!rcu_read_lock_any_held() &&			\
541f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq->mutex) &&		\
542f78f5b90SPaul E. McKenney 			 !lockdep_is_held(&wq_pool_mutex),		\
54324acfb71SThomas Gleixner 			 "RCU, wq->mutex or wq_pool_mutex should be held")
5445b95e1afSLai Jiangshan 
5454cb1ef64STejun Heo #define for_each_bh_worker_pool(pool, cpu)				\
5464cb1ef64STejun Heo 	for ((pool) = &per_cpu(bh_worker_pools, cpu)[0];		\
5474cb1ef64STejun Heo 	     (pool) < &per_cpu(bh_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
5484cb1ef64STejun Heo 	     (pool)++)
5494cb1ef64STejun Heo 
550f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu)				\
551f02ae73aSTejun Heo 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
552f02ae73aSTejun Heo 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
5537a62c2c8STejun Heo 	     (pool)++)
5544ce62e9eSTejun Heo 
55549e3cf44STejun Heo /**
55617116969STejun Heo  * for_each_pool - iterate through all worker_pools in the system
55717116969STejun Heo  * @pool: iteration cursor
558611c92a0STejun Heo  * @pi: integer used for iteration
559fa1b54e6STejun Heo  *
56024acfb71SThomas Gleixner  * This must be called either with wq_pool_mutex held or RCU read
56168e13a67SLai Jiangshan  * locked.  If the pool needs to be used beyond the locking in effect, the
56268e13a67SLai Jiangshan  * caller is responsible for guaranteeing that the pool stays online.
563fa1b54e6STejun Heo  *
564fa1b54e6STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
565fa1b54e6STejun Heo  * ignored.
56617116969STejun Heo  */
567611c92a0STejun Heo #define for_each_pool(pool, pi)						\
568611c92a0STejun Heo 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
56968e13a67SLai Jiangshan 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
570fa1b54e6STejun Heo 		else
57117116969STejun Heo 
57217116969STejun Heo /**
573822d8405STejun Heo  * for_each_pool_worker - iterate through all workers of a worker_pool
574822d8405STejun Heo  * @worker: iteration cursor
575822d8405STejun Heo  * @pool: worker_pool to iterate workers of
576822d8405STejun Heo  *
5771258fae7STejun Heo  * This must be called with wq_pool_attach_mutex.
578822d8405STejun Heo  *
579822d8405STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
580822d8405STejun Heo  * ignored.
581822d8405STejun Heo  */
582da028469SLai Jiangshan #define for_each_pool_worker(worker, pool)				\
583da028469SLai Jiangshan 	list_for_each_entry((worker), &(pool)->workers, node)		\
5841258fae7STejun Heo 		if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
585822d8405STejun Heo 		else
586822d8405STejun Heo 
587822d8405STejun Heo /**
58849e3cf44STejun Heo  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
58949e3cf44STejun Heo  * @pwq: iteration cursor
59049e3cf44STejun Heo  * @wq: the target workqueue
59176af4d93STejun Heo  *
59224acfb71SThomas Gleixner  * This must be called either with wq->mutex held or RCU read locked.
593794b18bcSTejun Heo  * If the pwq needs to be used beyond the locking in effect, the caller is
594794b18bcSTejun Heo  * responsible for guaranteeing that the pwq stays online.
59576af4d93STejun Heo  *
59676af4d93STejun Heo  * The if/else clause exists only for the lockdep assertion and can be
59776af4d93STejun Heo  * ignored.
59849e3cf44STejun Heo  */
59949e3cf44STejun Heo #define for_each_pwq(pwq, wq)						\
60049e9d1a9SSebastian Andrzej Siewior 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node,		\
6015a644662SJoel Fernandes (Google) 				 lockdep_is_held(&(wq->mutex)))
602f3421797STejun Heo 
603dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
604dc186ad7SThomas Gleixner 
605f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr;
606dc186ad7SThomas Gleixner 
60799777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
60899777288SStanislaw Gruszka {
60999777288SStanislaw Gruszka 	return ((struct work_struct *) addr)->func;
61099777288SStanislaw Gruszka }
61199777288SStanislaw Gruszka 
612b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
613b9fdac7fSDu, Changbin {
614b9fdac7fSDu, Changbin 	struct work_struct *work = addr;
615b9fdac7fSDu, Changbin 
616b9fdac7fSDu, Changbin 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
617b9fdac7fSDu, Changbin }
618b9fdac7fSDu, Changbin 
619dc186ad7SThomas Gleixner /*
620dc186ad7SThomas Gleixner  * fixup_init is called when:
621dc186ad7SThomas Gleixner  * - an active object is initialized
622dc186ad7SThomas Gleixner  */
62302a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
624dc186ad7SThomas Gleixner {
625dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
626dc186ad7SThomas Gleixner 
627dc186ad7SThomas Gleixner 	switch (state) {
628dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
629dc186ad7SThomas Gleixner 		cancel_work_sync(work);
630dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
63102a982a6SDu, Changbin 		return true;
632dc186ad7SThomas Gleixner 	default:
63302a982a6SDu, Changbin 		return false;
634dc186ad7SThomas Gleixner 	}
635dc186ad7SThomas Gleixner }
636dc186ad7SThomas Gleixner 
637dc186ad7SThomas Gleixner /*
638dc186ad7SThomas Gleixner  * fixup_free is called when:
639dc186ad7SThomas Gleixner  * - an active object is freed
640dc186ad7SThomas Gleixner  */
64102a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
642dc186ad7SThomas Gleixner {
643dc186ad7SThomas Gleixner 	struct work_struct *work = addr;
644dc186ad7SThomas Gleixner 
645dc186ad7SThomas Gleixner 	switch (state) {
646dc186ad7SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
647dc186ad7SThomas Gleixner 		cancel_work_sync(work);
648dc186ad7SThomas Gleixner 		debug_object_free(work, &work_debug_descr);
64902a982a6SDu, Changbin 		return true;
650dc186ad7SThomas Gleixner 	default:
65102a982a6SDu, Changbin 		return false;
652dc186ad7SThomas Gleixner 	}
653dc186ad7SThomas Gleixner }
654dc186ad7SThomas Gleixner 
655f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr = {
656dc186ad7SThomas Gleixner 	.name		= "work_struct",
65799777288SStanislaw Gruszka 	.debug_hint	= work_debug_hint,
658b9fdac7fSDu, Changbin 	.is_static_object = work_is_static_object,
659dc186ad7SThomas Gleixner 	.fixup_init	= work_fixup_init,
660dc186ad7SThomas Gleixner 	.fixup_free	= work_fixup_free,
661dc186ad7SThomas Gleixner };
662dc186ad7SThomas Gleixner 
663dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
664dc186ad7SThomas Gleixner {
665dc186ad7SThomas Gleixner 	debug_object_activate(work, &work_debug_descr);
666dc186ad7SThomas Gleixner }
667dc186ad7SThomas Gleixner 
668dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
669dc186ad7SThomas Gleixner {
670dc186ad7SThomas Gleixner 	debug_object_deactivate(work, &work_debug_descr);
671dc186ad7SThomas Gleixner }
672dc186ad7SThomas Gleixner 
673dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
674dc186ad7SThomas Gleixner {
675dc186ad7SThomas Gleixner 	if (onstack)
676dc186ad7SThomas Gleixner 		debug_object_init_on_stack(work, &work_debug_descr);
677dc186ad7SThomas Gleixner 	else
678dc186ad7SThomas Gleixner 		debug_object_init(work, &work_debug_descr);
679dc186ad7SThomas Gleixner }
680dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
681dc186ad7SThomas Gleixner 
682dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
683dc186ad7SThomas Gleixner {
684dc186ad7SThomas Gleixner 	debug_object_free(work, &work_debug_descr);
685dc186ad7SThomas Gleixner }
686dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
687dc186ad7SThomas Gleixner 
688ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
689ea2e64f2SThomas Gleixner {
690ea2e64f2SThomas Gleixner 	destroy_timer_on_stack(&work->timer);
691ea2e64f2SThomas Gleixner 	debug_object_free(&work->work, &work_debug_descr);
692ea2e64f2SThomas Gleixner }
693ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
694ea2e64f2SThomas Gleixner 
695dc186ad7SThomas Gleixner #else
696dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
697dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
698dc186ad7SThomas Gleixner #endif
699dc186ad7SThomas Gleixner 
7004e8b22bdSLi Bin /**
70167dc8325SCai Huoqing  * worker_pool_assign_id - allocate ID and assign it to @pool
7024e8b22bdSLi Bin  * @pool: the pool pointer of interest
7034e8b22bdSLi Bin  *
7044e8b22bdSLi Bin  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
7054e8b22bdSLi Bin  * successfully, -errno on failure.
7064e8b22bdSLi Bin  */
7079daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
7089daf9e67STejun Heo {
7099daf9e67STejun Heo 	int ret;
7109daf9e67STejun Heo 
71168e13a67SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
7125bcab335STejun Heo 
7134e8b22bdSLi Bin 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
7144e8b22bdSLi Bin 			GFP_KERNEL);
715229641a6STejun Heo 	if (ret >= 0) {
716e68035fbSTejun Heo 		pool->id = ret;
717229641a6STejun Heo 		return 0;
718229641a6STejun Heo 	}
7199daf9e67STejun Heo 	return ret;
7209daf9e67STejun Heo }
7219daf9e67STejun Heo 
7229f66cff2STejun Heo static struct pool_workqueue __rcu **
7239f66cff2STejun Heo unbound_pwq_slot(struct workqueue_struct *wq, int cpu)
7249f66cff2STejun Heo {
7259f66cff2STejun Heo        if (cpu >= 0)
7269f66cff2STejun Heo                return per_cpu_ptr(wq->cpu_pwq, cpu);
7279f66cff2STejun Heo        else
7289f66cff2STejun Heo                return &wq->dfl_pwq;
7299f66cff2STejun Heo }
7309f66cff2STejun Heo 
7319f66cff2STejun Heo /* @cpu < 0 for dfl_pwq */
7329f66cff2STejun Heo static struct pool_workqueue *unbound_pwq(struct workqueue_struct *wq, int cpu)
7339f66cff2STejun Heo {
7349f66cff2STejun Heo 	return rcu_dereference_check(*unbound_pwq_slot(wq, cpu),
7359f66cff2STejun Heo 				     lockdep_is_held(&wq_pool_mutex) ||
7369f66cff2STejun Heo 				     lockdep_is_held(&wq->mutex));
7379f66cff2STejun Heo }
7389f66cff2STejun Heo 
7395797b1c1STejun Heo /**
7405797b1c1STejun Heo  * unbound_effective_cpumask - effective cpumask of an unbound workqueue
7415797b1c1STejun Heo  * @wq: workqueue of interest
7425797b1c1STejun Heo  *
7435797b1c1STejun Heo  * @wq->unbound_attrs->cpumask contains the cpumask requested by the user which
7445797b1c1STejun Heo  * is masked with wq_unbound_cpumask to determine the effective cpumask. The
7455797b1c1STejun Heo  * default pwq is always mapped to the pool with the current effective cpumask.
7465797b1c1STejun Heo  */
7475797b1c1STejun Heo static struct cpumask *unbound_effective_cpumask(struct workqueue_struct *wq)
7485797b1c1STejun Heo {
7495797b1c1STejun Heo 	return unbound_pwq(wq, -1)->pool->attrs->__pod_cpumask;
7505797b1c1STejun Heo }
7515797b1c1STejun Heo 
75273f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
75373f53c4aSTejun Heo {
75473f53c4aSTejun Heo 	return color << WORK_STRUCT_COLOR_SHIFT;
75573f53c4aSTejun Heo }
75673f53c4aSTejun Heo 
757c4560c2cSLai Jiangshan static int get_work_color(unsigned long work_data)
75873f53c4aSTejun Heo {
759c4560c2cSLai Jiangshan 	return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
76073f53c4aSTejun Heo 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
76173f53c4aSTejun Heo }
76273f53c4aSTejun Heo 
76373f53c4aSTejun Heo static int work_next_color(int color)
76473f53c4aSTejun Heo {
76573f53c4aSTejun Heo 	return (color + 1) % WORK_NR_COLORS;
766a848e3b6SOleg Nesterov }
767a848e3b6SOleg Nesterov 
768456a78eeSTejun Heo static unsigned long pool_offq_flags(struct worker_pool *pool)
769456a78eeSTejun Heo {
770456a78eeSTejun Heo 	return (pool->flags & POOL_BH) ? WORK_OFFQ_BH : 0;
771456a78eeSTejun Heo }
772456a78eeSTejun Heo 
7734594bf15SDavid Howells /*
774112202d9STejun Heo  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
775112202d9STejun Heo  * contain the pointer to the queued pwq.  Once execution starts, the flag
7767c3eed5cSTejun Heo  * is cleared and the high bits contain OFFQ flags and pool ID.
7777a22ad75STejun Heo  *
778afe928c1STejun Heo  * set_work_pwq(), set_work_pool_and_clear_pending() and mark_work_canceling()
779afe928c1STejun Heo  * can be used to set the pwq, pool or clear work->data. These functions should
780afe928c1STejun Heo  * only be called while the work is owned - ie. while the PENDING bit is set.
7817a22ad75STejun Heo  *
782112202d9STejun Heo  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
7837c3eed5cSTejun Heo  * corresponding to a work.  Pool is available once the work has been
784112202d9STejun Heo  * queued anywhere after initialization until it is sync canceled.  pwq is
7857c3eed5cSTejun Heo  * available only while the work item is queued.
7864594bf15SDavid Howells  */
787bccdc1faSTejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data)
7887a22ad75STejun Heo {
7896183c009STejun Heo 	WARN_ON_ONCE(!work_pending(work));
790bccdc1faSTejun Heo 	atomic_long_set(&work->data, data | work_static(work));
7917a22ad75STejun Heo }
7927a22ad75STejun Heo 
793112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
794bccdc1faSTejun Heo 			 unsigned long flags)
795365970a1SDavid Howells {
796bccdc1faSTejun Heo 	set_work_data(work, (unsigned long)pwq | WORK_STRUCT_PENDING |
797bccdc1faSTejun Heo 		      WORK_STRUCT_PWQ | flags);
798365970a1SDavid Howells }
799365970a1SDavid Howells 
8004468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
801bccdc1faSTejun Heo 					   int pool_id, unsigned long flags)
8024468a00fSLai Jiangshan {
803bccdc1faSTejun Heo 	set_work_data(work, ((unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT) |
804bccdc1faSTejun Heo 		      WORK_STRUCT_PENDING | flags);
8054468a00fSLai Jiangshan }
8064468a00fSLai Jiangshan 
8077c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
808bccdc1faSTejun Heo 					    int pool_id, unsigned long flags)
8094d707b9fSOleg Nesterov {
81023657bb1STejun Heo 	/*
81123657bb1STejun Heo 	 * The following wmb is paired with the implied mb in
81223657bb1STejun Heo 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
81323657bb1STejun Heo 	 * here are visible to and precede any updates by the next PENDING
81423657bb1STejun Heo 	 * owner.
81523657bb1STejun Heo 	 */
81623657bb1STejun Heo 	smp_wmb();
817bccdc1faSTejun Heo 	set_work_data(work, ((unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT) |
818bccdc1faSTejun Heo 		      flags);
819346c09f8SRoman Pen 	/*
820346c09f8SRoman Pen 	 * The following mb guarantees that previous clear of a PENDING bit
821346c09f8SRoman Pen 	 * will not be reordered with any speculative LOADS or STORES from
822346c09f8SRoman Pen 	 * work->current_func, which is executed afterwards.  This possible
8238bdc6201SLiu Song 	 * reordering can lead to a missed execution on attempt to queue
824346c09f8SRoman Pen 	 * the same @work.  E.g. consider this case:
825346c09f8SRoman Pen 	 *
826346c09f8SRoman Pen 	 *   CPU#0                         CPU#1
827346c09f8SRoman Pen 	 *   ----------------------------  --------------------------------
828346c09f8SRoman Pen 	 *
829346c09f8SRoman Pen 	 * 1  STORE event_indicated
830346c09f8SRoman Pen 	 * 2  queue_work_on() {
831346c09f8SRoman Pen 	 * 3    test_and_set_bit(PENDING)
832346c09f8SRoman Pen 	 * 4 }                             set_..._and_clear_pending() {
833346c09f8SRoman Pen 	 * 5                                 set_work_data() # clear bit
834346c09f8SRoman Pen 	 * 6                                 smp_mb()
835346c09f8SRoman Pen 	 * 7                               work->current_func() {
836346c09f8SRoman Pen 	 * 8				      LOAD event_indicated
837346c09f8SRoman Pen 	 *				   }
838346c09f8SRoman Pen 	 *
839346c09f8SRoman Pen 	 * Without an explicit full barrier speculative LOAD on line 8 can
840346c09f8SRoman Pen 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
841346c09f8SRoman Pen 	 * CPU#0 observes the PENDING bit is still set and new execution of
842346c09f8SRoman Pen 	 * a @work is not queued in a hope, that CPU#1 will eventually
843346c09f8SRoman Pen 	 * finish the queued @work.  Meanwhile CPU#1 does not see
844346c09f8SRoman Pen 	 * event_indicated is set, because speculative LOAD was executed
845346c09f8SRoman Pen 	 * before actual STORE.
846346c09f8SRoman Pen 	 */
847346c09f8SRoman Pen 	smp_mb();
8484d707b9fSOleg Nesterov }
8494d707b9fSOleg Nesterov 
850afa4bb77SLinus Torvalds static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
851afa4bb77SLinus Torvalds {
852e9a8e01fSTejun Heo 	return (struct pool_workqueue *)(data & WORK_STRUCT_PWQ_MASK);
853afa4bb77SLinus Torvalds }
854afa4bb77SLinus Torvalds 
855112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
8567a22ad75STejun Heo {
857e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
8587a22ad75STejun Heo 
859112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
860afa4bb77SLinus Torvalds 		return work_struct_pwq(data);
861e120153dSTejun Heo 	else
862e120153dSTejun Heo 		return NULL;
8637a22ad75STejun Heo }
8647a22ad75STejun Heo 
8657c3eed5cSTejun Heo /**
8667c3eed5cSTejun Heo  * get_work_pool - return the worker_pool a given work was associated with
8677c3eed5cSTejun Heo  * @work: the work item of interest
8687c3eed5cSTejun Heo  *
86968e13a67SLai Jiangshan  * Pools are created and destroyed under wq_pool_mutex, and allows read
87024acfb71SThomas Gleixner  * access under RCU read lock.  As such, this function should be
87124acfb71SThomas Gleixner  * called under wq_pool_mutex or inside of a rcu_read_lock() region.
872fa1b54e6STejun Heo  *
873fa1b54e6STejun Heo  * All fields of the returned pool are accessible as long as the above
874fa1b54e6STejun Heo  * mentioned locking is in effect.  If the returned pool needs to be used
875fa1b54e6STejun Heo  * beyond the critical section, the caller is responsible for ensuring the
876fa1b54e6STejun Heo  * returned pool is and stays online.
877d185af30SYacine Belkadi  *
878d185af30SYacine Belkadi  * Return: The worker_pool @work was last associated with.  %NULL if none.
8797c3eed5cSTejun Heo  */
8807c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
8817a22ad75STejun Heo {
882e120153dSTejun Heo 	unsigned long data = atomic_long_read(&work->data);
8837c3eed5cSTejun Heo 	int pool_id;
8847a22ad75STejun Heo 
88568e13a67SLai Jiangshan 	assert_rcu_or_pool_mutex();
886fa1b54e6STejun Heo 
887112202d9STejun Heo 	if (data & WORK_STRUCT_PWQ)
888afa4bb77SLinus Torvalds 		return work_struct_pwq(data)->pool;
8897a22ad75STejun Heo 
8907c3eed5cSTejun Heo 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
8917c3eed5cSTejun Heo 	if (pool_id == WORK_OFFQ_POOL_NONE)
8927a22ad75STejun Heo 		return NULL;
8937a22ad75STejun Heo 
894fa1b54e6STejun Heo 	return idr_find(&worker_pool_idr, pool_id);
8957c3eed5cSTejun Heo }
8967c3eed5cSTejun Heo 
8971211f3b2STejun Heo static unsigned long shift_and_mask(unsigned long v, u32 shift, u32 bits)
8987c3eed5cSTejun Heo {
8991211f3b2STejun Heo 	return (v >> shift) & ((1 << bits) - 1);
9007c3eed5cSTejun Heo }
9017c3eed5cSTejun Heo 
9021211f3b2STejun Heo static void work_offqd_unpack(struct work_offq_data *offqd, unsigned long data)
903bbb68dfaSTejun Heo {
9041211f3b2STejun Heo 	WARN_ON_ONCE(data & WORK_STRUCT_PWQ);
905bbb68dfaSTejun Heo 
9061211f3b2STejun Heo 	offqd->pool_id = shift_and_mask(data, WORK_OFFQ_POOL_SHIFT,
9071211f3b2STejun Heo 					WORK_OFFQ_POOL_BITS);
90886898fa6STejun Heo 	offqd->disable = shift_and_mask(data, WORK_OFFQ_DISABLE_SHIFT,
90986898fa6STejun Heo 					WORK_OFFQ_DISABLE_BITS);
9101211f3b2STejun Heo 	offqd->flags = data & WORK_OFFQ_FLAG_MASK;
911bbb68dfaSTejun Heo }
912bbb68dfaSTejun Heo 
9131211f3b2STejun Heo static unsigned long work_offqd_pack_flags(struct work_offq_data *offqd)
914bbb68dfaSTejun Heo {
91586898fa6STejun Heo 	return ((unsigned long)offqd->disable << WORK_OFFQ_DISABLE_SHIFT) |
91686898fa6STejun Heo 		((unsigned long)offqd->flags);
917bbb68dfaSTejun Heo }
918bbb68dfaSTejun Heo 
919e22bee78STejun Heo /*
9203270476aSTejun Heo  * Policy functions.  These define the policies on how the global worker
9213270476aSTejun Heo  * pools are managed.  Unless noted otherwise, these functions assume that
922d565ed63STejun Heo  * they're being called with pool->lock held.
923e22bee78STejun Heo  */
924e22bee78STejun Heo 
925e22bee78STejun Heo /*
926e22bee78STejun Heo  * Need to wake up a worker?  Called from anything but currently
927e22bee78STejun Heo  * running workers.
928974271c4STejun Heo  *
929974271c4STejun Heo  * Note that, because unbound workers never contribute to nr_running, this
930706026c2STejun Heo  * function will always return %true for unbound pools as long as the
931974271c4STejun Heo  * worklist isn't empty.
932e22bee78STejun Heo  */
93363d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
934e22bee78STejun Heo {
9350219a352STejun Heo 	return !list_empty(&pool->worklist) && !pool->nr_running;
936e22bee78STejun Heo }
937e22bee78STejun Heo 
938e22bee78STejun Heo /* Can I start working?  Called from busy but !running workers. */
93963d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
940e22bee78STejun Heo {
94163d95a91STejun Heo 	return pool->nr_idle;
942e22bee78STejun Heo }
943e22bee78STejun Heo 
944e22bee78STejun Heo /* Do I need to keep working?  Called from currently running workers. */
94563d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
946e22bee78STejun Heo {
947bc35f7efSLai Jiangshan 	return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
948e22bee78STejun Heo }
949e22bee78STejun Heo 
950e22bee78STejun Heo /* Do we need a new worker?  Called from manager. */
95163d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
952e22bee78STejun Heo {
95363d95a91STejun Heo 	return need_more_worker(pool) && !may_start_working(pool);
954e22bee78STejun Heo }
955e22bee78STejun Heo 
956e22bee78STejun Heo /* Do we have too many workers and should some go away? */
95763d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
958e22bee78STejun Heo {
959692b4825STejun Heo 	bool managing = pool->flags & POOL_MANAGER_ACTIVE;
96063d95a91STejun Heo 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
96163d95a91STejun Heo 	int nr_busy = pool->nr_workers - nr_idle;
962e22bee78STejun Heo 
963e22bee78STejun Heo 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
964e22bee78STejun Heo }
965e22bee78STejun Heo 
9664690c4abSTejun Heo /**
967e22bee78STejun Heo  * worker_set_flags - set worker flags and adjust nr_running accordingly
968cb444766STejun Heo  * @worker: self
969d302f017STejun Heo  * @flags: flags to set
970d302f017STejun Heo  *
971228f1d00SLai Jiangshan  * Set @flags in @worker->flags and adjust nr_running accordingly.
972d302f017STejun Heo  */
973228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
974d302f017STejun Heo {
975bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
976e22bee78STejun Heo 
977bc8b50c2STejun Heo 	lockdep_assert_held(&pool->lock);
978cb444766STejun Heo 
979228f1d00SLai Jiangshan 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
980e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) &&
981e22bee78STejun Heo 	    !(worker->flags & WORKER_NOT_RUNNING)) {
982bc35f7efSLai Jiangshan 		pool->nr_running--;
983e22bee78STejun Heo 	}
984e22bee78STejun Heo 
985d302f017STejun Heo 	worker->flags |= flags;
986d302f017STejun Heo }
987d302f017STejun Heo 
988d302f017STejun Heo /**
989e22bee78STejun Heo  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
990cb444766STejun Heo  * @worker: self
991d302f017STejun Heo  * @flags: flags to clear
992d302f017STejun Heo  *
993e22bee78STejun Heo  * Clear @flags in @worker->flags and adjust nr_running accordingly.
994d302f017STejun Heo  */
995d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
996d302f017STejun Heo {
99763d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
998e22bee78STejun Heo 	unsigned int oflags = worker->flags;
999e22bee78STejun Heo 
1000bc8b50c2STejun Heo 	lockdep_assert_held(&pool->lock);
1001cb444766STejun Heo 
1002d302f017STejun Heo 	worker->flags &= ~flags;
1003e22bee78STejun Heo 
100442c025f3STejun Heo 	/*
100542c025f3STejun Heo 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
100642c025f3STejun Heo 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
100742c025f3STejun Heo 	 * of multiple flags, not a single flag.
100842c025f3STejun Heo 	 */
1009e22bee78STejun Heo 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
1010e22bee78STejun Heo 		if (!(worker->flags & WORKER_NOT_RUNNING))
1011bc35f7efSLai Jiangshan 			pool->nr_running++;
1012d302f017STejun Heo }
1013d302f017STejun Heo 
1014797e8345STejun Heo /* Return the first idle worker.  Called with pool->lock held. */
1015797e8345STejun Heo static struct worker *first_idle_worker(struct worker_pool *pool)
1016797e8345STejun Heo {
1017797e8345STejun Heo 	if (unlikely(list_empty(&pool->idle_list)))
1018797e8345STejun Heo 		return NULL;
1019797e8345STejun Heo 
1020797e8345STejun Heo 	return list_first_entry(&pool->idle_list, struct worker, entry);
1021797e8345STejun Heo }
1022797e8345STejun Heo 
1023797e8345STejun Heo /**
1024797e8345STejun Heo  * worker_enter_idle - enter idle state
1025797e8345STejun Heo  * @worker: worker which is entering idle state
1026797e8345STejun Heo  *
1027797e8345STejun Heo  * @worker is entering idle state.  Update stats and idle timer if
1028797e8345STejun Heo  * necessary.
1029797e8345STejun Heo  *
1030797e8345STejun Heo  * LOCKING:
1031797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1032797e8345STejun Heo  */
1033797e8345STejun Heo static void worker_enter_idle(struct worker *worker)
1034797e8345STejun Heo {
1035797e8345STejun Heo 	struct worker_pool *pool = worker->pool;
1036797e8345STejun Heo 
1037797e8345STejun Heo 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1038797e8345STejun Heo 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
1039797e8345STejun Heo 			 (worker->hentry.next || worker->hentry.pprev)))
1040797e8345STejun Heo 		return;
1041797e8345STejun Heo 
1042797e8345STejun Heo 	/* can't use worker_set_flags(), also called from create_worker() */
1043797e8345STejun Heo 	worker->flags |= WORKER_IDLE;
1044797e8345STejun Heo 	pool->nr_idle++;
1045797e8345STejun Heo 	worker->last_active = jiffies;
1046797e8345STejun Heo 
1047797e8345STejun Heo 	/* idle_list is LIFO */
1048797e8345STejun Heo 	list_add(&worker->entry, &pool->idle_list);
1049797e8345STejun Heo 
1050797e8345STejun Heo 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1051797e8345STejun Heo 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1052797e8345STejun Heo 
1053797e8345STejun Heo 	/* Sanity check nr_running. */
1054797e8345STejun Heo 	WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
1055797e8345STejun Heo }
1056797e8345STejun Heo 
1057797e8345STejun Heo /**
1058797e8345STejun Heo  * worker_leave_idle - leave idle state
1059797e8345STejun Heo  * @worker: worker which is leaving idle state
1060797e8345STejun Heo  *
1061797e8345STejun Heo  * @worker is leaving idle state.  Update stats.
1062797e8345STejun Heo  *
1063797e8345STejun Heo  * LOCKING:
1064797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1065797e8345STejun Heo  */
1066797e8345STejun Heo static void worker_leave_idle(struct worker *worker)
1067797e8345STejun Heo {
1068797e8345STejun Heo 	struct worker_pool *pool = worker->pool;
1069797e8345STejun Heo 
1070797e8345STejun Heo 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1071797e8345STejun Heo 		return;
1072797e8345STejun Heo 	worker_clr_flags(worker, WORKER_IDLE);
1073797e8345STejun Heo 	pool->nr_idle--;
1074797e8345STejun Heo 	list_del_init(&worker->entry);
1075797e8345STejun Heo }
1076797e8345STejun Heo 
1077797e8345STejun Heo /**
1078797e8345STejun Heo  * find_worker_executing_work - find worker which is executing a work
1079797e8345STejun Heo  * @pool: pool of interest
1080797e8345STejun Heo  * @work: work to find worker for
1081797e8345STejun Heo  *
1082797e8345STejun Heo  * Find a worker which is executing @work on @pool by searching
1083797e8345STejun Heo  * @pool->busy_hash which is keyed by the address of @work.  For a worker
1084797e8345STejun Heo  * to match, its current execution should match the address of @work and
1085797e8345STejun Heo  * its work function.  This is to avoid unwanted dependency between
1086797e8345STejun Heo  * unrelated work executions through a work item being recycled while still
1087797e8345STejun Heo  * being executed.
1088797e8345STejun Heo  *
1089797e8345STejun Heo  * This is a bit tricky.  A work item may be freed once its execution
1090797e8345STejun Heo  * starts and nothing prevents the freed area from being recycled for
1091797e8345STejun Heo  * another work item.  If the same work item address ends up being reused
1092797e8345STejun Heo  * before the original execution finishes, workqueue will identify the
1093797e8345STejun Heo  * recycled work item as currently executing and make it wait until the
1094797e8345STejun Heo  * current execution finishes, introducing an unwanted dependency.
1095797e8345STejun Heo  *
1096797e8345STejun Heo  * This function checks the work item address and work function to avoid
1097797e8345STejun Heo  * false positives.  Note that this isn't complete as one may construct a
1098797e8345STejun Heo  * work function which can introduce dependency onto itself through a
1099797e8345STejun Heo  * recycled work item.  Well, if somebody wants to shoot oneself in the
1100797e8345STejun Heo  * foot that badly, there's only so much we can do, and if such deadlock
1101797e8345STejun Heo  * actually occurs, it should be easy to locate the culprit work function.
1102797e8345STejun Heo  *
1103797e8345STejun Heo  * CONTEXT:
1104797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1105797e8345STejun Heo  *
1106797e8345STejun Heo  * Return:
1107797e8345STejun Heo  * Pointer to worker which is executing @work if found, %NULL
1108797e8345STejun Heo  * otherwise.
1109797e8345STejun Heo  */
1110797e8345STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
1111797e8345STejun Heo 						 struct work_struct *work)
1112797e8345STejun Heo {
1113797e8345STejun Heo 	struct worker *worker;
1114797e8345STejun Heo 
1115797e8345STejun Heo 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1116797e8345STejun Heo 			       (unsigned long)work)
1117797e8345STejun Heo 		if (worker->current_work == work &&
1118797e8345STejun Heo 		    worker->current_func == work->func)
1119797e8345STejun Heo 			return worker;
1120797e8345STejun Heo 
1121797e8345STejun Heo 	return NULL;
1122797e8345STejun Heo }
1123797e8345STejun Heo 
1124797e8345STejun Heo /**
1125797e8345STejun Heo  * move_linked_works - move linked works to a list
1126797e8345STejun Heo  * @work: start of series of works to be scheduled
1127797e8345STejun Heo  * @head: target list to append @work to
1128797e8345STejun Heo  * @nextp: out parameter for nested worklist walking
1129797e8345STejun Heo  *
1130873eaca6STejun Heo  * Schedule linked works starting from @work to @head. Work series to be
1131873eaca6STejun Heo  * scheduled starts at @work and includes any consecutive work with
1132873eaca6STejun Heo  * WORK_STRUCT_LINKED set in its predecessor. See assign_work() for details on
1133873eaca6STejun Heo  * @nextp.
1134797e8345STejun Heo  *
1135797e8345STejun Heo  * CONTEXT:
1136797e8345STejun Heo  * raw_spin_lock_irq(pool->lock).
1137797e8345STejun Heo  */
1138797e8345STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1139797e8345STejun Heo 			      struct work_struct **nextp)
1140797e8345STejun Heo {
1141797e8345STejun Heo 	struct work_struct *n;
1142797e8345STejun Heo 
1143797e8345STejun Heo 	/*
1144797e8345STejun Heo 	 * Linked worklist will always end before the end of the list,
1145797e8345STejun Heo 	 * use NULL for list head.
1146797e8345STejun Heo 	 */
1147797e8345STejun Heo 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1148797e8345STejun Heo 		list_move_tail(&work->entry, head);
1149797e8345STejun Heo 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1150797e8345STejun Heo 			break;
1151797e8345STejun Heo 	}
1152797e8345STejun Heo 
1153797e8345STejun Heo 	/*
1154797e8345STejun Heo 	 * If we're already inside safe list traversal and have moved
1155797e8345STejun Heo 	 * multiple works to the scheduled queue, the next position
1156797e8345STejun Heo 	 * needs to be updated.
1157797e8345STejun Heo 	 */
1158797e8345STejun Heo 	if (nextp)
1159797e8345STejun Heo 		*nextp = n;
1160797e8345STejun Heo }
1161797e8345STejun Heo 
1162797e8345STejun Heo /**
1163873eaca6STejun Heo  * assign_work - assign a work item and its linked work items to a worker
1164873eaca6STejun Heo  * @work: work to assign
1165873eaca6STejun Heo  * @worker: worker to assign to
1166873eaca6STejun Heo  * @nextp: out parameter for nested worklist walking
1167873eaca6STejun Heo  *
1168873eaca6STejun Heo  * Assign @work and its linked work items to @worker. If @work is already being
1169873eaca6STejun Heo  * executed by another worker in the same pool, it'll be punted there.
1170873eaca6STejun Heo  *
1171873eaca6STejun Heo  * If @nextp is not NULL, it's updated to point to the next work of the last
1172873eaca6STejun Heo  * scheduled work. This allows assign_work() to be nested inside
1173873eaca6STejun Heo  * list_for_each_entry_safe().
1174873eaca6STejun Heo  *
1175873eaca6STejun Heo  * Returns %true if @work was successfully assigned to @worker. %false if @work
1176873eaca6STejun Heo  * was punted to another worker already executing it.
1177873eaca6STejun Heo  */
1178873eaca6STejun Heo static bool assign_work(struct work_struct *work, struct worker *worker,
1179873eaca6STejun Heo 			struct work_struct **nextp)
1180873eaca6STejun Heo {
1181873eaca6STejun Heo 	struct worker_pool *pool = worker->pool;
1182873eaca6STejun Heo 	struct worker *collision;
1183873eaca6STejun Heo 
1184873eaca6STejun Heo 	lockdep_assert_held(&pool->lock);
1185873eaca6STejun Heo 
1186873eaca6STejun Heo 	/*
1187873eaca6STejun Heo 	 * A single work shouldn't be executed concurrently by multiple workers.
1188873eaca6STejun Heo 	 * __queue_work() ensures that @work doesn't jump to a different pool
1189873eaca6STejun Heo 	 * while still running in the previous pool. Here, we should ensure that
1190873eaca6STejun Heo 	 * @work is not executed concurrently by multiple workers from the same
1191873eaca6STejun Heo 	 * pool. Check whether anyone is already processing the work. If so,
1192873eaca6STejun Heo 	 * defer the work to the currently executing one.
1193873eaca6STejun Heo 	 */
1194873eaca6STejun Heo 	collision = find_worker_executing_work(pool, work);
1195873eaca6STejun Heo 	if (unlikely(collision)) {
1196873eaca6STejun Heo 		move_linked_works(work, &collision->scheduled, nextp);
1197873eaca6STejun Heo 		return false;
1198873eaca6STejun Heo 	}
1199873eaca6STejun Heo 
1200873eaca6STejun Heo 	move_linked_works(work, &worker->scheduled, nextp);
1201873eaca6STejun Heo 	return true;
1202873eaca6STejun Heo }
1203873eaca6STejun Heo 
12042f34d733STejun Heo static struct irq_work *bh_pool_irq_work(struct worker_pool *pool)
12052f34d733STejun Heo {
12062f34d733STejun Heo 	int high = pool->attrs->nice == HIGHPRI_NICE_LEVEL ? 1 : 0;
12072f34d733STejun Heo 
12082f34d733STejun Heo 	return &per_cpu(bh_pool_irq_works, pool->cpu)[high];
12092f34d733STejun Heo }
12102f34d733STejun Heo 
1211fd0a68a2STejun Heo static void kick_bh_pool(struct worker_pool *pool)
1212fd0a68a2STejun Heo {
1213fd0a68a2STejun Heo #ifdef CONFIG_SMP
12141acd92d9STejun Heo 	/* see drain_dead_softirq_workfn() for BH_DRAINING */
12151acd92d9STejun Heo 	if (unlikely(pool->cpu != smp_processor_id() &&
12161acd92d9STejun Heo 		     !(pool->flags & POOL_BH_DRAINING))) {
1217fd0a68a2STejun Heo 		irq_work_queue_on(bh_pool_irq_work(pool), pool->cpu);
1218fd0a68a2STejun Heo 		return;
1219fd0a68a2STejun Heo 	}
1220fd0a68a2STejun Heo #endif
1221fd0a68a2STejun Heo 	if (pool->attrs->nice == HIGHPRI_NICE_LEVEL)
1222fd0a68a2STejun Heo 		raise_softirq_irqoff(HI_SOFTIRQ);
1223fd0a68a2STejun Heo 	else
1224fd0a68a2STejun Heo 		raise_softirq_irqoff(TASKLET_SOFTIRQ);
1225fd0a68a2STejun Heo }
1226fd0a68a2STejun Heo 
1227873eaca6STejun Heo /**
12280219a352STejun Heo  * kick_pool - wake up an idle worker if necessary
12290219a352STejun Heo  * @pool: pool to kick
1230797e8345STejun Heo  *
12310219a352STejun Heo  * @pool may have pending work items. Wake up worker if necessary. Returns
12320219a352STejun Heo  * whether a worker was woken up.
1233797e8345STejun Heo  */
12340219a352STejun Heo static bool kick_pool(struct worker_pool *pool)
1235797e8345STejun Heo {
1236797e8345STejun Heo 	struct worker *worker = first_idle_worker(pool);
12378639ecebSTejun Heo 	struct task_struct *p;
1238797e8345STejun Heo 
12390219a352STejun Heo 	lockdep_assert_held(&pool->lock);
12400219a352STejun Heo 
12410219a352STejun Heo 	if (!need_more_worker(pool) || !worker)
12420219a352STejun Heo 		return false;
12430219a352STejun Heo 
12444cb1ef64STejun Heo 	if (pool->flags & POOL_BH) {
1245fd0a68a2STejun Heo 		kick_bh_pool(pool);
12464cb1ef64STejun Heo 		return true;
12474cb1ef64STejun Heo 	}
12484cb1ef64STejun Heo 
12498639ecebSTejun Heo 	p = worker->task;
12508639ecebSTejun Heo 
12518639ecebSTejun Heo #ifdef CONFIG_SMP
12528639ecebSTejun Heo 	/*
12538639ecebSTejun Heo 	 * Idle @worker is about to execute @work and waking up provides an
12548639ecebSTejun Heo 	 * opportunity to migrate @worker at a lower cost by setting the task's
12558639ecebSTejun Heo 	 * wake_cpu field. Let's see if we want to move @worker to improve
12568639ecebSTejun Heo 	 * execution locality.
12578639ecebSTejun Heo 	 *
12588639ecebSTejun Heo 	 * We're waking the worker that went idle the latest and there's some
12598639ecebSTejun Heo 	 * chance that @worker is marked idle but hasn't gone off CPU yet. If
12608639ecebSTejun Heo 	 * so, setting the wake_cpu won't do anything. As this is a best-effort
12618639ecebSTejun Heo 	 * optimization and the race window is narrow, let's leave as-is for
12628639ecebSTejun Heo 	 * now. If this becomes pronounced, we can skip over workers which are
12638639ecebSTejun Heo 	 * still on cpu when picking an idle worker.
12648639ecebSTejun Heo 	 *
12658639ecebSTejun Heo 	 * If @pool has non-strict affinity, @worker might have ended up outside
12668639ecebSTejun Heo 	 * its affinity scope. Repatriate.
12678639ecebSTejun Heo 	 */
12688639ecebSTejun Heo 	if (!pool->attrs->affn_strict &&
12698639ecebSTejun Heo 	    !cpumask_test_cpu(p->wake_cpu, pool->attrs->__pod_cpumask)) {
12708639ecebSTejun Heo 		struct work_struct *work = list_first_entry(&pool->worklist,
12718639ecebSTejun Heo 						struct work_struct, entry);
127257a01eafSSven Schnelle 		int wake_cpu = cpumask_any_and_distribute(pool->attrs->__pod_cpumask,
127357a01eafSSven Schnelle 							  cpu_online_mask);
127457a01eafSSven Schnelle 		if (wake_cpu < nr_cpu_ids) {
127557a01eafSSven Schnelle 			p->wake_cpu = wake_cpu;
12768639ecebSTejun Heo 			get_work_pwq(work)->stats[PWQ_STAT_REPATRIATED]++;
12778639ecebSTejun Heo 		}
127857a01eafSSven Schnelle 	}
12798639ecebSTejun Heo #endif
12808639ecebSTejun Heo 	wake_up_process(p);
12810219a352STejun Heo 	return true;
1282797e8345STejun Heo }
1283797e8345STejun Heo 
128463638450STejun Heo #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
128563638450STejun Heo 
128663638450STejun Heo /*
128763638450STejun Heo  * Concurrency-managed per-cpu work items that hog CPU for longer than
128863638450STejun Heo  * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
128963638450STejun Heo  * which prevents them from stalling other concurrency-managed work items. If a
129063638450STejun Heo  * work function keeps triggering this mechanism, it's likely that the work item
129163638450STejun Heo  * should be using an unbound workqueue instead.
129263638450STejun Heo  *
129363638450STejun Heo  * wq_cpu_intensive_report() tracks work functions which trigger such conditions
129463638450STejun Heo  * and report them so that they can be examined and converted to use unbound
129563638450STejun Heo  * workqueues as appropriate. To avoid flooding the console, each violating work
129663638450STejun Heo  * function is tracked and reported with exponential backoff.
129763638450STejun Heo  */
129863638450STejun Heo #define WCI_MAX_ENTS 128
129963638450STejun Heo 
130063638450STejun Heo struct wci_ent {
130163638450STejun Heo 	work_func_t		func;
130263638450STejun Heo 	atomic64_t		cnt;
130363638450STejun Heo 	struct hlist_node	hash_node;
130463638450STejun Heo };
130563638450STejun Heo 
130663638450STejun Heo static struct wci_ent wci_ents[WCI_MAX_ENTS];
130763638450STejun Heo static int wci_nr_ents;
130863638450STejun Heo static DEFINE_RAW_SPINLOCK(wci_lock);
130963638450STejun Heo static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
131063638450STejun Heo 
131163638450STejun Heo static struct wci_ent *wci_find_ent(work_func_t func)
131263638450STejun Heo {
131363638450STejun Heo 	struct wci_ent *ent;
131463638450STejun Heo 
131563638450STejun Heo 	hash_for_each_possible_rcu(wci_hash, ent, hash_node,
131663638450STejun Heo 				   (unsigned long)func) {
131763638450STejun Heo 		if (ent->func == func)
131863638450STejun Heo 			return ent;
131963638450STejun Heo 	}
132063638450STejun Heo 	return NULL;
132163638450STejun Heo }
132263638450STejun Heo 
132363638450STejun Heo static void wq_cpu_intensive_report(work_func_t func)
132463638450STejun Heo {
132563638450STejun Heo 	struct wci_ent *ent;
132663638450STejun Heo 
132763638450STejun Heo restart:
132863638450STejun Heo 	ent = wci_find_ent(func);
132963638450STejun Heo 	if (ent) {
133063638450STejun Heo 		u64 cnt;
133163638450STejun Heo 
133263638450STejun Heo 		/*
1333ccdec921SXuewen Yan 		 * Start reporting from the warning_thresh and back off
133463638450STejun Heo 		 * exponentially.
133563638450STejun Heo 		 */
133663638450STejun Heo 		cnt = atomic64_inc_return_relaxed(&ent->cnt);
1337ccdec921SXuewen Yan 		if (wq_cpu_intensive_warning_thresh &&
1338ccdec921SXuewen Yan 		    cnt >= wq_cpu_intensive_warning_thresh &&
1339ccdec921SXuewen Yan 		    is_power_of_2(cnt + 1 - wq_cpu_intensive_warning_thresh))
134063638450STejun Heo 			printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
134163638450STejun Heo 					ent->func, wq_cpu_intensive_thresh_us,
134263638450STejun Heo 					atomic64_read(&ent->cnt));
134363638450STejun Heo 		return;
134463638450STejun Heo 	}
134563638450STejun Heo 
134663638450STejun Heo 	/*
134763638450STejun Heo 	 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
134863638450STejun Heo 	 * is exhausted, something went really wrong and we probably made enough
134963638450STejun Heo 	 * noise already.
135063638450STejun Heo 	 */
135163638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS)
135263638450STejun Heo 		return;
135363638450STejun Heo 
135463638450STejun Heo 	raw_spin_lock(&wci_lock);
135563638450STejun Heo 
135663638450STejun Heo 	if (wci_nr_ents >= WCI_MAX_ENTS) {
135763638450STejun Heo 		raw_spin_unlock(&wci_lock);
135863638450STejun Heo 		return;
135963638450STejun Heo 	}
136063638450STejun Heo 
136163638450STejun Heo 	if (wci_find_ent(func)) {
136263638450STejun Heo 		raw_spin_unlock(&wci_lock);
136363638450STejun Heo 		goto restart;
136463638450STejun Heo 	}
136563638450STejun Heo 
136663638450STejun Heo 	ent = &wci_ents[wci_nr_ents++];
136763638450STejun Heo 	ent->func = func;
1368ccdec921SXuewen Yan 	atomic64_set(&ent->cnt, 0);
136963638450STejun Heo 	hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
137063638450STejun Heo 
137163638450STejun Heo 	raw_spin_unlock(&wci_lock);
1372ccdec921SXuewen Yan 
1373ccdec921SXuewen Yan 	goto restart;
137463638450STejun Heo }
137563638450STejun Heo 
137663638450STejun Heo #else	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
137763638450STejun Heo static void wq_cpu_intensive_report(work_func_t func) {}
137863638450STejun Heo #endif	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
137963638450STejun Heo 
1380c54d5046STejun Heo /**
13811da177e4SLinus Torvalds  * wq_worker_running - a worker is running again
13821da177e4SLinus Torvalds  * @task: task waking up
13831da177e4SLinus Torvalds  *
13841da177e4SLinus Torvalds  * This function is called when a worker returns from schedule()
13851da177e4SLinus Torvalds  */
13861da177e4SLinus Torvalds void wq_worker_running(struct task_struct *task)
13871da177e4SLinus Torvalds {
13881da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
13891da177e4SLinus Torvalds 
1390c8f6219bSZqiang 	if (!READ_ONCE(worker->sleeping))
13911da177e4SLinus Torvalds 		return;
13921da177e4SLinus Torvalds 
13931da177e4SLinus Torvalds 	/*
13941da177e4SLinus Torvalds 	 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
13951da177e4SLinus Torvalds 	 * and the nr_running increment below, we may ruin the nr_running reset
13961da177e4SLinus Torvalds 	 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
13971da177e4SLinus Torvalds 	 * pool. Protect against such race.
13981da177e4SLinus Torvalds 	 */
13991da177e4SLinus Torvalds 	preempt_disable();
14001da177e4SLinus Torvalds 	if (!(worker->flags & WORKER_NOT_RUNNING))
14011da177e4SLinus Torvalds 		worker->pool->nr_running++;
14021da177e4SLinus Torvalds 	preempt_enable();
1403616db877STejun Heo 
1404616db877STejun Heo 	/*
1405616db877STejun Heo 	 * CPU intensive auto-detection cares about how long a work item hogged
1406616db877STejun Heo 	 * CPU without sleeping. Reset the starting timestamp on wakeup.
1407616db877STejun Heo 	 */
1408616db877STejun Heo 	worker->current_at = worker->task->se.sum_exec_runtime;
1409616db877STejun Heo 
1410c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 0);
14111da177e4SLinus Torvalds }
14121da177e4SLinus Torvalds 
14131da177e4SLinus Torvalds /**
14141da177e4SLinus Torvalds  * wq_worker_sleeping - a worker is going to sleep
14151da177e4SLinus Torvalds  * @task: task going to sleep
14161da177e4SLinus Torvalds  *
14171da177e4SLinus Torvalds  * This function is called from schedule() when a busy worker is
14181da177e4SLinus Torvalds  * going to sleep.
14191da177e4SLinus Torvalds  */
14201da177e4SLinus Torvalds void wq_worker_sleeping(struct task_struct *task)
14211da177e4SLinus Torvalds {
14221da177e4SLinus Torvalds 	struct worker *worker = kthread_data(task);
14231da177e4SLinus Torvalds 	struct worker_pool *pool;
14241da177e4SLinus Torvalds 
14251da177e4SLinus Torvalds 	/*
14261da177e4SLinus Torvalds 	 * Rescuers, which may not have all the fields set up like normal
14271da177e4SLinus Torvalds 	 * workers, also reach here, let's not access anything before
14281da177e4SLinus Torvalds 	 * checking NOT_RUNNING.
14291da177e4SLinus Torvalds 	 */
14301da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING)
14311da177e4SLinus Torvalds 		return;
14321da177e4SLinus Torvalds 
14331da177e4SLinus Torvalds 	pool = worker->pool;
14341da177e4SLinus Torvalds 
14351da177e4SLinus Torvalds 	/* Return if preempted before wq_worker_running() was reached */
1436c8f6219bSZqiang 	if (READ_ONCE(worker->sleeping))
14371da177e4SLinus Torvalds 		return;
14381da177e4SLinus Torvalds 
1439c8f6219bSZqiang 	WRITE_ONCE(worker->sleeping, 1);
14401da177e4SLinus Torvalds 	raw_spin_lock_irq(&pool->lock);
14411da177e4SLinus Torvalds 
14421da177e4SLinus Torvalds 	/*
14431da177e4SLinus Torvalds 	 * Recheck in case unbind_workers() preempted us. We don't
14441da177e4SLinus Torvalds 	 * want to decrement nr_running after the worker is unbound
14451da177e4SLinus Torvalds 	 * and nr_running has been reset.
14461da177e4SLinus Torvalds 	 */
14471da177e4SLinus Torvalds 	if (worker->flags & WORKER_NOT_RUNNING) {
14481da177e4SLinus Torvalds 		raw_spin_unlock_irq(&pool->lock);
14491da177e4SLinus Torvalds 		return;
14501da177e4SLinus Torvalds 	}
14511da177e4SLinus Torvalds 
14521da177e4SLinus Torvalds 	pool->nr_running--;
14530219a352STejun Heo 	if (kick_pool(pool))
1454725e8ec5STejun Heo 		worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
14550219a352STejun Heo 
14561da177e4SLinus Torvalds 	raw_spin_unlock_irq(&pool->lock);
14571da177e4SLinus Torvalds }
14581da177e4SLinus Torvalds 
14591da177e4SLinus Torvalds /**
1460616db877STejun Heo  * wq_worker_tick - a scheduler tick occurred while a kworker is running
1461616db877STejun Heo  * @task: task currently running
1462616db877STejun Heo  *
146386dd6c04SIngo Molnar  * Called from sched_tick(). We're in the IRQ context and the current
1464616db877STejun Heo  * worker's fields which follow the 'K' locking rule can be accessed safely.
1465616db877STejun Heo  */
1466616db877STejun Heo void wq_worker_tick(struct task_struct *task)
1467616db877STejun Heo {
1468616db877STejun Heo 	struct worker *worker = kthread_data(task);
1469616db877STejun Heo 	struct pool_workqueue *pwq = worker->current_pwq;
1470616db877STejun Heo 	struct worker_pool *pool = worker->pool;
1471616db877STejun Heo 
1472616db877STejun Heo 	if (!pwq)
1473616db877STejun Heo 		return;
1474616db877STejun Heo 
14758a1dd1e5STejun Heo 	pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
14768a1dd1e5STejun Heo 
147718c8ae81SZqiang 	if (!wq_cpu_intensive_thresh_us)
147818c8ae81SZqiang 		return;
147918c8ae81SZqiang 
1480616db877STejun Heo 	/*
1481616db877STejun Heo 	 * If the current worker is concurrency managed and hogged the CPU for
1482616db877STejun Heo 	 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1483616db877STejun Heo 	 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1484c8f6219bSZqiang 	 *
1485c8f6219bSZqiang 	 * Set @worker->sleeping means that @worker is in the process of
1486c8f6219bSZqiang 	 * switching out voluntarily and won't be contributing to
1487c8f6219bSZqiang 	 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1488c8f6219bSZqiang 	 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1489c8f6219bSZqiang 	 * double decrements. The task is releasing the CPU anyway. Let's skip.
1490c8f6219bSZqiang 	 * We probably want to make this prettier in the future.
1491616db877STejun Heo 	 */
1492c8f6219bSZqiang 	if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1493616db877STejun Heo 	    worker->task->se.sum_exec_runtime - worker->current_at <
1494616db877STejun Heo 	    wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1495616db877STejun Heo 		return;
1496616db877STejun Heo 
1497616db877STejun Heo 	raw_spin_lock(&pool->lock);
1498616db877STejun Heo 
1499616db877STejun Heo 	worker_set_flags(worker, WORKER_CPU_INTENSIVE);
150063638450STejun Heo 	wq_cpu_intensive_report(worker->current_func);
1501616db877STejun Heo 	pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1502616db877STejun Heo 
15030219a352STejun Heo 	if (kick_pool(pool))
1504616db877STejun Heo 		pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1505616db877STejun Heo 
1506616db877STejun Heo 	raw_spin_unlock(&pool->lock);
1507616db877STejun Heo }
1508616db877STejun Heo 
1509616db877STejun Heo /**
15101da177e4SLinus Torvalds  * wq_worker_last_func - retrieve worker's last work function
15111da177e4SLinus Torvalds  * @task: Task to retrieve last work function of.
15121da177e4SLinus Torvalds  *
15131da177e4SLinus Torvalds  * Determine the last function a worker executed. This is called from
15141da177e4SLinus Torvalds  * the scheduler to get a worker's last known identity.
15151da177e4SLinus Torvalds  *
15169b41ea72SAndrew Morton  * CONTEXT:
15171da177e4SLinus Torvalds  * raw_spin_lock_irq(rq->lock)
15181da177e4SLinus Torvalds  *
1519f756d5e2SNathan Lynch  * This function is called during schedule() when a kworker is going
1520f756d5e2SNathan Lynch  * to sleep. It's used by psi to identify aggregation workers during
15211da177e4SLinus Torvalds  * dequeuing, to allow periodic aggregation to shut-off when that
15221da177e4SLinus Torvalds  * worker is the last task in the system or cgroup to go to sleep.
15231da177e4SLinus Torvalds  *
15241da177e4SLinus Torvalds  * As this function doesn't involve any workqueue-related locking, it
15251da177e4SLinus Torvalds  * only returns stable values when called from inside the scheduler's
15261da177e4SLinus Torvalds  * queuing and dequeuing paths, when @task, which must be a kworker,
1527365970a1SDavid Howells  * is guaranteed to not be processing any works.
1528365970a1SDavid Howells  *
1529365970a1SDavid Howells  * Return:
1530365970a1SDavid Howells  * The last work function %current executed as a worker, NULL if it
1531365970a1SDavid Howells  * hasn't executed any work yet.
1532365970a1SDavid Howells  */
1533365970a1SDavid Howells work_func_t wq_worker_last_func(struct task_struct *task)
1534365970a1SDavid Howells {
1535365970a1SDavid Howells 	struct worker *worker = kthread_data(task);
1536365970a1SDavid Howells 
1537365970a1SDavid Howells 	return worker->last_func;
1538365970a1SDavid Howells }
1539365970a1SDavid Howells 
1540d302f017STejun Heo /**
154191ccc6e7STejun Heo  * wq_node_nr_active - Determine wq_node_nr_active to use
154291ccc6e7STejun Heo  * @wq: workqueue of interest
154391ccc6e7STejun Heo  * @node: NUMA node, can be %NUMA_NO_NODE
154491ccc6e7STejun Heo  *
154591ccc6e7STejun Heo  * Determine wq_node_nr_active to use for @wq on @node. Returns:
154691ccc6e7STejun Heo  *
154791ccc6e7STejun Heo  * - %NULL for per-cpu workqueues as they don't need to use shared nr_active.
154891ccc6e7STejun Heo  *
154991ccc6e7STejun Heo  * - node_nr_active[nr_node_ids] if @node is %NUMA_NO_NODE.
155091ccc6e7STejun Heo  *
155191ccc6e7STejun Heo  * - Otherwise, node_nr_active[@node].
155291ccc6e7STejun Heo  */
155391ccc6e7STejun Heo static struct wq_node_nr_active *wq_node_nr_active(struct workqueue_struct *wq,
155491ccc6e7STejun Heo 						   int node)
155591ccc6e7STejun Heo {
155691ccc6e7STejun Heo 	if (!(wq->flags & WQ_UNBOUND))
155791ccc6e7STejun Heo 		return NULL;
155891ccc6e7STejun Heo 
155991ccc6e7STejun Heo 	if (node == NUMA_NO_NODE)
156091ccc6e7STejun Heo 		node = nr_node_ids;
156191ccc6e7STejun Heo 
156291ccc6e7STejun Heo 	return wq->node_nr_active[node];
156391ccc6e7STejun Heo }
156491ccc6e7STejun Heo 
156591ccc6e7STejun Heo /**
15665797b1c1STejun Heo  * wq_update_node_max_active - Update per-node max_actives to use
15675797b1c1STejun Heo  * @wq: workqueue to update
15685797b1c1STejun Heo  * @off_cpu: CPU that's going down, -1 if a CPU is not going down
15695797b1c1STejun Heo  *
15705797b1c1STejun Heo  * Update @wq->node_nr_active[]->max. @wq must be unbound. max_active is
15715797b1c1STejun Heo  * distributed among nodes according to the proportions of numbers of online
15725797b1c1STejun Heo  * cpus. The result is always between @wq->min_active and max_active.
15735797b1c1STejun Heo  */
15745797b1c1STejun Heo static void wq_update_node_max_active(struct workqueue_struct *wq, int off_cpu)
15755797b1c1STejun Heo {
15765797b1c1STejun Heo 	struct cpumask *effective = unbound_effective_cpumask(wq);
15775797b1c1STejun Heo 	int min_active = READ_ONCE(wq->min_active);
15785797b1c1STejun Heo 	int max_active = READ_ONCE(wq->max_active);
15795797b1c1STejun Heo 	int total_cpus, node;
15805797b1c1STejun Heo 
15815797b1c1STejun Heo 	lockdep_assert_held(&wq->mutex);
15825797b1c1STejun Heo 
1583c5f8cd6cSTejun Heo 	if (!wq_topo_initialized)
1584c5f8cd6cSTejun Heo 		return;
1585c5f8cd6cSTejun Heo 
158615930da4STejun Heo 	if (off_cpu >= 0 && !cpumask_test_cpu(off_cpu, effective))
15875797b1c1STejun Heo 		off_cpu = -1;
15885797b1c1STejun Heo 
15895797b1c1STejun Heo 	total_cpus = cpumask_weight_and(effective, cpu_online_mask);
15905797b1c1STejun Heo 	if (off_cpu >= 0)
15915797b1c1STejun Heo 		total_cpus--;
15925797b1c1STejun Heo 
159391f09870SLai Jiangshan 	/* If all CPUs of the wq get offline, use the default values */
159491f09870SLai Jiangshan 	if (unlikely(!total_cpus)) {
159591f09870SLai Jiangshan 		for_each_node(node)
159691f09870SLai Jiangshan 			wq_node_nr_active(wq, node)->max = min_active;
159791f09870SLai Jiangshan 
159891f09870SLai Jiangshan 		wq_node_nr_active(wq, NUMA_NO_NODE)->max = max_active;
159991f09870SLai Jiangshan 		return;
160091f09870SLai Jiangshan 	}
160191f09870SLai Jiangshan 
16025797b1c1STejun Heo 	for_each_node(node) {
16035797b1c1STejun Heo 		int node_cpus;
16045797b1c1STejun Heo 
16055797b1c1STejun Heo 		node_cpus = cpumask_weight_and(effective, cpumask_of_node(node));
16065797b1c1STejun Heo 		if (off_cpu >= 0 && cpu_to_node(off_cpu) == node)
16075797b1c1STejun Heo 			node_cpus--;
16085797b1c1STejun Heo 
16095797b1c1STejun Heo 		wq_node_nr_active(wq, node)->max =
16105797b1c1STejun Heo 			clamp(DIV_ROUND_UP(max_active * node_cpus, total_cpus),
16115797b1c1STejun Heo 			      min_active, max_active);
16125797b1c1STejun Heo 	}
16135797b1c1STejun Heo 
1614d40f9202STejun Heo 	wq_node_nr_active(wq, NUMA_NO_NODE)->max = max_active;
16155797b1c1STejun Heo }
16165797b1c1STejun Heo 
16175797b1c1STejun Heo /**
16188864b4e5STejun Heo  * get_pwq - get an extra reference on the specified pool_workqueue
16198864b4e5STejun Heo  * @pwq: pool_workqueue to get
16208864b4e5STejun Heo  *
16218864b4e5STejun Heo  * Obtain an extra reference on @pwq.  The caller should guarantee that
16228864b4e5STejun Heo  * @pwq has positive refcnt and be holding the matching pool->lock.
16238864b4e5STejun Heo  */
16248864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
16258864b4e5STejun Heo {
16268864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
16278864b4e5STejun Heo 	WARN_ON_ONCE(pwq->refcnt <= 0);
16288864b4e5STejun Heo 	pwq->refcnt++;
16298864b4e5STejun Heo }
16308864b4e5STejun Heo 
16318864b4e5STejun Heo /**
16328864b4e5STejun Heo  * put_pwq - put a pool_workqueue reference
16338864b4e5STejun Heo  * @pwq: pool_workqueue to put
16348864b4e5STejun Heo  *
16358864b4e5STejun Heo  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
16368864b4e5STejun Heo  * destruction.  The caller should be holding the matching pool->lock.
16378864b4e5STejun Heo  */
16388864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
16398864b4e5STejun Heo {
16408864b4e5STejun Heo 	lockdep_assert_held(&pwq->pool->lock);
16418864b4e5STejun Heo 	if (likely(--pwq->refcnt))
16428864b4e5STejun Heo 		return;
16438864b4e5STejun Heo 	/*
1644967b494eSTejun Heo 	 * @pwq can't be released under pool->lock, bounce to a dedicated
1645967b494eSTejun Heo 	 * kthread_worker to avoid A-A deadlocks.
16468864b4e5STejun Heo 	 */
1647687a9aa5STejun Heo 	kthread_queue_work(pwq_release_worker, &pwq->release_work);
16488864b4e5STejun Heo }
16498864b4e5STejun Heo 
1650dce90d47STejun Heo /**
1651dce90d47STejun Heo  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1652dce90d47STejun Heo  * @pwq: pool_workqueue to put (can be %NULL)
1653dce90d47STejun Heo  *
1654dce90d47STejun Heo  * put_pwq() with locking.  This function also allows %NULL @pwq.
1655dce90d47STejun Heo  */
1656dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1657dce90d47STejun Heo {
1658dce90d47STejun Heo 	if (pwq) {
1659dce90d47STejun Heo 		/*
166024acfb71SThomas Gleixner 		 * As both pwqs and pools are RCU protected, the
1661dce90d47STejun Heo 		 * following lock operations are safe.
1662dce90d47STejun Heo 		 */
1663a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
1664dce90d47STejun Heo 		put_pwq(pwq);
1665a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
1666dce90d47STejun Heo 	}
1667dce90d47STejun Heo }
1668dce90d47STejun Heo 
1669afa87ce8STejun Heo static bool pwq_is_empty(struct pool_workqueue *pwq)
1670afa87ce8STejun Heo {
1671afa87ce8STejun Heo 	return !pwq->nr_active && list_empty(&pwq->inactive_works);
1672afa87ce8STejun Heo }
1673afa87ce8STejun Heo 
16744c638030STejun Heo static void __pwq_activate_work(struct pool_workqueue *pwq,
16754c638030STejun Heo 				struct work_struct *work)
1676bf4ede01STejun Heo {
16771c270b79STejun Heo 	unsigned long *wdb = work_data_bits(work);
16781c270b79STejun Heo 
16791c270b79STejun Heo 	WARN_ON_ONCE(!(*wdb & WORK_STRUCT_INACTIVE));
1680bf4ede01STejun Heo 	trace_workqueue_activate_work(work);
168182607adcSTejun Heo 	if (list_empty(&pwq->pool->worklist))
168282607adcSTejun Heo 		pwq->pool->watchdog_ts = jiffies;
1683112202d9STejun Heo 	move_linked_works(work, &pwq->pool->worklist, NULL);
16841c270b79STejun Heo 	__clear_bit(WORK_STRUCT_INACTIVE_BIT, wdb);
16854c638030STejun Heo }
16864c638030STejun Heo 
16874c638030STejun Heo /**
16884c638030STejun Heo  * pwq_activate_work - Activate a work item if inactive
16894c638030STejun Heo  * @pwq: pool_workqueue @work belongs to
16904c638030STejun Heo  * @work: work item to activate
16914c638030STejun Heo  *
16924c638030STejun Heo  * Returns %true if activated. %false if already active.
16934c638030STejun Heo  */
16944c638030STejun Heo static bool pwq_activate_work(struct pool_workqueue *pwq,
16954c638030STejun Heo 			      struct work_struct *work)
16964c638030STejun Heo {
16974c638030STejun Heo 	struct worker_pool *pool = pwq->pool;
169891ccc6e7STejun Heo 	struct wq_node_nr_active *nna;
16994c638030STejun Heo 
17004c638030STejun Heo 	lockdep_assert_held(&pool->lock);
17014c638030STejun Heo 
17024c638030STejun Heo 	if (!(*work_data_bits(work) & WORK_STRUCT_INACTIVE))
17034c638030STejun Heo 		return false;
17044c638030STejun Heo 
170591ccc6e7STejun Heo 	nna = wq_node_nr_active(pwq->wq, pool->node);
170691ccc6e7STejun Heo 	if (nna)
170791ccc6e7STejun Heo 		atomic_inc(&nna->nr);
170891ccc6e7STejun Heo 
1709112202d9STejun Heo 	pwq->nr_active++;
17104c638030STejun Heo 	__pwq_activate_work(pwq, work);
17114c638030STejun Heo 	return true;
1712bf4ede01STejun Heo }
1713bf4ede01STejun Heo 
17145797b1c1STejun Heo static bool tryinc_node_nr_active(struct wq_node_nr_active *nna)
17155797b1c1STejun Heo {
17165797b1c1STejun Heo 	int max = READ_ONCE(nna->max);
17175797b1c1STejun Heo 
17185797b1c1STejun Heo 	while (true) {
17195797b1c1STejun Heo 		int old, tmp;
17205797b1c1STejun Heo 
17215797b1c1STejun Heo 		old = atomic_read(&nna->nr);
17225797b1c1STejun Heo 		if (old >= max)
17235797b1c1STejun Heo 			return false;
17245797b1c1STejun Heo 		tmp = atomic_cmpxchg_relaxed(&nna->nr, old, old + 1);
17255797b1c1STejun Heo 		if (tmp == old)
17265797b1c1STejun Heo 			return true;
17275797b1c1STejun Heo 	}
17285797b1c1STejun Heo }
17295797b1c1STejun Heo 
17301c270b79STejun Heo /**
17311c270b79STejun Heo  * pwq_tryinc_nr_active - Try to increment nr_active for a pwq
17321c270b79STejun Heo  * @pwq: pool_workqueue of interest
17335797b1c1STejun Heo  * @fill: max_active may have increased, try to increase concurrency level
17341c270b79STejun Heo  *
17351c270b79STejun Heo  * Try to increment nr_active for @pwq. Returns %true if an nr_active count is
17361c270b79STejun Heo  * successfully obtained. %false otherwise.
17371c270b79STejun Heo  */
17385797b1c1STejun Heo static bool pwq_tryinc_nr_active(struct pool_workqueue *pwq, bool fill)
17393aa62497SLai Jiangshan {
17401c270b79STejun Heo 	struct workqueue_struct *wq = pwq->wq;
17411c270b79STejun Heo 	struct worker_pool *pool = pwq->pool;
174291ccc6e7STejun Heo 	struct wq_node_nr_active *nna = wq_node_nr_active(wq, pool->node);
17435797b1c1STejun Heo 	bool obtained = false;
17441c270b79STejun Heo 
17451c270b79STejun Heo 	lockdep_assert_held(&pool->lock);
17461c270b79STejun Heo 
17475797b1c1STejun Heo 	if (!nna) {
17484cb1ef64STejun Heo 		/* BH or per-cpu workqueue, pwq->nr_active is sufficient */
17491c270b79STejun Heo 		obtained = pwq->nr_active < READ_ONCE(wq->max_active);
17505797b1c1STejun Heo 		goto out;
175191ccc6e7STejun Heo 	}
17525797b1c1STejun Heo 
17534c065dbcSWaiman Long 	if (unlikely(pwq->plugged))
17544c065dbcSWaiman Long 		return false;
17554c065dbcSWaiman Long 
17565797b1c1STejun Heo 	/*
17575797b1c1STejun Heo 	 * Unbound workqueue uses per-node shared nr_active $nna. If @pwq is
17585797b1c1STejun Heo 	 * already waiting on $nna, pwq_dec_nr_active() will maintain the
17595797b1c1STejun Heo 	 * concurrency level. Don't jump the line.
17605797b1c1STejun Heo 	 *
17615797b1c1STejun Heo 	 * We need to ignore the pending test after max_active has increased as
17625797b1c1STejun Heo 	 * pwq_dec_nr_active() can only maintain the concurrency level but not
17635797b1c1STejun Heo 	 * increase it. This is indicated by @fill.
17645797b1c1STejun Heo 	 */
17655797b1c1STejun Heo 	if (!list_empty(&pwq->pending_node) && likely(!fill))
17665797b1c1STejun Heo 		goto out;
17675797b1c1STejun Heo 
17685797b1c1STejun Heo 	obtained = tryinc_node_nr_active(nna);
17695797b1c1STejun Heo 	if (obtained)
17705797b1c1STejun Heo 		goto out;
17715797b1c1STejun Heo 
17725797b1c1STejun Heo 	/*
17735797b1c1STejun Heo 	 * Lockless acquisition failed. Lock, add ourself to $nna->pending_pwqs
17745797b1c1STejun Heo 	 * and try again. The smp_mb() is paired with the implied memory barrier
17755797b1c1STejun Heo 	 * of atomic_dec_return() in pwq_dec_nr_active() to ensure that either
17765797b1c1STejun Heo 	 * we see the decremented $nna->nr or they see non-empty
17775797b1c1STejun Heo 	 * $nna->pending_pwqs.
17785797b1c1STejun Heo 	 */
17795797b1c1STejun Heo 	raw_spin_lock(&nna->lock);
17805797b1c1STejun Heo 
17815797b1c1STejun Heo 	if (list_empty(&pwq->pending_node))
17825797b1c1STejun Heo 		list_add_tail(&pwq->pending_node, &nna->pending_pwqs);
17835797b1c1STejun Heo 	else if (likely(!fill))
17845797b1c1STejun Heo 		goto out_unlock;
17855797b1c1STejun Heo 
17865797b1c1STejun Heo 	smp_mb();
17875797b1c1STejun Heo 
17885797b1c1STejun Heo 	obtained = tryinc_node_nr_active(nna);
17895797b1c1STejun Heo 
17905797b1c1STejun Heo 	/*
17915797b1c1STejun Heo 	 * If @fill, @pwq might have already been pending. Being spuriously
17925797b1c1STejun Heo 	 * pending in cold paths doesn't affect anything. Let's leave it be.
17935797b1c1STejun Heo 	 */
17945797b1c1STejun Heo 	if (obtained && likely(!fill))
17955797b1c1STejun Heo 		list_del_init(&pwq->pending_node);
17965797b1c1STejun Heo 
17975797b1c1STejun Heo out_unlock:
17985797b1c1STejun Heo 	raw_spin_unlock(&nna->lock);
17995797b1c1STejun Heo out:
18005797b1c1STejun Heo 	if (obtained)
18015797b1c1STejun Heo 		pwq->nr_active++;
18021c270b79STejun Heo 	return obtained;
18031c270b79STejun Heo }
18041c270b79STejun Heo 
18051c270b79STejun Heo /**
18061c270b79STejun Heo  * pwq_activate_first_inactive - Activate the first inactive work item on a pwq
18071c270b79STejun Heo  * @pwq: pool_workqueue of interest
18085797b1c1STejun Heo  * @fill: max_active may have increased, try to increase concurrency level
18091c270b79STejun Heo  *
18101c270b79STejun Heo  * Activate the first inactive work item of @pwq if available and allowed by
18111c270b79STejun Heo  * max_active limit.
18121c270b79STejun Heo  *
18131c270b79STejun Heo  * Returns %true if an inactive work item has been activated. %false if no
18141c270b79STejun Heo  * inactive work item is found or max_active limit is reached.
18151c270b79STejun Heo  */
18165797b1c1STejun Heo static bool pwq_activate_first_inactive(struct pool_workqueue *pwq, bool fill)
18171c270b79STejun Heo {
18181c270b79STejun Heo 	struct work_struct *work =
18191c270b79STejun Heo 		list_first_entry_or_null(&pwq->inactive_works,
18203aa62497SLai Jiangshan 					 struct work_struct, entry);
18213aa62497SLai Jiangshan 
18225797b1c1STejun Heo 	if (work && pwq_tryinc_nr_active(pwq, fill)) {
18231c270b79STejun Heo 		__pwq_activate_work(pwq, work);
18241c270b79STejun Heo 		return true;
18251c270b79STejun Heo 	} else {
18261c270b79STejun Heo 		return false;
18271c270b79STejun Heo 	}
18281c270b79STejun Heo }
18291c270b79STejun Heo 
18301c270b79STejun Heo /**
1831516d3dc9SWaiman Long  * unplug_oldest_pwq - unplug the oldest pool_workqueue
1832516d3dc9SWaiman Long  * @wq: workqueue_struct where its oldest pwq is to be unplugged
18334c065dbcSWaiman Long  *
1834516d3dc9SWaiman Long  * This function should only be called for ordered workqueues where only the
1835516d3dc9SWaiman Long  * oldest pwq is unplugged, the others are plugged to suspend execution to
1836516d3dc9SWaiman Long  * ensure proper work item ordering::
18374c065dbcSWaiman Long  *
18384c065dbcSWaiman Long  *    dfl_pwq --------------+     [P] - plugged
18394c065dbcSWaiman Long  *                          |
18404c065dbcSWaiman Long  *                          v
18414c065dbcSWaiman Long  *    pwqs -> A -> B [P] -> C [P] (newest)
18424c065dbcSWaiman Long  *            |    |        |
18434c065dbcSWaiman Long  *            1    3        5
18444c065dbcSWaiman Long  *            |    |        |
18454c065dbcSWaiman Long  *            2    4        6
1846516d3dc9SWaiman Long  *
1847516d3dc9SWaiman Long  * When the oldest pwq is drained and removed, this function should be called
1848516d3dc9SWaiman Long  * to unplug the next oldest one to start its work item execution. Note that
1849516d3dc9SWaiman Long  * pwq's are linked into wq->pwqs with the oldest first, so the first one in
1850516d3dc9SWaiman Long  * the list is the oldest.
18514c065dbcSWaiman Long  */
18524c065dbcSWaiman Long static void unplug_oldest_pwq(struct workqueue_struct *wq)
18534c065dbcSWaiman Long {
18544c065dbcSWaiman Long 	struct pool_workqueue *pwq;
18554c065dbcSWaiman Long 
18564c065dbcSWaiman Long 	lockdep_assert_held(&wq->mutex);
18574c065dbcSWaiman Long 
18584c065dbcSWaiman Long 	/* Caller should make sure that pwqs isn't empty before calling */
18594c065dbcSWaiman Long 	pwq = list_first_entry_or_null(&wq->pwqs, struct pool_workqueue,
18604c065dbcSWaiman Long 				       pwqs_node);
18614c065dbcSWaiman Long 	raw_spin_lock_irq(&pwq->pool->lock);
18624c065dbcSWaiman Long 	if (pwq->plugged) {
18634c065dbcSWaiman Long 		pwq->plugged = false;
18644c065dbcSWaiman Long 		if (pwq_activate_first_inactive(pwq, true))
18654c065dbcSWaiman Long 			kick_pool(pwq->pool);
18664c065dbcSWaiman Long 	}
18674c065dbcSWaiman Long 	raw_spin_unlock_irq(&pwq->pool->lock);
18684c065dbcSWaiman Long }
18694c065dbcSWaiman Long 
18704c065dbcSWaiman Long /**
18715797b1c1STejun Heo  * node_activate_pending_pwq - Activate a pending pwq on a wq_node_nr_active
18725797b1c1STejun Heo  * @nna: wq_node_nr_active to activate a pending pwq for
18735797b1c1STejun Heo  * @caller_pool: worker_pool the caller is locking
18745797b1c1STejun Heo  *
18755797b1c1STejun Heo  * Activate a pwq in @nna->pending_pwqs. Called with @caller_pool locked.
18765797b1c1STejun Heo  * @caller_pool may be unlocked and relocked to lock other worker_pools.
18775797b1c1STejun Heo  */
18785797b1c1STejun Heo static void node_activate_pending_pwq(struct wq_node_nr_active *nna,
18795797b1c1STejun Heo 				      struct worker_pool *caller_pool)
18805797b1c1STejun Heo {
18815797b1c1STejun Heo 	struct worker_pool *locked_pool = caller_pool;
18825797b1c1STejun Heo 	struct pool_workqueue *pwq;
18835797b1c1STejun Heo 	struct work_struct *work;
18845797b1c1STejun Heo 
18855797b1c1STejun Heo 	lockdep_assert_held(&caller_pool->lock);
18865797b1c1STejun Heo 
18875797b1c1STejun Heo 	raw_spin_lock(&nna->lock);
18885797b1c1STejun Heo retry:
18895797b1c1STejun Heo 	pwq = list_first_entry_or_null(&nna->pending_pwqs,
18905797b1c1STejun Heo 				       struct pool_workqueue, pending_node);
18915797b1c1STejun Heo 	if (!pwq)
18925797b1c1STejun Heo 		goto out_unlock;
18935797b1c1STejun Heo 
18945797b1c1STejun Heo 	/*
18955797b1c1STejun Heo 	 * If @pwq is for a different pool than @locked_pool, we need to lock
18965797b1c1STejun Heo 	 * @pwq->pool->lock. Let's trylock first. If unsuccessful, do the unlock
18975797b1c1STejun Heo 	 * / lock dance. For that, we also need to release @nna->lock as it's
18985797b1c1STejun Heo 	 * nested inside pool locks.
18995797b1c1STejun Heo 	 */
19005797b1c1STejun Heo 	if (pwq->pool != locked_pool) {
19015797b1c1STejun Heo 		raw_spin_unlock(&locked_pool->lock);
19025797b1c1STejun Heo 		locked_pool = pwq->pool;
19035797b1c1STejun Heo 		if (!raw_spin_trylock(&locked_pool->lock)) {
19045797b1c1STejun Heo 			raw_spin_unlock(&nna->lock);
19055797b1c1STejun Heo 			raw_spin_lock(&locked_pool->lock);
19065797b1c1STejun Heo 			raw_spin_lock(&nna->lock);
19075797b1c1STejun Heo 			goto retry;
19085797b1c1STejun Heo 		}
19095797b1c1STejun Heo 	}
19105797b1c1STejun Heo 
19115797b1c1STejun Heo 	/*
19125797b1c1STejun Heo 	 * $pwq may not have any inactive work items due to e.g. cancellations.
19135797b1c1STejun Heo 	 * Drop it from pending_pwqs and see if there's another one.
19145797b1c1STejun Heo 	 */
19155797b1c1STejun Heo 	work = list_first_entry_or_null(&pwq->inactive_works,
19165797b1c1STejun Heo 					struct work_struct, entry);
19175797b1c1STejun Heo 	if (!work) {
19185797b1c1STejun Heo 		list_del_init(&pwq->pending_node);
19195797b1c1STejun Heo 		goto retry;
19205797b1c1STejun Heo 	}
19215797b1c1STejun Heo 
19225797b1c1STejun Heo 	/*
19235797b1c1STejun Heo 	 * Acquire an nr_active count and activate the inactive work item. If
19245797b1c1STejun Heo 	 * $pwq still has inactive work items, rotate it to the end of the
19255797b1c1STejun Heo 	 * pending_pwqs so that we round-robin through them. This means that
19265797b1c1STejun Heo 	 * inactive work items are not activated in queueing order which is fine
19275797b1c1STejun Heo 	 * given that there has never been any ordering across different pwqs.
19285797b1c1STejun Heo 	 */
19295797b1c1STejun Heo 	if (likely(tryinc_node_nr_active(nna))) {
19305797b1c1STejun Heo 		pwq->nr_active++;
19315797b1c1STejun Heo 		__pwq_activate_work(pwq, work);
19325797b1c1STejun Heo 
19335797b1c1STejun Heo 		if (list_empty(&pwq->inactive_works))
19345797b1c1STejun Heo 			list_del_init(&pwq->pending_node);
19355797b1c1STejun Heo 		else
19365797b1c1STejun Heo 			list_move_tail(&pwq->pending_node, &nna->pending_pwqs);
19375797b1c1STejun Heo 
19385797b1c1STejun Heo 		/* if activating a foreign pool, make sure it's running */
19395797b1c1STejun Heo 		if (pwq->pool != caller_pool)
19405797b1c1STejun Heo 			kick_pool(pwq->pool);
19415797b1c1STejun Heo 	}
19425797b1c1STejun Heo 
19435797b1c1STejun Heo out_unlock:
19445797b1c1STejun Heo 	raw_spin_unlock(&nna->lock);
19455797b1c1STejun Heo 	if (locked_pool != caller_pool) {
19465797b1c1STejun Heo 		raw_spin_unlock(&locked_pool->lock);
19475797b1c1STejun Heo 		raw_spin_lock(&caller_pool->lock);
19485797b1c1STejun Heo 	}
19495797b1c1STejun Heo }
19505797b1c1STejun Heo 
19515797b1c1STejun Heo /**
19521c270b79STejun Heo  * pwq_dec_nr_active - Retire an active count
19531c270b79STejun Heo  * @pwq: pool_workqueue of interest
19541c270b79STejun Heo  *
19551c270b79STejun Heo  * Decrement @pwq's nr_active and try to activate the first inactive work item.
19565797b1c1STejun Heo  * For unbound workqueues, this function may temporarily drop @pwq->pool->lock.
19571c270b79STejun Heo  */
19581c270b79STejun Heo static void pwq_dec_nr_active(struct pool_workqueue *pwq)
19591c270b79STejun Heo {
19601c270b79STejun Heo 	struct worker_pool *pool = pwq->pool;
196191ccc6e7STejun Heo 	struct wq_node_nr_active *nna = wq_node_nr_active(pwq->wq, pool->node);
19621c270b79STejun Heo 
19631c270b79STejun Heo 	lockdep_assert_held(&pool->lock);
19641c270b79STejun Heo 
196591ccc6e7STejun Heo 	/*
196691ccc6e7STejun Heo 	 * @pwq->nr_active should be decremented for both percpu and unbound
196791ccc6e7STejun Heo 	 * workqueues.
196891ccc6e7STejun Heo 	 */
19691c270b79STejun Heo 	pwq->nr_active--;
197091ccc6e7STejun Heo 
197191ccc6e7STejun Heo 	/*
197291ccc6e7STejun Heo 	 * For a percpu workqueue, it's simple. Just need to kick the first
197391ccc6e7STejun Heo 	 * inactive work item on @pwq itself.
197491ccc6e7STejun Heo 	 */
197591ccc6e7STejun Heo 	if (!nna) {
19765797b1c1STejun Heo 		pwq_activate_first_inactive(pwq, false);
197791ccc6e7STejun Heo 		return;
197891ccc6e7STejun Heo 	}
197991ccc6e7STejun Heo 
19805797b1c1STejun Heo 	/*
19815797b1c1STejun Heo 	 * If @pwq is for an unbound workqueue, it's more complicated because
19825797b1c1STejun Heo 	 * multiple pwqs and pools may be sharing the nr_active count. When a
19835797b1c1STejun Heo 	 * pwq needs to wait for an nr_active count, it puts itself on
19845797b1c1STejun Heo 	 * $nna->pending_pwqs. The following atomic_dec_return()'s implied
19855797b1c1STejun Heo 	 * memory barrier is paired with smp_mb() in pwq_tryinc_nr_active() to
19865797b1c1STejun Heo 	 * guarantee that either we see non-empty pending_pwqs or they see
19875797b1c1STejun Heo 	 * decremented $nna->nr.
19885797b1c1STejun Heo 	 *
19895797b1c1STejun Heo 	 * $nna->max may change as CPUs come online/offline and @pwq->wq's
19905797b1c1STejun Heo 	 * max_active gets updated. However, it is guaranteed to be equal to or
19915797b1c1STejun Heo 	 * larger than @pwq->wq->min_active which is above zero unless freezing.
19925797b1c1STejun Heo 	 * This maintains the forward progress guarantee.
19935797b1c1STejun Heo 	 */
19945797b1c1STejun Heo 	if (atomic_dec_return(&nna->nr) >= READ_ONCE(nna->max))
19955797b1c1STejun Heo 		return;
19965797b1c1STejun Heo 
19975797b1c1STejun Heo 	if (!list_empty(&nna->pending_pwqs))
19985797b1c1STejun Heo 		node_activate_pending_pwq(nna, pool);
19993aa62497SLai Jiangshan }
20003aa62497SLai Jiangshan 
2001bf4ede01STejun Heo /**
2002112202d9STejun Heo  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
2003112202d9STejun Heo  * @pwq: pwq of interest
2004c4560c2cSLai Jiangshan  * @work_data: work_data of work which left the queue
2005bf4ede01STejun Heo  *
2006bf4ede01STejun Heo  * A work either has completed or is removed from pending queue,
2007112202d9STejun Heo  * decrement nr_in_flight of its pwq and handle workqueue flushing.
2008bf4ede01STejun Heo  *
2009dd6c3c54STejun Heo  * NOTE:
2010dd6c3c54STejun Heo  * For unbound workqueues, this function may temporarily drop @pwq->pool->lock
2011dd6c3c54STejun Heo  * and thus should be called after all other state updates for the in-flight
2012dd6c3c54STejun Heo  * work item is complete.
2013dd6c3c54STejun Heo  *
2014bf4ede01STejun Heo  * CONTEXT:
2015a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
2016bf4ede01STejun Heo  */
2017c4560c2cSLai Jiangshan static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
2018bf4ede01STejun Heo {
2019c4560c2cSLai Jiangshan 	int color = get_work_color(work_data);
2020c4560c2cSLai Jiangshan 
20211c270b79STejun Heo 	if (!(work_data & WORK_STRUCT_INACTIVE))
20221c270b79STejun Heo 		pwq_dec_nr_active(pwq);
2023018f3a13SLai Jiangshan 
2024018f3a13SLai Jiangshan 	pwq->nr_in_flight[color]--;
2025bf4ede01STejun Heo 
2026bf4ede01STejun Heo 	/* is flush in progress and are we at the flushing tip? */
2027112202d9STejun Heo 	if (likely(pwq->flush_color != color))
20288864b4e5STejun Heo 		goto out_put;
2029bf4ede01STejun Heo 
2030bf4ede01STejun Heo 	/* are there still in-flight works? */
2031112202d9STejun Heo 	if (pwq->nr_in_flight[color])
20328864b4e5STejun Heo 		goto out_put;
2033bf4ede01STejun Heo 
2034112202d9STejun Heo 	/* this pwq is done, clear flush_color */
2035112202d9STejun Heo 	pwq->flush_color = -1;
2036bf4ede01STejun Heo 
2037bf4ede01STejun Heo 	/*
2038112202d9STejun Heo 	 * If this was the last pwq, wake up the first flusher.  It
2039bf4ede01STejun Heo 	 * will handle the rest.
2040bf4ede01STejun Heo 	 */
2041112202d9STejun Heo 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
2042112202d9STejun Heo 		complete(&pwq->wq->first_flusher->done);
20438864b4e5STejun Heo out_put:
20448864b4e5STejun Heo 	put_pwq(pwq);
2045bf4ede01STejun Heo }
2046bf4ede01STejun Heo 
204736e227d2STejun Heo /**
2048bbb68dfaSTejun Heo  * try_to_grab_pending - steal work item from worklist and disable irq
204936e227d2STejun Heo  * @work: work item to steal
2050c5f5b942STejun Heo  * @cflags: %WORK_CANCEL_ flags
2051c26e2f2eSTejun Heo  * @irq_flags: place to store irq state
205236e227d2STejun Heo  *
205336e227d2STejun Heo  * Try to grab PENDING bit of @work.  This function can handle @work in any
2054d185af30SYacine Belkadi  * stable state - idle, on timer or on worklist.
205536e227d2STejun Heo  *
2056d185af30SYacine Belkadi  * Return:
20573eb6b31bSMauro Carvalho Chehab  *
20583eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
205936e227d2STejun Heo  *  1		if @work was pending and we successfully stole PENDING
206036e227d2STejun Heo  *  0		if @work was idle and we claimed PENDING
206136e227d2STejun Heo  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
20623eb6b31bSMauro Carvalho Chehab  *  ========	================================================================
206336e227d2STejun Heo  *
2064d185af30SYacine Belkadi  * Note:
2065bbb68dfaSTejun Heo  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
2066e0aecdd8STejun Heo  * interrupted while holding PENDING and @work off queue, irq must be
2067e0aecdd8STejun Heo  * disabled on entry.  This, combined with delayed_work->timer being
2068e0aecdd8STejun Heo  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
2069bbb68dfaSTejun Heo  *
2070bbb68dfaSTejun Heo  * On successful return, >= 0, irq is disabled and the caller is
2071c26e2f2eSTejun Heo  * responsible for releasing it using local_irq_restore(*@irq_flags).
2072bbb68dfaSTejun Heo  *
2073e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
2074bf4ede01STejun Heo  */
2075c5f5b942STejun Heo static int try_to_grab_pending(struct work_struct *work, u32 cflags,
2076c26e2f2eSTejun Heo 			       unsigned long *irq_flags)
2077bf4ede01STejun Heo {
2078d565ed63STejun Heo 	struct worker_pool *pool;
2079112202d9STejun Heo 	struct pool_workqueue *pwq;
2080bf4ede01STejun Heo 
2081c26e2f2eSTejun Heo 	local_irq_save(*irq_flags);
2082bbb68dfaSTejun Heo 
208336e227d2STejun Heo 	/* try to steal the timer if it exists */
2084c5f5b942STejun Heo 	if (cflags & WORK_CANCEL_DELAYED) {
208536e227d2STejun Heo 		struct delayed_work *dwork = to_delayed_work(work);
208636e227d2STejun Heo 
2087e0aecdd8STejun Heo 		/*
2088e0aecdd8STejun Heo 		 * dwork->timer is irqsafe.  If del_timer() fails, it's
2089e0aecdd8STejun Heo 		 * guaranteed that the timer is not queued anywhere and not
2090e0aecdd8STejun Heo 		 * running on the local CPU.
2091e0aecdd8STejun Heo 		 */
209236e227d2STejun Heo 		if (likely(del_timer(&dwork->timer)))
209336e227d2STejun Heo 			return 1;
209436e227d2STejun Heo 	}
209536e227d2STejun Heo 
209636e227d2STejun Heo 	/* try to claim PENDING the normal way */
2097bf4ede01STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
2098bf4ede01STejun Heo 		return 0;
2099bf4ede01STejun Heo 
210024acfb71SThomas Gleixner 	rcu_read_lock();
2101bf4ede01STejun Heo 	/*
2102bf4ede01STejun Heo 	 * The queueing is in progress, or it is already queued. Try to
2103bf4ede01STejun Heo 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
2104bf4ede01STejun Heo 	 */
2105d565ed63STejun Heo 	pool = get_work_pool(work);
2106d565ed63STejun Heo 	if (!pool)
2107bbb68dfaSTejun Heo 		goto fail;
2108bf4ede01STejun Heo 
2109a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&pool->lock);
2110bf4ede01STejun Heo 	/*
2111112202d9STejun Heo 	 * work->data is guaranteed to point to pwq only while the work
2112112202d9STejun Heo 	 * item is queued on pwq->wq, and both updating work->data to point
2113112202d9STejun Heo 	 * to pwq on queueing and to pool on dequeueing are done under
2114112202d9STejun Heo 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
2115112202d9STejun Heo 	 * points to pwq which is associated with a locked pool, the work
21160b3dae68SLai Jiangshan 	 * item is currently queued on that pool.
2117bf4ede01STejun Heo 	 */
2118112202d9STejun Heo 	pwq = get_work_pwq(work);
2119112202d9STejun Heo 	if (pwq && pwq->pool == pool) {
2120c70e1779STejun Heo 		unsigned long work_data;
2121c70e1779STejun Heo 
2122bf4ede01STejun Heo 		debug_work_deactivate(work);
21233aa62497SLai Jiangshan 
21243aa62497SLai Jiangshan 		/*
2125018f3a13SLai Jiangshan 		 * A cancelable inactive work item must be in the
2126018f3a13SLai Jiangshan 		 * pwq->inactive_works since a queued barrier can't be
2127018f3a13SLai Jiangshan 		 * canceled (see the comments in insert_wq_barrier()).
2128018f3a13SLai Jiangshan 		 *
2129f97a4a1aSLai Jiangshan 		 * An inactive work item cannot be grabbed directly because
2130d812796eSLai Jiangshan 		 * it might have linked barrier work items which, if left
2131f97a4a1aSLai Jiangshan 		 * on the inactive_works list, will confuse pwq->nr_active
213216062836STejun Heo 		 * management later on and cause stall.  Make sure the work
213316062836STejun Heo 		 * item is activated before grabbing.
21343aa62497SLai Jiangshan 		 */
21354c638030STejun Heo 		pwq_activate_work(pwq, work);
21363aa62497SLai Jiangshan 
2137bf4ede01STejun Heo 		list_del_init(&work->entry);
213836e227d2STejun Heo 
2139c70e1779STejun Heo 		/*
2140c70e1779STejun Heo 		 * work->data points to pwq iff queued. Let's point to pool. As
2141c70e1779STejun Heo 		 * this destroys work->data needed by the next step, stash it.
2142c70e1779STejun Heo 		 */
2143c70e1779STejun Heo 		work_data = *work_data_bits(work);
2144456a78eeSTejun Heo 		set_work_pool_and_keep_pending(work, pool->id,
2145456a78eeSTejun Heo 					       pool_offq_flags(pool));
21464468a00fSLai Jiangshan 
2147dd6c3c54STejun Heo 		/* must be the last step, see the function comment */
2148c70e1779STejun Heo 		pwq_dec_nr_in_flight(pwq, work_data);
2149dd6c3c54STejun Heo 
2150a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock(&pool->lock);
215124acfb71SThomas Gleixner 		rcu_read_unlock();
215236e227d2STejun Heo 		return 1;
2153bf4ede01STejun Heo 	}
2154a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&pool->lock);
2155bbb68dfaSTejun Heo fail:
215624acfb71SThomas Gleixner 	rcu_read_unlock();
2157c26e2f2eSTejun Heo 	local_irq_restore(*irq_flags);
215836e227d2STejun Heo 	return -EAGAIN;
2159bf4ede01STejun Heo }
2160bf4ede01STejun Heo 
2161978b8409STejun Heo /**
2162978b8409STejun Heo  * work_grab_pending - steal work item from worklist and disable irq
2163978b8409STejun Heo  * @work: work item to steal
2164978b8409STejun Heo  * @cflags: %WORK_CANCEL_ flags
2165978b8409STejun Heo  * @irq_flags: place to store IRQ state
2166978b8409STejun Heo  *
2167978b8409STejun Heo  * Grab PENDING bit of @work. @work can be in any stable state - idle, on timer
2168978b8409STejun Heo  * or on worklist.
2169978b8409STejun Heo  *
2170f09b10b6STejun Heo  * Can be called from any context. IRQ is disabled on return with IRQ state
2171978b8409STejun Heo  * stored in *@irq_flags. The caller is responsible for re-enabling it using
2172978b8409STejun Heo  * local_irq_restore().
2173978b8409STejun Heo  *
2174978b8409STejun Heo  * Returns %true if @work was pending. %false if idle.
2175978b8409STejun Heo  */
2176978b8409STejun Heo static bool work_grab_pending(struct work_struct *work, u32 cflags,
2177978b8409STejun Heo 			      unsigned long *irq_flags)
2178978b8409STejun Heo {
2179978b8409STejun Heo 	int ret;
2180978b8409STejun Heo 
2181f09b10b6STejun Heo 	while (true) {
2182978b8409STejun Heo 		ret = try_to_grab_pending(work, cflags, irq_flags);
2183f09b10b6STejun Heo 		if (ret >= 0)
2184978b8409STejun Heo 			return ret;
2185f09b10b6STejun Heo 		cpu_relax();
2186f09b10b6STejun Heo 	}
2187978b8409STejun Heo }
2188978b8409STejun Heo 
2189bf4ede01STejun Heo /**
2190706026c2STejun Heo  * insert_work - insert a work into a pool
2191112202d9STejun Heo  * @pwq: pwq @work belongs to
21924690c4abSTejun Heo  * @work: work to insert
21934690c4abSTejun Heo  * @head: insertion point
21944690c4abSTejun Heo  * @extra_flags: extra WORK_STRUCT_* flags to set
21954690c4abSTejun Heo  *
2196112202d9STejun Heo  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
2197706026c2STejun Heo  * work_struct flags.
21984690c4abSTejun Heo  *
21994690c4abSTejun Heo  * CONTEXT:
2200a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
2201365970a1SDavid Howells  */
2202112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
2203112202d9STejun Heo 			struct list_head *head, unsigned int extra_flags)
2204b89deed3SOleg Nesterov {
2205fe089f87STejun Heo 	debug_work_activate(work);
2206e1d8aa9fSFrederic Weisbecker 
2207e89a85d6SWalter Wu 	/* record the work call stack in order to print it in KASAN reports */
2208f70da745SMarco Elver 	kasan_record_aux_stack_noalloc(work);
2209e89a85d6SWalter Wu 
22104690c4abSTejun Heo 	/* we own @work, set data and link */
2211112202d9STejun Heo 	set_work_pwq(work, pwq, extra_flags);
22121a4d9b0aSOleg Nesterov 	list_add_tail(&work->entry, head);
22138864b4e5STejun Heo 	get_pwq(pwq);
2214b89deed3SOleg Nesterov }
2215b89deed3SOleg Nesterov 
2216c8efcc25STejun Heo /*
2217c8efcc25STejun Heo  * Test whether @work is being queued from another work executing on the
22188d03ecfeSTejun Heo  * same workqueue.
2219c8efcc25STejun Heo  */
2220c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
2221c8efcc25STejun Heo {
2222c8efcc25STejun Heo 	struct worker *worker;
2223c8efcc25STejun Heo 
22248d03ecfeSTejun Heo 	worker = current_wq_worker();
2225c8efcc25STejun Heo 	/*
2226bf393fd4SBart Van Assche 	 * Return %true iff I'm a worker executing a work item on @wq.  If
22278d03ecfeSTejun Heo 	 * I'm @worker, it's safe to dereference it without locking.
2228c8efcc25STejun Heo 	 */
2229112202d9STejun Heo 	return worker && worker->current_pwq->wq == wq;
2230c8efcc25STejun Heo }
2231c8efcc25STejun Heo 
2232ef557180SMike Galbraith /*
2233ef557180SMike Galbraith  * When queueing an unbound work item to a wq, prefer local CPU if allowed
2234ef557180SMike Galbraith  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
2235ef557180SMike Galbraith  * avoid perturbing sensitive tasks.
2236ef557180SMike Galbraith  */
2237ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
2238ef557180SMike Galbraith {
2239ef557180SMike Galbraith 	int new_cpu;
2240ef557180SMike Galbraith 
2241f303fccbSTejun Heo 	if (likely(!wq_debug_force_rr_cpu)) {
2242ef557180SMike Galbraith 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
2243ef557180SMike Galbraith 			return cpu;
2244a8ec5880SAmmar Faizi 	} else {
2245a8ec5880SAmmar Faizi 		pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
2246f303fccbSTejun Heo 	}
2247f303fccbSTejun Heo 
2248ef557180SMike Galbraith 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
2249ef557180SMike Galbraith 	new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
2250ef557180SMike Galbraith 	if (unlikely(new_cpu >= nr_cpu_ids)) {
2251ef557180SMike Galbraith 		new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
2252ef557180SMike Galbraith 		if (unlikely(new_cpu >= nr_cpu_ids))
2253ef557180SMike Galbraith 			return cpu;
2254ef557180SMike Galbraith 	}
2255ef557180SMike Galbraith 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
2256ef557180SMike Galbraith 
2257ef557180SMike Galbraith 	return new_cpu;
2258ef557180SMike Galbraith }
2259ef557180SMike Galbraith 
2260d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
22611da177e4SLinus Torvalds 			 struct work_struct *work)
22621da177e4SLinus Torvalds {
2263112202d9STejun Heo 	struct pool_workqueue *pwq;
2264fe089f87STejun Heo 	struct worker_pool *last_pool, *pool;
22658a2e8e5dSTejun Heo 	unsigned int work_flags;
2266b75cac93SJoonsoo Kim 	unsigned int req_cpu = cpu;
22678930cabaSTejun Heo 
22688930cabaSTejun Heo 	/*
22698930cabaSTejun Heo 	 * While a work item is PENDING && off queue, a task trying to
22708930cabaSTejun Heo 	 * steal the PENDING will busy-loop waiting for it to either get
22718930cabaSTejun Heo 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
22728930cabaSTejun Heo 	 * happen with IRQ disabled.
22738930cabaSTejun Heo 	 */
22748e8eb730SFrederic Weisbecker 	lockdep_assert_irqs_disabled();
22751da177e4SLinus Torvalds 
227633e3f0a3SRichard Clark 	/*
227733e3f0a3SRichard Clark 	 * For a draining wq, only works from the same workqueue are
227833e3f0a3SRichard Clark 	 * allowed. The __WQ_DESTROYING helps to spot the issue that
227933e3f0a3SRichard Clark 	 * queues a new work item to a wq after destroy_workqueue(wq).
228033e3f0a3SRichard Clark 	 */
228133e3f0a3SRichard Clark 	if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
228233e3f0a3SRichard Clark 		     WARN_ON_ONCE(!is_chained_work(wq))))
2283e41e704bSTejun Heo 		return;
228424acfb71SThomas Gleixner 	rcu_read_lock();
22859e8cd2f5STejun Heo retry:
2286aa202f1fSHillf Danton 	/* pwq which will be used unless @work is executing elsewhere */
2287636b927eSTejun Heo 	if (req_cpu == WORK_CPU_UNBOUND) {
2288636b927eSTejun Heo 		if (wq->flags & WQ_UNBOUND)
2289ef557180SMike Galbraith 			cpu = wq_select_unbound_cpu(raw_smp_processor_id());
2290636b927eSTejun Heo 		else
2291aa202f1fSHillf Danton 			cpu = raw_smp_processor_id();
2292aa202f1fSHillf Danton 	}
2293f3421797STejun Heo 
2294636b927eSTejun Heo 	pwq = rcu_dereference(*per_cpu_ptr(wq->cpu_pwq, cpu));
2295fe089f87STejun Heo 	pool = pwq->pool;
2296fe089f87STejun Heo 
229718aa9effSTejun Heo 	/*
2298c9178087STejun Heo 	 * If @work was previously on a different pool, it might still be
2299c9178087STejun Heo 	 * running there, in which case the work needs to be queued on that
2300c9178087STejun Heo 	 * pool to guarantee non-reentrancy.
230118aa9effSTejun Heo 	 */
2302c9e7cf27STejun Heo 	last_pool = get_work_pool(work);
2303fe089f87STejun Heo 	if (last_pool && last_pool != pool) {
230418aa9effSTejun Heo 		struct worker *worker;
230518aa9effSTejun Heo 
2306a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock(&last_pool->lock);
230718aa9effSTejun Heo 
2308c9e7cf27STejun Heo 		worker = find_worker_executing_work(last_pool, work);
230918aa9effSTejun Heo 
2310112202d9STejun Heo 		if (worker && worker->current_pwq->wq == wq) {
2311c9178087STejun Heo 			pwq = worker->current_pwq;
2312fe089f87STejun Heo 			pool = pwq->pool;
2313fe089f87STejun Heo 			WARN_ON_ONCE(pool != last_pool);
23148594fadeSLai Jiangshan 		} else {
231518aa9effSTejun Heo 			/* meh... not running there, queue here */
2316a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock(&last_pool->lock);
2317fe089f87STejun Heo 			raw_spin_lock(&pool->lock);
231818aa9effSTejun Heo 		}
23198930cabaSTejun Heo 	} else {
2320fe089f87STejun Heo 		raw_spin_lock(&pool->lock);
23218930cabaSTejun Heo 	}
2322502ca9d8STejun Heo 
23239e8cd2f5STejun Heo 	/*
2324636b927eSTejun Heo 	 * pwq is determined and locked. For unbound pools, we could have raced
2325636b927eSTejun Heo 	 * with pwq release and it could already be dead. If its refcnt is zero,
2326636b927eSTejun Heo 	 * repeat pwq selection. Note that unbound pwqs never die without
2327636b927eSTejun Heo 	 * another pwq replacing it in cpu_pwq or while work items are executing
2328636b927eSTejun Heo 	 * on it, so the retrying is guaranteed to make forward-progress.
23299e8cd2f5STejun Heo 	 */
23309e8cd2f5STejun Heo 	if (unlikely(!pwq->refcnt)) {
23319e8cd2f5STejun Heo 		if (wq->flags & WQ_UNBOUND) {
2332fe089f87STejun Heo 			raw_spin_unlock(&pool->lock);
23339e8cd2f5STejun Heo 			cpu_relax();
23349e8cd2f5STejun Heo 			goto retry;
23359e8cd2f5STejun Heo 		}
23369e8cd2f5STejun Heo 		/* oops */
23379e8cd2f5STejun Heo 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
23389e8cd2f5STejun Heo 			  wq->name, cpu);
23399e8cd2f5STejun Heo 	}
23409e8cd2f5STejun Heo 
2341112202d9STejun Heo 	/* pwq determined, queue */
2342112202d9STejun Heo 	trace_workqueue_queue_work(req_cpu, pwq, work);
2343502ca9d8STejun Heo 
234424acfb71SThomas Gleixner 	if (WARN_ON(!list_empty(&work->entry)))
234524acfb71SThomas Gleixner 		goto out;
23461e19ffc6STejun Heo 
2347112202d9STejun Heo 	pwq->nr_in_flight[pwq->work_color]++;
2348112202d9STejun Heo 	work_flags = work_color_to_flags(pwq->work_color);
23491e19ffc6STejun Heo 
2350a045a272STejun Heo 	/*
2351a045a272STejun Heo 	 * Limit the number of concurrently active work items to max_active.
2352a045a272STejun Heo 	 * @work must also queue behind existing inactive work items to maintain
2353a045a272STejun Heo 	 * ordering when max_active changes. See wq_adjust_max_active().
2354a045a272STejun Heo 	 */
23555797b1c1STejun Heo 	if (list_empty(&pwq->inactive_works) && pwq_tryinc_nr_active(pwq, false)) {
2356fe089f87STejun Heo 		if (list_empty(&pool->worklist))
2357fe089f87STejun Heo 			pool->watchdog_ts = jiffies;
2358fe089f87STejun Heo 
2359cdadf009STejun Heo 		trace_workqueue_activate_work(work);
2360fe089f87STejun Heo 		insert_work(pwq, work, &pool->worklist, work_flags);
23610219a352STejun Heo 		kick_pool(pool);
23628a2e8e5dSTejun Heo 	} else {
2363f97a4a1aSLai Jiangshan 		work_flags |= WORK_STRUCT_INACTIVE;
2364fe089f87STejun Heo 		insert_work(pwq, work, &pwq->inactive_works, work_flags);
23658a2e8e5dSTejun Heo 	}
23661e19ffc6STejun Heo 
236724acfb71SThomas Gleixner out:
2368fe089f87STejun Heo 	raw_spin_unlock(&pool->lock);
236924acfb71SThomas Gleixner 	rcu_read_unlock();
23701da177e4SLinus Torvalds }
23711da177e4SLinus Torvalds 
237286898fa6STejun Heo static bool clear_pending_if_disabled(struct work_struct *work)
237386898fa6STejun Heo {
237486898fa6STejun Heo 	unsigned long data = *work_data_bits(work);
237586898fa6STejun Heo 	struct work_offq_data offqd;
237686898fa6STejun Heo 
237786898fa6STejun Heo 	if (likely((data & WORK_STRUCT_PWQ) ||
237886898fa6STejun Heo 		   !(data & WORK_OFFQ_DISABLE_MASK)))
237986898fa6STejun Heo 		return false;
238086898fa6STejun Heo 
238186898fa6STejun Heo 	work_offqd_unpack(&offqd, data);
238286898fa6STejun Heo 	set_work_pool_and_clear_pending(work, offqd.pool_id,
238386898fa6STejun Heo 					work_offqd_pack_flags(&offqd));
238486898fa6STejun Heo 	return true;
238586898fa6STejun Heo }
238686898fa6STejun Heo 
23870fcb78c2SRolf Eike Beer /**
2388c1a220e7SZhang Rui  * queue_work_on - queue work on specific cpu
2389c1a220e7SZhang Rui  * @cpu: CPU number to execute work on
2390c1a220e7SZhang Rui  * @wq: workqueue to use
2391c1a220e7SZhang Rui  * @work: work to queue
2392c1a220e7SZhang Rui  *
2393c1a220e7SZhang Rui  * We queue the work to a specific CPU, the caller must ensure it
2394443378f0SPaul E. McKenney  * can't go away.  Callers that fail to ensure that the specified
2395443378f0SPaul E. McKenney  * CPU cannot go away will execute on a randomly chosen CPU.
2396854f5cc5SPaul E. McKenney  * But note well that callers specifying a CPU that never has been
2397854f5cc5SPaul E. McKenney  * online will get a splat.
2398d185af30SYacine Belkadi  *
2399d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.
2400c1a220e7SZhang Rui  */
2401d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
2402d4283e93STejun Heo 		   struct work_struct *work)
2403c1a220e7SZhang Rui {
2404d4283e93STejun Heo 	bool ret = false;
2405c26e2f2eSTejun Heo 	unsigned long irq_flags;
24068930cabaSTejun Heo 
2407c26e2f2eSTejun Heo 	local_irq_save(irq_flags);
2408c1a220e7SZhang Rui 
240986898fa6STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)) &&
241086898fa6STejun Heo 	    !clear_pending_if_disabled(work)) {
24114690c4abSTejun Heo 		__queue_work(cpu, wq, work);
2412d4283e93STejun Heo 		ret = true;
2413c1a220e7SZhang Rui 	}
24148930cabaSTejun Heo 
2415c26e2f2eSTejun Heo 	local_irq_restore(irq_flags);
2416c1a220e7SZhang Rui 	return ret;
2417c1a220e7SZhang Rui }
2418ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
2419c1a220e7SZhang Rui 
24208204e0c1SAlexander Duyck /**
2421fef59c9cSTejun Heo  * select_numa_node_cpu - Select a CPU based on NUMA node
24228204e0c1SAlexander Duyck  * @node: NUMA node ID that we want to select a CPU from
24238204e0c1SAlexander Duyck  *
24248204e0c1SAlexander Duyck  * This function will attempt to find a "random" cpu available on a given
24258204e0c1SAlexander Duyck  * node. If there are no CPUs available on the given node it will return
24268204e0c1SAlexander Duyck  * WORK_CPU_UNBOUND indicating that we should just schedule to any
24278204e0c1SAlexander Duyck  * available CPU if we need to schedule this work.
24288204e0c1SAlexander Duyck  */
2429fef59c9cSTejun Heo static int select_numa_node_cpu(int node)
24308204e0c1SAlexander Duyck {
24318204e0c1SAlexander Duyck 	int cpu;
24328204e0c1SAlexander Duyck 
24338204e0c1SAlexander Duyck 	/* Delay binding to CPU if node is not valid or online */
24348204e0c1SAlexander Duyck 	if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
24358204e0c1SAlexander Duyck 		return WORK_CPU_UNBOUND;
24368204e0c1SAlexander Duyck 
24378204e0c1SAlexander Duyck 	/* Use local node/cpu if we are already there */
24388204e0c1SAlexander Duyck 	cpu = raw_smp_processor_id();
24398204e0c1SAlexander Duyck 	if (node == cpu_to_node(cpu))
24408204e0c1SAlexander Duyck 		return cpu;
24418204e0c1SAlexander Duyck 
24428204e0c1SAlexander Duyck 	/* Use "random" otherwise know as "first" online CPU of node */
24438204e0c1SAlexander Duyck 	cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
24448204e0c1SAlexander Duyck 
24458204e0c1SAlexander Duyck 	/* If CPU is valid return that, otherwise just defer */
24468204e0c1SAlexander Duyck 	return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
24478204e0c1SAlexander Duyck }
24488204e0c1SAlexander Duyck 
24498204e0c1SAlexander Duyck /**
24508204e0c1SAlexander Duyck  * queue_work_node - queue work on a "random" cpu for a given NUMA node
24518204e0c1SAlexander Duyck  * @node: NUMA node that we are targeting the work for
24528204e0c1SAlexander Duyck  * @wq: workqueue to use
24538204e0c1SAlexander Duyck  * @work: work to queue
24548204e0c1SAlexander Duyck  *
24558204e0c1SAlexander Duyck  * We queue the work to a "random" CPU within a given NUMA node. The basic
24568204e0c1SAlexander Duyck  * idea here is to provide a way to somehow associate work with a given
24578204e0c1SAlexander Duyck  * NUMA node.
24588204e0c1SAlexander Duyck  *
24598204e0c1SAlexander Duyck  * This function will only make a best effort attempt at getting this onto
24608204e0c1SAlexander Duyck  * the right NUMA node. If no node is requested or the requested node is
24618204e0c1SAlexander Duyck  * offline then we just fall back to standard queue_work behavior.
24628204e0c1SAlexander Duyck  *
24638204e0c1SAlexander Duyck  * Currently the "random" CPU ends up being the first available CPU in the
24648204e0c1SAlexander Duyck  * intersection of cpu_online_mask and the cpumask of the node, unless we
24658204e0c1SAlexander Duyck  * are running on the node. In that case we just use the current CPU.
24668204e0c1SAlexander Duyck  *
24678204e0c1SAlexander Duyck  * Return: %false if @work was already on a queue, %true otherwise.
24688204e0c1SAlexander Duyck  */
24698204e0c1SAlexander Duyck bool queue_work_node(int node, struct workqueue_struct *wq,
24708204e0c1SAlexander Duyck 		     struct work_struct *work)
24718204e0c1SAlexander Duyck {
2472c26e2f2eSTejun Heo 	unsigned long irq_flags;
24738204e0c1SAlexander Duyck 	bool ret = false;
24748204e0c1SAlexander Duyck 
24758204e0c1SAlexander Duyck 	/*
24768204e0c1SAlexander Duyck 	 * This current implementation is specific to unbound workqueues.
24778204e0c1SAlexander Duyck 	 * Specifically we only return the first available CPU for a given
24788204e0c1SAlexander Duyck 	 * node instead of cycling through individual CPUs within the node.
24798204e0c1SAlexander Duyck 	 *
24808204e0c1SAlexander Duyck 	 * If this is used with a per-cpu workqueue then the logic in
24818204e0c1SAlexander Duyck 	 * workqueue_select_cpu_near would need to be updated to allow for
24828204e0c1SAlexander Duyck 	 * some round robin type logic.
24838204e0c1SAlexander Duyck 	 */
24848204e0c1SAlexander Duyck 	WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
24858204e0c1SAlexander Duyck 
2486c26e2f2eSTejun Heo 	local_irq_save(irq_flags);
24878204e0c1SAlexander Duyck 
248886898fa6STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)) &&
248986898fa6STejun Heo 	    !clear_pending_if_disabled(work)) {
2490fef59c9cSTejun Heo 		int cpu = select_numa_node_cpu(node);
24918204e0c1SAlexander Duyck 
24928204e0c1SAlexander Duyck 		__queue_work(cpu, wq, work);
24938204e0c1SAlexander Duyck 		ret = true;
24948204e0c1SAlexander Duyck 	}
24958204e0c1SAlexander Duyck 
2496c26e2f2eSTejun Heo 	local_irq_restore(irq_flags);
24978204e0c1SAlexander Duyck 	return ret;
24988204e0c1SAlexander Duyck }
24998204e0c1SAlexander Duyck EXPORT_SYMBOL_GPL(queue_work_node);
25008204e0c1SAlexander Duyck 
25018c20feb6SKees Cook void delayed_work_timer_fn(struct timer_list *t)
25021da177e4SLinus Torvalds {
25038c20feb6SKees Cook 	struct delayed_work *dwork = from_timer(dwork, t, timer);
25041da177e4SLinus Torvalds 
2505e0aecdd8STejun Heo 	/* should have been called from irqsafe timer with irq already off */
250660c057bcSLai Jiangshan 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
25071da177e4SLinus Torvalds }
25081438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
25091da177e4SLinus Torvalds 
25107beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
251152bad64dSDavid Howells 				struct delayed_work *dwork, unsigned long delay)
25121da177e4SLinus Torvalds {
25137beb2edfSTejun Heo 	struct timer_list *timer = &dwork->timer;
25147beb2edfSTejun Heo 	struct work_struct *work = &dwork->work;
25151da177e4SLinus Torvalds 
2516637fdbaeSTejun Heo 	WARN_ON_ONCE(!wq);
25174b243563SSami Tolvanen 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
2518fc4b514fSTejun Heo 	WARN_ON_ONCE(timer_pending(timer));
2519fc4b514fSTejun Heo 	WARN_ON_ONCE(!list_empty(&work->entry));
25207beb2edfSTejun Heo 
25218852aac2STejun Heo 	/*
25228852aac2STejun Heo 	 * If @delay is 0, queue @dwork->work immediately.  This is for
25238852aac2STejun Heo 	 * both optimization and correctness.  The earliest @timer can
25248852aac2STejun Heo 	 * expire is on the closest next tick and delayed_work users depend
25258852aac2STejun Heo 	 * on that there's no such delay when @delay is 0.
25268852aac2STejun Heo 	 */
25278852aac2STejun Heo 	if (!delay) {
25288852aac2STejun Heo 		__queue_work(cpu, wq, &dwork->work);
25298852aac2STejun Heo 		return;
25308852aac2STejun Heo 	}
25318852aac2STejun Heo 
253260c057bcSLai Jiangshan 	dwork->wq = wq;
25331265057fSTejun Heo 	dwork->cpu = cpu;
25347beb2edfSTejun Heo 	timer->expires = jiffies + delay;
25357beb2edfSTejun Heo 
2536aae17ebbSLeonardo Bras 	if (housekeeping_enabled(HK_TYPE_TIMER)) {
2537aae17ebbSLeonardo Bras 		/* If the current cpu is a housekeeping cpu, use it. */
2538aae17ebbSLeonardo Bras 		cpu = smp_processor_id();
2539aae17ebbSLeonardo Bras 		if (!housekeeping_test_cpu(cpu, HK_TYPE_TIMER))
2540aae17ebbSLeonardo Bras 			cpu = housekeeping_any_cpu(HK_TYPE_TIMER);
25417beb2edfSTejun Heo 		add_timer_on(timer, cpu);
2542aae17ebbSLeonardo Bras 	} else {
2543aae17ebbSLeonardo Bras 		if (likely(cpu == WORK_CPU_UNBOUND))
2544c0e8c5b5SAnna-Maria Behnsen 			add_timer_global(timer);
2545aae17ebbSLeonardo Bras 		else
2546aae17ebbSLeonardo Bras 			add_timer_on(timer, cpu);
2547aae17ebbSLeonardo Bras 	}
25487beb2edfSTejun Heo }
25491da177e4SLinus Torvalds 
25500fcb78c2SRolf Eike Beer /**
25510fcb78c2SRolf Eike Beer  * queue_delayed_work_on - queue work on specific CPU after delay
25520fcb78c2SRolf Eike Beer  * @cpu: CPU number to execute work on
25530fcb78c2SRolf Eike Beer  * @wq: workqueue to use
2554af9997e4SRandy Dunlap  * @dwork: work to queue
25550fcb78c2SRolf Eike Beer  * @delay: number of jiffies to wait before queueing
25560fcb78c2SRolf Eike Beer  *
2557d185af30SYacine Belkadi  * Return: %false if @work was already on a queue, %true otherwise.  If
2558715f1300STejun Heo  * @delay is zero and @dwork is idle, it will be scheduled for immediate
2559715f1300STejun Heo  * execution.
25600fcb78c2SRolf Eike Beer  */
2561d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
256252bad64dSDavid Howells 			   struct delayed_work *dwork, unsigned long delay)
25637a6bc1cdSVenkatesh Pallipadi {
256452bad64dSDavid Howells 	struct work_struct *work = &dwork->work;
2565d4283e93STejun Heo 	bool ret = false;
2566c26e2f2eSTejun Heo 	unsigned long irq_flags;
25678930cabaSTejun Heo 
25688930cabaSTejun Heo 	/* read the comment in __queue_work() */
2569c26e2f2eSTejun Heo 	local_irq_save(irq_flags);
25707a6bc1cdSVenkatesh Pallipadi 
257186898fa6STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)) &&
257286898fa6STejun Heo 	    !clear_pending_if_disabled(work)) {
25737beb2edfSTejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
2574d4283e93STejun Heo 		ret = true;
25757a6bc1cdSVenkatesh Pallipadi 	}
25768930cabaSTejun Heo 
2577c26e2f2eSTejun Heo 	local_irq_restore(irq_flags);
25787a6bc1cdSVenkatesh Pallipadi 	return ret;
25797a6bc1cdSVenkatesh Pallipadi }
2580ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
25811da177e4SLinus Torvalds 
2582c8e55f36STejun Heo /**
25838376fe22STejun Heo  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
25848376fe22STejun Heo  * @cpu: CPU number to execute work on
25858376fe22STejun Heo  * @wq: workqueue to use
25868376fe22STejun Heo  * @dwork: work to queue
25878376fe22STejun Heo  * @delay: number of jiffies to wait before queueing
25888376fe22STejun Heo  *
25898376fe22STejun Heo  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
25908376fe22STejun Heo  * modify @dwork's timer so that it expires after @delay.  If @delay is
25918376fe22STejun Heo  * zero, @work is guaranteed to be scheduled immediately regardless of its
25928376fe22STejun Heo  * current state.
25938376fe22STejun Heo  *
2594d185af30SYacine Belkadi  * Return: %false if @dwork was idle and queued, %true if @dwork was
25958376fe22STejun Heo  * pending and its timer was modified.
25968376fe22STejun Heo  *
2597e0aecdd8STejun Heo  * This function is safe to call from any context including IRQ handler.
25988376fe22STejun Heo  * See try_to_grab_pending() for details.
25998376fe22STejun Heo  */
26008376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
26018376fe22STejun Heo 			 struct delayed_work *dwork, unsigned long delay)
26028376fe22STejun Heo {
2603c26e2f2eSTejun Heo 	unsigned long irq_flags;
2604f09b10b6STejun Heo 	bool ret;
26058376fe22STejun Heo 
2606f09b10b6STejun Heo 	ret = work_grab_pending(&dwork->work, WORK_CANCEL_DELAYED, &irq_flags);
26078376fe22STejun Heo 
2608f09b10b6STejun Heo 	if (!clear_pending_if_disabled(&dwork->work))
26098376fe22STejun Heo 		__queue_delayed_work(cpu, wq, dwork, delay);
26108376fe22STejun Heo 
2611f09b10b6STejun Heo 	local_irq_restore(irq_flags);
26128376fe22STejun Heo 	return ret;
26138376fe22STejun Heo }
26148376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
26158376fe22STejun Heo 
261605f0fe6bSTejun Heo static void rcu_work_rcufn(struct rcu_head *rcu)
261705f0fe6bSTejun Heo {
261805f0fe6bSTejun Heo 	struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
261905f0fe6bSTejun Heo 
262005f0fe6bSTejun Heo 	/* read the comment in __queue_work() */
262105f0fe6bSTejun Heo 	local_irq_disable();
262205f0fe6bSTejun Heo 	__queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
262305f0fe6bSTejun Heo 	local_irq_enable();
262405f0fe6bSTejun Heo }
262505f0fe6bSTejun Heo 
262605f0fe6bSTejun Heo /**
262705f0fe6bSTejun Heo  * queue_rcu_work - queue work after a RCU grace period
262805f0fe6bSTejun Heo  * @wq: workqueue to use
262905f0fe6bSTejun Heo  * @rwork: work to queue
263005f0fe6bSTejun Heo  *
263105f0fe6bSTejun Heo  * Return: %false if @rwork was already pending, %true otherwise.  Note
263205f0fe6bSTejun Heo  * that a full RCU grace period is guaranteed only after a %true return.
2633bf393fd4SBart Van Assche  * While @rwork is guaranteed to be executed after a %false return, the
263405f0fe6bSTejun Heo  * execution may happen before a full RCU grace period has passed.
263505f0fe6bSTejun Heo  */
263605f0fe6bSTejun Heo bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
263705f0fe6bSTejun Heo {
263805f0fe6bSTejun Heo 	struct work_struct *work = &rwork->work;
263905f0fe6bSTejun Heo 
264086898fa6STejun Heo 	/*
264186898fa6STejun Heo 	 * rcu_work can't be canceled or disabled. Warn if the user reached
264286898fa6STejun Heo 	 * inside @rwork and disabled the inner work.
264386898fa6STejun Heo 	 */
264486898fa6STejun Heo 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)) &&
264586898fa6STejun Heo 	    !WARN_ON_ONCE(clear_pending_if_disabled(work))) {
264605f0fe6bSTejun Heo 		rwork->wq = wq;
2647a7e30c0eSUladzislau Rezki 		call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
264805f0fe6bSTejun Heo 		return true;
264905f0fe6bSTejun Heo 	}
265005f0fe6bSTejun Heo 
265105f0fe6bSTejun Heo 	return false;
265205f0fe6bSTejun Heo }
265305f0fe6bSTejun Heo EXPORT_SYMBOL(queue_rcu_work);
265405f0fe6bSTejun Heo 
2655f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
2656c34056a3STejun Heo {
2657c34056a3STejun Heo 	struct worker *worker;
2658c34056a3STejun Heo 
2659f7537df5SLai Jiangshan 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
2660c8e55f36STejun Heo 	if (worker) {
2661c8e55f36STejun Heo 		INIT_LIST_HEAD(&worker->entry);
2662affee4b2STejun Heo 		INIT_LIST_HEAD(&worker->scheduled);
2663da028469SLai Jiangshan 		INIT_LIST_HEAD(&worker->node);
2664e22bee78STejun Heo 		/* on creation a worker is in !idle && prep state */
2665e22bee78STejun Heo 		worker->flags = WORKER_PREP;
2666c8e55f36STejun Heo 	}
2667c34056a3STejun Heo 	return worker;
2668c34056a3STejun Heo }
2669c34056a3STejun Heo 
26709546b29eSTejun Heo static cpumask_t *pool_allowed_cpus(struct worker_pool *pool)
26719546b29eSTejun Heo {
26728639ecebSTejun Heo 	if (pool->cpu < 0 && pool->attrs->affn_strict)
26739546b29eSTejun Heo 		return pool->attrs->__pod_cpumask;
26748639ecebSTejun Heo 	else
26758639ecebSTejun Heo 		return pool->attrs->cpumask;
26769546b29eSTejun Heo }
26779546b29eSTejun Heo 
2678c34056a3STejun Heo /**
26794736cbf7SLai Jiangshan  * worker_attach_to_pool() - attach a worker to a pool
26804736cbf7SLai Jiangshan  * @worker: worker to be attached
26814736cbf7SLai Jiangshan  * @pool: the target pool
26824736cbf7SLai Jiangshan  *
26834736cbf7SLai Jiangshan  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
26844736cbf7SLai Jiangshan  * cpu-binding of @worker are kept coordinated with the pool across
26854736cbf7SLai Jiangshan  * cpu-[un]hotplugs.
26864736cbf7SLai Jiangshan  */
26874736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
26884736cbf7SLai Jiangshan 				  struct worker_pool *pool)
26894736cbf7SLai Jiangshan {
26901258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
26914736cbf7SLai Jiangshan 
26924736cbf7SLai Jiangshan 	/*
26934cb1ef64STejun Heo 	 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains stable
26944cb1ef64STejun Heo 	 * across this function. See the comments above the flag definition for
26954cb1ef64STejun Heo 	 * details. BH workers are, while per-CPU, always DISASSOCIATED.
26964736cbf7SLai Jiangshan 	 */
26974cb1ef64STejun Heo 	if (pool->flags & POOL_DISASSOCIATED) {
26984736cbf7SLai Jiangshan 		worker->flags |= WORKER_UNBOUND;
26994cb1ef64STejun Heo 	} else {
27004cb1ef64STejun Heo 		WARN_ON_ONCE(pool->flags & POOL_BH);
27015c25b5ffSPeter Zijlstra 		kthread_set_per_cpu(worker->task, pool->cpu);
27024cb1ef64STejun Heo 	}
27034736cbf7SLai Jiangshan 
2704640f17c8SPeter Zijlstra 	if (worker->rescue_wq)
27059546b29eSTejun Heo 		set_cpus_allowed_ptr(worker->task, pool_allowed_cpus(pool));
2706640f17c8SPeter Zijlstra 
27074736cbf7SLai Jiangshan 	list_add_tail(&worker->node, &pool->workers);
2708a2d812a2STejun Heo 	worker->pool = pool;
27094736cbf7SLai Jiangshan 
27101258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
27114736cbf7SLai Jiangshan }
27124736cbf7SLai Jiangshan 
27134736cbf7SLai Jiangshan /**
271460f5a4bcSLai Jiangshan  * worker_detach_from_pool() - detach a worker from its pool
271560f5a4bcSLai Jiangshan  * @worker: worker which is attached to its pool
271660f5a4bcSLai Jiangshan  *
27174736cbf7SLai Jiangshan  * Undo the attaching which had been done in worker_attach_to_pool().  The
27184736cbf7SLai Jiangshan  * caller worker shouldn't access to the pool after detached except it has
27194736cbf7SLai Jiangshan  * other reference to the pool.
272060f5a4bcSLai Jiangshan  */
2721a2d812a2STejun Heo static void worker_detach_from_pool(struct worker *worker)
272260f5a4bcSLai Jiangshan {
2723a2d812a2STejun Heo 	struct worker_pool *pool = worker->pool;
272460f5a4bcSLai Jiangshan 	struct completion *detach_completion = NULL;
272560f5a4bcSLai Jiangshan 
27264cb1ef64STejun Heo 	/* there is one permanent BH worker per CPU which should never detach */
27274cb1ef64STejun Heo 	WARN_ON_ONCE(pool->flags & POOL_BH);
27284cb1ef64STejun Heo 
27291258fae7STejun Heo 	mutex_lock(&wq_pool_attach_mutex);
2730a2d812a2STejun Heo 
27315c25b5ffSPeter Zijlstra 	kthread_set_per_cpu(worker->task, -1);
2732da028469SLai Jiangshan 	list_del(&worker->node);
2733a2d812a2STejun Heo 	worker->pool = NULL;
2734a2d812a2STejun Heo 
2735e02b9312SValentin Schneider 	if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
273660f5a4bcSLai Jiangshan 		detach_completion = pool->detach_completion;
27371258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
273860f5a4bcSLai Jiangshan 
2739b62c0751SLai Jiangshan 	/* clear leftover flags without pool->lock after it is detached */
2740b62c0751SLai Jiangshan 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2741b62c0751SLai Jiangshan 
274260f5a4bcSLai Jiangshan 	if (detach_completion)
274360f5a4bcSLai Jiangshan 		complete(detach_completion);
274460f5a4bcSLai Jiangshan }
274560f5a4bcSLai Jiangshan 
2746*2a1b02bcSTejun Heo static int format_worker_id(char *buf, size_t size, struct worker *worker,
2747*2a1b02bcSTejun Heo 			    struct worker_pool *pool)
2748*2a1b02bcSTejun Heo {
2749*2a1b02bcSTejun Heo 	if (worker->rescue_wq)
2750*2a1b02bcSTejun Heo 		return scnprintf(buf, size, "kworker/R-%s",
2751*2a1b02bcSTejun Heo 				 worker->rescue_wq->name);
2752*2a1b02bcSTejun Heo 
2753*2a1b02bcSTejun Heo 	if (pool) {
2754*2a1b02bcSTejun Heo 		if (pool->cpu >= 0)
2755*2a1b02bcSTejun Heo 			return scnprintf(buf, size, "kworker/%d:%d%s",
2756*2a1b02bcSTejun Heo 					 pool->cpu, worker->id,
2757*2a1b02bcSTejun Heo 					 pool->attrs->nice < 0  ? "H" : "");
2758*2a1b02bcSTejun Heo 		else
2759*2a1b02bcSTejun Heo 			return scnprintf(buf, size, "kworker/u%d:%d",
2760*2a1b02bcSTejun Heo 					 pool->id, worker->id);
2761*2a1b02bcSTejun Heo 	} else {
2762*2a1b02bcSTejun Heo 		return scnprintf(buf, size, "kworker/dying");
2763*2a1b02bcSTejun Heo 	}
2764*2a1b02bcSTejun Heo }
2765*2a1b02bcSTejun Heo 
276660f5a4bcSLai Jiangshan /**
2767c34056a3STejun Heo  * create_worker - create a new workqueue worker
276863d95a91STejun Heo  * @pool: pool the new worker will belong to
2769c34056a3STejun Heo  *
2770051e1850SLai Jiangshan  * Create and start a new worker which is attached to @pool.
2771c34056a3STejun Heo  *
2772c34056a3STejun Heo  * CONTEXT:
2773c34056a3STejun Heo  * Might sleep.  Does GFP_KERNEL allocations.
2774c34056a3STejun Heo  *
2775d185af30SYacine Belkadi  * Return:
2776c34056a3STejun Heo  * Pointer to the newly created worker.
2777c34056a3STejun Heo  */
2778bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
2779c34056a3STejun Heo {
2780e441b56fSZhen Lei 	struct worker *worker;
2781e441b56fSZhen Lei 	int id;
2782c34056a3STejun Heo 
27837cda9aaeSLai Jiangshan 	/* ID is needed to determine kthread name */
2784e441b56fSZhen Lei 	id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
27853f0ea0b8SPetr Mladek 	if (id < 0) {
27863f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
27873f0ea0b8SPetr Mladek 			    ERR_PTR(id));
2788e441b56fSZhen Lei 		return NULL;
27893f0ea0b8SPetr Mladek 	}
2790c34056a3STejun Heo 
2791f7537df5SLai Jiangshan 	worker = alloc_worker(pool->node);
27923f0ea0b8SPetr Mladek 	if (!worker) {
27933f0ea0b8SPetr Mladek 		pr_err_once("workqueue: Failed to allocate a worker\n");
2794c34056a3STejun Heo 		goto fail;
27953f0ea0b8SPetr Mladek 	}
2796c34056a3STejun Heo 
2797c34056a3STejun Heo 	worker->id = id;
2798c34056a3STejun Heo 
27994cb1ef64STejun Heo 	if (!(pool->flags & POOL_BH)) {
2800*2a1b02bcSTejun Heo 		char id_buf[WORKER_ID_LEN];
2801e3c916a4STejun Heo 
2802*2a1b02bcSTejun Heo 		format_worker_id(id_buf, sizeof(id_buf), worker, pool);
28034cb1ef64STejun Heo 		worker->task = kthread_create_on_node(worker_thread, worker,
2804*2a1b02bcSTejun Heo 						      pool->node, "%s", id_buf);
28053f0ea0b8SPetr Mladek 		if (IS_ERR(worker->task)) {
280660f54038SPetr Mladek 			if (PTR_ERR(worker->task) == -EINTR) {
2807*2a1b02bcSTejun Heo 				pr_err("workqueue: Interrupted when creating a worker thread \"%s\"\n",
280860f54038SPetr Mladek 				       id_buf);
280960f54038SPetr Mladek 			} else {
28103f0ea0b8SPetr Mladek 				pr_err_once("workqueue: Failed to create a worker thread: %pe",
28113f0ea0b8SPetr Mladek 					    worker->task);
281260f54038SPetr Mladek 			}
2813c34056a3STejun Heo 			goto fail;
28143f0ea0b8SPetr Mladek 		}
2815c34056a3STejun Heo 
281691151228SOleg Nesterov 		set_user_nice(worker->task, pool->attrs->nice);
28179546b29eSTejun Heo 		kthread_bind_mask(worker->task, pool_allowed_cpus(pool));
28184cb1ef64STejun Heo 	}
281991151228SOleg Nesterov 
2820da028469SLai Jiangshan 	/* successful, attach the worker to the pool */
28214736cbf7SLai Jiangshan 	worker_attach_to_pool(worker, pool);
2822822d8405STejun Heo 
2823051e1850SLai Jiangshan 	/* start the newly created worker */
2824a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
28250219a352STejun Heo 
2826051e1850SLai Jiangshan 	worker->pool->nr_workers++;
2827051e1850SLai Jiangshan 	worker_enter_idle(worker);
28280219a352STejun Heo 
28290219a352STejun Heo 	/*
28300219a352STejun Heo 	 * @worker is waiting on a completion in kthread() and will trigger hung
28316a229b0eSTejun Heo 	 * check if not woken up soon. As kick_pool() is noop if @pool is empty,
28326a229b0eSTejun Heo 	 * wake it up explicitly.
28330219a352STejun Heo 	 */
28344cb1ef64STejun Heo 	if (worker->task)
2835051e1850SLai Jiangshan 		wake_up_process(worker->task);
28360219a352STejun Heo 
2837a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2838051e1850SLai Jiangshan 
2839c34056a3STejun Heo 	return worker;
2840822d8405STejun Heo 
2841c34056a3STejun Heo fail:
2842e441b56fSZhen Lei 	ida_free(&pool->worker_ida, id);
2843c34056a3STejun Heo 	kfree(worker);
2844c34056a3STejun Heo 	return NULL;
2845c34056a3STejun Heo }
2846c34056a3STejun Heo 
2847793777bcSValentin Schneider static void unbind_worker(struct worker *worker)
2848793777bcSValentin Schneider {
2849793777bcSValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2850793777bcSValentin Schneider 
2851793777bcSValentin Schneider 	kthread_set_per_cpu(worker->task, -1);
2852793777bcSValentin Schneider 	if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2853793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2854793777bcSValentin Schneider 	else
2855793777bcSValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2856793777bcSValentin Schneider }
2857793777bcSValentin Schneider 
2858e02b9312SValentin Schneider static void wake_dying_workers(struct list_head *cull_list)
2859e02b9312SValentin Schneider {
2860e02b9312SValentin Schneider 	struct worker *worker, *tmp;
2861e02b9312SValentin Schneider 
2862e02b9312SValentin Schneider 	list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2863e02b9312SValentin Schneider 		list_del_init(&worker->entry);
2864e02b9312SValentin Schneider 		unbind_worker(worker);
2865e02b9312SValentin Schneider 		/*
2866e02b9312SValentin Schneider 		 * If the worker was somehow already running, then it had to be
2867e02b9312SValentin Schneider 		 * in pool->idle_list when set_worker_dying() happened or we
2868e02b9312SValentin Schneider 		 * wouldn't have gotten here.
2869c34056a3STejun Heo 		 *
2870e02b9312SValentin Schneider 		 * Thus, the worker must either have observed the WORKER_DIE
2871e02b9312SValentin Schneider 		 * flag, or have set its state to TASK_IDLE. Either way, the
2872e02b9312SValentin Schneider 		 * below will be observed by the worker and is safe to do
2873e02b9312SValentin Schneider 		 * outside of pool->lock.
2874e02b9312SValentin Schneider 		 */
2875e02b9312SValentin Schneider 		wake_up_process(worker->task);
2876e02b9312SValentin Schneider 	}
2877e02b9312SValentin Schneider }
2878e02b9312SValentin Schneider 
2879e02b9312SValentin Schneider /**
2880e02b9312SValentin Schneider  * set_worker_dying - Tag a worker for destruction
2881e02b9312SValentin Schneider  * @worker: worker to be destroyed
2882e02b9312SValentin Schneider  * @list: transfer worker away from its pool->idle_list and into list
2883e02b9312SValentin Schneider  *
2884e02b9312SValentin Schneider  * Tag @worker for destruction and adjust @pool stats accordingly.  The worker
2885e02b9312SValentin Schneider  * should be idle.
2886c8e55f36STejun Heo  *
2887c8e55f36STejun Heo  * CONTEXT:
2888a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
2889c34056a3STejun Heo  */
2890e02b9312SValentin Schneider static void set_worker_dying(struct worker *worker, struct list_head *list)
2891c34056a3STejun Heo {
2892bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
2893c34056a3STejun Heo 
2894cd549687STejun Heo 	lockdep_assert_held(&pool->lock);
2895e02b9312SValentin Schneider 	lockdep_assert_held(&wq_pool_attach_mutex);
2896cd549687STejun Heo 
2897c34056a3STejun Heo 	/* sanity check frenzy */
28986183c009STejun Heo 	if (WARN_ON(worker->current_work) ||
289973eb7fe7SLai Jiangshan 	    WARN_ON(!list_empty(&worker->scheduled)) ||
290073eb7fe7SLai Jiangshan 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
29016183c009STejun Heo 		return;
2902c34056a3STejun Heo 
2903bd7bdd43STejun Heo 	pool->nr_workers--;
2904bd7bdd43STejun Heo 	pool->nr_idle--;
2905c8e55f36STejun Heo 
2906cb444766STejun Heo 	worker->flags |= WORKER_DIE;
2907e02b9312SValentin Schneider 
2908e02b9312SValentin Schneider 	list_move(&worker->entry, list);
2909e02b9312SValentin Schneider 	list_move(&worker->node, &pool->dying_workers);
2910c34056a3STejun Heo }
2911c34056a3STejun Heo 
29123f959aa3SValentin Schneider /**
29133f959aa3SValentin Schneider  * idle_worker_timeout - check if some idle workers can now be deleted.
29143f959aa3SValentin Schneider  * @t: The pool's idle_timer that just expired
29153f959aa3SValentin Schneider  *
29163f959aa3SValentin Schneider  * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
29173f959aa3SValentin Schneider  * worker_leave_idle(), as a worker flicking between idle and active while its
29183f959aa3SValentin Schneider  * pool is at the too_many_workers() tipping point would cause too much timer
29193f959aa3SValentin Schneider  * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
29203f959aa3SValentin Schneider  * it expire and re-evaluate things from there.
29213f959aa3SValentin Schneider  */
292232a6c723SKees Cook static void idle_worker_timeout(struct timer_list *t)
2923e22bee78STejun Heo {
292432a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, idle_timer);
29253f959aa3SValentin Schneider 	bool do_cull = false;
29263f959aa3SValentin Schneider 
29273f959aa3SValentin Schneider 	if (work_pending(&pool->idle_cull_work))
29283f959aa3SValentin Schneider 		return;
29293f959aa3SValentin Schneider 
29303f959aa3SValentin Schneider 	raw_spin_lock_irq(&pool->lock);
29313f959aa3SValentin Schneider 
29323f959aa3SValentin Schneider 	if (too_many_workers(pool)) {
29333f959aa3SValentin Schneider 		struct worker *worker;
29343f959aa3SValentin Schneider 		unsigned long expires;
29353f959aa3SValentin Schneider 
29363f959aa3SValentin Schneider 		/* idle_list is kept in LIFO order, check the last one */
2937d70f5d57SLai Jiangshan 		worker = list_last_entry(&pool->idle_list, struct worker, entry);
29383f959aa3SValentin Schneider 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
29393f959aa3SValentin Schneider 		do_cull = !time_before(jiffies, expires);
29403f959aa3SValentin Schneider 
29413f959aa3SValentin Schneider 		if (!do_cull)
29423f959aa3SValentin Schneider 			mod_timer(&pool->idle_timer, expires);
29433f959aa3SValentin Schneider 	}
29443f959aa3SValentin Schneider 	raw_spin_unlock_irq(&pool->lock);
29453f959aa3SValentin Schneider 
29463f959aa3SValentin Schneider 	if (do_cull)
29473f959aa3SValentin Schneider 		queue_work(system_unbound_wq, &pool->idle_cull_work);
29483f959aa3SValentin Schneider }
29493f959aa3SValentin Schneider 
29503f959aa3SValentin Schneider /**
29513f959aa3SValentin Schneider  * idle_cull_fn - cull workers that have been idle for too long.
29523f959aa3SValentin Schneider  * @work: the pool's work for handling these idle workers
29533f959aa3SValentin Schneider  *
29543f959aa3SValentin Schneider  * This goes through a pool's idle workers and gets rid of those that have been
29553f959aa3SValentin Schneider  * idle for at least IDLE_WORKER_TIMEOUT seconds.
2956e02b9312SValentin Schneider  *
2957e02b9312SValentin Schneider  * We don't want to disturb isolated CPUs because of a pcpu kworker being
2958e02b9312SValentin Schneider  * culled, so this also resets worker affinity. This requires a sleepable
2959e02b9312SValentin Schneider  * context, hence the split between timer callback and work item.
29603f959aa3SValentin Schneider  */
29613f959aa3SValentin Schneider static void idle_cull_fn(struct work_struct *work)
29623f959aa3SValentin Schneider {
29633f959aa3SValentin Schneider 	struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
29649680540cSYang Yingliang 	LIST_HEAD(cull_list);
2965e22bee78STejun Heo 
2966e02b9312SValentin Schneider 	/*
2967e02b9312SValentin Schneider 	 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2968e02b9312SValentin Schneider 	 * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2969e02b9312SValentin Schneider 	 * path. This is required as a previously-preempted worker could run after
2970e02b9312SValentin Schneider 	 * set_worker_dying() has happened but before wake_dying_workers() did.
2971e02b9312SValentin Schneider 	 */
2972e02b9312SValentin Schneider 	mutex_lock(&wq_pool_attach_mutex);
2973a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
2974e22bee78STejun Heo 
29753347fc9fSLai Jiangshan 	while (too_many_workers(pool)) {
2976e22bee78STejun Heo 		struct worker *worker;
2977e22bee78STejun Heo 		unsigned long expires;
2978e22bee78STejun Heo 
2979d70f5d57SLai Jiangshan 		worker = list_last_entry(&pool->idle_list, struct worker, entry);
2980e22bee78STejun Heo 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2981e22bee78STejun Heo 
29823347fc9fSLai Jiangshan 		if (time_before(jiffies, expires)) {
298363d95a91STejun Heo 			mod_timer(&pool->idle_timer, expires);
29843347fc9fSLai Jiangshan 			break;
2985e22bee78STejun Heo 		}
29863347fc9fSLai Jiangshan 
2987e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
2988e22bee78STejun Heo 	}
2989e22bee78STejun Heo 
2990a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
2991e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
2992e02b9312SValentin Schneider 	mutex_unlock(&wq_pool_attach_mutex);
2993e22bee78STejun Heo }
2994e22bee78STejun Heo 
2995493a1724STejun Heo static void send_mayday(struct work_struct *work)
2996e22bee78STejun Heo {
2997112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
2998112202d9STejun Heo 	struct workqueue_struct *wq = pwq->wq;
2999493a1724STejun Heo 
30002e109a28STejun Heo 	lockdep_assert_held(&wq_mayday_lock);
3001e22bee78STejun Heo 
3002493008a8STejun Heo 	if (!wq->rescuer)
3003493a1724STejun Heo 		return;
3004e22bee78STejun Heo 
3005e22bee78STejun Heo 	/* mayday mayday mayday */
3006493a1724STejun Heo 	if (list_empty(&pwq->mayday_node)) {
300777668c8bSLai Jiangshan 		/*
300877668c8bSLai Jiangshan 		 * If @pwq is for an unbound wq, its base ref may be put at
300977668c8bSLai Jiangshan 		 * any time due to an attribute change.  Pin @pwq until the
301077668c8bSLai Jiangshan 		 * rescuer is done with it.
301177668c8bSLai Jiangshan 		 */
301277668c8bSLai Jiangshan 		get_pwq(pwq);
3013493a1724STejun Heo 		list_add_tail(&pwq->mayday_node, &wq->maydays);
3014e22bee78STejun Heo 		wake_up_process(wq->rescuer->task);
3015725e8ec5STejun Heo 		pwq->stats[PWQ_STAT_MAYDAY]++;
3016493a1724STejun Heo 	}
3017e22bee78STejun Heo }
3018e22bee78STejun Heo 
301932a6c723SKees Cook static void pool_mayday_timeout(struct timer_list *t)
3020e22bee78STejun Heo {
302132a6c723SKees Cook 	struct worker_pool *pool = from_timer(pool, t, mayday_timer);
3022e22bee78STejun Heo 	struct work_struct *work;
3023e22bee78STejun Heo 
3024a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
3025a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock(&wq_mayday_lock);		/* for wq->maydays */
3026e22bee78STejun Heo 
302763d95a91STejun Heo 	if (need_to_create_worker(pool)) {
3028e22bee78STejun Heo 		/*
3029e22bee78STejun Heo 		 * We've been trying to create a new worker but
3030e22bee78STejun Heo 		 * haven't been successful.  We might be hitting an
3031e22bee78STejun Heo 		 * allocation deadlock.  Send distress signals to
3032e22bee78STejun Heo 		 * rescuers.
3033e22bee78STejun Heo 		 */
303463d95a91STejun Heo 		list_for_each_entry(work, &pool->worklist, entry)
3035e22bee78STejun Heo 			send_mayday(work);
3036e22bee78STejun Heo 	}
3037e22bee78STejun Heo 
3038a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock(&wq_mayday_lock);
3039a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
3040e22bee78STejun Heo 
304163d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
3042e22bee78STejun Heo }
3043e22bee78STejun Heo 
3044e22bee78STejun Heo /**
3045e22bee78STejun Heo  * maybe_create_worker - create a new worker if necessary
304663d95a91STejun Heo  * @pool: pool to create a new worker for
3047e22bee78STejun Heo  *
304863d95a91STejun Heo  * Create a new worker for @pool if necessary.  @pool is guaranteed to
3049e22bee78STejun Heo  * have at least one idle worker on return from this function.  If
3050e22bee78STejun Heo  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
305163d95a91STejun Heo  * sent to all rescuers with works scheduled on @pool to resolve
3052e22bee78STejun Heo  * possible allocation deadlock.
3053e22bee78STejun Heo  *
3054c5aa87bbSTejun Heo  * On return, need_to_create_worker() is guaranteed to be %false and
3055c5aa87bbSTejun Heo  * may_start_working() %true.
3056e22bee78STejun Heo  *
3057e22bee78STejun Heo  * LOCKING:
3058a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3059e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.  Called only from
3060e22bee78STejun Heo  * manager.
3061e22bee78STejun Heo  */
306229187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
3063d565ed63STejun Heo __releases(&pool->lock)
3064d565ed63STejun Heo __acquires(&pool->lock)
3065e22bee78STejun Heo {
3066e22bee78STejun Heo restart:
3067a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
30689f9c2364STejun Heo 
3069e22bee78STejun Heo 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
307063d95a91STejun Heo 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
3071e22bee78STejun Heo 
3072e22bee78STejun Heo 	while (true) {
3073051e1850SLai Jiangshan 		if (create_worker(pool) || !need_to_create_worker(pool))
3074e22bee78STejun Heo 			break;
3075e22bee78STejun Heo 
3076e212f361SLai Jiangshan 		schedule_timeout_interruptible(CREATE_COOLDOWN);
30779f9c2364STejun Heo 
307863d95a91STejun Heo 		if (!need_to_create_worker(pool))
3079e22bee78STejun Heo 			break;
3080e22bee78STejun Heo 	}
3081e22bee78STejun Heo 
308263d95a91STejun Heo 	del_timer_sync(&pool->mayday_timer);
3083a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
3084051e1850SLai Jiangshan 	/*
3085051e1850SLai Jiangshan 	 * This is necessary even after a new worker was just successfully
3086051e1850SLai Jiangshan 	 * created as @pool->lock was dropped and the new worker might have
3087051e1850SLai Jiangshan 	 * already become busy.
3088051e1850SLai Jiangshan 	 */
308963d95a91STejun Heo 	if (need_to_create_worker(pool))
3090e22bee78STejun Heo 		goto restart;
3091e22bee78STejun Heo }
3092e22bee78STejun Heo 
3093e22bee78STejun Heo /**
3094e22bee78STejun Heo  * manage_workers - manage worker pool
3095e22bee78STejun Heo  * @worker: self
3096e22bee78STejun Heo  *
3097706026c2STejun Heo  * Assume the manager role and manage the worker pool @worker belongs
3098e22bee78STejun Heo  * to.  At any given time, there can be only zero or one manager per
3099706026c2STejun Heo  * pool.  The exclusion is handled automatically by this function.
3100e22bee78STejun Heo  *
3101e22bee78STejun Heo  * The caller can safely start processing works on false return.  On
3102e22bee78STejun Heo  * true return, it's guaranteed that need_to_create_worker() is false
3103e22bee78STejun Heo  * and may_start_working() is true.
3104e22bee78STejun Heo  *
3105e22bee78STejun Heo  * CONTEXT:
3106a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3107e22bee78STejun Heo  * multiple times.  Does GFP_KERNEL allocations.
3108e22bee78STejun Heo  *
3109d185af30SYacine Belkadi  * Return:
311029187a9eSTejun Heo  * %false if the pool doesn't need management and the caller can safely
311129187a9eSTejun Heo  * start processing works, %true if management function was performed and
311229187a9eSTejun Heo  * the conditions that the caller verified before calling the function may
311329187a9eSTejun Heo  * no longer be true.
3114e22bee78STejun Heo  */
3115e22bee78STejun Heo static bool manage_workers(struct worker *worker)
3116e22bee78STejun Heo {
311763d95a91STejun Heo 	struct worker_pool *pool = worker->pool;
3118e22bee78STejun Heo 
3119692b4825STejun Heo 	if (pool->flags & POOL_MANAGER_ACTIVE)
312029187a9eSTejun Heo 		return false;
3121692b4825STejun Heo 
3122692b4825STejun Heo 	pool->flags |= POOL_MANAGER_ACTIVE;
31232607d7a6STejun Heo 	pool->manager = worker;
3124e22bee78STejun Heo 
312529187a9eSTejun Heo 	maybe_create_worker(pool);
3126e22bee78STejun Heo 
31272607d7a6STejun Heo 	pool->manager = NULL;
3128692b4825STejun Heo 	pool->flags &= ~POOL_MANAGER_ACTIVE;
3129d8bb65abSSebastian Andrzej Siewior 	rcuwait_wake_up(&manager_wait);
313029187a9eSTejun Heo 	return true;
3131e22bee78STejun Heo }
3132e22bee78STejun Heo 
3133a62428c0STejun Heo /**
3134a62428c0STejun Heo  * process_one_work - process single work
3135c34056a3STejun Heo  * @worker: self
3136a62428c0STejun Heo  * @work: work to process
3137a62428c0STejun Heo  *
3138a62428c0STejun Heo  * Process @work.  This function contains all the logics necessary to
3139a62428c0STejun Heo  * process a single work including synchronization against and
3140a62428c0STejun Heo  * interaction with other workers on the same cpu, queueing and
3141a62428c0STejun Heo  * flushing.  As long as context requirement is met, any worker can
3142a62428c0STejun Heo  * call this function to process a work.
3143a62428c0STejun Heo  *
3144a62428c0STejun Heo  * CONTEXT:
3145a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
3146a62428c0STejun Heo  */
3147c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
3148d565ed63STejun Heo __releases(&pool->lock)
3149d565ed63STejun Heo __acquires(&pool->lock)
31501da177e4SLinus Torvalds {
3151112202d9STejun Heo 	struct pool_workqueue *pwq = get_work_pwq(work);
3152bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
3153c4560c2cSLai Jiangshan 	unsigned long work_data;
3154c35aea39STejun Heo 	int lockdep_start_depth, rcu_start_depth;
31551acd92d9STejun Heo 	bool bh_draining = pool->flags & POOL_BH_DRAINING;
31564e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
31574e6045f1SJohannes Berg 	/*
3158a62428c0STejun Heo 	 * It is permissible to free the struct work_struct from
3159a62428c0STejun Heo 	 * inside the function that is called from it, this we need to
3160a62428c0STejun Heo 	 * take into account for lockdep too.  To avoid bogus "held
3161a62428c0STejun Heo 	 * lock freed" warnings as well as problems when looking into
3162a62428c0STejun Heo 	 * work->lockdep_map, make a copy and use that here.
31634e6045f1SJohannes Berg 	 */
31644d82a1deSPeter Zijlstra 	struct lockdep_map lockdep_map;
31654d82a1deSPeter Zijlstra 
31664d82a1deSPeter Zijlstra 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
31674e6045f1SJohannes Berg #endif
3168807407c0SLai Jiangshan 	/* ensure we're on the correct CPU */
316985327af6SLai Jiangshan 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
3170ec22ca5eSTejun Heo 		     raw_smp_processor_id() != pool->cpu);
317125511a47STejun Heo 
31728930cabaSTejun Heo 	/* claim and dequeue */
3173dc186ad7SThomas Gleixner 	debug_work_deactivate(work);
3174c9e7cf27STejun Heo 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
3175c34056a3STejun Heo 	worker->current_work = work;
3176a2c1c57bSTejun Heo 	worker->current_func = work->func;
3177112202d9STejun Heo 	worker->current_pwq = pwq;
31784cb1ef64STejun Heo 	if (worker->task)
3179616db877STejun Heo 		worker->current_at = worker->task->se.sum_exec_runtime;
3180c4560c2cSLai Jiangshan 	work_data = *work_data_bits(work);
3181d812796eSLai Jiangshan 	worker->current_color = get_work_color(work_data);
31827a22ad75STejun Heo 
31838bf89593STejun Heo 	/*
31848bf89593STejun Heo 	 * Record wq name for cmdline and debug reporting, may get
31858bf89593STejun Heo 	 * overridden through set_worker_desc().
31868bf89593STejun Heo 	 */
31878bf89593STejun Heo 	strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
31888bf89593STejun Heo 
3189a62428c0STejun Heo 	list_del_init(&work->entry);
3190a62428c0STejun Heo 
3191649027d7STejun Heo 	/*
3192228f1d00SLai Jiangshan 	 * CPU intensive works don't participate in concurrency management.
3193228f1d00SLai Jiangshan 	 * They're the scheduler's responsibility.  This takes @worker out
3194228f1d00SLai Jiangshan 	 * of concurrency management and the next code block will chain
3195228f1d00SLai Jiangshan 	 * execution of the pending work items.
3196fb0e7bebSTejun Heo 	 */
3197616db877STejun Heo 	if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
3198228f1d00SLai Jiangshan 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
3199fb0e7bebSTejun Heo 
3200974271c4STejun Heo 	/*
32010219a352STejun Heo 	 * Kick @pool if necessary. It's always noop for per-cpu worker pools
32020219a352STejun Heo 	 * since nr_running would always be >= 1 at this point. This is used to
32030219a352STejun Heo 	 * chain execution of the pending work items for WORKER_NOT_RUNNING
32040219a352STejun Heo 	 * workers such as the UNBOUND and CPU_INTENSIVE ones.
3205974271c4STejun Heo 	 */
32060219a352STejun Heo 	kick_pool(pool);
3207974271c4STejun Heo 
32088930cabaSTejun Heo 	/*
32097c3eed5cSTejun Heo 	 * Record the last pool and clear PENDING which should be the last
3210d565ed63STejun Heo 	 * update to @work.  Also, do this inside @pool->lock so that
321123657bb1STejun Heo 	 * PENDING and queued state changes happen together while IRQ is
321223657bb1STejun Heo 	 * disabled.
32138930cabaSTejun Heo 	 */
3214456a78eeSTejun Heo 	set_work_pool_and_clear_pending(work, pool->id, pool_offq_flags(pool));
32151da177e4SLinus Torvalds 
3216fe48ba7dSMirsad Goran Todorovac 	pwq->stats[PWQ_STAT_STARTED]++;
3217a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
3218365970a1SDavid Howells 
3219c35aea39STejun Heo 	rcu_start_depth = rcu_preempt_depth();
3220c35aea39STejun Heo 	lockdep_start_depth = lockdep_depth(current);
32211acd92d9STejun Heo 	/* see drain_dead_softirq_workfn() */
32221acd92d9STejun Heo 	if (!bh_draining)
3223a1d14934SPeter Zijlstra 		lock_map_acquire(&pwq->wq->lockdep_map);
32243295f0efSIngo Molnar 	lock_map_acquire(&lockdep_map);
3225e6f3faa7SPeter Zijlstra 	/*
3226f52be570SPeter Zijlstra 	 * Strictly speaking we should mark the invariant state without holding
3227f52be570SPeter Zijlstra 	 * any locks, that is, before these two lock_map_acquire()'s.
3228e6f3faa7SPeter Zijlstra 	 *
3229e6f3faa7SPeter Zijlstra 	 * However, that would result in:
3230e6f3faa7SPeter Zijlstra 	 *
3231e6f3faa7SPeter Zijlstra 	 *   A(W1)
3232e6f3faa7SPeter Zijlstra 	 *   WFC(C)
3233e6f3faa7SPeter Zijlstra 	 *		A(W1)
3234e6f3faa7SPeter Zijlstra 	 *		C(C)
3235e6f3faa7SPeter Zijlstra 	 *
3236e6f3faa7SPeter Zijlstra 	 * Which would create W1->C->W1 dependencies, even though there is no
3237e6f3faa7SPeter Zijlstra 	 * actual deadlock possible. There are two solutions, using a
3238e6f3faa7SPeter Zijlstra 	 * read-recursive acquire on the work(queue) 'locks', but this will then
3239f52be570SPeter Zijlstra 	 * hit the lockdep limitation on recursive locks, or simply discard
3240e6f3faa7SPeter Zijlstra 	 * these locks.
3241e6f3faa7SPeter Zijlstra 	 *
3242e6f3faa7SPeter Zijlstra 	 * AFAICT there is no possible deadlock scenario between the
3243e6f3faa7SPeter Zijlstra 	 * flush_work() and complete() primitives (except for single-threaded
3244e6f3faa7SPeter Zijlstra 	 * workqueues), so hiding them isn't a problem.
3245e6f3faa7SPeter Zijlstra 	 */
3246f52be570SPeter Zijlstra 	lockdep_invariant_state(true);
3247e36c886aSArjan van de Ven 	trace_workqueue_execute_start(work);
3248a2c1c57bSTejun Heo 	worker->current_func(work);
3249e36c886aSArjan van de Ven 	/*
3250e36c886aSArjan van de Ven 	 * While we must be careful to not use "work" after this, the trace
3251e36c886aSArjan van de Ven 	 * point will only record its address.
3252e36c886aSArjan van de Ven 	 */
32531c5da0ecSDaniel Jordan 	trace_workqueue_execute_end(work, worker->current_func);
3254725e8ec5STejun Heo 	pwq->stats[PWQ_STAT_COMPLETED]++;
32553295f0efSIngo Molnar 	lock_map_release(&lockdep_map);
32561acd92d9STejun Heo 	if (!bh_draining)
3257112202d9STejun Heo 		lock_map_release(&pwq->wq->lockdep_map);
32581da177e4SLinus Torvalds 
3259c35aea39STejun Heo 	if (unlikely((worker->task && in_atomic()) ||
3260c35aea39STejun Heo 		     lockdep_depth(current) != lockdep_start_depth ||
3261c35aea39STejun Heo 		     rcu_preempt_depth() != rcu_start_depth)) {
3262c35aea39STejun Heo 		pr_err("BUG: workqueue leaked atomic, lock or RCU: %s[%d]\n"
3263c35aea39STejun Heo 		       "     preempt=0x%08x lock=%d->%d RCU=%d->%d workfn=%ps\n",
3264c35aea39STejun Heo 		       current->comm, task_pid_nr(current), preempt_count(),
3265c35aea39STejun Heo 		       lockdep_start_depth, lockdep_depth(current),
3266c35aea39STejun Heo 		       rcu_start_depth, rcu_preempt_depth(),
3267c35aea39STejun Heo 		       worker->current_func);
3268d5abe669SPeter Zijlstra 		debug_show_held_locks(current);
3269d5abe669SPeter Zijlstra 		dump_stack();
3270d5abe669SPeter Zijlstra 	}
3271d5abe669SPeter Zijlstra 
3272b22ce278STejun Heo 	/*
3273025f50f3SSebastian Andrzej Siewior 	 * The following prevents a kworker from hogging CPU on !PREEMPTION
3274b22ce278STejun Heo 	 * kernels, where a requeueing work item waiting for something to
3275b22ce278STejun Heo 	 * happen could deadlock with stop_machine as such work item could
3276b22ce278STejun Heo 	 * indefinitely requeue itself while all other CPUs are trapped in
3277789cbbecSJoe Lawrence 	 * stop_machine. At the same time, report a quiescent RCU state so
3278789cbbecSJoe Lawrence 	 * the same condition doesn't freeze RCU.
3279b22ce278STejun Heo 	 */
32804cb1ef64STejun Heo 	if (worker->task)
3281a7e6425eSPaul E. McKenney 		cond_resched();
3282b22ce278STejun Heo 
3283a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
3284a62428c0STejun Heo 
3285616db877STejun Heo 	/*
3286616db877STejun Heo 	 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
3287616db877STejun Heo 	 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
3288616db877STejun Heo 	 * wq_cpu_intensive_thresh_us. Clear it.
3289616db877STejun Heo 	 */
3290fb0e7bebSTejun Heo 	worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
3291fb0e7bebSTejun Heo 
32921b69ac6bSJohannes Weiner 	/* tag the worker for identification in schedule() */
32931b69ac6bSJohannes Weiner 	worker->last_func = worker->current_func;
32941b69ac6bSJohannes Weiner 
3295a62428c0STejun Heo 	/* we're done with it, release */
329642f8570fSSasha Levin 	hash_del(&worker->hentry);
3297c34056a3STejun Heo 	worker->current_work = NULL;
3298a2c1c57bSTejun Heo 	worker->current_func = NULL;
3299112202d9STejun Heo 	worker->current_pwq = NULL;
3300d812796eSLai Jiangshan 	worker->current_color = INT_MAX;
3301dd6c3c54STejun Heo 
3302dd6c3c54STejun Heo 	/* must be the last step, see the function comment */
3303c4560c2cSLai Jiangshan 	pwq_dec_nr_in_flight(pwq, work_data);
33041da177e4SLinus Torvalds }
33051da177e4SLinus Torvalds 
3306affee4b2STejun Heo /**
3307affee4b2STejun Heo  * process_scheduled_works - process scheduled works
3308affee4b2STejun Heo  * @worker: self
3309affee4b2STejun Heo  *
3310affee4b2STejun Heo  * Process all scheduled works.  Please note that the scheduled list
3311affee4b2STejun Heo  * may change while processing a work, so this function repeatedly
3312affee4b2STejun Heo  * fetches a work from the top and executes it.
3313affee4b2STejun Heo  *
3314affee4b2STejun Heo  * CONTEXT:
3315a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3316affee4b2STejun Heo  * multiple times.
3317affee4b2STejun Heo  */
3318affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
33191da177e4SLinus Torvalds {
3320c0ab017dSTejun Heo 	struct work_struct *work;
3321c0ab017dSTejun Heo 	bool first = true;
3322c0ab017dSTejun Heo 
3323c0ab017dSTejun Heo 	while ((work = list_first_entry_or_null(&worker->scheduled,
3324c0ab017dSTejun Heo 						struct work_struct, entry))) {
3325c0ab017dSTejun Heo 		if (first) {
3326c0ab017dSTejun Heo 			worker->pool->watchdog_ts = jiffies;
3327c0ab017dSTejun Heo 			first = false;
3328c0ab017dSTejun Heo 		}
3329c34056a3STejun Heo 		process_one_work(worker, work);
3330a62428c0STejun Heo 	}
33311da177e4SLinus Torvalds }
33321da177e4SLinus Torvalds 
3333197f6accSTejun Heo static void set_pf_worker(bool val)
3334197f6accSTejun Heo {
3335197f6accSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
3336197f6accSTejun Heo 	if (val)
3337197f6accSTejun Heo 		current->flags |= PF_WQ_WORKER;
3338197f6accSTejun Heo 	else
3339197f6accSTejun Heo 		current->flags &= ~PF_WQ_WORKER;
3340197f6accSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
3341197f6accSTejun Heo }
3342197f6accSTejun Heo 
33434690c4abSTejun Heo /**
33444690c4abSTejun Heo  * worker_thread - the worker thread function
3345c34056a3STejun Heo  * @__worker: self
33464690c4abSTejun Heo  *
3347c5aa87bbSTejun Heo  * The worker thread function.  All workers belong to a worker_pool -
3348c5aa87bbSTejun Heo  * either a per-cpu one or dynamic unbound one.  These workers process all
3349c5aa87bbSTejun Heo  * work items regardless of their specific target workqueue.  The only
3350c5aa87bbSTejun Heo  * exception is work items which belong to workqueues with a rescuer which
3351c5aa87bbSTejun Heo  * will be explained in rescuer_thread().
3352d185af30SYacine Belkadi  *
3353d185af30SYacine Belkadi  * Return: 0
33544690c4abSTejun Heo  */
3355c34056a3STejun Heo static int worker_thread(void *__worker)
33561da177e4SLinus Torvalds {
3357c34056a3STejun Heo 	struct worker *worker = __worker;
3358bd7bdd43STejun Heo 	struct worker_pool *pool = worker->pool;
33591da177e4SLinus Torvalds 
3360e22bee78STejun Heo 	/* tell the scheduler that this is a workqueue worker */
3361197f6accSTejun Heo 	set_pf_worker(true);
3362c8e55f36STejun Heo woke_up:
3363a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
3364affee4b2STejun Heo 
3365a9ab775bSTejun Heo 	/* am I supposed to die? */
3366a9ab775bSTejun Heo 	if (unlikely(worker->flags & WORKER_DIE)) {
3367a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
3368197f6accSTejun Heo 		set_pf_worker(false);
336960f5a4bcSLai Jiangshan 
3370e441b56fSZhen Lei 		ida_free(&pool->worker_ida, worker->id);
3371a2d812a2STejun Heo 		worker_detach_from_pool(worker);
3372e02b9312SValentin Schneider 		WARN_ON_ONCE(!list_empty(&worker->entry));
337360f5a4bcSLai Jiangshan 		kfree(worker);
3374c8e55f36STejun Heo 		return 0;
3375c8e55f36STejun Heo 	}
3376c8e55f36STejun Heo 
3377c8e55f36STejun Heo 	worker_leave_idle(worker);
3378db7bccf4STejun Heo recheck:
3379e22bee78STejun Heo 	/* no more worker necessary? */
338063d95a91STejun Heo 	if (!need_more_worker(pool))
3381e22bee78STejun Heo 		goto sleep;
3382e22bee78STejun Heo 
3383e22bee78STejun Heo 	/* do we need to manage? */
338463d95a91STejun Heo 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
3385e22bee78STejun Heo 		goto recheck;
3386e22bee78STejun Heo 
3387c8e55f36STejun Heo 	/*
3388c8e55f36STejun Heo 	 * ->scheduled list can only be filled while a worker is
3389c8e55f36STejun Heo 	 * preparing to process a work or actually processing it.
3390c8e55f36STejun Heo 	 * Make sure nobody diddled with it while I was sleeping.
3391c8e55f36STejun Heo 	 */
33926183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
3393c8e55f36STejun Heo 
3394e22bee78STejun Heo 	/*
3395a9ab775bSTejun Heo 	 * Finish PREP stage.  We're guaranteed to have at least one idle
3396a9ab775bSTejun Heo 	 * worker or that someone else has already assumed the manager
3397a9ab775bSTejun Heo 	 * role.  This is where @worker starts participating in concurrency
3398a9ab775bSTejun Heo 	 * management if applicable and concurrency management is restored
3399a9ab775bSTejun Heo 	 * after being rebound.  See rebind_workers() for details.
3400e22bee78STejun Heo 	 */
3401a9ab775bSTejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
3402e22bee78STejun Heo 
3403e22bee78STejun Heo 	do {
3404affee4b2STejun Heo 		struct work_struct *work =
3405bd7bdd43STejun Heo 			list_first_entry(&pool->worklist,
3406affee4b2STejun Heo 					 struct work_struct, entry);
3407affee4b2STejun Heo 
3408873eaca6STejun Heo 		if (assign_work(work, worker, NULL))
3409affee4b2STejun Heo 			process_scheduled_works(worker);
341063d95a91STejun Heo 	} while (keep_working(pool));
3411affee4b2STejun Heo 
3412228f1d00SLai Jiangshan 	worker_set_flags(worker, WORKER_PREP);
3413d313dd85STejun Heo sleep:
3414c8e55f36STejun Heo 	/*
3415d565ed63STejun Heo 	 * pool->lock is held and there's no work to process and no need to
3416d565ed63STejun Heo 	 * manage, sleep.  Workers are woken up only while holding
3417d565ed63STejun Heo 	 * pool->lock or from local cpu, so setting the current state
3418d565ed63STejun Heo 	 * before releasing pool->lock is enough to prevent losing any
3419d565ed63STejun Heo 	 * event.
3420c8e55f36STejun Heo 	 */
3421c8e55f36STejun Heo 	worker_enter_idle(worker);
3422c5a94a61SPeter Zijlstra 	__set_current_state(TASK_IDLE);
3423a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
34241da177e4SLinus Torvalds 	schedule();
3425c8e55f36STejun Heo 	goto woke_up;
34261da177e4SLinus Torvalds }
34271da177e4SLinus Torvalds 
3428e22bee78STejun Heo /**
3429e22bee78STejun Heo  * rescuer_thread - the rescuer thread function
3430111c225aSTejun Heo  * @__rescuer: self
3431e22bee78STejun Heo  *
3432e22bee78STejun Heo  * Workqueue rescuer thread function.  There's one rescuer for each
3433493008a8STejun Heo  * workqueue which has WQ_MEM_RECLAIM set.
3434e22bee78STejun Heo  *
3435706026c2STejun Heo  * Regular work processing on a pool may block trying to create a new
3436e22bee78STejun Heo  * worker which uses GFP_KERNEL allocation which has slight chance of
3437e22bee78STejun Heo  * developing into deadlock if some works currently on the same queue
3438e22bee78STejun Heo  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
3439e22bee78STejun Heo  * the problem rescuer solves.
3440e22bee78STejun Heo  *
3441706026c2STejun Heo  * When such condition is possible, the pool summons rescuers of all
3442706026c2STejun Heo  * workqueues which have works queued on the pool and let them process
3443e22bee78STejun Heo  * those works so that forward progress can be guaranteed.
3444e22bee78STejun Heo  *
3445e22bee78STejun Heo  * This should happen rarely.
3446d185af30SYacine Belkadi  *
3447d185af30SYacine Belkadi  * Return: 0
3448e22bee78STejun Heo  */
3449111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
3450e22bee78STejun Heo {
3451111c225aSTejun Heo 	struct worker *rescuer = __rescuer;
3452111c225aSTejun Heo 	struct workqueue_struct *wq = rescuer->rescue_wq;
34534d595b86SLai Jiangshan 	bool should_stop;
3454e22bee78STejun Heo 
3455e22bee78STejun Heo 	set_user_nice(current, RESCUER_NICE_LEVEL);
3456111c225aSTejun Heo 
3457111c225aSTejun Heo 	/*
3458111c225aSTejun Heo 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
3459111c225aSTejun Heo 	 * doesn't participate in concurrency management.
3460111c225aSTejun Heo 	 */
3461197f6accSTejun Heo 	set_pf_worker(true);
3462e22bee78STejun Heo repeat:
3463c5a94a61SPeter Zijlstra 	set_current_state(TASK_IDLE);
34641da177e4SLinus Torvalds 
34654d595b86SLai Jiangshan 	/*
34664d595b86SLai Jiangshan 	 * By the time the rescuer is requested to stop, the workqueue
34674d595b86SLai Jiangshan 	 * shouldn't have any work pending, but @wq->maydays may still have
34684d595b86SLai Jiangshan 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
34694d595b86SLai Jiangshan 	 * all the work items before the rescuer got to them.  Go through
34704d595b86SLai Jiangshan 	 * @wq->maydays processing before acting on should_stop so that the
34714d595b86SLai Jiangshan 	 * list is always empty on exit.
34724d595b86SLai Jiangshan 	 */
34734d595b86SLai Jiangshan 	should_stop = kthread_should_stop();
34741da177e4SLinus Torvalds 
3475493a1724STejun Heo 	/* see whether any pwq is asking for help */
3476a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&wq_mayday_lock);
3477493a1724STejun Heo 
3478493a1724STejun Heo 	while (!list_empty(&wq->maydays)) {
3479493a1724STejun Heo 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
3480493a1724STejun Heo 					struct pool_workqueue, mayday_node);
3481112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
3482e22bee78STejun Heo 		struct work_struct *work, *n;
3483e22bee78STejun Heo 
3484e22bee78STejun Heo 		__set_current_state(TASK_RUNNING);
3485493a1724STejun Heo 		list_del_init(&pwq->mayday_node);
3486493a1724STejun Heo 
3487a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
3488e22bee78STejun Heo 
348951697d39SLai Jiangshan 		worker_attach_to_pool(rescuer, pool);
349051697d39SLai Jiangshan 
3491a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
3492e22bee78STejun Heo 
3493e22bee78STejun Heo 		/*
3494e22bee78STejun Heo 		 * Slurp in all works issued via this workqueue and
3495e22bee78STejun Heo 		 * process'em.
3496e22bee78STejun Heo 		 */
3497873eaca6STejun Heo 		WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
349882607adcSTejun Heo 		list_for_each_entry_safe(work, n, &pool->worklist, entry) {
3499873eaca6STejun Heo 			if (get_work_pwq(work) == pwq &&
3500873eaca6STejun Heo 			    assign_work(work, rescuer, &n))
3501725e8ec5STejun Heo 				pwq->stats[PWQ_STAT_RESCUED]++;
350282607adcSTejun Heo 		}
3503e22bee78STejun Heo 
3504873eaca6STejun Heo 		if (!list_empty(&rescuer->scheduled)) {
3505e22bee78STejun Heo 			process_scheduled_works(rescuer);
35067576958aSTejun Heo 
35077576958aSTejun Heo 			/*
3508008847f6SNeilBrown 			 * The above execution of rescued work items could
3509008847f6SNeilBrown 			 * have created more to rescue through
3510f97a4a1aSLai Jiangshan 			 * pwq_activate_first_inactive() or chained
3511008847f6SNeilBrown 			 * queueing.  Let's put @pwq back on mayday list so
3512008847f6SNeilBrown 			 * that such back-to-back work items, which may be
3513008847f6SNeilBrown 			 * being used to relieve memory pressure, don't
3514008847f6SNeilBrown 			 * incur MAYDAY_INTERVAL delay inbetween.
3515008847f6SNeilBrown 			 */
35164f3f4cf3SLai Jiangshan 			if (pwq->nr_active && need_to_create_worker(pool)) {
3517a9b8a985SSebastian Andrzej Siewior 				raw_spin_lock(&wq_mayday_lock);
3518e66b39afSTejun Heo 				/*
3519e66b39afSTejun Heo 				 * Queue iff we aren't racing destruction
3520e66b39afSTejun Heo 				 * and somebody else hasn't queued it already.
3521e66b39afSTejun Heo 				 */
3522e66b39afSTejun Heo 				if (wq->rescuer && list_empty(&pwq->mayday_node)) {
3523008847f6SNeilBrown 					get_pwq(pwq);
3524e66b39afSTejun Heo 					list_add_tail(&pwq->mayday_node, &wq->maydays);
3525e66b39afSTejun Heo 				}
3526a9b8a985SSebastian Andrzej Siewior 				raw_spin_unlock(&wq_mayday_lock);
3527008847f6SNeilBrown 			}
3528008847f6SNeilBrown 		}
3529008847f6SNeilBrown 
3530008847f6SNeilBrown 		/*
353177668c8bSLai Jiangshan 		 * Put the reference grabbed by send_mayday().  @pool won't
353213b1d625SLai Jiangshan 		 * go away while we're still attached to it.
353377668c8bSLai Jiangshan 		 */
353477668c8bSLai Jiangshan 		put_pwq(pwq);
353577668c8bSLai Jiangshan 
353677668c8bSLai Jiangshan 		/*
35370219a352STejun Heo 		 * Leave this pool. Notify regular workers; otherwise, we end up
35380219a352STejun Heo 		 * with 0 concurrency and stalling the execution.
35397576958aSTejun Heo 		 */
35400219a352STejun Heo 		kick_pool(pool);
35417576958aSTejun Heo 
3542a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
354313b1d625SLai Jiangshan 
3544a2d812a2STejun Heo 		worker_detach_from_pool(rescuer);
354513b1d625SLai Jiangshan 
3546a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
35471da177e4SLinus Torvalds 	}
35481da177e4SLinus Torvalds 
3549a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&wq_mayday_lock);
3550493a1724STejun Heo 
35514d595b86SLai Jiangshan 	if (should_stop) {
35524d595b86SLai Jiangshan 		__set_current_state(TASK_RUNNING);
3553197f6accSTejun Heo 		set_pf_worker(false);
35544d595b86SLai Jiangshan 		return 0;
35554d595b86SLai Jiangshan 	}
35564d595b86SLai Jiangshan 
3557111c225aSTejun Heo 	/* rescuers should never participate in concurrency management */
3558111c225aSTejun Heo 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
3559e22bee78STejun Heo 	schedule();
3560e22bee78STejun Heo 	goto repeat;
35611da177e4SLinus Torvalds }
35621da177e4SLinus Torvalds 
35634cb1ef64STejun Heo static void bh_worker(struct worker *worker)
35644cb1ef64STejun Heo {
35654cb1ef64STejun Heo 	struct worker_pool *pool = worker->pool;
35664cb1ef64STejun Heo 	int nr_restarts = BH_WORKER_RESTARTS;
35674cb1ef64STejun Heo 	unsigned long end = jiffies + BH_WORKER_JIFFIES;
35684cb1ef64STejun Heo 
35694cb1ef64STejun Heo 	raw_spin_lock_irq(&pool->lock);
35704cb1ef64STejun Heo 	worker_leave_idle(worker);
35714cb1ef64STejun Heo 
35724cb1ef64STejun Heo 	/*
35734cb1ef64STejun Heo 	 * This function follows the structure of worker_thread(). See there for
35744cb1ef64STejun Heo 	 * explanations on each step.
35754cb1ef64STejun Heo 	 */
35764cb1ef64STejun Heo 	if (!need_more_worker(pool))
35774cb1ef64STejun Heo 		goto done;
35784cb1ef64STejun Heo 
35794cb1ef64STejun Heo 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
35804cb1ef64STejun Heo 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
35814cb1ef64STejun Heo 
35824cb1ef64STejun Heo 	do {
35834cb1ef64STejun Heo 		struct work_struct *work =
35844cb1ef64STejun Heo 			list_first_entry(&pool->worklist,
35854cb1ef64STejun Heo 					 struct work_struct, entry);
35864cb1ef64STejun Heo 
35874cb1ef64STejun Heo 		if (assign_work(work, worker, NULL))
35884cb1ef64STejun Heo 			process_scheduled_works(worker);
35894cb1ef64STejun Heo 	} while (keep_working(pool) &&
35904cb1ef64STejun Heo 		 --nr_restarts && time_before(jiffies, end));
35914cb1ef64STejun Heo 
35924cb1ef64STejun Heo 	worker_set_flags(worker, WORKER_PREP);
35934cb1ef64STejun Heo done:
35944cb1ef64STejun Heo 	worker_enter_idle(worker);
35954cb1ef64STejun Heo 	kick_pool(pool);
35964cb1ef64STejun Heo 	raw_spin_unlock_irq(&pool->lock);
35974cb1ef64STejun Heo }
35984cb1ef64STejun Heo 
35994cb1ef64STejun Heo /*
36004cb1ef64STejun Heo  * TODO: Convert all tasklet users to workqueue and use softirq directly.
36014cb1ef64STejun Heo  *
36024cb1ef64STejun Heo  * This is currently called from tasklet[_hi]action() and thus is also called
36034cb1ef64STejun Heo  * whenever there are tasklets to run. Let's do an early exit if there's nothing
36044cb1ef64STejun Heo  * queued. Once conversion from tasklet is complete, the need_more_worker() test
36054cb1ef64STejun Heo  * can be dropped.
36064cb1ef64STejun Heo  *
36074cb1ef64STejun Heo  * After full conversion, we'll add worker->softirq_action, directly use the
36084cb1ef64STejun Heo  * softirq action and obtain the worker pointer from the softirq_action pointer.
36094cb1ef64STejun Heo  */
36104cb1ef64STejun Heo void workqueue_softirq_action(bool highpri)
36114cb1ef64STejun Heo {
36124cb1ef64STejun Heo 	struct worker_pool *pool =
36134cb1ef64STejun Heo 		&per_cpu(bh_worker_pools, smp_processor_id())[highpri];
36144cb1ef64STejun Heo 	if (need_more_worker(pool))
36154cb1ef64STejun Heo 		bh_worker(list_first_entry(&pool->workers, struct worker, node));
36164cb1ef64STejun Heo }
36174cb1ef64STejun Heo 
36181acd92d9STejun Heo struct wq_drain_dead_softirq_work {
36191acd92d9STejun Heo 	struct work_struct	work;
36201acd92d9STejun Heo 	struct worker_pool	*pool;
36211acd92d9STejun Heo 	struct completion	done;
36221acd92d9STejun Heo };
36231acd92d9STejun Heo 
36241acd92d9STejun Heo static void drain_dead_softirq_workfn(struct work_struct *work)
36251acd92d9STejun Heo {
36261acd92d9STejun Heo 	struct wq_drain_dead_softirq_work *dead_work =
36271acd92d9STejun Heo 		container_of(work, struct wq_drain_dead_softirq_work, work);
36281acd92d9STejun Heo 	struct worker_pool *pool = dead_work->pool;
36291acd92d9STejun Heo 	bool repeat;
36301acd92d9STejun Heo 
36311acd92d9STejun Heo 	/*
36321acd92d9STejun Heo 	 * @pool's CPU is dead and we want to execute its still pending work
36331acd92d9STejun Heo 	 * items from this BH work item which is running on a different CPU. As
36341acd92d9STejun Heo 	 * its CPU is dead, @pool can't be kicked and, as work execution path
36351acd92d9STejun Heo 	 * will be nested, a lockdep annotation needs to be suppressed. Mark
36361acd92d9STejun Heo 	 * @pool with %POOL_BH_DRAINING for the special treatments.
36371acd92d9STejun Heo 	 */
36381acd92d9STejun Heo 	raw_spin_lock_irq(&pool->lock);
36391acd92d9STejun Heo 	pool->flags |= POOL_BH_DRAINING;
36401acd92d9STejun Heo 	raw_spin_unlock_irq(&pool->lock);
36411acd92d9STejun Heo 
36421acd92d9STejun Heo 	bh_worker(list_first_entry(&pool->workers, struct worker, node));
36431acd92d9STejun Heo 
36441acd92d9STejun Heo 	raw_spin_lock_irq(&pool->lock);
36451acd92d9STejun Heo 	pool->flags &= ~POOL_BH_DRAINING;
36461acd92d9STejun Heo 	repeat = need_more_worker(pool);
36471acd92d9STejun Heo 	raw_spin_unlock_irq(&pool->lock);
36481acd92d9STejun Heo 
36491acd92d9STejun Heo 	/*
36501acd92d9STejun Heo 	 * bh_worker() might hit consecutive execution limit and bail. If there
36511acd92d9STejun Heo 	 * still are pending work items, reschedule self and return so that we
36521acd92d9STejun Heo 	 * don't hog this CPU's BH.
36531acd92d9STejun Heo 	 */
36541acd92d9STejun Heo 	if (repeat) {
36551acd92d9STejun Heo 		if (pool->attrs->nice == HIGHPRI_NICE_LEVEL)
36561acd92d9STejun Heo 			queue_work(system_bh_highpri_wq, work);
36571acd92d9STejun Heo 		else
36581acd92d9STejun Heo 			queue_work(system_bh_wq, work);
36591acd92d9STejun Heo 	} else {
36601acd92d9STejun Heo 		complete(&dead_work->done);
36611acd92d9STejun Heo 	}
36621acd92d9STejun Heo }
36631acd92d9STejun Heo 
36641acd92d9STejun Heo /*
36651acd92d9STejun Heo  * @cpu is dead. Drain the remaining BH work items on the current CPU. It's
36661acd92d9STejun Heo  * possible to allocate dead_work per CPU and avoid flushing. However, then we
36671acd92d9STejun Heo  * have to worry about draining overlapping with CPU coming back online or
36681acd92d9STejun Heo  * nesting (one CPU's dead_work queued on another CPU which is also dead and so
36691acd92d9STejun Heo  * on). Let's keep it simple and drain them synchronously. These are BH work
36701acd92d9STejun Heo  * items which shouldn't be requeued on the same pool. Shouldn't take long.
36711acd92d9STejun Heo  */
36721acd92d9STejun Heo void workqueue_softirq_dead(unsigned int cpu)
36731acd92d9STejun Heo {
36741acd92d9STejun Heo 	int i;
36751acd92d9STejun Heo 
36761acd92d9STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
36771acd92d9STejun Heo 		struct worker_pool *pool = &per_cpu(bh_worker_pools, cpu)[i];
36781acd92d9STejun Heo 		struct wq_drain_dead_softirq_work dead_work;
36791acd92d9STejun Heo 
36801acd92d9STejun Heo 		if (!need_more_worker(pool))
36811acd92d9STejun Heo 			continue;
36821acd92d9STejun Heo 
3683e7cc3be6SLai Jiangshan 		INIT_WORK_ONSTACK(&dead_work.work, drain_dead_softirq_workfn);
36841acd92d9STejun Heo 		dead_work.pool = pool;
36851acd92d9STejun Heo 		init_completion(&dead_work.done);
36861acd92d9STejun Heo 
36871acd92d9STejun Heo 		if (pool->attrs->nice == HIGHPRI_NICE_LEVEL)
36881acd92d9STejun Heo 			queue_work(system_bh_highpri_wq, &dead_work.work);
36891acd92d9STejun Heo 		else
36901acd92d9STejun Heo 			queue_work(system_bh_wq, &dead_work.work);
36911acd92d9STejun Heo 
36921acd92d9STejun Heo 		wait_for_completion(&dead_work.done);
369331103f40SZqiang 		destroy_work_on_stack(&dead_work.work);
36941acd92d9STejun Heo 	}
36951acd92d9STejun Heo }
36961acd92d9STejun Heo 
3697fca839c0STejun Heo /**
3698fca839c0STejun Heo  * check_flush_dependency - check for flush dependency sanity
3699fca839c0STejun Heo  * @target_wq: workqueue being flushed
3700fca839c0STejun Heo  * @target_work: work item being flushed (NULL for workqueue flushes)
3701fca839c0STejun Heo  *
3702fca839c0STejun Heo  * %current is trying to flush the whole @target_wq or @target_work on it.
3703fca839c0STejun Heo  * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
3704fca839c0STejun Heo  * reclaiming memory or running on a workqueue which doesn't have
3705fca839c0STejun Heo  * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
3706fca839c0STejun Heo  * a deadlock.
3707fca839c0STejun Heo  */
3708fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
3709fca839c0STejun Heo 				   struct work_struct *target_work)
3710fca839c0STejun Heo {
3711fca839c0STejun Heo 	work_func_t target_func = target_work ? target_work->func : NULL;
3712fca839c0STejun Heo 	struct worker *worker;
3713fca839c0STejun Heo 
3714fca839c0STejun Heo 	if (target_wq->flags & WQ_MEM_RECLAIM)
3715fca839c0STejun Heo 		return;
3716fca839c0STejun Heo 
3717fca839c0STejun Heo 	worker = current_wq_worker();
3718fca839c0STejun Heo 
3719fca839c0STejun Heo 	WARN_ONCE(current->flags & PF_MEMALLOC,
3720d75f773cSSakari Ailus 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
3721fca839c0STejun Heo 		  current->pid, current->comm, target_wq->name, target_func);
372223d11a58STejun Heo 	WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
372323d11a58STejun Heo 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
3724d75f773cSSakari Ailus 		  "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
3725fca839c0STejun Heo 		  worker->current_pwq->wq->name, worker->current_func,
3726fca839c0STejun Heo 		  target_wq->name, target_func);
3727fca839c0STejun Heo }
3728fca839c0STejun Heo 
3729fc2e4d70SOleg Nesterov struct wq_barrier {
3730fc2e4d70SOleg Nesterov 	struct work_struct	work;
3731fc2e4d70SOleg Nesterov 	struct completion	done;
37322607d7a6STejun Heo 	struct task_struct	*task;	/* purely informational */
3733fc2e4d70SOleg Nesterov };
3734fc2e4d70SOleg Nesterov 
3735fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
3736fc2e4d70SOleg Nesterov {
3737fc2e4d70SOleg Nesterov 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
3738fc2e4d70SOleg Nesterov 	complete(&barr->done);
3739fc2e4d70SOleg Nesterov }
3740fc2e4d70SOleg Nesterov 
37414690c4abSTejun Heo /**
37424690c4abSTejun Heo  * insert_wq_barrier - insert a barrier work
3743112202d9STejun Heo  * @pwq: pwq to insert barrier into
37444690c4abSTejun Heo  * @barr: wq_barrier to insert
3745affee4b2STejun Heo  * @target: target work to attach @barr to
3746affee4b2STejun Heo  * @worker: worker currently executing @target, NULL if @target is not executing
37474690c4abSTejun Heo  *
3748affee4b2STejun Heo  * @barr is linked to @target such that @barr is completed only after
3749affee4b2STejun Heo  * @target finishes execution.  Please note that the ordering
3750affee4b2STejun Heo  * guarantee is observed only with respect to @target and on the local
3751affee4b2STejun Heo  * cpu.
3752affee4b2STejun Heo  *
3753affee4b2STejun Heo  * Currently, a queued barrier can't be canceled.  This is because
3754affee4b2STejun Heo  * try_to_grab_pending() can't determine whether the work to be
3755affee4b2STejun Heo  * grabbed is at the head of the queue and thus can't clear LINKED
3756affee4b2STejun Heo  * flag of the previous work while there must be a valid next work
3757affee4b2STejun Heo  * after a work with LINKED flag set.
3758affee4b2STejun Heo  *
3759affee4b2STejun Heo  * Note that when @worker is non-NULL, @target may be modified
3760112202d9STejun Heo  * underneath us, so we can't reliably determine pwq from @target.
37614690c4abSTejun Heo  *
37624690c4abSTejun Heo  * CONTEXT:
3763a9b8a985SSebastian Andrzej Siewior  * raw_spin_lock_irq(pool->lock).
37644690c4abSTejun Heo  */
3765112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
3766affee4b2STejun Heo 			      struct wq_barrier *barr,
3767affee4b2STejun Heo 			      struct work_struct *target, struct worker *worker)
3768fc2e4d70SOleg Nesterov {
37694cb1ef64STejun Heo 	static __maybe_unused struct lock_class_key bh_key, thr_key;
3770d812796eSLai Jiangshan 	unsigned int work_flags = 0;
3771d812796eSLai Jiangshan 	unsigned int work_color;
3772affee4b2STejun Heo 	struct list_head *head;
3773affee4b2STejun Heo 
3774dc186ad7SThomas Gleixner 	/*
3775d565ed63STejun Heo 	 * debugobject calls are safe here even with pool->lock locked
3776dc186ad7SThomas Gleixner 	 * as we know for sure that this will not trigger any of the
3777dc186ad7SThomas Gleixner 	 * checks and call back into the fixup functions where we
3778dc186ad7SThomas Gleixner 	 * might deadlock.
37794cb1ef64STejun Heo 	 *
37804cb1ef64STejun Heo 	 * BH and threaded workqueues need separate lockdep keys to avoid
37814cb1ef64STejun Heo 	 * spuriously triggering "inconsistent {SOFTIRQ-ON-W} -> {IN-SOFTIRQ-W}
37824cb1ef64STejun Heo 	 * usage".
3783dc186ad7SThomas Gleixner 	 */
37844cb1ef64STejun Heo 	INIT_WORK_ONSTACK_KEY(&barr->work, wq_barrier_func,
37854cb1ef64STejun Heo 			      (pwq->wq->flags & WQ_BH) ? &bh_key : &thr_key);
378622df02bbSTejun Heo 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
378752fa5bc5SBoqun Feng 
3788fd1a5b04SByungchul Park 	init_completion_map(&barr->done, &target->lockdep_map);
3789fd1a5b04SByungchul Park 
37902607d7a6STejun Heo 	barr->task = current;
379183c22520SOleg Nesterov 
37925797b1c1STejun Heo 	/* The barrier work item does not participate in nr_active. */
3793018f3a13SLai Jiangshan 	work_flags |= WORK_STRUCT_INACTIVE;
3794018f3a13SLai Jiangshan 
3795affee4b2STejun Heo 	/*
3796affee4b2STejun Heo 	 * If @target is currently being executed, schedule the
3797affee4b2STejun Heo 	 * barrier to the worker; otherwise, put it after @target.
3798affee4b2STejun Heo 	 */
3799d812796eSLai Jiangshan 	if (worker) {
3800affee4b2STejun Heo 		head = worker->scheduled.next;
3801d812796eSLai Jiangshan 		work_color = worker->current_color;
3802d812796eSLai Jiangshan 	} else {
3803affee4b2STejun Heo 		unsigned long *bits = work_data_bits(target);
3804affee4b2STejun Heo 
3805affee4b2STejun Heo 		head = target->entry.next;
3806affee4b2STejun Heo 		/* there can already be other linked works, inherit and set */
3807d21cece0SLai Jiangshan 		work_flags |= *bits & WORK_STRUCT_LINKED;
3808d812796eSLai Jiangshan 		work_color = get_work_color(*bits);
3809affee4b2STejun Heo 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
3810affee4b2STejun Heo 	}
3811affee4b2STejun Heo 
3812d812796eSLai Jiangshan 	pwq->nr_in_flight[work_color]++;
3813d812796eSLai Jiangshan 	work_flags |= work_color_to_flags(work_color);
3814d812796eSLai Jiangshan 
3815d21cece0SLai Jiangshan 	insert_work(pwq, &barr->work, head, work_flags);
3816fc2e4d70SOleg Nesterov }
3817fc2e4d70SOleg Nesterov 
381873f53c4aSTejun Heo /**
3819112202d9STejun Heo  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
382073f53c4aSTejun Heo  * @wq: workqueue being flushed
382173f53c4aSTejun Heo  * @flush_color: new flush color, < 0 for no-op
382273f53c4aSTejun Heo  * @work_color: new work color, < 0 for no-op
382373f53c4aSTejun Heo  *
3824112202d9STejun Heo  * Prepare pwqs for workqueue flushing.
382573f53c4aSTejun Heo  *
3826112202d9STejun Heo  * If @flush_color is non-negative, flush_color on all pwqs should be
3827112202d9STejun Heo  * -1.  If no pwq has in-flight commands at the specified color, all
3828112202d9STejun Heo  * pwq->flush_color's stay at -1 and %false is returned.  If any pwq
3829112202d9STejun Heo  * has in flight commands, its pwq->flush_color is set to
3830112202d9STejun Heo  * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
383173f53c4aSTejun Heo  * wakeup logic is armed and %true is returned.
383273f53c4aSTejun Heo  *
383373f53c4aSTejun Heo  * The caller should have initialized @wq->first_flusher prior to
383473f53c4aSTejun Heo  * calling this function with non-negative @flush_color.  If
383573f53c4aSTejun Heo  * @flush_color is negative, no flush color update is done and %false
383673f53c4aSTejun Heo  * is returned.
383773f53c4aSTejun Heo  *
3838112202d9STejun Heo  * If @work_color is non-negative, all pwqs should have the same
383973f53c4aSTejun Heo  * work_color which is previous to @work_color and all will be
384073f53c4aSTejun Heo  * advanced to @work_color.
384173f53c4aSTejun Heo  *
384273f53c4aSTejun Heo  * CONTEXT:
38433c25a55dSLai Jiangshan  * mutex_lock(wq->mutex).
384473f53c4aSTejun Heo  *
3845d185af30SYacine Belkadi  * Return:
384673f53c4aSTejun Heo  * %true if @flush_color >= 0 and there's something to flush.  %false
384773f53c4aSTejun Heo  * otherwise.
384873f53c4aSTejun Heo  */
3849112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
385073f53c4aSTejun Heo 				      int flush_color, int work_color)
38511da177e4SLinus Torvalds {
385273f53c4aSTejun Heo 	bool wait = false;
385349e3cf44STejun Heo 	struct pool_workqueue *pwq;
38541da177e4SLinus Torvalds 
385573f53c4aSTejun Heo 	if (flush_color >= 0) {
38566183c009STejun Heo 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
3857112202d9STejun Heo 		atomic_set(&wq->nr_pwqs_to_flush, 1);
3858dc186ad7SThomas Gleixner 	}
385914441960SOleg Nesterov 
386049e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
3861112202d9STejun Heo 		struct worker_pool *pool = pwq->pool;
38621da177e4SLinus Torvalds 
3863a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
386473f53c4aSTejun Heo 
386573f53c4aSTejun Heo 		if (flush_color >= 0) {
38666183c009STejun Heo 			WARN_ON_ONCE(pwq->flush_color != -1);
386773f53c4aSTejun Heo 
3868112202d9STejun Heo 			if (pwq->nr_in_flight[flush_color]) {
3869112202d9STejun Heo 				pwq->flush_color = flush_color;
3870112202d9STejun Heo 				atomic_inc(&wq->nr_pwqs_to_flush);
387173f53c4aSTejun Heo 				wait = true;
38721da177e4SLinus Torvalds 			}
387373f53c4aSTejun Heo 		}
387473f53c4aSTejun Heo 
387573f53c4aSTejun Heo 		if (work_color >= 0) {
38766183c009STejun Heo 			WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
3877112202d9STejun Heo 			pwq->work_color = work_color;
387873f53c4aSTejun Heo 		}
387973f53c4aSTejun Heo 
3880a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
38811da177e4SLinus Torvalds 	}
38821da177e4SLinus Torvalds 
3883112202d9STejun Heo 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
388473f53c4aSTejun Heo 		complete(&wq->first_flusher->done);
388573f53c4aSTejun Heo 
388673f53c4aSTejun Heo 	return wait;
388783c22520SOleg Nesterov }
38881da177e4SLinus Torvalds 
3889c35aea39STejun Heo static void touch_wq_lockdep_map(struct workqueue_struct *wq)
3890c35aea39STejun Heo {
38914cb1ef64STejun Heo #ifdef CONFIG_LOCKDEP
38924cb1ef64STejun Heo 	if (wq->flags & WQ_BH)
38934cb1ef64STejun Heo 		local_bh_disable();
38944cb1ef64STejun Heo 
3895c35aea39STejun Heo 	lock_map_acquire(&wq->lockdep_map);
3896c35aea39STejun Heo 	lock_map_release(&wq->lockdep_map);
38974cb1ef64STejun Heo 
38984cb1ef64STejun Heo 	if (wq->flags & WQ_BH)
38994cb1ef64STejun Heo 		local_bh_enable();
39004cb1ef64STejun Heo #endif
3901c35aea39STejun Heo }
3902c35aea39STejun Heo 
3903c35aea39STejun Heo static void touch_work_lockdep_map(struct work_struct *work,
3904c35aea39STejun Heo 				   struct workqueue_struct *wq)
3905c35aea39STejun Heo {
39064cb1ef64STejun Heo #ifdef CONFIG_LOCKDEP
39074cb1ef64STejun Heo 	if (wq->flags & WQ_BH)
39084cb1ef64STejun Heo 		local_bh_disable();
39094cb1ef64STejun Heo 
3910c35aea39STejun Heo 	lock_map_acquire(&work->lockdep_map);
3911c35aea39STejun Heo 	lock_map_release(&work->lockdep_map);
39124cb1ef64STejun Heo 
39134cb1ef64STejun Heo 	if (wq->flags & WQ_BH)
39144cb1ef64STejun Heo 		local_bh_enable();
39154cb1ef64STejun Heo #endif
3916c35aea39STejun Heo }
3917c35aea39STejun Heo 
39180fcb78c2SRolf Eike Beer /**
3919c4f135d6STetsuo Handa  * __flush_workqueue - ensure that any scheduled work has run to completion.
39200fcb78c2SRolf Eike Beer  * @wq: workqueue to flush
39211da177e4SLinus Torvalds  *
3922c5aa87bbSTejun Heo  * This function sleeps until all work items which were queued on entry
3923c5aa87bbSTejun Heo  * have finished execution, but it is not livelocked by new incoming ones.
39241da177e4SLinus Torvalds  */
3925c4f135d6STetsuo Handa void __flush_workqueue(struct workqueue_struct *wq)
39261da177e4SLinus Torvalds {
392773f53c4aSTejun Heo 	struct wq_flusher this_flusher = {
392873f53c4aSTejun Heo 		.list = LIST_HEAD_INIT(this_flusher.list),
392973f53c4aSTejun Heo 		.flush_color = -1,
3930fd1a5b04SByungchul Park 		.done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
393173f53c4aSTejun Heo 	};
393273f53c4aSTejun Heo 	int next_color;
3933b1f4ec17SOleg Nesterov 
39343347fa09STejun Heo 	if (WARN_ON(!wq_online))
39353347fa09STejun Heo 		return;
39363347fa09STejun Heo 
3937c35aea39STejun Heo 	touch_wq_lockdep_map(wq);
393887915adcSJohannes Berg 
39393c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
394073f53c4aSTejun Heo 
394173f53c4aSTejun Heo 	/*
394273f53c4aSTejun Heo 	 * Start-to-wait phase
394373f53c4aSTejun Heo 	 */
394473f53c4aSTejun Heo 	next_color = work_next_color(wq->work_color);
394573f53c4aSTejun Heo 
394673f53c4aSTejun Heo 	if (next_color != wq->flush_color) {
394773f53c4aSTejun Heo 		/*
394873f53c4aSTejun Heo 		 * Color space is not full.  The current work_color
394973f53c4aSTejun Heo 		 * becomes our flush_color and work_color is advanced
395073f53c4aSTejun Heo 		 * by one.
395173f53c4aSTejun Heo 		 */
39526183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
395373f53c4aSTejun Heo 		this_flusher.flush_color = wq->work_color;
395473f53c4aSTejun Heo 		wq->work_color = next_color;
395573f53c4aSTejun Heo 
395673f53c4aSTejun Heo 		if (!wq->first_flusher) {
395773f53c4aSTejun Heo 			/* no flush in progress, become the first flusher */
39586183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
395973f53c4aSTejun Heo 
396073f53c4aSTejun Heo 			wq->first_flusher = &this_flusher;
396173f53c4aSTejun Heo 
3962112202d9STejun Heo 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
396373f53c4aSTejun Heo 						       wq->work_color)) {
396473f53c4aSTejun Heo 				/* nothing to flush, done */
396573f53c4aSTejun Heo 				wq->flush_color = next_color;
396673f53c4aSTejun Heo 				wq->first_flusher = NULL;
396773f53c4aSTejun Heo 				goto out_unlock;
396873f53c4aSTejun Heo 			}
396973f53c4aSTejun Heo 		} else {
397073f53c4aSTejun Heo 			/* wait in queue */
39716183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
397273f53c4aSTejun Heo 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
3973112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
397473f53c4aSTejun Heo 		}
397573f53c4aSTejun Heo 	} else {
397673f53c4aSTejun Heo 		/*
397773f53c4aSTejun Heo 		 * Oops, color space is full, wait on overflow queue.
397873f53c4aSTejun Heo 		 * The next flush completion will assign us
397973f53c4aSTejun Heo 		 * flush_color and transfer to flusher_queue.
398073f53c4aSTejun Heo 		 */
398173f53c4aSTejun Heo 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
398273f53c4aSTejun Heo 	}
398373f53c4aSTejun Heo 
3984fca839c0STejun Heo 	check_flush_dependency(wq, NULL);
3985fca839c0STejun Heo 
39863c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
398773f53c4aSTejun Heo 
398873f53c4aSTejun Heo 	wait_for_completion(&this_flusher.done);
398973f53c4aSTejun Heo 
399073f53c4aSTejun Heo 	/*
399173f53c4aSTejun Heo 	 * Wake-up-and-cascade phase
399273f53c4aSTejun Heo 	 *
399373f53c4aSTejun Heo 	 * First flushers are responsible for cascading flushes and
399473f53c4aSTejun Heo 	 * handling overflow.  Non-first flushers can simply return.
399573f53c4aSTejun Heo 	 */
399600d5d15bSChris Wilson 	if (READ_ONCE(wq->first_flusher) != &this_flusher)
399773f53c4aSTejun Heo 		return;
399873f53c4aSTejun Heo 
39993c25a55dSLai Jiangshan 	mutex_lock(&wq->mutex);
400073f53c4aSTejun Heo 
40014ce48b37STejun Heo 	/* we might have raced, check again with mutex held */
40024ce48b37STejun Heo 	if (wq->first_flusher != &this_flusher)
40034ce48b37STejun Heo 		goto out_unlock;
40044ce48b37STejun Heo 
400500d5d15bSChris Wilson 	WRITE_ONCE(wq->first_flusher, NULL);
400673f53c4aSTejun Heo 
40076183c009STejun Heo 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
40086183c009STejun Heo 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
400973f53c4aSTejun Heo 
401073f53c4aSTejun Heo 	while (true) {
401173f53c4aSTejun Heo 		struct wq_flusher *next, *tmp;
401273f53c4aSTejun Heo 
401373f53c4aSTejun Heo 		/* complete all the flushers sharing the current flush color */
401473f53c4aSTejun Heo 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
401573f53c4aSTejun Heo 			if (next->flush_color != wq->flush_color)
401673f53c4aSTejun Heo 				break;
401773f53c4aSTejun Heo 			list_del_init(&next->list);
401873f53c4aSTejun Heo 			complete(&next->done);
401973f53c4aSTejun Heo 		}
402073f53c4aSTejun Heo 
40216183c009STejun Heo 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
402273f53c4aSTejun Heo 			     wq->flush_color != work_next_color(wq->work_color));
402373f53c4aSTejun Heo 
402473f53c4aSTejun Heo 		/* this flush_color is finished, advance by one */
402573f53c4aSTejun Heo 		wq->flush_color = work_next_color(wq->flush_color);
402673f53c4aSTejun Heo 
402773f53c4aSTejun Heo 		/* one color has been freed, handle overflow queue */
402873f53c4aSTejun Heo 		if (!list_empty(&wq->flusher_overflow)) {
402973f53c4aSTejun Heo 			/*
403073f53c4aSTejun Heo 			 * Assign the same color to all overflowed
403173f53c4aSTejun Heo 			 * flushers, advance work_color and append to
403273f53c4aSTejun Heo 			 * flusher_queue.  This is the start-to-wait
403373f53c4aSTejun Heo 			 * phase for these overflowed flushers.
403473f53c4aSTejun Heo 			 */
403573f53c4aSTejun Heo 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
403673f53c4aSTejun Heo 				tmp->flush_color = wq->work_color;
403773f53c4aSTejun Heo 
403873f53c4aSTejun Heo 			wq->work_color = work_next_color(wq->work_color);
403973f53c4aSTejun Heo 
404073f53c4aSTejun Heo 			list_splice_tail_init(&wq->flusher_overflow,
404173f53c4aSTejun Heo 					      &wq->flusher_queue);
4042112202d9STejun Heo 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
404373f53c4aSTejun Heo 		}
404473f53c4aSTejun Heo 
404573f53c4aSTejun Heo 		if (list_empty(&wq->flusher_queue)) {
40466183c009STejun Heo 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
404773f53c4aSTejun Heo 			break;
404873f53c4aSTejun Heo 		}
404973f53c4aSTejun Heo 
405073f53c4aSTejun Heo 		/*
405173f53c4aSTejun Heo 		 * Need to flush more colors.  Make the next flusher
4052112202d9STejun Heo 		 * the new first flusher and arm pwqs.
405373f53c4aSTejun Heo 		 */
40546183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
40556183c009STejun Heo 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
405673f53c4aSTejun Heo 
405773f53c4aSTejun Heo 		list_del_init(&next->list);
405873f53c4aSTejun Heo 		wq->first_flusher = next;
405973f53c4aSTejun Heo 
4060112202d9STejun Heo 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
406173f53c4aSTejun Heo 			break;
406273f53c4aSTejun Heo 
406373f53c4aSTejun Heo 		/*
406473f53c4aSTejun Heo 		 * Meh... this color is already done, clear first
406573f53c4aSTejun Heo 		 * flusher and repeat cascading.
406673f53c4aSTejun Heo 		 */
406773f53c4aSTejun Heo 		wq->first_flusher = NULL;
406873f53c4aSTejun Heo 	}
406973f53c4aSTejun Heo 
407073f53c4aSTejun Heo out_unlock:
40713c25a55dSLai Jiangshan 	mutex_unlock(&wq->mutex);
40721da177e4SLinus Torvalds }
4073c4f135d6STetsuo Handa EXPORT_SYMBOL(__flush_workqueue);
40741da177e4SLinus Torvalds 
40759c5a2ba7STejun Heo /**
40769c5a2ba7STejun Heo  * drain_workqueue - drain a workqueue
40779c5a2ba7STejun Heo  * @wq: workqueue to drain
40789c5a2ba7STejun Heo  *
40799c5a2ba7STejun Heo  * Wait until the workqueue becomes empty.  While draining is in progress,
40809c5a2ba7STejun Heo  * only chain queueing is allowed.  IOW, only currently pending or running
40819c5a2ba7STejun Heo  * work items on @wq can queue further work items on it.  @wq is flushed
4082b749b1b6SChen Hanxiao  * repeatedly until it becomes empty.  The number of flushing is determined
40839c5a2ba7STejun Heo  * by the depth of chaining and should be relatively short.  Whine if it
40849c5a2ba7STejun Heo  * takes too long.
40859c5a2ba7STejun Heo  */
40869c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
40879c5a2ba7STejun Heo {
40889c5a2ba7STejun Heo 	unsigned int flush_cnt = 0;
408949e3cf44STejun Heo 	struct pool_workqueue *pwq;
40909c5a2ba7STejun Heo 
40919c5a2ba7STejun Heo 	/*
40929c5a2ba7STejun Heo 	 * __queue_work() needs to test whether there are drainers, is much
40939c5a2ba7STejun Heo 	 * hotter than drain_workqueue() and already looks at @wq->flags.
4094618b01ebSTejun Heo 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
40959c5a2ba7STejun Heo 	 */
409687fc741eSLai Jiangshan 	mutex_lock(&wq->mutex);
40979c5a2ba7STejun Heo 	if (!wq->nr_drainers++)
4098618b01ebSTejun Heo 		wq->flags |= __WQ_DRAINING;
409987fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
41009c5a2ba7STejun Heo reflush:
4101c4f135d6STetsuo Handa 	__flush_workqueue(wq);
41029c5a2ba7STejun Heo 
4103b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
410476af4d93STejun Heo 
410549e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
4106fa2563e4SThomas Tuttle 		bool drained;
41079c5a2ba7STejun Heo 
4108a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
4109afa87ce8STejun Heo 		drained = pwq_is_empty(pwq);
4110a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
4111fa2563e4SThomas Tuttle 
4112fa2563e4SThomas Tuttle 		if (drained)
41139c5a2ba7STejun Heo 			continue;
41149c5a2ba7STejun Heo 
41159c5a2ba7STejun Heo 		if (++flush_cnt == 10 ||
41169c5a2ba7STejun Heo 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
4117e9ad2eb3SStephen Zhang 			pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
4118e9ad2eb3SStephen Zhang 				wq->name, __func__, flush_cnt);
411976af4d93STejun Heo 
4120b09f4fd3SLai Jiangshan 		mutex_unlock(&wq->mutex);
41219c5a2ba7STejun Heo 		goto reflush;
41229c5a2ba7STejun Heo 	}
41239c5a2ba7STejun Heo 
41249c5a2ba7STejun Heo 	if (!--wq->nr_drainers)
4125618b01ebSTejun Heo 		wq->flags &= ~__WQ_DRAINING;
412687fc741eSLai Jiangshan 	mutex_unlock(&wq->mutex);
41279c5a2ba7STejun Heo }
41289c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
41299c5a2ba7STejun Heo 
4130d6e89786SJohannes Berg static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
4131d6e89786SJohannes Berg 			     bool from_cancel)
4132baf59022STejun Heo {
4133baf59022STejun Heo 	struct worker *worker = NULL;
4134c9e7cf27STejun Heo 	struct worker_pool *pool;
4135112202d9STejun Heo 	struct pool_workqueue *pwq;
4136c35aea39STejun Heo 	struct workqueue_struct *wq;
4137baf59022STejun Heo 
413824acfb71SThomas Gleixner 	rcu_read_lock();
4139fa1b54e6STejun Heo 	pool = get_work_pool(work);
4140fa1b54e6STejun Heo 	if (!pool) {
414124acfb71SThomas Gleixner 		rcu_read_unlock();
4142fa1b54e6STejun Heo 		return false;
4143fa1b54e6STejun Heo 	}
4144fa1b54e6STejun Heo 
4145a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
41460b3dae68SLai Jiangshan 	/* see the comment in try_to_grab_pending() with the same code */
4147112202d9STejun Heo 	pwq = get_work_pwq(work);
4148112202d9STejun Heo 	if (pwq) {
4149112202d9STejun Heo 		if (unlikely(pwq->pool != pool))
4150baf59022STejun Heo 			goto already_gone;
4151606a5020STejun Heo 	} else {
4152c9e7cf27STejun Heo 		worker = find_worker_executing_work(pool, work);
4153baf59022STejun Heo 		if (!worker)
4154baf59022STejun Heo 			goto already_gone;
4155112202d9STejun Heo 		pwq = worker->current_pwq;
4156606a5020STejun Heo 	}
4157baf59022STejun Heo 
4158c35aea39STejun Heo 	wq = pwq->wq;
4159c35aea39STejun Heo 	check_flush_dependency(wq, work);
4160fca839c0STejun Heo 
4161112202d9STejun Heo 	insert_wq_barrier(pwq, barr, work, worker);
4162a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
4163baf59022STejun Heo 
4164c35aea39STejun Heo 	touch_work_lockdep_map(work, wq);
4165c35aea39STejun Heo 
4166e159489bSTejun Heo 	/*
4167a1d14934SPeter Zijlstra 	 * Force a lock recursion deadlock when using flush_work() inside a
4168a1d14934SPeter Zijlstra 	 * single-threaded or rescuer equipped workqueue.
4169a1d14934SPeter Zijlstra 	 *
4170a1d14934SPeter Zijlstra 	 * For single threaded workqueues the deadlock happens when the work
4171a1d14934SPeter Zijlstra 	 * is after the work issuing the flush_work(). For rescuer equipped
4172a1d14934SPeter Zijlstra 	 * workqueues the deadlock happens when the rescuer stalls, blocking
4173a1d14934SPeter Zijlstra 	 * forward progress.
4174e159489bSTejun Heo 	 */
4175c35aea39STejun Heo 	if (!from_cancel && (wq->saved_max_active == 1 || wq->rescuer))
4176c35aea39STejun Heo 		touch_wq_lockdep_map(wq);
4177c35aea39STejun Heo 
417824acfb71SThomas Gleixner 	rcu_read_unlock();
4179baf59022STejun Heo 	return true;
4180baf59022STejun Heo already_gone:
4181a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
418224acfb71SThomas Gleixner 	rcu_read_unlock();
4183baf59022STejun Heo 	return false;
4184baf59022STejun Heo }
4185baf59022STejun Heo 
4186d6e89786SJohannes Berg static bool __flush_work(struct work_struct *work, bool from_cancel)
4187d6e89786SJohannes Berg {
4188d6e89786SJohannes Berg 	struct wq_barrier barr;
4189134874e2STejun Heo 	unsigned long data;
4190d6e89786SJohannes Berg 
4191d6e89786SJohannes Berg 	if (WARN_ON(!wq_online))
4192d6e89786SJohannes Berg 		return false;
4193d6e89786SJohannes Berg 
41944d43d395STetsuo Handa 	if (WARN_ON(!work->func))
41954d43d395STetsuo Handa 		return false;
41964d43d395STetsuo Handa 
4197134874e2STejun Heo 	if (!start_flush_work(work, &barr, from_cancel))
4198134874e2STejun Heo 		return false;
4199134874e2STejun Heo 
4200134874e2STejun Heo 	/*
4201134874e2STejun Heo 	 * start_flush_work() returned %true. If @from_cancel is set, we know
4202134874e2STejun Heo 	 * that @work must have been executing during start_flush_work() and
4203134874e2STejun Heo 	 * can't currently be queued. Its data must contain OFFQ bits. If @work
4204134874e2STejun Heo 	 * was queued on a BH workqueue, we also know that it was running in the
4205134874e2STejun Heo 	 * BH context and thus can be busy-waited.
4206134874e2STejun Heo 	 */
4207134874e2STejun Heo 	data = *work_data_bits(work);
4208134874e2STejun Heo 	if (from_cancel &&
4209134874e2STejun Heo 	    !WARN_ON_ONCE(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_BH)) {
4210134874e2STejun Heo 		/*
4211134874e2STejun Heo 		 * On RT, prevent a live lock when %current preempted soft
4212134874e2STejun Heo 		 * interrupt processing or prevents ksoftirqd from running by
4213134874e2STejun Heo 		 * keeping flipping BH. If the BH work item runs on a different
4214134874e2STejun Heo 		 * CPU then this has no effect other than doing the BH
4215134874e2STejun Heo 		 * disable/enable dance for nothing. This is copied from
4216134874e2STejun Heo 		 * kernel/softirq.c::tasklet_unlock_spin_wait().
4217134874e2STejun Heo 		 */
4218134874e2STejun Heo 		while (!try_wait_for_completion(&barr.done)) {
4219134874e2STejun Heo 			if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
4220134874e2STejun Heo 				local_bh_disable();
4221134874e2STejun Heo 				local_bh_enable();
4222134874e2STejun Heo 			} else {
4223134874e2STejun Heo 				cpu_relax();
4224134874e2STejun Heo 			}
4225134874e2STejun Heo 		}
4226134874e2STejun Heo 	} else {
4227d6e89786SJohannes Berg 		wait_for_completion(&barr.done);
4228134874e2STejun Heo 	}
4229134874e2STejun Heo 
4230d6e89786SJohannes Berg 	destroy_work_on_stack(&barr.work);
4231d6e89786SJohannes Berg 	return true;
4232d6e89786SJohannes Berg }
4233d6e89786SJohannes Berg 
4234db700897SOleg Nesterov /**
4235401a8d04STejun Heo  * flush_work - wait for a work to finish executing the last queueing instance
4236401a8d04STejun Heo  * @work: the work to flush
4237db700897SOleg Nesterov  *
4238606a5020STejun Heo  * Wait until @work has finished execution.  @work is guaranteed to be idle
4239606a5020STejun Heo  * on return if it hasn't been requeued since flush started.
4240401a8d04STejun Heo  *
4241d185af30SYacine Belkadi  * Return:
4242401a8d04STejun Heo  * %true if flush_work() waited for the work to finish execution,
4243401a8d04STejun Heo  * %false if it was already idle.
4244db700897SOleg Nesterov  */
4245401a8d04STejun Heo bool flush_work(struct work_struct *work)
4246db700897SOleg Nesterov {
4247134874e2STejun Heo 	might_sleep();
4248d6e89786SJohannes Berg 	return __flush_work(work, false);
4249606a5020STejun Heo }
4250db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
4251db700897SOleg Nesterov 
4252cdc6e4b3STejun Heo /**
4253cdc6e4b3STejun Heo  * flush_delayed_work - wait for a dwork to finish executing the last queueing
4254cdc6e4b3STejun Heo  * @dwork: the delayed work to flush
4255cdc6e4b3STejun Heo  *
4256cdc6e4b3STejun Heo  * Delayed timer is cancelled and the pending work is queued for
4257cdc6e4b3STejun Heo  * immediate execution.  Like flush_work(), this function only
4258cdc6e4b3STejun Heo  * considers the last queueing instance of @dwork.
4259cdc6e4b3STejun Heo  *
4260cdc6e4b3STejun Heo  * Return:
4261cdc6e4b3STejun Heo  * %true if flush_work() waited for the work to finish execution,
4262cdc6e4b3STejun Heo  * %false if it was already idle.
4263cdc6e4b3STejun Heo  */
4264cdc6e4b3STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
4265cdc6e4b3STejun Heo {
4266cdc6e4b3STejun Heo 	local_irq_disable();
4267cdc6e4b3STejun Heo 	if (del_timer_sync(&dwork->timer))
4268cdc6e4b3STejun Heo 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
4269cdc6e4b3STejun Heo 	local_irq_enable();
4270cdc6e4b3STejun Heo 	return flush_work(&dwork->work);
4271cdc6e4b3STejun Heo }
4272cdc6e4b3STejun Heo EXPORT_SYMBOL(flush_delayed_work);
4273cdc6e4b3STejun Heo 
4274cdc6e4b3STejun Heo /**
4275cdc6e4b3STejun Heo  * flush_rcu_work - wait for a rwork to finish executing the last queueing
4276cdc6e4b3STejun Heo  * @rwork: the rcu work to flush
4277cdc6e4b3STejun Heo  *
4278cdc6e4b3STejun Heo  * Return:
4279cdc6e4b3STejun Heo  * %true if flush_rcu_work() waited for the work to finish execution,
4280cdc6e4b3STejun Heo  * %false if it was already idle.
4281cdc6e4b3STejun Heo  */
4282cdc6e4b3STejun Heo bool flush_rcu_work(struct rcu_work *rwork)
4283cdc6e4b3STejun Heo {
4284cdc6e4b3STejun Heo 	if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
4285cdc6e4b3STejun Heo 		rcu_barrier();
4286cdc6e4b3STejun Heo 		flush_work(&rwork->work);
4287cdc6e4b3STejun Heo 		return true;
4288cdc6e4b3STejun Heo 	} else {
4289cdc6e4b3STejun Heo 		return flush_work(&rwork->work);
4290cdc6e4b3STejun Heo 	}
4291cdc6e4b3STejun Heo }
4292cdc6e4b3STejun Heo EXPORT_SYMBOL(flush_rcu_work);
4293cdc6e4b3STejun Heo 
429486898fa6STejun Heo static void work_offqd_disable(struct work_offq_data *offqd)
429586898fa6STejun Heo {
429686898fa6STejun Heo 	const unsigned long max = (1lu << WORK_OFFQ_DISABLE_BITS) - 1;
429786898fa6STejun Heo 
429886898fa6STejun Heo 	if (likely(offqd->disable < max))
429986898fa6STejun Heo 		offqd->disable++;
430086898fa6STejun Heo 	else
430186898fa6STejun Heo 		WARN_ONCE(true, "workqueue: work disable count overflowed\n");
430286898fa6STejun Heo }
430386898fa6STejun Heo 
430486898fa6STejun Heo static void work_offqd_enable(struct work_offq_data *offqd)
430586898fa6STejun Heo {
430686898fa6STejun Heo 	if (likely(offqd->disable > 0))
430786898fa6STejun Heo 		offqd->disable--;
430886898fa6STejun Heo 	else
430986898fa6STejun Heo 		WARN_ONCE(true, "workqueue: work disable count underflowed\n");
431086898fa6STejun Heo }
431186898fa6STejun Heo 
4312c5f5b942STejun Heo static bool __cancel_work(struct work_struct *work, u32 cflags)
4313cdc6e4b3STejun Heo {
43141211f3b2STejun Heo 	struct work_offq_data offqd;
4315c26e2f2eSTejun Heo 	unsigned long irq_flags;
4316cdc6e4b3STejun Heo 	int ret;
4317cdc6e4b3STejun Heo 
431886898fa6STejun Heo 	ret = work_grab_pending(work, cflags, &irq_flags);
4319cdc6e4b3STejun Heo 
43201211f3b2STejun Heo 	work_offqd_unpack(&offqd, *work_data_bits(work));
4321cdc6e4b3STejun Heo 
432286898fa6STejun Heo 	if (cflags & WORK_CANCEL_DISABLE)
432386898fa6STejun Heo 		work_offqd_disable(&offqd);
432486898fa6STejun Heo 
43251211f3b2STejun Heo 	set_work_pool_and_clear_pending(work, offqd.pool_id,
43261211f3b2STejun Heo 					work_offqd_pack_flags(&offqd));
4327c26e2f2eSTejun Heo 	local_irq_restore(irq_flags);
4328cdc6e4b3STejun Heo 	return ret;
4329cdc6e4b3STejun Heo }
4330cdc6e4b3STejun Heo 
4331c5f5b942STejun Heo static bool __cancel_work_sync(struct work_struct *work, u32 cflags)
4332401a8d04STejun Heo {
4333978b8409STejun Heo 	bool ret;
43341f1f642eSOleg Nesterov 
4335f09b10b6STejun Heo 	ret = __cancel_work(work, cflags | WORK_CANCEL_DISABLE);
4336bbb68dfaSTejun Heo 
4337134874e2STejun Heo 	if (*work_data_bits(work) & WORK_OFFQ_BH)
4338134874e2STejun Heo 		WARN_ON_ONCE(in_hardirq());
4339134874e2STejun Heo 	else
4340134874e2STejun Heo 		might_sleep();
4341bbb68dfaSTejun Heo 
43423347fa09STejun Heo 	/*
4343c7a40c49STejun Heo 	 * Skip __flush_work() during early boot when we know that @work isn't
4344c7a40c49STejun Heo 	 * executing. This allows canceling during early boot.
43453347fa09STejun Heo 	 */
43463347fa09STejun Heo 	if (wq_online)
4347d6e89786SJohannes Berg 		__flush_work(work, true);
43483347fa09STejun Heo 
4349f09b10b6STejun Heo 	if (!(cflags & WORK_CANCEL_DISABLE))
4350f09b10b6STejun Heo 		enable_work(work);
43518603e1b3STejun Heo 
43521f1f642eSOleg Nesterov 	return ret;
43531f1f642eSOleg Nesterov }
43541f1f642eSOleg Nesterov 
4355cdc6e4b3STejun Heo /*
4356cdc6e4b3STejun Heo  * See cancel_delayed_work()
4357cdc6e4b3STejun Heo  */
4358cdc6e4b3STejun Heo bool cancel_work(struct work_struct *work)
4359cdc6e4b3STejun Heo {
4360c5f5b942STejun Heo 	return __cancel_work(work, 0);
4361cdc6e4b3STejun Heo }
4362cdc6e4b3STejun Heo EXPORT_SYMBOL(cancel_work);
4363cdc6e4b3STejun Heo 
43646e84d644SOleg Nesterov /**
4365401a8d04STejun Heo  * cancel_work_sync - cancel a work and wait for it to finish
4366401a8d04STejun Heo  * @work: the work to cancel
43676e84d644SOleg Nesterov  *
4368134874e2STejun Heo  * Cancel @work and wait for its execution to finish. This function can be used
4369134874e2STejun Heo  * even if the work re-queues itself or migrates to another workqueue. On return
4370134874e2STejun Heo  * from this function, @work is guaranteed to be not pending or executing on any
4371134874e2STejun Heo  * CPU as long as there aren't racing enqueues.
43721f1f642eSOleg Nesterov  *
4373134874e2STejun Heo  * cancel_work_sync(&delayed_work->work) must not be used for delayed_work's.
4374134874e2STejun Heo  * Use cancel_delayed_work_sync() instead.
43756e84d644SOleg Nesterov  *
4376134874e2STejun Heo  * Must be called from a sleepable context if @work was last queued on a non-BH
4377134874e2STejun Heo  * workqueue. Can also be called from non-hardirq atomic contexts including BH
4378134874e2STejun Heo  * if @work was last queued on a BH workqueue.
4379401a8d04STejun Heo  *
4380134874e2STejun Heo  * Returns %true if @work was pending, %false otherwise.
43816e84d644SOleg Nesterov  */
4382401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
43836e84d644SOleg Nesterov {
4384c5f5b942STejun Heo 	return __cancel_work_sync(work, 0);
4385b89deed3SOleg Nesterov }
438628e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
4387b89deed3SOleg Nesterov 
43886e84d644SOleg Nesterov /**
438957b30ae7STejun Heo  * cancel_delayed_work - cancel a delayed work
439057b30ae7STejun Heo  * @dwork: delayed_work to cancel
439109383498STejun Heo  *
4392d185af30SYacine Belkadi  * Kill off a pending delayed_work.
4393d185af30SYacine Belkadi  *
4394d185af30SYacine Belkadi  * Return: %true if @dwork was pending and canceled; %false if it wasn't
4395d185af30SYacine Belkadi  * pending.
4396d185af30SYacine Belkadi  *
4397d185af30SYacine Belkadi  * Note:
4398d185af30SYacine Belkadi  * The work callback function may still be running on return, unless
4399d185af30SYacine Belkadi  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
4400d185af30SYacine Belkadi  * use cancel_delayed_work_sync() to wait on it.
440109383498STejun Heo  *
440257b30ae7STejun Heo  * This function is safe to call from any context including IRQ handler.
440309383498STejun Heo  */
440457b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
440509383498STejun Heo {
4406c5f5b942STejun Heo 	return __cancel_work(&dwork->work, WORK_CANCEL_DELAYED);
440709383498STejun Heo }
440857b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
440909383498STejun Heo 
441009383498STejun Heo /**
4411401a8d04STejun Heo  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
4412401a8d04STejun Heo  * @dwork: the delayed work cancel
4413401a8d04STejun Heo  *
4414401a8d04STejun Heo  * This is cancel_work_sync() for delayed works.
4415401a8d04STejun Heo  *
4416d185af30SYacine Belkadi  * Return:
4417401a8d04STejun Heo  * %true if @dwork was pending, %false otherwise.
4418401a8d04STejun Heo  */
4419401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
44206e84d644SOleg Nesterov {
4421c5f5b942STejun Heo 	return __cancel_work_sync(&dwork->work, WORK_CANCEL_DELAYED);
44226e84d644SOleg Nesterov }
4423f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
44241da177e4SLinus Torvalds 
44250fcb78c2SRolf Eike Beer /**
442686898fa6STejun Heo  * disable_work - Disable and cancel a work item
442786898fa6STejun Heo  * @work: work item to disable
442886898fa6STejun Heo  *
442986898fa6STejun Heo  * Disable @work by incrementing its disable count and cancel it if currently
443086898fa6STejun Heo  * pending. As long as the disable count is non-zero, any attempt to queue @work
443186898fa6STejun Heo  * will fail and return %false. The maximum supported disable depth is 2 to the
443286898fa6STejun Heo  * power of %WORK_OFFQ_DISABLE_BITS, currently 65536.
443386898fa6STejun Heo  *
4434f09b10b6STejun Heo  * Can be called from any context. Returns %true if @work was pending, %false
4435f09b10b6STejun Heo  * otherwise.
443686898fa6STejun Heo  */
443786898fa6STejun Heo bool disable_work(struct work_struct *work)
443886898fa6STejun Heo {
443986898fa6STejun Heo 	return __cancel_work(work, WORK_CANCEL_DISABLE);
444086898fa6STejun Heo }
444186898fa6STejun Heo EXPORT_SYMBOL_GPL(disable_work);
444286898fa6STejun Heo 
444386898fa6STejun Heo /**
444486898fa6STejun Heo  * disable_work_sync - Disable, cancel and drain a work item
444586898fa6STejun Heo  * @work: work item to disable
444686898fa6STejun Heo  *
444786898fa6STejun Heo  * Similar to disable_work() but also wait for @work to finish if currently
444886898fa6STejun Heo  * executing.
444986898fa6STejun Heo  *
4450134874e2STejun Heo  * Must be called from a sleepable context if @work was last queued on a non-BH
4451134874e2STejun Heo  * workqueue. Can also be called from non-hardirq atomic contexts including BH
4452134874e2STejun Heo  * if @work was last queued on a BH workqueue.
4453134874e2STejun Heo  *
4454134874e2STejun Heo  * Returns %true if @work was pending, %false otherwise.
445586898fa6STejun Heo  */
445686898fa6STejun Heo bool disable_work_sync(struct work_struct *work)
445786898fa6STejun Heo {
445886898fa6STejun Heo 	return __cancel_work_sync(work, WORK_CANCEL_DISABLE);
445986898fa6STejun Heo }
446086898fa6STejun Heo EXPORT_SYMBOL_GPL(disable_work_sync);
446186898fa6STejun Heo 
446286898fa6STejun Heo /**
446386898fa6STejun Heo  * enable_work - Enable a work item
446486898fa6STejun Heo  * @work: work item to enable
446586898fa6STejun Heo  *
446686898fa6STejun Heo  * Undo disable_work[_sync]() by decrementing @work's disable count. @work can
446786898fa6STejun Heo  * only be queued if its disable count is 0.
446886898fa6STejun Heo  *
4469f09b10b6STejun Heo  * Can be called from any context. Returns %true if the disable count reached 0.
4470f09b10b6STejun Heo  * Otherwise, %false.
447186898fa6STejun Heo  */
447286898fa6STejun Heo bool enable_work(struct work_struct *work)
447386898fa6STejun Heo {
447486898fa6STejun Heo 	struct work_offq_data offqd;
447586898fa6STejun Heo 	unsigned long irq_flags;
447686898fa6STejun Heo 
447786898fa6STejun Heo 	work_grab_pending(work, 0, &irq_flags);
447886898fa6STejun Heo 
447986898fa6STejun Heo 	work_offqd_unpack(&offqd, *work_data_bits(work));
448086898fa6STejun Heo 	work_offqd_enable(&offqd);
448186898fa6STejun Heo 	set_work_pool_and_clear_pending(work, offqd.pool_id,
448286898fa6STejun Heo 					work_offqd_pack_flags(&offqd));
448386898fa6STejun Heo 	local_irq_restore(irq_flags);
448486898fa6STejun Heo 
448586898fa6STejun Heo 	return !offqd.disable;
448686898fa6STejun Heo }
448786898fa6STejun Heo EXPORT_SYMBOL_GPL(enable_work);
448886898fa6STejun Heo 
448986898fa6STejun Heo /**
449086898fa6STejun Heo  * disable_delayed_work - Disable and cancel a delayed work item
449186898fa6STejun Heo  * @dwork: delayed work item to disable
449286898fa6STejun Heo  *
449386898fa6STejun Heo  * disable_work() for delayed work items.
449486898fa6STejun Heo  */
449586898fa6STejun Heo bool disable_delayed_work(struct delayed_work *dwork)
449686898fa6STejun Heo {
449786898fa6STejun Heo 	return __cancel_work(&dwork->work,
449886898fa6STejun Heo 			     WORK_CANCEL_DELAYED | WORK_CANCEL_DISABLE);
449986898fa6STejun Heo }
450086898fa6STejun Heo EXPORT_SYMBOL_GPL(disable_delayed_work);
450186898fa6STejun Heo 
450286898fa6STejun Heo /**
450386898fa6STejun Heo  * disable_delayed_work_sync - Disable, cancel and drain a delayed work item
450486898fa6STejun Heo  * @dwork: delayed work item to disable
450586898fa6STejun Heo  *
450686898fa6STejun Heo  * disable_work_sync() for delayed work items.
450786898fa6STejun Heo  */
450886898fa6STejun Heo bool disable_delayed_work_sync(struct delayed_work *dwork)
450986898fa6STejun Heo {
451086898fa6STejun Heo 	return __cancel_work_sync(&dwork->work,
451186898fa6STejun Heo 				  WORK_CANCEL_DELAYED | WORK_CANCEL_DISABLE);
451286898fa6STejun Heo }
451386898fa6STejun Heo EXPORT_SYMBOL_GPL(disable_delayed_work_sync);
451486898fa6STejun Heo 
451586898fa6STejun Heo /**
451686898fa6STejun Heo  * enable_delayed_work - Enable a delayed work item
451786898fa6STejun Heo  * @dwork: delayed work item to enable
451886898fa6STejun Heo  *
451986898fa6STejun Heo  * enable_work() for delayed work items.
452086898fa6STejun Heo  */
452186898fa6STejun Heo bool enable_delayed_work(struct delayed_work *dwork)
452286898fa6STejun Heo {
452386898fa6STejun Heo 	return enable_work(&dwork->work);
452486898fa6STejun Heo }
452586898fa6STejun Heo EXPORT_SYMBOL_GPL(enable_delayed_work);
452686898fa6STejun Heo 
452786898fa6STejun Heo /**
452831ddd871STejun Heo  * schedule_on_each_cpu - execute a function synchronously on each online CPU
4529b6136773SAndrew Morton  * @func: the function to call
4530b6136773SAndrew Morton  *
453131ddd871STejun Heo  * schedule_on_each_cpu() executes @func on each online CPU using the
453231ddd871STejun Heo  * system workqueue and blocks until all CPUs have completed.
4533b6136773SAndrew Morton  * schedule_on_each_cpu() is very slow.
453431ddd871STejun Heo  *
4535d185af30SYacine Belkadi  * Return:
453631ddd871STejun Heo  * 0 on success, -errno on failure.
4537b6136773SAndrew Morton  */
453865f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
453915316ba8SChristoph Lameter {
454015316ba8SChristoph Lameter 	int cpu;
454138f51568SNamhyung Kim 	struct work_struct __percpu *works;
454215316ba8SChristoph Lameter 
4543b6136773SAndrew Morton 	works = alloc_percpu(struct work_struct);
4544b6136773SAndrew Morton 	if (!works)
454515316ba8SChristoph Lameter 		return -ENOMEM;
4546b6136773SAndrew Morton 
4547ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
454893981800STejun Heo 
454915316ba8SChristoph Lameter 	for_each_online_cpu(cpu) {
45509bfb1839SIngo Molnar 		struct work_struct *work = per_cpu_ptr(works, cpu);
45519bfb1839SIngo Molnar 
45529bfb1839SIngo Molnar 		INIT_WORK(work, func);
45538de6d308SOleg Nesterov 		schedule_work_on(cpu, work);
455415316ba8SChristoph Lameter 	}
455593981800STejun Heo 
455693981800STejun Heo 	for_each_online_cpu(cpu)
45578616a89aSOleg Nesterov 		flush_work(per_cpu_ptr(works, cpu));
455893981800STejun Heo 
4559ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
4560b6136773SAndrew Morton 	free_percpu(works);
456115316ba8SChristoph Lameter 	return 0;
456215316ba8SChristoph Lameter }
456315316ba8SChristoph Lameter 
4564eef6a7d5SAlan Stern /**
45651fa44ecaSJames Bottomley  * execute_in_process_context - reliably execute the routine with user context
45661fa44ecaSJames Bottomley  * @fn:		the function to execute
45671fa44ecaSJames Bottomley  * @ew:		guaranteed storage for the execute work structure (must
45681fa44ecaSJames Bottomley  *		be available when the work executes)
45691fa44ecaSJames Bottomley  *
45701fa44ecaSJames Bottomley  * Executes the function immediately if process context is available,
45711fa44ecaSJames Bottomley  * otherwise schedules the function for delayed execution.
45721fa44ecaSJames Bottomley  *
4573d185af30SYacine Belkadi  * Return:	0 - function was executed
45741fa44ecaSJames Bottomley  *		1 - function was scheduled for execution
45751fa44ecaSJames Bottomley  */
457665f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
45771fa44ecaSJames Bottomley {
45781fa44ecaSJames Bottomley 	if (!in_interrupt()) {
457965f27f38SDavid Howells 		fn(&ew->work);
45801fa44ecaSJames Bottomley 		return 0;
45811fa44ecaSJames Bottomley 	}
45821fa44ecaSJames Bottomley 
458365f27f38SDavid Howells 	INIT_WORK(&ew->work, fn);
45841fa44ecaSJames Bottomley 	schedule_work(&ew->work);
45851fa44ecaSJames Bottomley 
45861fa44ecaSJames Bottomley 	return 1;
45871fa44ecaSJames Bottomley }
45881fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
45891fa44ecaSJames Bottomley 
45907a4e344cSTejun Heo /**
45917a4e344cSTejun Heo  * free_workqueue_attrs - free a workqueue_attrs
45927a4e344cSTejun Heo  * @attrs: workqueue_attrs to free
45937a4e344cSTejun Heo  *
45947a4e344cSTejun Heo  * Undo alloc_workqueue_attrs().
45957a4e344cSTejun Heo  */
4596513c98d0SDaniel Jordan void free_workqueue_attrs(struct workqueue_attrs *attrs)
45977a4e344cSTejun Heo {
45987a4e344cSTejun Heo 	if (attrs) {
45997a4e344cSTejun Heo 		free_cpumask_var(attrs->cpumask);
46009546b29eSTejun Heo 		free_cpumask_var(attrs->__pod_cpumask);
46017a4e344cSTejun Heo 		kfree(attrs);
46027a4e344cSTejun Heo 	}
46037a4e344cSTejun Heo }
46047a4e344cSTejun Heo 
46057a4e344cSTejun Heo /**
46067a4e344cSTejun Heo  * alloc_workqueue_attrs - allocate a workqueue_attrs
46077a4e344cSTejun Heo  *
46087a4e344cSTejun Heo  * Allocate a new workqueue_attrs, initialize with default settings and
4609d185af30SYacine Belkadi  * return it.
4610d185af30SYacine Belkadi  *
4611d185af30SYacine Belkadi  * Return: The allocated new workqueue_attr on success. %NULL on failure.
46127a4e344cSTejun Heo  */
4613513c98d0SDaniel Jordan struct workqueue_attrs *alloc_workqueue_attrs(void)
46147a4e344cSTejun Heo {
46157a4e344cSTejun Heo 	struct workqueue_attrs *attrs;
46167a4e344cSTejun Heo 
4617be69d00dSThomas Gleixner 	attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
46187a4e344cSTejun Heo 	if (!attrs)
46197a4e344cSTejun Heo 		goto fail;
4620be69d00dSThomas Gleixner 	if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
46217a4e344cSTejun Heo 		goto fail;
46229546b29eSTejun Heo 	if (!alloc_cpumask_var(&attrs->__pod_cpumask, GFP_KERNEL))
46239546b29eSTejun Heo 		goto fail;
46247a4e344cSTejun Heo 
462513e2e556STejun Heo 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
4626523a301eSTejun Heo 	attrs->affn_scope = WQ_AFFN_DFL;
46277a4e344cSTejun Heo 	return attrs;
46287a4e344cSTejun Heo fail:
46297a4e344cSTejun Heo 	free_workqueue_attrs(attrs);
46307a4e344cSTejun Heo 	return NULL;
46317a4e344cSTejun Heo }
46327a4e344cSTejun Heo 
463329c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
463429c91e99STejun Heo 				 const struct workqueue_attrs *from)
463529c91e99STejun Heo {
463629c91e99STejun Heo 	to->nice = from->nice;
463729c91e99STejun Heo 	cpumask_copy(to->cpumask, from->cpumask);
46389546b29eSTejun Heo 	cpumask_copy(to->__pod_cpumask, from->__pod_cpumask);
46398639ecebSTejun Heo 	to->affn_strict = from->affn_strict;
464084193c07STejun Heo 
46412865a8fbSShaohua Li 	/*
464284193c07STejun Heo 	 * Unlike hash and equality test, copying shouldn't ignore wq-only
464384193c07STejun Heo 	 * fields as copying is used for both pool and wq attrs. Instead,
464484193c07STejun Heo 	 * get_unbound_pool() explicitly clears the fields.
46452865a8fbSShaohua Li 	 */
464684193c07STejun Heo 	to->affn_scope = from->affn_scope;
4647af73f5c9STejun Heo 	to->ordered = from->ordered;
464829c91e99STejun Heo }
464929c91e99STejun Heo 
46505de7a03cSTejun Heo /*
46515de7a03cSTejun Heo  * Some attrs fields are workqueue-only. Clear them for worker_pool's. See the
46525de7a03cSTejun Heo  * comments in 'struct workqueue_attrs' definition.
46535de7a03cSTejun Heo  */
46545de7a03cSTejun Heo static void wqattrs_clear_for_pool(struct workqueue_attrs *attrs)
46555de7a03cSTejun Heo {
465684193c07STejun Heo 	attrs->affn_scope = WQ_AFFN_NR_TYPES;
46575de7a03cSTejun Heo 	attrs->ordered = false;
4658ae1296a7SLai Jiangshan 	if (attrs->affn_strict)
4659ae1296a7SLai Jiangshan 		cpumask_copy(attrs->cpumask, cpu_possible_mask);
46605de7a03cSTejun Heo }
46615de7a03cSTejun Heo 
466229c91e99STejun Heo /* hash value of the content of @attr */
466329c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
466429c91e99STejun Heo {
466529c91e99STejun Heo 	u32 hash = 0;
466629c91e99STejun Heo 
466729c91e99STejun Heo 	hash = jhash_1word(attrs->nice, hash);
4668ae1296a7SLai Jiangshan 	hash = jhash_1word(attrs->affn_strict, hash);
46699546b29eSTejun Heo 	hash = jhash(cpumask_bits(attrs->__pod_cpumask),
46709546b29eSTejun Heo 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
4671ae1296a7SLai Jiangshan 	if (!attrs->affn_strict)
4672ae1296a7SLai Jiangshan 		hash = jhash(cpumask_bits(attrs->cpumask),
4673ae1296a7SLai Jiangshan 			     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
467429c91e99STejun Heo 	return hash;
467529c91e99STejun Heo }
467629c91e99STejun Heo 
467729c91e99STejun Heo /* content equality test */
467829c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
467929c91e99STejun Heo 			  const struct workqueue_attrs *b)
468029c91e99STejun Heo {
468129c91e99STejun Heo 	if (a->nice != b->nice)
468229c91e99STejun Heo 		return false;
4683ae1296a7SLai Jiangshan 	if (a->affn_strict != b->affn_strict)
468429c91e99STejun Heo 		return false;
46859546b29eSTejun Heo 	if (!cpumask_equal(a->__pod_cpumask, b->__pod_cpumask))
46869546b29eSTejun Heo 		return false;
4687ae1296a7SLai Jiangshan 	if (!a->affn_strict && !cpumask_equal(a->cpumask, b->cpumask))
46888639ecebSTejun Heo 		return false;
468929c91e99STejun Heo 	return true;
469029c91e99STejun Heo }
469129c91e99STejun Heo 
46920f36ee24STejun Heo /* Update @attrs with actually available CPUs */
46930f36ee24STejun Heo static void wqattrs_actualize_cpumask(struct workqueue_attrs *attrs,
46940f36ee24STejun Heo 				      const cpumask_t *unbound_cpumask)
46950f36ee24STejun Heo {
46960f36ee24STejun Heo 	/*
46970f36ee24STejun Heo 	 * Calculate the effective CPU mask of @attrs given @unbound_cpumask. If
46980f36ee24STejun Heo 	 * @attrs->cpumask doesn't overlap with @unbound_cpumask, we fallback to
46990f36ee24STejun Heo 	 * @unbound_cpumask.
47000f36ee24STejun Heo 	 */
47010f36ee24STejun Heo 	cpumask_and(attrs->cpumask, attrs->cpumask, unbound_cpumask);
47020f36ee24STejun Heo 	if (unlikely(cpumask_empty(attrs->cpumask)))
47030f36ee24STejun Heo 		cpumask_copy(attrs->cpumask, unbound_cpumask);
47040f36ee24STejun Heo }
47050f36ee24STejun Heo 
470684193c07STejun Heo /* find wq_pod_type to use for @attrs */
470784193c07STejun Heo static const struct wq_pod_type *
470884193c07STejun Heo wqattrs_pod_type(const struct workqueue_attrs *attrs)
470984193c07STejun Heo {
4710523a301eSTejun Heo 	enum wq_affn_scope scope;
4711523a301eSTejun Heo 	struct wq_pod_type *pt;
4712523a301eSTejun Heo 
4713523a301eSTejun Heo 	/* to synchronize access to wq_affn_dfl */
4714523a301eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
4715523a301eSTejun Heo 
4716523a301eSTejun Heo 	if (attrs->affn_scope == WQ_AFFN_DFL)
4717523a301eSTejun Heo 		scope = wq_affn_dfl;
4718523a301eSTejun Heo 	else
4719523a301eSTejun Heo 		scope = attrs->affn_scope;
4720523a301eSTejun Heo 
4721523a301eSTejun Heo 	pt = &wq_pod_types[scope];
472284193c07STejun Heo 
472384193c07STejun Heo 	if (!WARN_ON_ONCE(attrs->affn_scope == WQ_AFFN_NR_TYPES) &&
472484193c07STejun Heo 	    likely(pt->nr_pods))
472584193c07STejun Heo 		return pt;
472684193c07STejun Heo 
472784193c07STejun Heo 	/*
472884193c07STejun Heo 	 * Before workqueue_init_topology(), only SYSTEM is available which is
472984193c07STejun Heo 	 * initialized in workqueue_init_early().
473084193c07STejun Heo 	 */
473184193c07STejun Heo 	pt = &wq_pod_types[WQ_AFFN_SYSTEM];
473284193c07STejun Heo 	BUG_ON(!pt->nr_pods);
473384193c07STejun Heo 	return pt;
473484193c07STejun Heo }
473584193c07STejun Heo 
47367a4e344cSTejun Heo /**
47377a4e344cSTejun Heo  * init_worker_pool - initialize a newly zalloc'd worker_pool
47387a4e344cSTejun Heo  * @pool: worker_pool to initialize
47397a4e344cSTejun Heo  *
4740402dd89dSShailendra Verma  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
4741d185af30SYacine Belkadi  *
4742d185af30SYacine Belkadi  * Return: 0 on success, -errno on failure.  Even on failure, all fields
474329c91e99STejun Heo  * inside @pool proper are initialized and put_unbound_pool() can be called
474429c91e99STejun Heo  * on @pool safely to release it.
47457a4e344cSTejun Heo  */
47467a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
47474e1a1f9aSTejun Heo {
4748a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_init(&pool->lock);
474929c91e99STejun Heo 	pool->id = -1;
475029c91e99STejun Heo 	pool->cpu = -1;
4751f3f90ad4STejun Heo 	pool->node = NUMA_NO_NODE;
47524e1a1f9aSTejun Heo 	pool->flags |= POOL_DISASSOCIATED;
475382607adcSTejun Heo 	pool->watchdog_ts = jiffies;
47544e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->worklist);
47554e1a1f9aSTejun Heo 	INIT_LIST_HEAD(&pool->idle_list);
47564e1a1f9aSTejun Heo 	hash_init(pool->busy_hash);
47574e1a1f9aSTejun Heo 
475832a6c723SKees Cook 	timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
47593f959aa3SValentin Schneider 	INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
47604e1a1f9aSTejun Heo 
476132a6c723SKees Cook 	timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
47624e1a1f9aSTejun Heo 
4763da028469SLai Jiangshan 	INIT_LIST_HEAD(&pool->workers);
4764e02b9312SValentin Schneider 	INIT_LIST_HEAD(&pool->dying_workers);
47657a4e344cSTejun Heo 
47667cda9aaeSLai Jiangshan 	ida_init(&pool->worker_ida);
476729c91e99STejun Heo 	INIT_HLIST_NODE(&pool->hash_node);
476829c91e99STejun Heo 	pool->refcnt = 1;
476929c91e99STejun Heo 
477029c91e99STejun Heo 	/* shouldn't fail above this point */
4771be69d00dSThomas Gleixner 	pool->attrs = alloc_workqueue_attrs();
47727a4e344cSTejun Heo 	if (!pool->attrs)
47737a4e344cSTejun Heo 		return -ENOMEM;
47745de7a03cSTejun Heo 
47755de7a03cSTejun Heo 	wqattrs_clear_for_pool(pool->attrs);
47765de7a03cSTejun Heo 
47777a4e344cSTejun Heo 	return 0;
47784e1a1f9aSTejun Heo }
47794e1a1f9aSTejun Heo 
4780669de8bdSBart Van Assche #ifdef CONFIG_LOCKDEP
4781669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
4782669de8bdSBart Van Assche {
4783669de8bdSBart Van Assche 	char *lock_name;
4784669de8bdSBart Van Assche 
4785669de8bdSBart Van Assche 	lockdep_register_key(&wq->key);
4786669de8bdSBart Van Assche 	lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
4787669de8bdSBart Van Assche 	if (!lock_name)
4788669de8bdSBart Van Assche 		lock_name = wq->name;
478969a106c0SQian Cai 
479069a106c0SQian Cai 	wq->lock_name = lock_name;
4791669de8bdSBart Van Assche 	lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
4792669de8bdSBart Van Assche }
4793669de8bdSBart Van Assche 
4794669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
4795669de8bdSBart Van Assche {
4796669de8bdSBart Van Assche 	lockdep_unregister_key(&wq->key);
4797669de8bdSBart Van Assche }
4798669de8bdSBart Van Assche 
4799669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
4800669de8bdSBart Van Assche {
4801669de8bdSBart Van Assche 	if (wq->lock_name != wq->name)
4802669de8bdSBart Van Assche 		kfree(wq->lock_name);
4803669de8bdSBart Van Assche }
4804669de8bdSBart Van Assche #else
4805669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
4806669de8bdSBart Van Assche {
4807669de8bdSBart Van Assche }
4808669de8bdSBart Van Assche 
4809669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
4810669de8bdSBart Van Assche {
4811669de8bdSBart Van Assche }
4812669de8bdSBart Van Assche 
4813669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
4814669de8bdSBart Van Assche {
4815669de8bdSBart Van Assche }
4816669de8bdSBart Van Assche #endif
4817669de8bdSBart Van Assche 
481891ccc6e7STejun Heo static void free_node_nr_active(struct wq_node_nr_active **nna_ar)
481991ccc6e7STejun Heo {
482091ccc6e7STejun Heo 	int node;
482191ccc6e7STejun Heo 
482291ccc6e7STejun Heo 	for_each_node(node) {
482391ccc6e7STejun Heo 		kfree(nna_ar[node]);
482491ccc6e7STejun Heo 		nna_ar[node] = NULL;
482591ccc6e7STejun Heo 	}
482691ccc6e7STejun Heo 
482791ccc6e7STejun Heo 	kfree(nna_ar[nr_node_ids]);
482891ccc6e7STejun Heo 	nna_ar[nr_node_ids] = NULL;
482991ccc6e7STejun Heo }
483091ccc6e7STejun Heo 
483191ccc6e7STejun Heo static void init_node_nr_active(struct wq_node_nr_active *nna)
483291ccc6e7STejun Heo {
4833c5f8cd6cSTejun Heo 	nna->max = WQ_DFL_MIN_ACTIVE;
483491ccc6e7STejun Heo 	atomic_set(&nna->nr, 0);
48355797b1c1STejun Heo 	raw_spin_lock_init(&nna->lock);
48365797b1c1STejun Heo 	INIT_LIST_HEAD(&nna->pending_pwqs);
483791ccc6e7STejun Heo }
483891ccc6e7STejun Heo 
483991ccc6e7STejun Heo /*
484091ccc6e7STejun Heo  * Each node's nr_active counter will be accessed mostly from its own node and
484191ccc6e7STejun Heo  * should be allocated in the node.
484291ccc6e7STejun Heo  */
484391ccc6e7STejun Heo static int alloc_node_nr_active(struct wq_node_nr_active **nna_ar)
484491ccc6e7STejun Heo {
484591ccc6e7STejun Heo 	struct wq_node_nr_active *nna;
484691ccc6e7STejun Heo 	int node;
484791ccc6e7STejun Heo 
484891ccc6e7STejun Heo 	for_each_node(node) {
484991ccc6e7STejun Heo 		nna = kzalloc_node(sizeof(*nna), GFP_KERNEL, node);
485091ccc6e7STejun Heo 		if (!nna)
485191ccc6e7STejun Heo 			goto err_free;
485291ccc6e7STejun Heo 		init_node_nr_active(nna);
485391ccc6e7STejun Heo 		nna_ar[node] = nna;
485491ccc6e7STejun Heo 	}
485591ccc6e7STejun Heo 
485691ccc6e7STejun Heo 	/* [nr_node_ids] is used as the fallback */
485791ccc6e7STejun Heo 	nna = kzalloc_node(sizeof(*nna), GFP_KERNEL, NUMA_NO_NODE);
485891ccc6e7STejun Heo 	if (!nna)
485991ccc6e7STejun Heo 		goto err_free;
486091ccc6e7STejun Heo 	init_node_nr_active(nna);
486191ccc6e7STejun Heo 	nna_ar[nr_node_ids] = nna;
486291ccc6e7STejun Heo 
486391ccc6e7STejun Heo 	return 0;
486491ccc6e7STejun Heo 
486591ccc6e7STejun Heo err_free:
486691ccc6e7STejun Heo 	free_node_nr_active(nna_ar);
486791ccc6e7STejun Heo 	return -ENOMEM;
486891ccc6e7STejun Heo }
486991ccc6e7STejun Heo 
4870e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
4871e2dca7adSTejun Heo {
4872e2dca7adSTejun Heo 	struct workqueue_struct *wq =
4873e2dca7adSTejun Heo 		container_of(rcu, struct workqueue_struct, rcu);
4874e2dca7adSTejun Heo 
487591ccc6e7STejun Heo 	if (wq->flags & WQ_UNBOUND)
487691ccc6e7STejun Heo 		free_node_nr_active(wq->node_nr_active);
487791ccc6e7STejun Heo 
4878669de8bdSBart Van Assche 	wq_free_lockdep(wq);
4879ee1ceef7STejun Heo 	free_percpu(wq->cpu_pwq);
4880e2dca7adSTejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
4881e2dca7adSTejun Heo 	kfree(wq);
4882e2dca7adSTejun Heo }
4883e2dca7adSTejun Heo 
488429c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
488529c91e99STejun Heo {
488629c91e99STejun Heo 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
488729c91e99STejun Heo 
48887cda9aaeSLai Jiangshan 	ida_destroy(&pool->worker_ida);
488929c91e99STejun Heo 	free_workqueue_attrs(pool->attrs);
489029c91e99STejun Heo 	kfree(pool);
489129c91e99STejun Heo }
489229c91e99STejun Heo 
489329c91e99STejun Heo /**
489429c91e99STejun Heo  * put_unbound_pool - put a worker_pool
489529c91e99STejun Heo  * @pool: worker_pool to put
489629c91e99STejun Heo  *
489724acfb71SThomas Gleixner  * Put @pool.  If its refcnt reaches zero, it gets destroyed in RCU
4898c5aa87bbSTejun Heo  * safe manner.  get_unbound_pool() calls this function on its failure path
4899c5aa87bbSTejun Heo  * and this function should be able to release pools which went through,
4900c5aa87bbSTejun Heo  * successfully or not, init_worker_pool().
4901a892caccSTejun Heo  *
4902a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
490329c91e99STejun Heo  */
490429c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
490529c91e99STejun Heo {
490660f5a4bcSLai Jiangshan 	DECLARE_COMPLETION_ONSTACK(detach_completion);
490729c91e99STejun Heo 	struct worker *worker;
49089680540cSYang Yingliang 	LIST_HEAD(cull_list);
4909e02b9312SValentin Schneider 
4910a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
4911a892caccSTejun Heo 
4912a892caccSTejun Heo 	if (--pool->refcnt)
491329c91e99STejun Heo 		return;
491429c91e99STejun Heo 
491529c91e99STejun Heo 	/* sanity checks */
491661d0fbb4SLai Jiangshan 	if (WARN_ON(!(pool->cpu < 0)) ||
4917a892caccSTejun Heo 	    WARN_ON(!list_empty(&pool->worklist)))
491829c91e99STejun Heo 		return;
491929c91e99STejun Heo 
492029c91e99STejun Heo 	/* release id and unhash */
492129c91e99STejun Heo 	if (pool->id >= 0)
492229c91e99STejun Heo 		idr_remove(&worker_pool_idr, pool->id);
492329c91e99STejun Heo 	hash_del(&pool->hash_node);
492429c91e99STejun Heo 
4925c5aa87bbSTejun Heo 	/*
4926692b4825STejun Heo 	 * Become the manager and destroy all workers.  This prevents
4927692b4825STejun Heo 	 * @pool's workers from blocking on attach_mutex.  We're the last
4928692b4825STejun Heo 	 * manager and @pool gets freed with the flag set.
49299ab03be4SValentin Schneider 	 *
49309ab03be4SValentin Schneider 	 * Having a concurrent manager is quite unlikely to happen as we can
49319ab03be4SValentin Schneider 	 * only get here with
49329ab03be4SValentin Schneider 	 *   pwq->refcnt == pool->refcnt == 0
49339ab03be4SValentin Schneider 	 * which implies no work queued to the pool, which implies no worker can
49349ab03be4SValentin Schneider 	 * become the manager. However a worker could have taken the role of
49359ab03be4SValentin Schneider 	 * manager before the refcnts dropped to 0, since maybe_create_worker()
49369ab03be4SValentin Schneider 	 * drops pool->lock
4937c5aa87bbSTejun Heo 	 */
49389ab03be4SValentin Schneider 	while (true) {
49399ab03be4SValentin Schneider 		rcuwait_wait_event(&manager_wait,
49409ab03be4SValentin Schneider 				   !(pool->flags & POOL_MANAGER_ACTIVE),
4941d8bb65abSSebastian Andrzej Siewior 				   TASK_UNINTERRUPTIBLE);
4942e02b9312SValentin Schneider 
4943e02b9312SValentin Schneider 		mutex_lock(&wq_pool_attach_mutex);
49449ab03be4SValentin Schneider 		raw_spin_lock_irq(&pool->lock);
49459ab03be4SValentin Schneider 		if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
4946692b4825STejun Heo 			pool->flags |= POOL_MANAGER_ACTIVE;
49479ab03be4SValentin Schneider 			break;
49489ab03be4SValentin Schneider 		}
49499ab03be4SValentin Schneider 		raw_spin_unlock_irq(&pool->lock);
4950e02b9312SValentin Schneider 		mutex_unlock(&wq_pool_attach_mutex);
49519ab03be4SValentin Schneider 	}
4952692b4825STejun Heo 
49531037de36SLai Jiangshan 	while ((worker = first_idle_worker(pool)))
4954e02b9312SValentin Schneider 		set_worker_dying(worker, &cull_list);
495529c91e99STejun Heo 	WARN_ON(pool->nr_workers || pool->nr_idle);
4956a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
495760f5a4bcSLai Jiangshan 
4958e02b9312SValentin Schneider 	wake_dying_workers(&cull_list);
4959e02b9312SValentin Schneider 
4960e02b9312SValentin Schneider 	if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
496160f5a4bcSLai Jiangshan 		pool->detach_completion = &detach_completion;
49621258fae7STejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
496360f5a4bcSLai Jiangshan 
496460f5a4bcSLai Jiangshan 	if (pool->detach_completion)
496560f5a4bcSLai Jiangshan 		wait_for_completion(pool->detach_completion);
496660f5a4bcSLai Jiangshan 
496729c91e99STejun Heo 	/* shut down the timers */
496829c91e99STejun Heo 	del_timer_sync(&pool->idle_timer);
49693f959aa3SValentin Schneider 	cancel_work_sync(&pool->idle_cull_work);
497029c91e99STejun Heo 	del_timer_sync(&pool->mayday_timer);
497129c91e99STejun Heo 
497224acfb71SThomas Gleixner 	/* RCU protected to allow dereferences from get_work_pool() */
497325b00775SPaul E. McKenney 	call_rcu(&pool->rcu, rcu_free_pool);
497429c91e99STejun Heo }
497529c91e99STejun Heo 
497629c91e99STejun Heo /**
497729c91e99STejun Heo  * get_unbound_pool - get a worker_pool with the specified attributes
497829c91e99STejun Heo  * @attrs: the attributes of the worker_pool to get
497929c91e99STejun Heo  *
498029c91e99STejun Heo  * Obtain a worker_pool which has the same attributes as @attrs, bump the
498129c91e99STejun Heo  * reference count and return it.  If there already is a matching
498229c91e99STejun Heo  * worker_pool, it will be used; otherwise, this function attempts to
4983d185af30SYacine Belkadi  * create a new one.
4984a892caccSTejun Heo  *
4985a892caccSTejun Heo  * Should be called with wq_pool_mutex held.
4986d185af30SYacine Belkadi  *
4987d185af30SYacine Belkadi  * Return: On success, a worker_pool with the same attributes as @attrs.
4988d185af30SYacine Belkadi  * On failure, %NULL.
498929c91e99STejun Heo  */
499029c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
499129c91e99STejun Heo {
499284193c07STejun Heo 	struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_NUMA];
499329c91e99STejun Heo 	u32 hash = wqattrs_hash(attrs);
499429c91e99STejun Heo 	struct worker_pool *pool;
499584193c07STejun Heo 	int pod, node = NUMA_NO_NODE;
499629c91e99STejun Heo 
4997a892caccSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
499829c91e99STejun Heo 
499929c91e99STejun Heo 	/* do we already have a matching pool? */
500029c91e99STejun Heo 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
500129c91e99STejun Heo 		if (wqattrs_equal(pool->attrs, attrs)) {
500229c91e99STejun Heo 			pool->refcnt++;
50033fb1823cSLai Jiangshan 			return pool;
500429c91e99STejun Heo 		}
500529c91e99STejun Heo 	}
500629c91e99STejun Heo 
50079546b29eSTejun Heo 	/* If __pod_cpumask is contained inside a NUMA pod, that's our node */
500884193c07STejun Heo 	for (pod = 0; pod < pt->nr_pods; pod++) {
50099546b29eSTejun Heo 		if (cpumask_subset(attrs->__pod_cpumask, pt->pod_cpus[pod])) {
501084193c07STejun Heo 			node = pt->pod_node[pod];
5011e2273584SXunlei Pang 			break;
5012e2273584SXunlei Pang 		}
5013e2273584SXunlei Pang 	}
5014e2273584SXunlei Pang 
501529c91e99STejun Heo 	/* nope, create a new one */
501684193c07STejun Heo 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, node);
501729c91e99STejun Heo 	if (!pool || init_worker_pool(pool) < 0)
501829c91e99STejun Heo 		goto fail;
501929c91e99STejun Heo 
502084193c07STejun Heo 	pool->node = node;
50215de7a03cSTejun Heo 	copy_workqueue_attrs(pool->attrs, attrs);
50225de7a03cSTejun Heo 	wqattrs_clear_for_pool(pool->attrs);
50232865a8fbSShaohua Li 
502429c91e99STejun Heo 	if (worker_pool_assign_id(pool) < 0)
502529c91e99STejun Heo 		goto fail;
502629c91e99STejun Heo 
502729c91e99STejun Heo 	/* create and start the initial worker */
50283347fa09STejun Heo 	if (wq_online && !create_worker(pool))
502929c91e99STejun Heo 		goto fail;
503029c91e99STejun Heo 
503129c91e99STejun Heo 	/* install */
503229c91e99STejun Heo 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
50333fb1823cSLai Jiangshan 
503429c91e99STejun Heo 	return pool;
503529c91e99STejun Heo fail:
503629c91e99STejun Heo 	if (pool)
503729c91e99STejun Heo 		put_unbound_pool(pool);
503829c91e99STejun Heo 	return NULL;
503929c91e99STejun Heo }
504029c91e99STejun Heo 
50418864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
50428864b4e5STejun Heo {
50438864b4e5STejun Heo 	kmem_cache_free(pwq_cache,
50448864b4e5STejun Heo 			container_of(rcu, struct pool_workqueue, rcu));
50458864b4e5STejun Heo }
50468864b4e5STejun Heo 
50478864b4e5STejun Heo /*
5048967b494eSTejun Heo  * Scheduled on pwq_release_worker by put_pwq() when an unbound pwq hits zero
5049967b494eSTejun Heo  * refcnt and needs to be destroyed.
50508864b4e5STejun Heo  */
5051687a9aa5STejun Heo static void pwq_release_workfn(struct kthread_work *work)
50528864b4e5STejun Heo {
50538864b4e5STejun Heo 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
5054687a9aa5STejun Heo 						  release_work);
50558864b4e5STejun Heo 	struct workqueue_struct *wq = pwq->wq;
50568864b4e5STejun Heo 	struct worker_pool *pool = pwq->pool;
5057b42b0bddSYang Yingliang 	bool is_last = false;
50588864b4e5STejun Heo 
5059b42b0bddSYang Yingliang 	/*
5060687a9aa5STejun Heo 	 * When @pwq is not linked, it doesn't hold any reference to the
5061b42b0bddSYang Yingliang 	 * @wq, and @wq is invalid to access.
5062b42b0bddSYang Yingliang 	 */
5063b42b0bddSYang Yingliang 	if (!list_empty(&pwq->pwqs_node)) {
50643c25a55dSLai Jiangshan 		mutex_lock(&wq->mutex);
50658864b4e5STejun Heo 		list_del_rcu(&pwq->pwqs_node);
5066bc0caf09STejun Heo 		is_last = list_empty(&wq->pwqs);
50674c065dbcSWaiman Long 
50684c065dbcSWaiman Long 		/*
50694c065dbcSWaiman Long 		 * For ordered workqueue with a plugged dfl_pwq, restart it now.
50704c065dbcSWaiman Long 		 */
50714c065dbcSWaiman Long 		if (!is_last && (wq->flags & __WQ_ORDERED))
50724c065dbcSWaiman Long 			unplug_oldest_pwq(wq);
50734c065dbcSWaiman Long 
50743c25a55dSLai Jiangshan 		mutex_unlock(&wq->mutex);
5075b42b0bddSYang Yingliang 	}
50768864b4e5STejun Heo 
5077687a9aa5STejun Heo 	if (wq->flags & WQ_UNBOUND) {
5078a892caccSTejun Heo 		mutex_lock(&wq_pool_mutex);
50798864b4e5STejun Heo 		put_unbound_pool(pool);
5080a892caccSTejun Heo 		mutex_unlock(&wq_pool_mutex);
5081687a9aa5STejun Heo 	}
5082a892caccSTejun Heo 
50835797b1c1STejun Heo 	if (!list_empty(&pwq->pending_node)) {
50845797b1c1STejun Heo 		struct wq_node_nr_active *nna =
50855797b1c1STejun Heo 			wq_node_nr_active(pwq->wq, pwq->pool->node);
50865797b1c1STejun Heo 
50875797b1c1STejun Heo 		raw_spin_lock_irq(&nna->lock);
50885797b1c1STejun Heo 		list_del_init(&pwq->pending_node);
50895797b1c1STejun Heo 		raw_spin_unlock_irq(&nna->lock);
50905797b1c1STejun Heo 	}
50915797b1c1STejun Heo 
509225b00775SPaul E. McKenney 	call_rcu(&pwq->rcu, rcu_free_pwq);
50938864b4e5STejun Heo 
50948864b4e5STejun Heo 	/*
50958864b4e5STejun Heo 	 * If we're the last pwq going away, @wq is already dead and no one
5096e2dca7adSTejun Heo 	 * is gonna access it anymore.  Schedule RCU free.
50978864b4e5STejun Heo 	 */
5098669de8bdSBart Van Assche 	if (is_last) {
5099669de8bdSBart Van Assche 		wq_unregister_lockdep(wq);
510025b00775SPaul E. McKenney 		call_rcu(&wq->rcu, rcu_free_wq);
51016029a918STejun Heo 	}
5102669de8bdSBart Van Assche }
51038864b4e5STejun Heo 
510467dc8325SCai Huoqing /* initialize newly allocated @pwq which is associated with @wq and @pool */
5105f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
5106f147f29eSTejun Heo 		     struct worker_pool *pool)
5107d2c1d404STejun Heo {
5108e9a8e01fSTejun Heo 	BUG_ON((unsigned long)pwq & ~WORK_STRUCT_PWQ_MASK);
5109d2c1d404STejun Heo 
5110e50aba9aSTejun Heo 	memset(pwq, 0, sizeof(*pwq));
5111e50aba9aSTejun Heo 
5112d2c1d404STejun Heo 	pwq->pool = pool;
5113d2c1d404STejun Heo 	pwq->wq = wq;
5114d2c1d404STejun Heo 	pwq->flush_color = -1;
51158864b4e5STejun Heo 	pwq->refcnt = 1;
5116f97a4a1aSLai Jiangshan 	INIT_LIST_HEAD(&pwq->inactive_works);
51175797b1c1STejun Heo 	INIT_LIST_HEAD(&pwq->pending_node);
51181befcf30STejun Heo 	INIT_LIST_HEAD(&pwq->pwqs_node);
5119d2c1d404STejun Heo 	INIT_LIST_HEAD(&pwq->mayday_node);
5120687a9aa5STejun Heo 	kthread_init_work(&pwq->release_work, pwq_release_workfn);
5121f147f29eSTejun Heo }
5122d2c1d404STejun Heo 
5123f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
51241befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
5125f147f29eSTejun Heo {
5126f147f29eSTejun Heo 	struct workqueue_struct *wq = pwq->wq;
5127f147f29eSTejun Heo 
5128f147f29eSTejun Heo 	lockdep_assert_held(&wq->mutex);
512975ccf595STejun Heo 
51301befcf30STejun Heo 	/* may be called multiple times, ignore if already linked */
51311befcf30STejun Heo 	if (!list_empty(&pwq->pwqs_node))
51321befcf30STejun Heo 		return;
51331befcf30STejun Heo 
513429b1cb41SLai Jiangshan 	/* set the matching work_color */
513575ccf595STejun Heo 	pwq->work_color = wq->work_color;
5136983ca25eSTejun Heo 
5137983ca25eSTejun Heo 	/* link in @pwq */
513826fb7e3dSWaiman Long 	list_add_tail_rcu(&pwq->pwqs_node, &wq->pwqs);
5139df2d5ae4STejun Heo }
51406029a918STejun Heo 
5141f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
5142f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
5143f147f29eSTejun Heo 					const struct workqueue_attrs *attrs)
5144f147f29eSTejun Heo {
5145f147f29eSTejun Heo 	struct worker_pool *pool;
5146f147f29eSTejun Heo 	struct pool_workqueue *pwq;
5147f147f29eSTejun Heo 
5148f147f29eSTejun Heo 	lockdep_assert_held(&wq_pool_mutex);
5149f147f29eSTejun Heo 
5150f147f29eSTejun Heo 	pool = get_unbound_pool(attrs);
5151f147f29eSTejun Heo 	if (!pool)
5152f147f29eSTejun Heo 		return NULL;
5153f147f29eSTejun Heo 
5154e50aba9aSTejun Heo 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
5155f147f29eSTejun Heo 	if (!pwq) {
5156f147f29eSTejun Heo 		put_unbound_pool(pool);
5157f147f29eSTejun Heo 		return NULL;
5158f147f29eSTejun Heo 	}
5159f147f29eSTejun Heo 
5160f147f29eSTejun Heo 	init_pwq(pwq, wq, pool);
5161f147f29eSTejun Heo 	return pwq;
5162d2c1d404STejun Heo }
5163d2c1d404STejun Heo 
51644c16bd32STejun Heo /**
5165fef59c9cSTejun Heo  * wq_calc_pod_cpumask - calculate a wq_attrs' cpumask for a pod
5166042f7df1SLai Jiangshan  * @attrs: the wq_attrs of the default pwq of the target workqueue
516784193c07STejun Heo  * @cpu: the target CPU
51684c16bd32STejun Heo  * @cpu_going_down: if >= 0, the CPU to consider as offline
51694c16bd32STejun Heo  *
5170fef59c9cSTejun Heo  * Calculate the cpumask a workqueue with @attrs should use on @pod. If
5171fef59c9cSTejun Heo  * @cpu_going_down is >= 0, that cpu is considered offline during calculation.
51729546b29eSTejun Heo  * The result is stored in @attrs->__pod_cpumask.
51734c16bd32STejun Heo  *
5174fef59c9cSTejun Heo  * If pod affinity is not enabled, @attrs->cpumask is always used. If enabled
5175fef59c9cSTejun Heo  * and @pod has online CPUs requested by @attrs, the returned cpumask is the
5176fef59c9cSTejun Heo  * intersection of the possible CPUs of @pod and @attrs->cpumask.
51774c16bd32STejun Heo  *
5178fef59c9cSTejun Heo  * The caller is responsible for ensuring that the cpumask of @pod stays stable.
51794c16bd32STejun Heo  */
51809546b29eSTejun Heo static void wq_calc_pod_cpumask(struct workqueue_attrs *attrs, int cpu,
51819546b29eSTejun Heo 				int cpu_going_down)
51824c16bd32STejun Heo {
518384193c07STejun Heo 	const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
518484193c07STejun Heo 	int pod = pt->cpu_pod[cpu];
51854c16bd32STejun Heo 
5186fef59c9cSTejun Heo 	/* does @pod have any online CPUs @attrs wants? */
51879546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, pt->pod_cpus[pod], attrs->cpumask);
51889546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, attrs->__pod_cpumask, cpu_online_mask);
51894c16bd32STejun Heo 	if (cpu_going_down >= 0)
51909546b29eSTejun Heo 		cpumask_clear_cpu(cpu_going_down, attrs->__pod_cpumask);
51914c16bd32STejun Heo 
51929546b29eSTejun Heo 	if (cpumask_empty(attrs->__pod_cpumask)) {
51939546b29eSTejun Heo 		cpumask_copy(attrs->__pod_cpumask, attrs->cpumask);
519484193c07STejun Heo 		return;
519584193c07STejun Heo 	}
51964c16bd32STejun Heo 
5197fef59c9cSTejun Heo 	/* yeap, return possible CPUs in @pod that @attrs wants */
51989546b29eSTejun Heo 	cpumask_and(attrs->__pod_cpumask, attrs->cpumask, pt->pod_cpus[pod]);
51991ad0f0a7SMichael Bringmann 
52009546b29eSTejun Heo 	if (cpumask_empty(attrs->__pod_cpumask))
52011ad0f0a7SMichael Bringmann 		pr_warn_once("WARNING: workqueue cpumask: online intersect > "
52021ad0f0a7SMichael Bringmann 				"possible intersect\n");
52034c16bd32STejun Heo }
52044c16bd32STejun Heo 
52059f66cff2STejun Heo /* install @pwq into @wq and return the old pwq, @cpu < 0 for dfl_pwq */
5206636b927eSTejun Heo static struct pool_workqueue *install_unbound_pwq(struct workqueue_struct *wq,
5207636b927eSTejun Heo 					int cpu, struct pool_workqueue *pwq)
52081befcf30STejun Heo {
52099f66cff2STejun Heo 	struct pool_workqueue __rcu **slot = unbound_pwq_slot(wq, cpu);
52101befcf30STejun Heo 	struct pool_workqueue *old_pwq;
52111befcf30STejun Heo 
52125b95e1afSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
52131befcf30STejun Heo 	lockdep_assert_held(&wq->mutex);
52141befcf30STejun Heo 
52151befcf30STejun Heo 	/* link_pwq() can handle duplicate calls */
52161befcf30STejun Heo 	link_pwq(pwq);
52171befcf30STejun Heo 
52189f66cff2STejun Heo 	old_pwq = rcu_access_pointer(*slot);
52199f66cff2STejun Heo 	rcu_assign_pointer(*slot, pwq);
52201befcf30STejun Heo 	return old_pwq;
52211befcf30STejun Heo }
52221befcf30STejun Heo 
52232d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
52242d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
52252d5f0764SLai Jiangshan 	struct workqueue_struct	*wq;		/* target workqueue */
52262d5f0764SLai Jiangshan 	struct workqueue_attrs	*attrs;		/* attrs to apply */
5227042f7df1SLai Jiangshan 	struct list_head	list;		/* queued for batching commit */
52282d5f0764SLai Jiangshan 	struct pool_workqueue	*dfl_pwq;
52292d5f0764SLai Jiangshan 	struct pool_workqueue	*pwq_tbl[];
52302d5f0764SLai Jiangshan };
52312d5f0764SLai Jiangshan 
52322d5f0764SLai Jiangshan /* free the resources after success or abort */
52332d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
52342d5f0764SLai Jiangshan {
52352d5f0764SLai Jiangshan 	if (ctx) {
5236636b927eSTejun Heo 		int cpu;
52372d5f0764SLai Jiangshan 
5238636b927eSTejun Heo 		for_each_possible_cpu(cpu)
5239636b927eSTejun Heo 			put_pwq_unlocked(ctx->pwq_tbl[cpu]);
52402d5f0764SLai Jiangshan 		put_pwq_unlocked(ctx->dfl_pwq);
52412d5f0764SLai Jiangshan 
52422d5f0764SLai Jiangshan 		free_workqueue_attrs(ctx->attrs);
52432d5f0764SLai Jiangshan 
52442d5f0764SLai Jiangshan 		kfree(ctx);
52452d5f0764SLai Jiangshan 	}
52462d5f0764SLai Jiangshan }
52472d5f0764SLai Jiangshan 
52482d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
52492d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
52502d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
525199c621efSLai Jiangshan 		      const struct workqueue_attrs *attrs,
525299c621efSLai Jiangshan 		      const cpumask_var_t unbound_cpumask)
52532d5f0764SLai Jiangshan {
52542d5f0764SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
52559546b29eSTejun Heo 	struct workqueue_attrs *new_attrs;
5256636b927eSTejun Heo 	int cpu;
52572d5f0764SLai Jiangshan 
52582d5f0764SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
52592d5f0764SLai Jiangshan 
526084193c07STejun Heo 	if (WARN_ON(attrs->affn_scope < 0 ||
526184193c07STejun Heo 		    attrs->affn_scope >= WQ_AFFN_NR_TYPES))
526284193c07STejun Heo 		return ERR_PTR(-EINVAL);
526384193c07STejun Heo 
5264636b927eSTejun Heo 	ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_cpu_ids), GFP_KERNEL);
52652d5f0764SLai Jiangshan 
5266be69d00dSThomas Gleixner 	new_attrs = alloc_workqueue_attrs();
52679546b29eSTejun Heo 	if (!ctx || !new_attrs)
52682d5f0764SLai Jiangshan 		goto out_free;
52692d5f0764SLai Jiangshan 
5270042f7df1SLai Jiangshan 	/*
52712d5f0764SLai Jiangshan 	 * If something goes wrong during CPU up/down, we'll fall back to
52722d5f0764SLai Jiangshan 	 * the default pwq covering whole @attrs->cpumask.  Always create
52732d5f0764SLai Jiangshan 	 * it even if we don't use it immediately.
52742d5f0764SLai Jiangshan 	 */
52750f36ee24STejun Heo 	copy_workqueue_attrs(new_attrs, attrs);
52760f36ee24STejun Heo 	wqattrs_actualize_cpumask(new_attrs, unbound_cpumask);
52779546b29eSTejun Heo 	cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
52782d5f0764SLai Jiangshan 	ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
52792d5f0764SLai Jiangshan 	if (!ctx->dfl_pwq)
52802d5f0764SLai Jiangshan 		goto out_free;
52812d5f0764SLai Jiangshan 
5282636b927eSTejun Heo 	for_each_possible_cpu(cpu) {
5283af73f5c9STejun Heo 		if (new_attrs->ordered) {
52842d5f0764SLai Jiangshan 			ctx->dfl_pwq->refcnt++;
5285636b927eSTejun Heo 			ctx->pwq_tbl[cpu] = ctx->dfl_pwq;
5286636b927eSTejun Heo 		} else {
52879546b29eSTejun Heo 			wq_calc_pod_cpumask(new_attrs, cpu, -1);
52889546b29eSTejun Heo 			ctx->pwq_tbl[cpu] = alloc_unbound_pwq(wq, new_attrs);
5289636b927eSTejun Heo 			if (!ctx->pwq_tbl[cpu])
5290636b927eSTejun Heo 				goto out_free;
52912d5f0764SLai Jiangshan 		}
52922d5f0764SLai Jiangshan 	}
52932d5f0764SLai Jiangshan 
5294042f7df1SLai Jiangshan 	/* save the user configured attrs and sanitize it. */
5295042f7df1SLai Jiangshan 	copy_workqueue_attrs(new_attrs, attrs);
5296042f7df1SLai Jiangshan 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
52979546b29eSTejun Heo 	cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
52982d5f0764SLai Jiangshan 	ctx->attrs = new_attrs;
5299042f7df1SLai Jiangshan 
53004c065dbcSWaiman Long 	/*
53014c065dbcSWaiman Long 	 * For initialized ordered workqueues, there should only be one pwq
53024c065dbcSWaiman Long 	 * (dfl_pwq). Set the plugged flag of ctx->dfl_pwq to suspend execution
53034c065dbcSWaiman Long 	 * of newly queued work items until execution of older work items in
53044c065dbcSWaiman Long 	 * the old pwq's have completed.
53054c065dbcSWaiman Long 	 */
53064c065dbcSWaiman Long 	if ((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs))
53074c065dbcSWaiman Long 		ctx->dfl_pwq->plugged = true;
53084c065dbcSWaiman Long 
53092d5f0764SLai Jiangshan 	ctx->wq = wq;
53102d5f0764SLai Jiangshan 	return ctx;
53112d5f0764SLai Jiangshan 
53122d5f0764SLai Jiangshan out_free:
53132d5f0764SLai Jiangshan 	free_workqueue_attrs(new_attrs);
53142d5f0764SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
531584193c07STejun Heo 	return ERR_PTR(-ENOMEM);
53162d5f0764SLai Jiangshan }
53172d5f0764SLai Jiangshan 
53182d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
53192d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
53202d5f0764SLai Jiangshan {
5321636b927eSTejun Heo 	int cpu;
53222d5f0764SLai Jiangshan 
53232d5f0764SLai Jiangshan 	/* all pwqs have been created successfully, let's install'em */
53242d5f0764SLai Jiangshan 	mutex_lock(&ctx->wq->mutex);
53252d5f0764SLai Jiangshan 
53262d5f0764SLai Jiangshan 	copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
53272d5f0764SLai Jiangshan 
53289f66cff2STejun Heo 	/* save the previous pwqs and install the new ones */
5329636b927eSTejun Heo 	for_each_possible_cpu(cpu)
5330636b927eSTejun Heo 		ctx->pwq_tbl[cpu] = install_unbound_pwq(ctx->wq, cpu,
5331636b927eSTejun Heo 							ctx->pwq_tbl[cpu]);
53329f66cff2STejun Heo 	ctx->dfl_pwq = install_unbound_pwq(ctx->wq, -1, ctx->dfl_pwq);
53332d5f0764SLai Jiangshan 
53345797b1c1STejun Heo 	/* update node_nr_active->max */
53355797b1c1STejun Heo 	wq_update_node_max_active(ctx->wq, -1);
53365797b1c1STejun Heo 
5337d64f2fa0SJuri Lelli 	/* rescuer needs to respect wq cpumask changes */
5338d64f2fa0SJuri Lelli 	if (ctx->wq->rescuer)
5339d64f2fa0SJuri Lelli 		set_cpus_allowed_ptr(ctx->wq->rescuer->task,
5340d64f2fa0SJuri Lelli 				     unbound_effective_cpumask(ctx->wq));
5341d64f2fa0SJuri Lelli 
53422d5f0764SLai Jiangshan 	mutex_unlock(&ctx->wq->mutex);
53432d5f0764SLai Jiangshan }
53442d5f0764SLai Jiangshan 
5345a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
5346a0111cf6SLai Jiangshan 					const struct workqueue_attrs *attrs)
5347a0111cf6SLai Jiangshan {
5348a0111cf6SLai Jiangshan 	struct apply_wqattrs_ctx *ctx;
5349a0111cf6SLai Jiangshan 
5350a0111cf6SLai Jiangshan 	/* only unbound workqueues can change attributes */
5351a0111cf6SLai Jiangshan 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
5352a0111cf6SLai Jiangshan 		return -EINVAL;
5353a0111cf6SLai Jiangshan 
535499c621efSLai Jiangshan 	ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
535584193c07STejun Heo 	if (IS_ERR(ctx))
535684193c07STejun Heo 		return PTR_ERR(ctx);
5357a0111cf6SLai Jiangshan 
5358a0111cf6SLai Jiangshan 	/* the ctx has been prepared successfully, let's commit it */
5359a0111cf6SLai Jiangshan 	apply_wqattrs_commit(ctx);
5360a0111cf6SLai Jiangshan 	apply_wqattrs_cleanup(ctx);
5361a0111cf6SLai Jiangshan 
53626201171eSwanghaibin 	return 0;
5363a0111cf6SLai Jiangshan }
5364a0111cf6SLai Jiangshan 
53659e8cd2f5STejun Heo /**
53669e8cd2f5STejun Heo  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
53679e8cd2f5STejun Heo  * @wq: the target workqueue
53689e8cd2f5STejun Heo  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
53699e8cd2f5STejun Heo  *
5370fef59c9cSTejun Heo  * Apply @attrs to an unbound workqueue @wq. Unless disabled, this function maps
5371fef59c9cSTejun Heo  * a separate pwq to each CPU pod with possibles CPUs in @attrs->cpumask so that
5372fef59c9cSTejun Heo  * work items are affine to the pod it was issued on. Older pwqs are released as
5373fef59c9cSTejun Heo  * in-flight work items finish. Note that a work item which repeatedly requeues
5374fef59c9cSTejun Heo  * itself back-to-back will stay on its current pwq.
53759e8cd2f5STejun Heo  *
5376d185af30SYacine Belkadi  * Performs GFP_KERNEL allocations.
5377d185af30SYacine Belkadi  *
5378ffd8bea8SSebastian Andrzej Siewior  * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
5379509b3204SDaniel Jordan  *
5380d185af30SYacine Belkadi  * Return: 0 on success and -errno on failure.
53819e8cd2f5STejun Heo  */
5382513c98d0SDaniel Jordan int apply_workqueue_attrs(struct workqueue_struct *wq,
53839e8cd2f5STejun Heo 			  const struct workqueue_attrs *attrs)
53849e8cd2f5STejun Heo {
5385a0111cf6SLai Jiangshan 	int ret;
53869e8cd2f5STejun Heo 
5387509b3204SDaniel Jordan 	lockdep_assert_cpus_held();
5388509b3204SDaniel Jordan 
5389509b3204SDaniel Jordan 	mutex_lock(&wq_pool_mutex);
5390a0111cf6SLai Jiangshan 	ret = apply_workqueue_attrs_locked(wq, attrs);
5391509b3204SDaniel Jordan 	mutex_unlock(&wq_pool_mutex);
53922d5f0764SLai Jiangshan 
53932d5f0764SLai Jiangshan 	return ret;
53949e8cd2f5STejun Heo }
53959e8cd2f5STejun Heo 
53964c16bd32STejun Heo /**
5397fef59c9cSTejun Heo  * wq_update_pod - update pod affinity of a wq for CPU hot[un]plug
53984c16bd32STejun Heo  * @wq: the target workqueue
53994cbfd3deSTejun Heo  * @cpu: the CPU to update pool association for
54004cbfd3deSTejun Heo  * @hotplug_cpu: the CPU coming up or going down
54014c16bd32STejun Heo  * @online: whether @cpu is coming up or going down
54024c16bd32STejun Heo  *
54034c16bd32STejun Heo  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
5404fef59c9cSTejun Heo  * %CPU_DOWN_FAILED.  @cpu is being hot[un]plugged, update pod affinity of
54054c16bd32STejun Heo  * @wq accordingly.
54064c16bd32STejun Heo  *
54074c16bd32STejun Heo  *
5408fef59c9cSTejun Heo  * If pod affinity can't be adjusted due to memory allocation failure, it falls
5409fef59c9cSTejun Heo  * back to @wq->dfl_pwq which may not be optimal but is always correct.
5410fef59c9cSTejun Heo  *
5411fef59c9cSTejun Heo  * Note that when the last allowed CPU of a pod goes offline for a workqueue
5412fef59c9cSTejun Heo  * with a cpumask spanning multiple pods, the workers which were already
5413fef59c9cSTejun Heo  * executing the work items for the workqueue will lose their CPU affinity and
5414fef59c9cSTejun Heo  * may execute on any CPU. This is similar to how per-cpu workqueues behave on
5415fef59c9cSTejun Heo  * CPU_DOWN. If a workqueue user wants strict affinity, it's the user's
5416fef59c9cSTejun Heo  * responsibility to flush the work item from CPU_DOWN_PREPARE.
54174c16bd32STejun Heo  */
5418fef59c9cSTejun Heo static void wq_update_pod(struct workqueue_struct *wq, int cpu,
54194cbfd3deSTejun Heo 			  int hotplug_cpu, bool online)
54204c16bd32STejun Heo {
54214cbfd3deSTejun Heo 	int off_cpu = online ? -1 : hotplug_cpu;
54224c16bd32STejun Heo 	struct pool_workqueue *old_pwq = NULL, *pwq;
54234c16bd32STejun Heo 	struct workqueue_attrs *target_attrs;
54244c16bd32STejun Heo 
54254c16bd32STejun Heo 	lockdep_assert_held(&wq_pool_mutex);
54264c16bd32STejun Heo 
542784193c07STejun Heo 	if (!(wq->flags & WQ_UNBOUND) || wq->unbound_attrs->ordered)
54284c16bd32STejun Heo 		return;
54294c16bd32STejun Heo 
54304c16bd32STejun Heo 	/*
54314c16bd32STejun Heo 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
54324c16bd32STejun Heo 	 * Let's use a preallocated one.  The following buf is protected by
54334c16bd32STejun Heo 	 * CPU hotplug exclusion.
54344c16bd32STejun Heo 	 */
5435fef59c9cSTejun Heo 	target_attrs = wq_update_pod_attrs_buf;
54364c16bd32STejun Heo 
54374c16bd32STejun Heo 	copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
54380f36ee24STejun Heo 	wqattrs_actualize_cpumask(target_attrs, wq_unbound_cpumask);
54394c16bd32STejun Heo 
5440636b927eSTejun Heo 	/* nothing to do if the target cpumask matches the current pwq */
54419546b29eSTejun Heo 	wq_calc_pod_cpumask(target_attrs, cpu, off_cpu);
54429f66cff2STejun Heo 	if (wqattrs_equal(target_attrs, unbound_pwq(wq, cpu)->pool->attrs))
5443f7142ed4SLai Jiangshan 		return;
54444c16bd32STejun Heo 
54454c16bd32STejun Heo 	/* create a new pwq */
54464c16bd32STejun Heo 	pwq = alloc_unbound_pwq(wq, target_attrs);
54474c16bd32STejun Heo 	if (!pwq) {
5448fef59c9cSTejun Heo 		pr_warn("workqueue: allocation failed while updating CPU pod affinity of \"%s\"\n",
54494c16bd32STejun Heo 			wq->name);
545077f300b1SDaeseok Youn 		goto use_dfl_pwq;
54514c16bd32STejun Heo 	}
54524c16bd32STejun Heo 
5453f7142ed4SLai Jiangshan 	/* Install the new pwq. */
54544c16bd32STejun Heo 	mutex_lock(&wq->mutex);
5455636b927eSTejun Heo 	old_pwq = install_unbound_pwq(wq, cpu, pwq);
54564c16bd32STejun Heo 	goto out_unlock;
54574c16bd32STejun Heo 
54584c16bd32STejun Heo use_dfl_pwq:
5459f7142ed4SLai Jiangshan 	mutex_lock(&wq->mutex);
54609f66cff2STejun Heo 	pwq = unbound_pwq(wq, -1);
54619f66cff2STejun Heo 	raw_spin_lock_irq(&pwq->pool->lock);
54629f66cff2STejun Heo 	get_pwq(pwq);
54639f66cff2STejun Heo 	raw_spin_unlock_irq(&pwq->pool->lock);
54649f66cff2STejun Heo 	old_pwq = install_unbound_pwq(wq, cpu, pwq);
54654c16bd32STejun Heo out_unlock:
54664c16bd32STejun Heo 	mutex_unlock(&wq->mutex);
54674c16bd32STejun Heo 	put_pwq_unlocked(old_pwq);
54684c16bd32STejun Heo }
54694c16bd32STejun Heo 
547030cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
54711da177e4SLinus Torvalds {
547249e3cf44STejun Heo 	bool highpri = wq->flags & WQ_HIGHPRI;
54738a2b7538STejun Heo 	int cpu, ret;
5474e1d8aa9fSFrederic Weisbecker 
5475687a9aa5STejun Heo 	wq->cpu_pwq = alloc_percpu(struct pool_workqueue *);
5476ee1ceef7STejun Heo 	if (!wq->cpu_pwq)
5477687a9aa5STejun Heo 		goto enomem;
547830cdf249STejun Heo 
5479636b927eSTejun Heo 	if (!(wq->flags & WQ_UNBOUND)) {
548030cdf249STejun Heo 		for_each_possible_cpu(cpu) {
54814cb1ef64STejun Heo 			struct pool_workqueue **pwq_p;
54824cb1ef64STejun Heo 			struct worker_pool __percpu *pools;
54834cb1ef64STejun Heo 			struct worker_pool *pool;
54844cb1ef64STejun Heo 
54854cb1ef64STejun Heo 			if (wq->flags & WQ_BH)
54864cb1ef64STejun Heo 				pools = bh_worker_pools;
54874cb1ef64STejun Heo 			else
54884cb1ef64STejun Heo 				pools = cpu_worker_pools;
54894cb1ef64STejun Heo 
54904cb1ef64STejun Heo 			pool = &(per_cpu_ptr(pools, cpu)[highpri]);
54914cb1ef64STejun Heo 			pwq_p = per_cpu_ptr(wq->cpu_pwq, cpu);
549230cdf249STejun Heo 
5493687a9aa5STejun Heo 			*pwq_p = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL,
5494687a9aa5STejun Heo 						       pool->node);
5495687a9aa5STejun Heo 			if (!*pwq_p)
5496687a9aa5STejun Heo 				goto enomem;
5497687a9aa5STejun Heo 
5498687a9aa5STejun Heo 			init_pwq(*pwq_p, wq, pool);
5499f147f29eSTejun Heo 
5500f147f29eSTejun Heo 			mutex_lock(&wq->mutex);
5501687a9aa5STejun Heo 			link_pwq(*pwq_p);
5502f147f29eSTejun Heo 			mutex_unlock(&wq->mutex);
550330cdf249STejun Heo 		}
550430cdf249STejun Heo 		return 0;
5505509b3204SDaniel Jordan 	}
5506509b3204SDaniel Jordan 
5507ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
5508509b3204SDaniel Jordan 	if (wq->flags & __WQ_ORDERED) {
55099f66cff2STejun Heo 		struct pool_workqueue *dfl_pwq;
55109f66cff2STejun Heo 
55118a2b7538STejun Heo 		ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
55128a2b7538STejun Heo 		/* there should only be single pwq for ordering guarantee */
55139f66cff2STejun Heo 		dfl_pwq = rcu_access_pointer(wq->dfl_pwq);
55149f66cff2STejun Heo 		WARN(!ret && (wq->pwqs.next != &dfl_pwq->pwqs_node ||
55159f66cff2STejun Heo 			      wq->pwqs.prev != &dfl_pwq->pwqs_node),
55168a2b7538STejun Heo 		     "ordering guarantee broken for workqueue %s\n", wq->name);
55179e8cd2f5STejun Heo 	} else {
5518509b3204SDaniel Jordan 		ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
55199e8cd2f5STejun Heo 	}
5520ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
5521509b3204SDaniel Jordan 
552264344553SZqiang 	/* for unbound pwq, flush the pwq_release_worker ensures that the
552364344553SZqiang 	 * pwq_release_workfn() completes before calling kfree(wq).
552464344553SZqiang 	 */
552564344553SZqiang 	if (ret)
552664344553SZqiang 		kthread_flush_worker(pwq_release_worker);
552764344553SZqiang 
5528509b3204SDaniel Jordan 	return ret;
5529687a9aa5STejun Heo 
5530687a9aa5STejun Heo enomem:
5531687a9aa5STejun Heo 	if (wq->cpu_pwq) {
55327b42f401SZqiang 		for_each_possible_cpu(cpu) {
55337b42f401SZqiang 			struct pool_workqueue *pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
55347b42f401SZqiang 
55357b42f401SZqiang 			if (pwq)
55367b42f401SZqiang 				kmem_cache_free(pwq_cache, pwq);
55377b42f401SZqiang 		}
5538687a9aa5STejun Heo 		free_percpu(wq->cpu_pwq);
5539687a9aa5STejun Heo 		wq->cpu_pwq = NULL;
5540687a9aa5STejun Heo 	}
5541687a9aa5STejun Heo 	return -ENOMEM;
55420f900049STejun Heo }
55430f900049STejun Heo 
5544f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
5545f3421797STejun Heo 			       const char *name)
5546b71ab8c2STejun Heo {
5547636b927eSTejun Heo 	if (max_active < 1 || max_active > WQ_MAX_ACTIVE)
5548044c782cSValentin Ilie 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
5549636b927eSTejun Heo 			max_active, name, 1, WQ_MAX_ACTIVE);
5550b71ab8c2STejun Heo 
5551636b927eSTejun Heo 	return clamp_val(max_active, 1, WQ_MAX_ACTIVE);
5552b71ab8c2STejun Heo }
5553b71ab8c2STejun Heo 
5554983c7515STejun Heo /*
5555983c7515STejun Heo  * Workqueues which may be used during memory reclaim should have a rescuer
5556983c7515STejun Heo  * to guarantee forward progress.
5557983c7515STejun Heo  */
5558983c7515STejun Heo static int init_rescuer(struct workqueue_struct *wq)
5559983c7515STejun Heo {
5560983c7515STejun Heo 	struct worker *rescuer;
5561*2a1b02bcSTejun Heo 	char id_buf[WORKER_ID_LEN];
5562b92b36eaSDan Carpenter 	int ret;
5563983c7515STejun Heo 
5564983c7515STejun Heo 	if (!(wq->flags & WQ_MEM_RECLAIM))
5565983c7515STejun Heo 		return 0;
5566983c7515STejun Heo 
5567983c7515STejun Heo 	rescuer = alloc_worker(NUMA_NO_NODE);
55684c0736a7SPetr Mladek 	if (!rescuer) {
55694c0736a7SPetr Mladek 		pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
55704c0736a7SPetr Mladek 		       wq->name);
5571983c7515STejun Heo 		return -ENOMEM;
55724c0736a7SPetr Mladek 	}
5573983c7515STejun Heo 
5574983c7515STejun Heo 	rescuer->rescue_wq = wq;
5575*2a1b02bcSTejun Heo 	format_worker_id(id_buf, sizeof(id_buf), rescuer, NULL);
5576*2a1b02bcSTejun Heo 
5577*2a1b02bcSTejun Heo 	rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", id_buf);
5578f187b697SSean Fu 	if (IS_ERR(rescuer->task)) {
5579b92b36eaSDan Carpenter 		ret = PTR_ERR(rescuer->task);
55804c0736a7SPetr Mladek 		pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
55814c0736a7SPetr Mladek 		       wq->name, ERR_PTR(ret));
5582983c7515STejun Heo 		kfree(rescuer);
5583b92b36eaSDan Carpenter 		return ret;
5584983c7515STejun Heo 	}
5585983c7515STejun Heo 
5586983c7515STejun Heo 	wq->rescuer = rescuer;
558785f0ab43SJuri Lelli 	if (wq->flags & WQ_UNBOUND)
558849584bb8SWaiman Long 		kthread_bind_mask(rescuer->task, wq_unbound_cpumask);
558985f0ab43SJuri Lelli 	else
5590983c7515STejun Heo 		kthread_bind_mask(rescuer->task, cpu_possible_mask);
5591983c7515STejun Heo 	wake_up_process(rescuer->task);
5592983c7515STejun Heo 
5593983c7515STejun Heo 	return 0;
5594983c7515STejun Heo }
5595983c7515STejun Heo 
5596a045a272STejun Heo /**
5597a045a272STejun Heo  * wq_adjust_max_active - update a wq's max_active to the current setting
5598a045a272STejun Heo  * @wq: target workqueue
5599a045a272STejun Heo  *
5600a045a272STejun Heo  * If @wq isn't freezing, set @wq->max_active to the saved_max_active and
5601a045a272STejun Heo  * activate inactive work items accordingly. If @wq is freezing, clear
5602a045a272STejun Heo  * @wq->max_active to zero.
5603a045a272STejun Heo  */
5604a045a272STejun Heo static void wq_adjust_max_active(struct workqueue_struct *wq)
5605a045a272STejun Heo {
5606c5404d4eSTejun Heo 	bool activated;
56075797b1c1STejun Heo 	int new_max, new_min;
5608a045a272STejun Heo 
5609a045a272STejun Heo 	lockdep_assert_held(&wq->mutex);
5610a045a272STejun Heo 
5611a045a272STejun Heo 	if ((wq->flags & WQ_FREEZABLE) && workqueue_freezing) {
56125797b1c1STejun Heo 		new_max = 0;
56135797b1c1STejun Heo 		new_min = 0;
56145797b1c1STejun Heo 	} else {
56155797b1c1STejun Heo 		new_max = wq->saved_max_active;
56165797b1c1STejun Heo 		new_min = wq->saved_min_active;
5617a045a272STejun Heo 	}
5618a045a272STejun Heo 
56195797b1c1STejun Heo 	if (wq->max_active == new_max && wq->min_active == new_min)
5620a045a272STejun Heo 		return;
5621a045a272STejun Heo 
5622a045a272STejun Heo 	/*
56235797b1c1STejun Heo 	 * Update @wq->max/min_active and then kick inactive work items if more
5624a045a272STejun Heo 	 * active work items are allowed. This doesn't break work item ordering
5625a045a272STejun Heo 	 * because new work items are always queued behind existing inactive
5626a045a272STejun Heo 	 * work items if there are any.
5627a045a272STejun Heo 	 */
56285797b1c1STejun Heo 	WRITE_ONCE(wq->max_active, new_max);
56295797b1c1STejun Heo 	WRITE_ONCE(wq->min_active, new_min);
56305797b1c1STejun Heo 
56315797b1c1STejun Heo 	if (wq->flags & WQ_UNBOUND)
56325797b1c1STejun Heo 		wq_update_node_max_active(wq, -1);
56335797b1c1STejun Heo 
56345797b1c1STejun Heo 	if (new_max == 0)
56355797b1c1STejun Heo 		return;
5636a045a272STejun Heo 
5637c5404d4eSTejun Heo 	/*
5638c5404d4eSTejun Heo 	 * Round-robin through pwq's activating the first inactive work item
5639c5404d4eSTejun Heo 	 * until max_active is filled.
5640c5404d4eSTejun Heo 	 */
5641c5404d4eSTejun Heo 	do {
5642c5404d4eSTejun Heo 		struct pool_workqueue *pwq;
5643c5404d4eSTejun Heo 
5644c5404d4eSTejun Heo 		activated = false;
5645a045a272STejun Heo 		for_each_pwq(pwq, wq) {
5646c26e2f2eSTejun Heo 			unsigned long irq_flags;
5647a045a272STejun Heo 
5648c5404d4eSTejun Heo 			/* can be called during early boot w/ irq disabled */
5649c26e2f2eSTejun Heo 			raw_spin_lock_irqsave(&pwq->pool->lock, irq_flags);
56505797b1c1STejun Heo 			if (pwq_activate_first_inactive(pwq, true)) {
5651c5404d4eSTejun Heo 				activated = true;
5652a045a272STejun Heo 				kick_pool(pwq->pool);
5653c5404d4eSTejun Heo 			}
5654c26e2f2eSTejun Heo 			raw_spin_unlock_irqrestore(&pwq->pool->lock, irq_flags);
5655a045a272STejun Heo 		}
5656c5404d4eSTejun Heo 	} while (activated);
5657a045a272STejun Heo }
5658a045a272STejun Heo 
5659a2775bbcSMathieu Malaterre __printf(1, 4)
5660669de8bdSBart Van Assche struct workqueue_struct *alloc_workqueue(const char *fmt,
566197e37d7bSTejun Heo 					 unsigned int flags,
5662669de8bdSBart Van Assche 					 int max_active, ...)
56633af24433SOleg Nesterov {
5664ecf6881fSTejun Heo 	va_list args;
56653af24433SOleg Nesterov 	struct workqueue_struct *wq;
566691ccc6e7STejun Heo 	size_t wq_size;
566791ccc6e7STejun Heo 	int name_len;
5668b196be89STejun Heo 
56694cb1ef64STejun Heo 	if (flags & WQ_BH) {
56704cb1ef64STejun Heo 		if (WARN_ON_ONCE(flags & ~__WQ_BH_ALLOWS))
56714cb1ef64STejun Heo 			return NULL;
56724cb1ef64STejun Heo 		if (WARN_ON_ONCE(max_active))
56734cb1ef64STejun Heo 			return NULL;
56744cb1ef64STejun Heo 	}
56754cb1ef64STejun Heo 
5676cee22a15SViresh Kumar 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
5677cee22a15SViresh Kumar 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
5678cee22a15SViresh Kumar 		flags |= WQ_UNBOUND;
5679cee22a15SViresh Kumar 
5680ecf6881fSTejun Heo 	/* allocate wq and format name */
568191ccc6e7STejun Heo 	if (flags & WQ_UNBOUND)
568291ccc6e7STejun Heo 		wq_size = struct_size(wq, node_nr_active, nr_node_ids + 1);
568391ccc6e7STejun Heo 	else
568491ccc6e7STejun Heo 		wq_size = sizeof(*wq);
568591ccc6e7STejun Heo 
568691ccc6e7STejun Heo 	wq = kzalloc(wq_size, GFP_KERNEL);
5687b196be89STejun Heo 	if (!wq)
5688d2c1d404STejun Heo 		return NULL;
5689b196be89STejun Heo 
56906029a918STejun Heo 	if (flags & WQ_UNBOUND) {
5691be69d00dSThomas Gleixner 		wq->unbound_attrs = alloc_workqueue_attrs();
56926029a918STejun Heo 		if (!wq->unbound_attrs)
56936029a918STejun Heo 			goto err_free_wq;
56946029a918STejun Heo 	}
56956029a918STejun Heo 
5696669de8bdSBart Van Assche 	va_start(args, max_active);
569791ccc6e7STejun Heo 	name_len = vsnprintf(wq->name, sizeof(wq->name), fmt, args);
5698b196be89STejun Heo 	va_end(args);
56993af24433SOleg Nesterov 
570091ccc6e7STejun Heo 	if (name_len >= WQ_NAME_LEN)
570191ccc6e7STejun Heo 		pr_warn_once("workqueue: name exceeds WQ_NAME_LEN. Truncating to: %s\n",
570291ccc6e7STejun Heo 			     wq->name);
570331c89007SAudra Mitchell 
57044cb1ef64STejun Heo 	if (flags & WQ_BH) {
57054cb1ef64STejun Heo 		/*
57064cb1ef64STejun Heo 		 * BH workqueues always share a single execution context per CPU
57074cb1ef64STejun Heo 		 * and don't impose any max_active limit.
57084cb1ef64STejun Heo 		 */
57094cb1ef64STejun Heo 		max_active = INT_MAX;
57104cb1ef64STejun Heo 	} else {
5711d320c038STejun Heo 		max_active = max_active ?: WQ_DFL_ACTIVE;
5712b196be89STejun Heo 		max_active = wq_clamp_max_active(max_active, flags, wq->name);
57134cb1ef64STejun Heo 	}
57143af24433SOleg Nesterov 
5715b196be89STejun Heo 	/* init wq */
571697e37d7bSTejun Heo 	wq->flags = flags;
5717a045a272STejun Heo 	wq->max_active = max_active;
57185797b1c1STejun Heo 	wq->min_active = min(max_active, WQ_DFL_MIN_ACTIVE);
57195797b1c1STejun Heo 	wq->saved_max_active = wq->max_active;
57205797b1c1STejun Heo 	wq->saved_min_active = wq->min_active;
57213c25a55dSLai Jiangshan 	mutex_init(&wq->mutex);
5722112202d9STejun Heo 	atomic_set(&wq->nr_pwqs_to_flush, 0);
572330cdf249STejun Heo 	INIT_LIST_HEAD(&wq->pwqs);
572473f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_queue);
572573f53c4aSTejun Heo 	INIT_LIST_HEAD(&wq->flusher_overflow);
5726493a1724STejun Heo 	INIT_LIST_HEAD(&wq->maydays);
57273af24433SOleg Nesterov 
5728669de8bdSBart Van Assche 	wq_init_lockdep(wq);
5729cce1a165SOleg Nesterov 	INIT_LIST_HEAD(&wq->list);
57303af24433SOleg Nesterov 
573191ccc6e7STejun Heo 	if (flags & WQ_UNBOUND) {
573291ccc6e7STejun Heo 		if (alloc_node_nr_active(wq->node_nr_active) < 0)
573382efcab3SBart Van Assche 			goto err_unreg_lockdep;
573491ccc6e7STejun Heo 	}
573591ccc6e7STejun Heo 
573691ccc6e7STejun Heo 	if (alloc_and_link_pwqs(wq) < 0)
573791ccc6e7STejun Heo 		goto err_free_node_nr_active;
57381537663fSTejun Heo 
573940c17f75STejun Heo 	if (wq_online && init_rescuer(wq) < 0)
5740d2c1d404STejun Heo 		goto err_destroy;
5741e22bee78STejun Heo 
5742226223abSTejun Heo 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
5743226223abSTejun Heo 		goto err_destroy;
5744226223abSTejun Heo 
57456af8bf3dSOleg Nesterov 	/*
574668e13a67SLai Jiangshan 	 * wq_pool_mutex protects global freeze state and workqueues list.
574768e13a67SLai Jiangshan 	 * Grab it, adjust max_active and add the new @wq to workqueues
574868e13a67SLai Jiangshan 	 * list.
57496af8bf3dSOleg Nesterov 	 */
575068e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
5751a0a1a5fdSTejun Heo 
5752a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
5753a045a272STejun Heo 	wq_adjust_max_active(wq);
5754a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
5755a0a1a5fdSTejun Heo 
5756e2dca7adSTejun Heo 	list_add_tail_rcu(&wq->list, &workqueues);
5757a0a1a5fdSTejun Heo 
575868e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
57593af24433SOleg Nesterov 
57603af24433SOleg Nesterov 	return wq;
5761d2c1d404STejun Heo 
576291ccc6e7STejun Heo err_free_node_nr_active:
576391ccc6e7STejun Heo 	if (wq->flags & WQ_UNBOUND)
576491ccc6e7STejun Heo 		free_node_nr_active(wq->node_nr_active);
576582efcab3SBart Van Assche err_unreg_lockdep:
5766009bb421SBart Van Assche 	wq_unregister_lockdep(wq);
5767009bb421SBart Van Assche 	wq_free_lockdep(wq);
576882efcab3SBart Van Assche err_free_wq:
57696029a918STejun Heo 	free_workqueue_attrs(wq->unbound_attrs);
57704690c4abSTejun Heo 	kfree(wq);
5771d2c1d404STejun Heo 	return NULL;
5772d2c1d404STejun Heo err_destroy:
5773d2c1d404STejun Heo 	destroy_workqueue(wq);
57744690c4abSTejun Heo 	return NULL;
57751da177e4SLinus Torvalds }
5776669de8bdSBart Van Assche EXPORT_SYMBOL_GPL(alloc_workqueue);
57771da177e4SLinus Torvalds 
5778c29eb853STejun Heo static bool pwq_busy(struct pool_workqueue *pwq)
5779c29eb853STejun Heo {
5780c29eb853STejun Heo 	int i;
5781c29eb853STejun Heo 
5782c29eb853STejun Heo 	for (i = 0; i < WORK_NR_COLORS; i++)
5783c29eb853STejun Heo 		if (pwq->nr_in_flight[i])
5784c29eb853STejun Heo 			return true;
5785c29eb853STejun Heo 
57869f66cff2STejun Heo 	if ((pwq != rcu_access_pointer(pwq->wq->dfl_pwq)) && (pwq->refcnt > 1))
5787c29eb853STejun Heo 		return true;
5788afa87ce8STejun Heo 	if (!pwq_is_empty(pwq))
5789c29eb853STejun Heo 		return true;
5790c29eb853STejun Heo 
5791c29eb853STejun Heo 	return false;
5792c29eb853STejun Heo }
5793c29eb853STejun Heo 
57943af24433SOleg Nesterov /**
57953af24433SOleg Nesterov  * destroy_workqueue - safely terminate a workqueue
57963af24433SOleg Nesterov  * @wq: target workqueue
57973af24433SOleg Nesterov  *
57983af24433SOleg Nesterov  * Safely destroy a workqueue. All work currently pending will be done first.
57993af24433SOleg Nesterov  */
58003af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
58013af24433SOleg Nesterov {
580249e3cf44STejun Heo 	struct pool_workqueue *pwq;
5803636b927eSTejun Heo 	int cpu;
58043af24433SOleg Nesterov 
5805def98c84STejun Heo 	/*
5806def98c84STejun Heo 	 * Remove it from sysfs first so that sanity check failure doesn't
5807def98c84STejun Heo 	 * lead to sysfs name conflicts.
5808def98c84STejun Heo 	 */
5809def98c84STejun Heo 	workqueue_sysfs_unregister(wq);
5810def98c84STejun Heo 
581133e3f0a3SRichard Clark 	/* mark the workqueue destruction is in progress */
581233e3f0a3SRichard Clark 	mutex_lock(&wq->mutex);
581333e3f0a3SRichard Clark 	wq->flags |= __WQ_DESTROYING;
581433e3f0a3SRichard Clark 	mutex_unlock(&wq->mutex);
581533e3f0a3SRichard Clark 
58169c5a2ba7STejun Heo 	/* drain it before proceeding with destruction */
58179c5a2ba7STejun Heo 	drain_workqueue(wq);
5818c8efcc25STejun Heo 
5819def98c84STejun Heo 	/* kill rescuer, if sanity checks fail, leave it w/o rescuer */
5820def98c84STejun Heo 	if (wq->rescuer) {
5821def98c84STejun Heo 		struct worker *rescuer = wq->rescuer;
5822def98c84STejun Heo 
5823def98c84STejun Heo 		/* this prevents new queueing */
5824a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&wq_mayday_lock);
5825def98c84STejun Heo 		wq->rescuer = NULL;
5826a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&wq_mayday_lock);
5827def98c84STejun Heo 
5828def98c84STejun Heo 		/* rescuer will empty maydays list before exiting */
5829def98c84STejun Heo 		kthread_stop(rescuer->task);
58308efe1223STejun Heo 		kfree(rescuer);
5831def98c84STejun Heo 	}
5832def98c84STejun Heo 
5833c29eb853STejun Heo 	/*
5834c29eb853STejun Heo 	 * Sanity checks - grab all the locks so that we wait for all
5835c29eb853STejun Heo 	 * in-flight operations which may do put_pwq().
5836c29eb853STejun Heo 	 */
5837c29eb853STejun Heo 	mutex_lock(&wq_pool_mutex);
5838b09f4fd3SLai Jiangshan 	mutex_lock(&wq->mutex);
583949e3cf44STejun Heo 	for_each_pwq(pwq, wq) {
5840a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pwq->pool->lock);
5841c29eb853STejun Heo 		if (WARN_ON(pwq_busy(pwq))) {
58421d9a6159SKefeng Wang 			pr_warn("%s: %s has the following busy pwq\n",
5843e66b39afSTejun Heo 				__func__, wq->name);
5844c29eb853STejun Heo 			show_pwq(pwq);
5845a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pwq->pool->lock);
5846b09f4fd3SLai Jiangshan 			mutex_unlock(&wq->mutex);
5847c29eb853STejun Heo 			mutex_unlock(&wq_pool_mutex);
584855df0933SImran Khan 			show_one_workqueue(wq);
58496183c009STejun Heo 			return;
585076af4d93STejun Heo 		}
5851a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pwq->pool->lock);
585276af4d93STejun Heo 	}
5853b09f4fd3SLai Jiangshan 	mutex_unlock(&wq->mutex);
58546183c009STejun Heo 
5855a0a1a5fdSTejun Heo 	/*
5856a0a1a5fdSTejun Heo 	 * wq list is used to freeze wq, remove from list after
5857a0a1a5fdSTejun Heo 	 * flushing is complete in case freeze races us.
5858a0a1a5fdSTejun Heo 	 */
5859e2dca7adSTejun Heo 	list_del_rcu(&wq->list);
586068e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
58613af24433SOleg Nesterov 
58628864b4e5STejun Heo 	/*
5863636b927eSTejun Heo 	 * We're the sole accessor of @wq. Directly access cpu_pwq and dfl_pwq
5864636b927eSTejun Heo 	 * to put the base refs. @wq will be auto-destroyed from the last
5865636b927eSTejun Heo 	 * pwq_put. RCU read lock prevents @wq from going away from under us.
58668864b4e5STejun Heo 	 */
5867636b927eSTejun Heo 	rcu_read_lock();
5868636b927eSTejun Heo 
5869636b927eSTejun Heo 	for_each_possible_cpu(cpu) {
58709f66cff2STejun Heo 		put_pwq_unlocked(unbound_pwq(wq, cpu));
58719f66cff2STejun Heo 		RCU_INIT_POINTER(*unbound_pwq_slot(wq, cpu), NULL);
58724c16bd32STejun Heo 	}
58734c16bd32STejun Heo 
58749f66cff2STejun Heo 	put_pwq_unlocked(unbound_pwq(wq, -1));
58759f66cff2STejun Heo 	RCU_INIT_POINTER(*unbound_pwq_slot(wq, -1), NULL);
5876636b927eSTejun Heo 
5877636b927eSTejun Heo 	rcu_read_unlock();
58783af24433SOleg Nesterov }
58793af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
58803af24433SOleg Nesterov 
5881dcd989cbSTejun Heo /**
5882dcd989cbSTejun Heo  * workqueue_set_max_active - adjust max_active of a workqueue
5883dcd989cbSTejun Heo  * @wq: target workqueue
5884dcd989cbSTejun Heo  * @max_active: new max_active value.
5885dcd989cbSTejun Heo  *
58865797b1c1STejun Heo  * Set max_active of @wq to @max_active. See the alloc_workqueue() function
58875797b1c1STejun Heo  * comment.
5888dcd989cbSTejun Heo  *
5889dcd989cbSTejun Heo  * CONTEXT:
5890dcd989cbSTejun Heo  * Don't call from IRQ context.
5891dcd989cbSTejun Heo  */
5892dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
5893dcd989cbSTejun Heo {
58944cb1ef64STejun Heo 	/* max_active doesn't mean anything for BH workqueues */
58954cb1ef64STejun Heo 	if (WARN_ON(wq->flags & WQ_BH))
58964cb1ef64STejun Heo 		return;
58978719dceaSTejun Heo 	/* disallow meddling with max_active for ordered workqueues */
58983bc1e711STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED))
58998719dceaSTejun Heo 		return;
59008719dceaSTejun Heo 
5901f3421797STejun Heo 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
5902dcd989cbSTejun Heo 
5903a357fc03SLai Jiangshan 	mutex_lock(&wq->mutex);
5904dcd989cbSTejun Heo 
5905dcd989cbSTejun Heo 	wq->saved_max_active = max_active;
59065797b1c1STejun Heo 	if (wq->flags & WQ_UNBOUND)
59075797b1c1STejun Heo 		wq->saved_min_active = min(wq->saved_min_active, max_active);
59085797b1c1STejun Heo 
5909a045a272STejun Heo 	wq_adjust_max_active(wq);
5910dcd989cbSTejun Heo 
5911a357fc03SLai Jiangshan 	mutex_unlock(&wq->mutex);
5912dcd989cbSTejun Heo }
5913dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
5914dcd989cbSTejun Heo 
5915dcd989cbSTejun Heo /**
59168f172181STejun Heo  * workqueue_set_min_active - adjust min_active of an unbound workqueue
59178f172181STejun Heo  * @wq: target unbound workqueue
59188f172181STejun Heo  * @min_active: new min_active value
59198f172181STejun Heo  *
59208f172181STejun Heo  * Set min_active of an unbound workqueue. Unlike other types of workqueues, an
59218f172181STejun Heo  * unbound workqueue is not guaranteed to be able to process max_active
59228f172181STejun Heo  * interdependent work items. Instead, an unbound workqueue is guaranteed to be
59238f172181STejun Heo  * able to process min_active number of interdependent work items which is
59248f172181STejun Heo  * %WQ_DFL_MIN_ACTIVE by default.
59258f172181STejun Heo  *
59268f172181STejun Heo  * Use this function to adjust the min_active value between 0 and the current
59278f172181STejun Heo  * max_active.
59288f172181STejun Heo  */
59298f172181STejun Heo void workqueue_set_min_active(struct workqueue_struct *wq, int min_active)
59308f172181STejun Heo {
59318f172181STejun Heo 	/* min_active is only meaningful for non-ordered unbound workqueues */
59328f172181STejun Heo 	if (WARN_ON((wq->flags & (WQ_BH | WQ_UNBOUND | __WQ_ORDERED)) !=
59338f172181STejun Heo 		    WQ_UNBOUND))
59348f172181STejun Heo 		return;
59358f172181STejun Heo 
59368f172181STejun Heo 	mutex_lock(&wq->mutex);
59378f172181STejun Heo 	wq->saved_min_active = clamp(min_active, 0, wq->saved_max_active);
59388f172181STejun Heo 	wq_adjust_max_active(wq);
59398f172181STejun Heo 	mutex_unlock(&wq->mutex);
59408f172181STejun Heo }
59418f172181STejun Heo 
59428f172181STejun Heo /**
594327d4ee03SLukas Wunner  * current_work - retrieve %current task's work struct
594427d4ee03SLukas Wunner  *
594527d4ee03SLukas Wunner  * Determine if %current task is a workqueue worker and what it's working on.
594627d4ee03SLukas Wunner  * Useful to find out the context that the %current task is running in.
594727d4ee03SLukas Wunner  *
594827d4ee03SLukas Wunner  * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
594927d4ee03SLukas Wunner  */
595027d4ee03SLukas Wunner struct work_struct *current_work(void)
595127d4ee03SLukas Wunner {
595227d4ee03SLukas Wunner 	struct worker *worker = current_wq_worker();
595327d4ee03SLukas Wunner 
595427d4ee03SLukas Wunner 	return worker ? worker->current_work : NULL;
595527d4ee03SLukas Wunner }
595627d4ee03SLukas Wunner EXPORT_SYMBOL(current_work);
595727d4ee03SLukas Wunner 
595827d4ee03SLukas Wunner /**
5959e6267616STejun Heo  * current_is_workqueue_rescuer - is %current workqueue rescuer?
5960e6267616STejun Heo  *
5961e6267616STejun Heo  * Determine whether %current is a workqueue rescuer.  Can be used from
5962e6267616STejun Heo  * work functions to determine whether it's being run off the rescuer task.
5963d185af30SYacine Belkadi  *
5964d185af30SYacine Belkadi  * Return: %true if %current is a workqueue rescuer. %false otherwise.
5965e6267616STejun Heo  */
5966e6267616STejun Heo bool current_is_workqueue_rescuer(void)
5967e6267616STejun Heo {
5968e6267616STejun Heo 	struct worker *worker = current_wq_worker();
5969e6267616STejun Heo 
59706a092dfdSLai Jiangshan 	return worker && worker->rescue_wq;
5971e6267616STejun Heo }
5972e6267616STejun Heo 
5973e6267616STejun Heo /**
5974dcd989cbSTejun Heo  * workqueue_congested - test whether a workqueue is congested
5975dcd989cbSTejun Heo  * @cpu: CPU in question
5976dcd989cbSTejun Heo  * @wq: target workqueue
5977dcd989cbSTejun Heo  *
5978dcd989cbSTejun Heo  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
5979dcd989cbSTejun Heo  * no synchronization around this function and the test result is
5980dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
5981dcd989cbSTejun Heo  *
5982d3251859STejun Heo  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
5983636b927eSTejun Heo  *
5984636b927eSTejun Heo  * With the exception of ordered workqueues, all workqueues have per-cpu
5985636b927eSTejun Heo  * pool_workqueues, each with its own congested state. A workqueue being
5986636b927eSTejun Heo  * congested on one CPU doesn't mean that the workqueue is contested on any
5987636b927eSTejun Heo  * other CPUs.
5988d3251859STejun Heo  *
5989d185af30SYacine Belkadi  * Return:
5990dcd989cbSTejun Heo  * %true if congested, %false otherwise.
5991dcd989cbSTejun Heo  */
5992d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
5993dcd989cbSTejun Heo {
59947fb98ea7STejun Heo 	struct pool_workqueue *pwq;
599576af4d93STejun Heo 	bool ret;
599676af4d93STejun Heo 
599724acfb71SThomas Gleixner 	rcu_read_lock();
599824acfb71SThomas Gleixner 	preempt_disable();
59997fb98ea7STejun Heo 
6000d3251859STejun Heo 	if (cpu == WORK_CPU_UNBOUND)
6001d3251859STejun Heo 		cpu = smp_processor_id();
6002d3251859STejun Heo 
6003687a9aa5STejun Heo 	pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
6004f97a4a1aSLai Jiangshan 	ret = !list_empty(&pwq->inactive_works);
6005636b927eSTejun Heo 
600624acfb71SThomas Gleixner 	preempt_enable();
600724acfb71SThomas Gleixner 	rcu_read_unlock();
600876af4d93STejun Heo 
600976af4d93STejun Heo 	return ret;
6010dcd989cbSTejun Heo }
6011dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
6012dcd989cbSTejun Heo 
6013dcd989cbSTejun Heo /**
6014dcd989cbSTejun Heo  * work_busy - test whether a work is currently pending or running
6015dcd989cbSTejun Heo  * @work: the work to be tested
6016dcd989cbSTejun Heo  *
6017dcd989cbSTejun Heo  * Test whether @work is currently pending or running.  There is no
6018dcd989cbSTejun Heo  * synchronization around this function and the test result is
6019dcd989cbSTejun Heo  * unreliable and only useful as advisory hints or for debugging.
6020dcd989cbSTejun Heo  *
6021d185af30SYacine Belkadi  * Return:
6022dcd989cbSTejun Heo  * OR'd bitmask of WORK_BUSY_* bits.
6023dcd989cbSTejun Heo  */
6024dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
6025dcd989cbSTejun Heo {
6026fa1b54e6STejun Heo 	struct worker_pool *pool;
6027c26e2f2eSTejun Heo 	unsigned long irq_flags;
6028dcd989cbSTejun Heo 	unsigned int ret = 0;
6029dcd989cbSTejun Heo 
6030dcd989cbSTejun Heo 	if (work_pending(work))
6031dcd989cbSTejun Heo 		ret |= WORK_BUSY_PENDING;
6032038366c5SLai Jiangshan 
603324acfb71SThomas Gleixner 	rcu_read_lock();
6034fa1b54e6STejun Heo 	pool = get_work_pool(work);
6035038366c5SLai Jiangshan 	if (pool) {
6036c26e2f2eSTejun Heo 		raw_spin_lock_irqsave(&pool->lock, irq_flags);
6037c9e7cf27STejun Heo 		if (find_worker_executing_work(pool, work))
6038dcd989cbSTejun Heo 			ret |= WORK_BUSY_RUNNING;
6039c26e2f2eSTejun Heo 		raw_spin_unlock_irqrestore(&pool->lock, irq_flags);
6040038366c5SLai Jiangshan 	}
604124acfb71SThomas Gleixner 	rcu_read_unlock();
6042dcd989cbSTejun Heo 
6043dcd989cbSTejun Heo 	return ret;
6044dcd989cbSTejun Heo }
6045dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
6046dcd989cbSTejun Heo 
60473d1cb205STejun Heo /**
60483d1cb205STejun Heo  * set_worker_desc - set description for the current work item
60493d1cb205STejun Heo  * @fmt: printf-style format string
60503d1cb205STejun Heo  * @...: arguments for the format string
60513d1cb205STejun Heo  *
60523d1cb205STejun Heo  * This function can be called by a running work function to describe what
60533d1cb205STejun Heo  * the work item is about.  If the worker task gets dumped, this
60543d1cb205STejun Heo  * information will be printed out together to help debugging.  The
60553d1cb205STejun Heo  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
60563d1cb205STejun Heo  */
60573d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
60583d1cb205STejun Heo {
60593d1cb205STejun Heo 	struct worker *worker = current_wq_worker();
60603d1cb205STejun Heo 	va_list args;
60613d1cb205STejun Heo 
60623d1cb205STejun Heo 	if (worker) {
60633d1cb205STejun Heo 		va_start(args, fmt);
60643d1cb205STejun Heo 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
60653d1cb205STejun Heo 		va_end(args);
60663d1cb205STejun Heo 	}
60673d1cb205STejun Heo }
60685c750d58SSteffen Maier EXPORT_SYMBOL_GPL(set_worker_desc);
60693d1cb205STejun Heo 
60703d1cb205STejun Heo /**
60713d1cb205STejun Heo  * print_worker_info - print out worker information and description
60723d1cb205STejun Heo  * @log_lvl: the log level to use when printing
60733d1cb205STejun Heo  * @task: target task
60743d1cb205STejun Heo  *
60753d1cb205STejun Heo  * If @task is a worker and currently executing a work item, print out the
60763d1cb205STejun Heo  * name of the workqueue being serviced and worker description set with
60773d1cb205STejun Heo  * set_worker_desc() by the currently executing work item.
60783d1cb205STejun Heo  *
60793d1cb205STejun Heo  * This function can be safely called on any task as long as the
60803d1cb205STejun Heo  * task_struct itself is accessible.  While safe, this function isn't
60813d1cb205STejun Heo  * synchronized and may print out mixups or garbages of limited length.
60823d1cb205STejun Heo  */
60833d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
60843d1cb205STejun Heo {
60853d1cb205STejun Heo 	work_func_t *fn = NULL;
60863d1cb205STejun Heo 	char name[WQ_NAME_LEN] = { };
60873d1cb205STejun Heo 	char desc[WORKER_DESC_LEN] = { };
60883d1cb205STejun Heo 	struct pool_workqueue *pwq = NULL;
60893d1cb205STejun Heo 	struct workqueue_struct *wq = NULL;
60903d1cb205STejun Heo 	struct worker *worker;
60913d1cb205STejun Heo 
60923d1cb205STejun Heo 	if (!(task->flags & PF_WQ_WORKER))
60933d1cb205STejun Heo 		return;
60943d1cb205STejun Heo 
60953d1cb205STejun Heo 	/*
60963d1cb205STejun Heo 	 * This function is called without any synchronization and @task
60973d1cb205STejun Heo 	 * could be in any state.  Be careful with dereferences.
60983d1cb205STejun Heo 	 */
6099e700591aSPetr Mladek 	worker = kthread_probe_data(task);
61003d1cb205STejun Heo 
61013d1cb205STejun Heo 	/*
61028bf89593STejun Heo 	 * Carefully copy the associated workqueue's workfn, name and desc.
61038bf89593STejun Heo 	 * Keep the original last '\0' in case the original is garbage.
61043d1cb205STejun Heo 	 */
6105fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
6106fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
6107fe557319SChristoph Hellwig 	copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
6108fe557319SChristoph Hellwig 	copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
6109fe557319SChristoph Hellwig 	copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
61103d1cb205STejun Heo 
61113d1cb205STejun Heo 	if (fn || name[0] || desc[0]) {
6112d75f773cSSakari Ailus 		printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
61138bf89593STejun Heo 		if (strcmp(name, desc))
61143d1cb205STejun Heo 			pr_cont(" (%s)", desc);
61153d1cb205STejun Heo 		pr_cont("\n");
61163d1cb205STejun Heo 	}
61173d1cb205STejun Heo }
61183d1cb205STejun Heo 
61193494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
61203494fc30STejun Heo {
61213494fc30STejun Heo 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
61223494fc30STejun Heo 	if (pool->node != NUMA_NO_NODE)
61233494fc30STejun Heo 		pr_cont(" node=%d", pool->node);
61244cb1ef64STejun Heo 	pr_cont(" flags=0x%x", pool->flags);
61254cb1ef64STejun Heo 	if (pool->flags & POOL_BH)
61264cb1ef64STejun Heo 		pr_cont(" bh%s",
61274cb1ef64STejun Heo 			pool->attrs->nice == HIGHPRI_NICE_LEVEL ? "-hi" : "");
61284cb1ef64STejun Heo 	else
61294cb1ef64STejun Heo 		pr_cont(" nice=%d", pool->attrs->nice);
61304cb1ef64STejun Heo }
61314cb1ef64STejun Heo 
61324cb1ef64STejun Heo static void pr_cont_worker_id(struct worker *worker)
61334cb1ef64STejun Heo {
61344cb1ef64STejun Heo 	struct worker_pool *pool = worker->pool;
61354cb1ef64STejun Heo 
61364cb1ef64STejun Heo 	if (pool->flags & WQ_BH)
61374cb1ef64STejun Heo 		pr_cont("bh%s",
61384cb1ef64STejun Heo 			pool->attrs->nice == HIGHPRI_NICE_LEVEL ? "-hi" : "");
61394cb1ef64STejun Heo 	else
61404cb1ef64STejun Heo 		pr_cont("%d%s", task_pid_nr(worker->task),
61414cb1ef64STejun Heo 			worker->rescue_wq ? "(RESCUER)" : "");
61423494fc30STejun Heo }
61433494fc30STejun Heo 
6144c76feb0dSPaul E. McKenney struct pr_cont_work_struct {
6145c76feb0dSPaul E. McKenney 	bool comma;
6146c76feb0dSPaul E. McKenney 	work_func_t func;
6147c76feb0dSPaul E. McKenney 	long ctr;
6148c76feb0dSPaul E. McKenney };
6149c76feb0dSPaul E. McKenney 
6150c76feb0dSPaul E. McKenney static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
6151c76feb0dSPaul E. McKenney {
6152c76feb0dSPaul E. McKenney 	if (!pcwsp->ctr)
6153c76feb0dSPaul E. McKenney 		goto out_record;
6154c76feb0dSPaul E. McKenney 	if (func == pcwsp->func) {
6155c76feb0dSPaul E. McKenney 		pcwsp->ctr++;
6156c76feb0dSPaul E. McKenney 		return;
6157c76feb0dSPaul E. McKenney 	}
6158c76feb0dSPaul E. McKenney 	if (pcwsp->ctr == 1)
6159c76feb0dSPaul E. McKenney 		pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
6160c76feb0dSPaul E. McKenney 	else
6161c76feb0dSPaul E. McKenney 		pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
6162c76feb0dSPaul E. McKenney 	pcwsp->ctr = 0;
6163c76feb0dSPaul E. McKenney out_record:
6164c76feb0dSPaul E. McKenney 	if ((long)func == -1L)
6165c76feb0dSPaul E. McKenney 		return;
6166c76feb0dSPaul E. McKenney 	pcwsp->comma = comma;
6167c76feb0dSPaul E. McKenney 	pcwsp->func = func;
6168c76feb0dSPaul E. McKenney 	pcwsp->ctr = 1;
6169c76feb0dSPaul E. McKenney }
6170c76feb0dSPaul E. McKenney 
6171c76feb0dSPaul E. McKenney static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
61723494fc30STejun Heo {
61733494fc30STejun Heo 	if (work->func == wq_barrier_func) {
61743494fc30STejun Heo 		struct wq_barrier *barr;
61753494fc30STejun Heo 
61763494fc30STejun Heo 		barr = container_of(work, struct wq_barrier, work);
61773494fc30STejun Heo 
6178c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
61793494fc30STejun Heo 		pr_cont("%s BAR(%d)", comma ? "," : "",
61803494fc30STejun Heo 			task_pid_nr(barr->task));
61813494fc30STejun Heo 	} else {
6182c76feb0dSPaul E. McKenney 		if (!comma)
6183c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
6184c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, work->func, pcwsp);
61853494fc30STejun Heo 	}
61863494fc30STejun Heo }
61873494fc30STejun Heo 
61883494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
61893494fc30STejun Heo {
6190c76feb0dSPaul E. McKenney 	struct pr_cont_work_struct pcws = { .ctr = 0, };
61913494fc30STejun Heo 	struct worker_pool *pool = pwq->pool;
61923494fc30STejun Heo 	struct work_struct *work;
61933494fc30STejun Heo 	struct worker *worker;
61943494fc30STejun Heo 	bool has_in_flight = false, has_pending = false;
61953494fc30STejun Heo 	int bkt;
61963494fc30STejun Heo 
61973494fc30STejun Heo 	pr_info("  pwq %d:", pool->id);
61983494fc30STejun Heo 	pr_cont_pool_info(pool);
61993494fc30STejun Heo 
6200a045a272STejun Heo 	pr_cont(" active=%d refcnt=%d%s\n",
6201a045a272STejun Heo 		pwq->nr_active, pwq->refcnt,
62023494fc30STejun Heo 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
62033494fc30STejun Heo 
62043494fc30STejun Heo 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
62053494fc30STejun Heo 		if (worker->current_pwq == pwq) {
62063494fc30STejun Heo 			has_in_flight = true;
62073494fc30STejun Heo 			break;
62083494fc30STejun Heo 		}
62093494fc30STejun Heo 	}
62103494fc30STejun Heo 	if (has_in_flight) {
62113494fc30STejun Heo 		bool comma = false;
62123494fc30STejun Heo 
62133494fc30STejun Heo 		pr_info("    in-flight:");
62143494fc30STejun Heo 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
62153494fc30STejun Heo 			if (worker->current_pwq != pwq)
62163494fc30STejun Heo 				continue;
62173494fc30STejun Heo 
62184cb1ef64STejun Heo 			pr_cont(" %s", comma ? "," : "");
62194cb1ef64STejun Heo 			pr_cont_worker_id(worker);
62204cb1ef64STejun Heo 			pr_cont(":%ps", worker->current_func);
62213494fc30STejun Heo 			list_for_each_entry(work, &worker->scheduled, entry)
6222c76feb0dSPaul E. McKenney 				pr_cont_work(false, work, &pcws);
6223c76feb0dSPaul E. McKenney 			pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
62243494fc30STejun Heo 			comma = true;
62253494fc30STejun Heo 		}
62263494fc30STejun Heo 		pr_cont("\n");
62273494fc30STejun Heo 	}
62283494fc30STejun Heo 
62293494fc30STejun Heo 	list_for_each_entry(work, &pool->worklist, entry) {
62303494fc30STejun Heo 		if (get_work_pwq(work) == pwq) {
62313494fc30STejun Heo 			has_pending = true;
62323494fc30STejun Heo 			break;
62333494fc30STejun Heo 		}
62343494fc30STejun Heo 	}
62353494fc30STejun Heo 	if (has_pending) {
62363494fc30STejun Heo 		bool comma = false;
62373494fc30STejun Heo 
62383494fc30STejun Heo 		pr_info("    pending:");
62393494fc30STejun Heo 		list_for_each_entry(work, &pool->worklist, entry) {
62403494fc30STejun Heo 			if (get_work_pwq(work) != pwq)
62413494fc30STejun Heo 				continue;
62423494fc30STejun Heo 
6243c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
62443494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
62453494fc30STejun Heo 		}
6246c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
62473494fc30STejun Heo 		pr_cont("\n");
62483494fc30STejun Heo 	}
62493494fc30STejun Heo 
6250f97a4a1aSLai Jiangshan 	if (!list_empty(&pwq->inactive_works)) {
62513494fc30STejun Heo 		bool comma = false;
62523494fc30STejun Heo 
6253f97a4a1aSLai Jiangshan 		pr_info("    inactive:");
6254f97a4a1aSLai Jiangshan 		list_for_each_entry(work, &pwq->inactive_works, entry) {
6255c76feb0dSPaul E. McKenney 			pr_cont_work(comma, work, &pcws);
62563494fc30STejun Heo 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
62573494fc30STejun Heo 		}
6258c76feb0dSPaul E. McKenney 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
62593494fc30STejun Heo 		pr_cont("\n");
62603494fc30STejun Heo 	}
62613494fc30STejun Heo }
62623494fc30STejun Heo 
62633494fc30STejun Heo /**
626455df0933SImran Khan  * show_one_workqueue - dump state of specified workqueue
626555df0933SImran Khan  * @wq: workqueue whose state will be printed
62663494fc30STejun Heo  */
626755df0933SImran Khan void show_one_workqueue(struct workqueue_struct *wq)
62683494fc30STejun Heo {
62693494fc30STejun Heo 	struct pool_workqueue *pwq;
62703494fc30STejun Heo 	bool idle = true;
6271c26e2f2eSTejun Heo 	unsigned long irq_flags;
62723494fc30STejun Heo 
62733494fc30STejun Heo 	for_each_pwq(pwq, wq) {
6274afa87ce8STejun Heo 		if (!pwq_is_empty(pwq)) {
62753494fc30STejun Heo 			idle = false;
62763494fc30STejun Heo 			break;
62773494fc30STejun Heo 		}
62783494fc30STejun Heo 	}
627955df0933SImran Khan 	if (idle) /* Nothing to print for idle workqueue */
628055df0933SImran Khan 		return;
62813494fc30STejun Heo 
62823494fc30STejun Heo 	pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
62833494fc30STejun Heo 
62843494fc30STejun Heo 	for_each_pwq(pwq, wq) {
6285c26e2f2eSTejun Heo 		raw_spin_lock_irqsave(&pwq->pool->lock, irq_flags);
6286afa87ce8STejun Heo 		if (!pwq_is_empty(pwq)) {
628757116ce1SJohan Hovold 			/*
628857116ce1SJohan Hovold 			 * Defer printing to avoid deadlocks in console
628957116ce1SJohan Hovold 			 * drivers that queue work while holding locks
629057116ce1SJohan Hovold 			 * also taken in their write paths.
629157116ce1SJohan Hovold 			 */
629257116ce1SJohan Hovold 			printk_deferred_enter();
62933494fc30STejun Heo 			show_pwq(pwq);
629457116ce1SJohan Hovold 			printk_deferred_exit();
629557116ce1SJohan Hovold 		}
6296c26e2f2eSTejun Heo 		raw_spin_unlock_irqrestore(&pwq->pool->lock, irq_flags);
629762635ea8SSergey Senozhatsky 		/*
629862635ea8SSergey Senozhatsky 		 * We could be printing a lot from atomic context, e.g.
629955df0933SImran Khan 		 * sysrq-t -> show_all_workqueues(). Avoid triggering
630062635ea8SSergey Senozhatsky 		 * hard lockup.
630162635ea8SSergey Senozhatsky 		 */
630262635ea8SSergey Senozhatsky 		touch_nmi_watchdog();
63033494fc30STejun Heo 	}
630455df0933SImran Khan 
63053494fc30STejun Heo }
63063494fc30STejun Heo 
630755df0933SImran Khan /**
630855df0933SImran Khan  * show_one_worker_pool - dump state of specified worker pool
630955df0933SImran Khan  * @pool: worker pool whose state will be printed
631055df0933SImran Khan  */
631155df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool)
631255df0933SImran Khan {
63133494fc30STejun Heo 	struct worker *worker;
63143494fc30STejun Heo 	bool first = true;
6315c26e2f2eSTejun Heo 	unsigned long irq_flags;
6316335a42ebSPetr Mladek 	unsigned long hung = 0;
63173494fc30STejun Heo 
6318c26e2f2eSTejun Heo 	raw_spin_lock_irqsave(&pool->lock, irq_flags);
63193494fc30STejun Heo 	if (pool->nr_workers == pool->nr_idle)
63203494fc30STejun Heo 		goto next_pool;
6321335a42ebSPetr Mladek 
6322335a42ebSPetr Mladek 	/* How long the first pending work is waiting for a worker. */
6323335a42ebSPetr Mladek 	if (!list_empty(&pool->worklist))
6324335a42ebSPetr Mladek 		hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
6325335a42ebSPetr Mladek 
632657116ce1SJohan Hovold 	/*
632757116ce1SJohan Hovold 	 * Defer printing to avoid deadlocks in console drivers that
632857116ce1SJohan Hovold 	 * queue work while holding locks also taken in their write
632957116ce1SJohan Hovold 	 * paths.
633057116ce1SJohan Hovold 	 */
633157116ce1SJohan Hovold 	printk_deferred_enter();
63323494fc30STejun Heo 	pr_info("pool %d:", pool->id);
63333494fc30STejun Heo 	pr_cont_pool_info(pool);
6334335a42ebSPetr Mladek 	pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
63353494fc30STejun Heo 	if (pool->manager)
63363494fc30STejun Heo 		pr_cont(" manager: %d",
63373494fc30STejun Heo 			task_pid_nr(pool->manager->task));
63383494fc30STejun Heo 	list_for_each_entry(worker, &pool->idle_list, entry) {
63394cb1ef64STejun Heo 		pr_cont(" %s", first ? "idle: " : "");
63404cb1ef64STejun Heo 		pr_cont_worker_id(worker);
63413494fc30STejun Heo 		first = false;
63423494fc30STejun Heo 	}
63433494fc30STejun Heo 	pr_cont("\n");
634457116ce1SJohan Hovold 	printk_deferred_exit();
63453494fc30STejun Heo next_pool:
6346c26e2f2eSTejun Heo 	raw_spin_unlock_irqrestore(&pool->lock, irq_flags);
634762635ea8SSergey Senozhatsky 	/*
634862635ea8SSergey Senozhatsky 	 * We could be printing a lot from atomic context, e.g.
634955df0933SImran Khan 	 * sysrq-t -> show_all_workqueues(). Avoid triggering
635062635ea8SSergey Senozhatsky 	 * hard lockup.
635162635ea8SSergey Senozhatsky 	 */
635262635ea8SSergey Senozhatsky 	touch_nmi_watchdog();
635355df0933SImran Khan 
63543494fc30STejun Heo }
63553494fc30STejun Heo 
635655df0933SImran Khan /**
635755df0933SImran Khan  * show_all_workqueues - dump workqueue state
635855df0933SImran Khan  *
6359704bc669SJungseung Lee  * Called from a sysrq handler and prints out all busy workqueues and pools.
636055df0933SImran Khan  */
636155df0933SImran Khan void show_all_workqueues(void)
636255df0933SImran Khan {
636355df0933SImran Khan 	struct workqueue_struct *wq;
636455df0933SImran Khan 	struct worker_pool *pool;
636555df0933SImran Khan 	int pi;
636655df0933SImran Khan 
636755df0933SImran Khan 	rcu_read_lock();
636855df0933SImran Khan 
636955df0933SImran Khan 	pr_info("Showing busy workqueues and worker pools:\n");
637055df0933SImran Khan 
637155df0933SImran Khan 	list_for_each_entry_rcu(wq, &workqueues, list)
637255df0933SImran Khan 		show_one_workqueue(wq);
637355df0933SImran Khan 
637455df0933SImran Khan 	for_each_pool(pool, pi)
637555df0933SImran Khan 		show_one_worker_pool(pool);
637655df0933SImran Khan 
637724acfb71SThomas Gleixner 	rcu_read_unlock();
63783494fc30STejun Heo }
63793494fc30STejun Heo 
6380704bc669SJungseung Lee /**
6381704bc669SJungseung Lee  * show_freezable_workqueues - dump freezable workqueue state
6382704bc669SJungseung Lee  *
6383704bc669SJungseung Lee  * Called from try_to_freeze_tasks() and prints out all freezable workqueues
6384704bc669SJungseung Lee  * still busy.
6385704bc669SJungseung Lee  */
6386704bc669SJungseung Lee void show_freezable_workqueues(void)
6387704bc669SJungseung Lee {
6388704bc669SJungseung Lee 	struct workqueue_struct *wq;
6389704bc669SJungseung Lee 
6390704bc669SJungseung Lee 	rcu_read_lock();
6391704bc669SJungseung Lee 
6392704bc669SJungseung Lee 	pr_info("Showing freezable workqueues that are still busy:\n");
6393704bc669SJungseung Lee 
6394704bc669SJungseung Lee 	list_for_each_entry_rcu(wq, &workqueues, list) {
6395704bc669SJungseung Lee 		if (!(wq->flags & WQ_FREEZABLE))
6396704bc669SJungseung Lee 			continue;
6397704bc669SJungseung Lee 		show_one_workqueue(wq);
6398704bc669SJungseung Lee 	}
6399704bc669SJungseung Lee 
6400704bc669SJungseung Lee 	rcu_read_unlock();
6401704bc669SJungseung Lee }
6402704bc669SJungseung Lee 
64036b59808bSTejun Heo /* used to show worker information through /proc/PID/{comm,stat,status} */
64046b59808bSTejun Heo void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
64056b59808bSTejun Heo {
6406197f6accSTejun Heo 	/* stabilize PF_WQ_WORKER and worker pool association */
64076b59808bSTejun Heo 	mutex_lock(&wq_pool_attach_mutex);
64086b59808bSTejun Heo 
6409197f6accSTejun Heo 	if (task->flags & PF_WQ_WORKER) {
6410197f6accSTejun Heo 		struct worker *worker = kthread_data(task);
6411197f6accSTejun Heo 		struct worker_pool *pool = worker->pool;
6412*2a1b02bcSTejun Heo 		int off;
6413*2a1b02bcSTejun Heo 
6414*2a1b02bcSTejun Heo 		off = format_worker_id(buf, size, worker, pool);
64156b59808bSTejun Heo 
64166b59808bSTejun Heo 		if (pool) {
6417a9b8a985SSebastian Andrzej Siewior 			raw_spin_lock_irq(&pool->lock);
64186b59808bSTejun Heo 			/*
6419197f6accSTejun Heo 			 * ->desc tracks information (wq name or
6420197f6accSTejun Heo 			 * set_worker_desc()) for the latest execution.  If
6421197f6accSTejun Heo 			 * current, prepend '+', otherwise '-'.
64226b59808bSTejun Heo 			 */
64236b59808bSTejun Heo 			if (worker->desc[0] != '\0') {
64246b59808bSTejun Heo 				if (worker->current_work)
64256b59808bSTejun Heo 					scnprintf(buf + off, size - off, "+%s",
64266b59808bSTejun Heo 						  worker->desc);
64276b59808bSTejun Heo 				else
64286b59808bSTejun Heo 					scnprintf(buf + off, size - off, "-%s",
64296b59808bSTejun Heo 						  worker->desc);
64306b59808bSTejun Heo 			}
6431a9b8a985SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&pool->lock);
64326b59808bSTejun Heo 		}
6433*2a1b02bcSTejun Heo 	} else {
6434*2a1b02bcSTejun Heo 		strscpy(buf, task->comm, size);
6435197f6accSTejun Heo 	}
64366b59808bSTejun Heo 
64376b59808bSTejun Heo 	mutex_unlock(&wq_pool_attach_mutex);
64386b59808bSTejun Heo }
64396b59808bSTejun Heo 
644066448bc2SMathieu Malaterre #ifdef CONFIG_SMP
644166448bc2SMathieu Malaterre 
6442db7bccf4STejun Heo /*
6443db7bccf4STejun Heo  * CPU hotplug.
6444db7bccf4STejun Heo  *
6445e22bee78STejun Heo  * There are two challenges in supporting CPU hotplug.  Firstly, there
6446112202d9STejun Heo  * are a lot of assumptions on strong associations among work, pwq and
6447706026c2STejun Heo  * pool which make migrating pending and scheduled works very
6448e22bee78STejun Heo  * difficult to implement without impacting hot paths.  Secondly,
644994cf58bbSTejun Heo  * worker pools serve mix of short, long and very long running works making
6450e22bee78STejun Heo  * blocked draining impractical.
6451e22bee78STejun Heo  *
645224647570STejun Heo  * This is solved by allowing the pools to be disassociated from the CPU
6453628c78e7STejun Heo  * running as an unbound one and allowing it to be reattached later if the
6454628c78e7STejun Heo  * cpu comes back online.
6455db7bccf4STejun Heo  */
6456db7bccf4STejun Heo 
6457e8b3f8dbSLai Jiangshan static void unbind_workers(int cpu)
6458db7bccf4STejun Heo {
64594ce62e9eSTejun Heo 	struct worker_pool *pool;
6460db7bccf4STejun Heo 	struct worker *worker;
6461db7bccf4STejun Heo 
6462f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
64631258fae7STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
6464a9b8a985SSebastian Andrzej Siewior 		raw_spin_lock_irq(&pool->lock);
6465e22bee78STejun Heo 
6466f2d5a0eeSTejun Heo 		/*
646792f9c5c4SLai Jiangshan 		 * We've blocked all attach/detach operations. Make all workers
646894cf58bbSTejun Heo 		 * unbound and set DISASSOCIATED.  Before this, all workers
646911b45b0bSLai Jiangshan 		 * must be on the cpu.  After this, they may become diasporas.
6470b4ac9384SLai Jiangshan 		 * And the preemption disabled section in their sched callbacks
6471b4ac9384SLai Jiangshan 		 * are guaranteed to see WORKER_UNBOUND since the code here
6472b4ac9384SLai Jiangshan 		 * is on the same cpu.
6473f2d5a0eeSTejun Heo 		 */
6474da028469SLai Jiangshan 		for_each_pool_worker(worker, pool)
6475403c821dSTejun Heo 			worker->flags |= WORKER_UNBOUND;
6476db7bccf4STejun Heo 
647724647570STejun Heo 		pool->flags |= POOL_DISASSOCIATED;
6478f2d5a0eeSTejun Heo 
6479e22bee78STejun Heo 		/*
6480989442d7SLai Jiangshan 		 * The handling of nr_running in sched callbacks are disabled
6481989442d7SLai Jiangshan 		 * now.  Zap nr_running.  After this, nr_running stays zero and
6482989442d7SLai Jiangshan 		 * need_more_worker() and keep_working() are always true as
6483989442d7SLai Jiangshan 		 * long as the worklist is not empty.  This pool now behaves as
6484989442d7SLai Jiangshan 		 * an unbound (in terms of concurrency management) pool which
6485eb283428SLai Jiangshan 		 * are served by workers tied to the pool.
6486e22bee78STejun Heo 		 */
6487bc35f7efSLai Jiangshan 		pool->nr_running = 0;
6488eb283428SLai Jiangshan 
6489eb283428SLai Jiangshan 		/*
6490eb283428SLai Jiangshan 		 * With concurrency management just turned off, a busy
6491eb283428SLai Jiangshan 		 * worker blocking could lead to lengthy stalls.  Kick off
6492eb283428SLai Jiangshan 		 * unbound chain execution of currently pending work items.
6493eb283428SLai Jiangshan 		 */
64940219a352STejun Heo 		kick_pool(pool);
6495989442d7SLai Jiangshan 
6496a9b8a985SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&pool->lock);
6497989442d7SLai Jiangshan 
6498793777bcSValentin Schneider 		for_each_pool_worker(worker, pool)
6499793777bcSValentin Schneider 			unbind_worker(worker);
6500989442d7SLai Jiangshan 
6501989442d7SLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
6502eb283428SLai Jiangshan 	}
6503db7bccf4STejun Heo }
6504db7bccf4STejun Heo 
6505bd7c089eSTejun Heo /**
6506bd7c089eSTejun Heo  * rebind_workers - rebind all workers of a pool to the associated CPU
6507bd7c089eSTejun Heo  * @pool: pool of interest
6508bd7c089eSTejun Heo  *
6509a9ab775bSTejun Heo  * @pool->cpu is coming online.  Rebind all workers to the CPU.
6510bd7c089eSTejun Heo  */
6511bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
6512bd7c089eSTejun Heo {
6513a9ab775bSTejun Heo 	struct worker *worker;
6514bd7c089eSTejun Heo 
65151258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
6516bd7c089eSTejun Heo 
6517bd7c089eSTejun Heo 	/*
6518a9ab775bSTejun Heo 	 * Restore CPU affinity of all workers.  As all idle workers should
6519a9ab775bSTejun Heo 	 * be on the run-queue of the associated CPU before any local
6520402dd89dSShailendra Verma 	 * wake-ups for concurrency management happen, restore CPU affinity
6521a9ab775bSTejun Heo 	 * of all workers first and then clear UNBOUND.  As we're called
6522a9ab775bSTejun Heo 	 * from CPU_ONLINE, the following shouldn't fail.
6523bd7c089eSTejun Heo 	 */
6524c63a2e52SValentin Schneider 	for_each_pool_worker(worker, pool) {
6525c63a2e52SValentin Schneider 		kthread_set_per_cpu(worker->task, pool->cpu);
6526c63a2e52SValentin Schneider 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
65279546b29eSTejun Heo 						  pool_allowed_cpus(pool)) < 0);
6528c63a2e52SValentin Schneider 	}
6529a9ab775bSTejun Heo 
6530a9b8a985SSebastian Andrzej Siewior 	raw_spin_lock_irq(&pool->lock);
6531f7c17d26SWanpeng Li 
65323de5e884SLai Jiangshan 	pool->flags &= ~POOL_DISASSOCIATED;
6533a9ab775bSTejun Heo 
6534da028469SLai Jiangshan 	for_each_pool_worker(worker, pool) {
6535a9ab775bSTejun Heo 		unsigned int worker_flags = worker->flags;
6536a9ab775bSTejun Heo 
6537a9ab775bSTejun Heo 		/*
6538a9ab775bSTejun Heo 		 * We want to clear UNBOUND but can't directly call
6539a9ab775bSTejun Heo 		 * worker_clr_flags() or adjust nr_running.  Atomically
6540a9ab775bSTejun Heo 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
6541a9ab775bSTejun Heo 		 * @worker will clear REBOUND using worker_clr_flags() when
6542a9ab775bSTejun Heo 		 * it initiates the next execution cycle thus restoring
6543a9ab775bSTejun Heo 		 * concurrency management.  Note that when or whether
6544a9ab775bSTejun Heo 		 * @worker clears REBOUND doesn't affect correctness.
6545a9ab775bSTejun Heo 		 *
6546c95491edSMark Rutland 		 * WRITE_ONCE() is necessary because @worker->flags may be
6547a9ab775bSTejun Heo 		 * tested without holding any lock in
65486d25be57SThomas Gleixner 		 * wq_worker_running().  Without it, NOT_RUNNING test may
6549a9ab775bSTejun Heo 		 * fail incorrectly leading to premature concurrency
6550a9ab775bSTejun Heo 		 * management operations.
6551bd7c089eSTejun Heo 		 */
6552a9ab775bSTejun Heo 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
6553a9ab775bSTejun Heo 		worker_flags |= WORKER_REBOUND;
6554a9ab775bSTejun Heo 		worker_flags &= ~WORKER_UNBOUND;
6555c95491edSMark Rutland 		WRITE_ONCE(worker->flags, worker_flags);
6556bd7c089eSTejun Heo 	}
6557a9ab775bSTejun Heo 
6558a9b8a985SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&pool->lock);
6559bd7c089eSTejun Heo }
6560bd7c089eSTejun Heo 
65617dbc725eSTejun Heo /**
65627dbc725eSTejun Heo  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
65637dbc725eSTejun Heo  * @pool: unbound pool of interest
65647dbc725eSTejun Heo  * @cpu: the CPU which is coming up
65657dbc725eSTejun Heo  *
65667dbc725eSTejun Heo  * An unbound pool may end up with a cpumask which doesn't have any online
65677dbc725eSTejun Heo  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
65687dbc725eSTejun Heo  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
65697dbc725eSTejun Heo  * online CPU before, cpus_allowed of all its workers should be restored.
65707dbc725eSTejun Heo  */
65717dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
65727dbc725eSTejun Heo {
65737dbc725eSTejun Heo 	static cpumask_t cpumask;
65747dbc725eSTejun Heo 	struct worker *worker;
65757dbc725eSTejun Heo 
65761258fae7STejun Heo 	lockdep_assert_held(&wq_pool_attach_mutex);
65777dbc725eSTejun Heo 
65787dbc725eSTejun Heo 	/* is @cpu allowed for @pool? */
65797dbc725eSTejun Heo 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
65807dbc725eSTejun Heo 		return;
65817dbc725eSTejun Heo 
65827dbc725eSTejun Heo 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
65837dbc725eSTejun Heo 
65847dbc725eSTejun Heo 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
6585da028469SLai Jiangshan 	for_each_pool_worker(worker, pool)
6586d945b5e9SPeter Zijlstra 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
65877dbc725eSTejun Heo }
65887dbc725eSTejun Heo 
65897ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
65901da177e4SLinus Torvalds {
65914ce62e9eSTejun Heo 	struct worker_pool *pool;
65921da177e4SLinus Torvalds 
6593f02ae73aSTejun Heo 	for_each_cpu_worker_pool(pool, cpu) {
65943ce63377STejun Heo 		if (pool->nr_workers)
65953ce63377STejun Heo 			continue;
6596051e1850SLai Jiangshan 		if (!create_worker(pool))
65977ee681b2SThomas Gleixner 			return -ENOMEM;
65983af24433SOleg Nesterov 	}
65997ee681b2SThomas Gleixner 	return 0;
66007ee681b2SThomas Gleixner }
66011da177e4SLinus Torvalds 
66027ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
66037ee681b2SThomas Gleixner {
66047ee681b2SThomas Gleixner 	struct worker_pool *pool;
66057ee681b2SThomas Gleixner 	struct workqueue_struct *wq;
66067ee681b2SThomas Gleixner 	int pi;
66077ee681b2SThomas Gleixner 
660868e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
66097dbc725eSTejun Heo 
66107dbc725eSTejun Heo 	for_each_pool(pool, pi) {
66114cb1ef64STejun Heo 		/* BH pools aren't affected by hotplug */
66124cb1ef64STejun Heo 		if (pool->flags & POOL_BH)
66134cb1ef64STejun Heo 			continue;
661494cf58bbSTejun Heo 
66154cb1ef64STejun Heo 		mutex_lock(&wq_pool_attach_mutex);
6616f05b558dSLai Jiangshan 		if (pool->cpu == cpu)
661794cf58bbSTejun Heo 			rebind_workers(pool);
6618f05b558dSLai Jiangshan 		else if (pool->cpu < 0)
66197dbc725eSTejun Heo 			restore_unbound_workers_cpumask(pool, cpu);
66201258fae7STejun Heo 		mutex_unlock(&wq_pool_attach_mutex);
662194cf58bbSTejun Heo 	}
66227dbc725eSTejun Heo 
6623fef59c9cSTejun Heo 	/* update pod affinity of unbound workqueues */
66244cbfd3deSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
662584193c07STejun Heo 		struct workqueue_attrs *attrs = wq->unbound_attrs;
662684193c07STejun Heo 
662784193c07STejun Heo 		if (attrs) {
662884193c07STejun Heo 			const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
66294cbfd3deSTejun Heo 			int tcpu;
66304cbfd3deSTejun Heo 
663184193c07STejun Heo 			for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
6632fef59c9cSTejun Heo 				wq_update_pod(wq, tcpu, cpu, true);
66335797b1c1STejun Heo 
66345797b1c1STejun Heo 			mutex_lock(&wq->mutex);
66355797b1c1STejun Heo 			wq_update_node_max_active(wq, -1);
66365797b1c1STejun Heo 			mutex_unlock(&wq->mutex);
66374cbfd3deSTejun Heo 		}
66384cbfd3deSTejun Heo 	}
66394c16bd32STejun Heo 
664068e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
66417ee681b2SThomas Gleixner 	return 0;
664265758202STejun Heo }
664365758202STejun Heo 
66447ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
664565758202STejun Heo {
66464c16bd32STejun Heo 	struct workqueue_struct *wq;
66478db25e78STejun Heo 
66484c16bd32STejun Heo 	/* unbinding per-cpu workers should happen on the local CPU */
6649e8b3f8dbSLai Jiangshan 	if (WARN_ON(cpu != smp_processor_id()))
6650e8b3f8dbSLai Jiangshan 		return -1;
6651e8b3f8dbSLai Jiangshan 
6652e8b3f8dbSLai Jiangshan 	unbind_workers(cpu);
66534c16bd32STejun Heo 
6654fef59c9cSTejun Heo 	/* update pod affinity of unbound workqueues */
66554c16bd32STejun Heo 	mutex_lock(&wq_pool_mutex);
66564cbfd3deSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
665784193c07STejun Heo 		struct workqueue_attrs *attrs = wq->unbound_attrs;
665884193c07STejun Heo 
665984193c07STejun Heo 		if (attrs) {
666084193c07STejun Heo 			const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
66614cbfd3deSTejun Heo 			int tcpu;
66624cbfd3deSTejun Heo 
666384193c07STejun Heo 			for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
6664fef59c9cSTejun Heo 				wq_update_pod(wq, tcpu, cpu, false);
66655797b1c1STejun Heo 
66665797b1c1STejun Heo 			mutex_lock(&wq->mutex);
66675797b1c1STejun Heo 			wq_update_node_max_active(wq, cpu);
66685797b1c1STejun Heo 			mutex_unlock(&wq->mutex);
66694cbfd3deSTejun Heo 		}
66704cbfd3deSTejun Heo 	}
66714c16bd32STejun Heo 	mutex_unlock(&wq_pool_mutex);
66724c16bd32STejun Heo 
66737ee681b2SThomas Gleixner 	return 0;
667465758202STejun Heo }
667565758202STejun Heo 
66762d3854a3SRusty Russell struct work_for_cpu {
6677ed48ece2STejun Heo 	struct work_struct work;
66782d3854a3SRusty Russell 	long (*fn)(void *);
66792d3854a3SRusty Russell 	void *arg;
66802d3854a3SRusty Russell 	long ret;
66812d3854a3SRusty Russell };
66822d3854a3SRusty Russell 
6683ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
66842d3854a3SRusty Russell {
6685ed48ece2STejun Heo 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
6686ed48ece2STejun Heo 
66872d3854a3SRusty Russell 	wfc->ret = wfc->fn(wfc->arg);
66882d3854a3SRusty Russell }
66892d3854a3SRusty Russell 
66902d3854a3SRusty Russell /**
6691265f3ed0SFrederic Weisbecker  * work_on_cpu_key - run a function in thread context on a particular cpu
66922d3854a3SRusty Russell  * @cpu: the cpu to run on
66932d3854a3SRusty Russell  * @fn: the function to run
66942d3854a3SRusty Russell  * @arg: the function arg
6695265f3ed0SFrederic Weisbecker  * @key: The lock class key for lock debugging purposes
66962d3854a3SRusty Russell  *
669731ad9081SRusty Russell  * It is up to the caller to ensure that the cpu doesn't go offline.
66986b44003eSAndrew Morton  * The caller must not hold any locks which would prevent @fn from completing.
6699d185af30SYacine Belkadi  *
6700d185af30SYacine Belkadi  * Return: The value @fn returns.
67012d3854a3SRusty Russell  */
6702265f3ed0SFrederic Weisbecker long work_on_cpu_key(int cpu, long (*fn)(void *),
6703265f3ed0SFrederic Weisbecker 		     void *arg, struct lock_class_key *key)
67042d3854a3SRusty Russell {
6705ed48ece2STejun Heo 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
67062d3854a3SRusty Russell 
6707265f3ed0SFrederic Weisbecker 	INIT_WORK_ONSTACK_KEY(&wfc.work, work_for_cpu_fn, key);
6708ed48ece2STejun Heo 	schedule_work_on(cpu, &wfc.work);
670912997d1aSBjorn Helgaas 	flush_work(&wfc.work);
6710440a1136SChuansheng Liu 	destroy_work_on_stack(&wfc.work);
67112d3854a3SRusty Russell 	return wfc.ret;
67122d3854a3SRusty Russell }
6713265f3ed0SFrederic Weisbecker EXPORT_SYMBOL_GPL(work_on_cpu_key);
67140e8d6a93SThomas Gleixner 
67150e8d6a93SThomas Gleixner /**
6716265f3ed0SFrederic Weisbecker  * work_on_cpu_safe_key - run a function in thread context on a particular cpu
67170e8d6a93SThomas Gleixner  * @cpu: the cpu to run on
67180e8d6a93SThomas Gleixner  * @fn:  the function to run
67190e8d6a93SThomas Gleixner  * @arg: the function argument
6720265f3ed0SFrederic Weisbecker  * @key: The lock class key for lock debugging purposes
67210e8d6a93SThomas Gleixner  *
67220e8d6a93SThomas Gleixner  * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
67230e8d6a93SThomas Gleixner  * any locks which would prevent @fn from completing.
67240e8d6a93SThomas Gleixner  *
67250e8d6a93SThomas Gleixner  * Return: The value @fn returns.
67260e8d6a93SThomas Gleixner  */
6727265f3ed0SFrederic Weisbecker long work_on_cpu_safe_key(int cpu, long (*fn)(void *),
6728265f3ed0SFrederic Weisbecker 			  void *arg, struct lock_class_key *key)
67290e8d6a93SThomas Gleixner {
67300e8d6a93SThomas Gleixner 	long ret = -ENODEV;
67310e8d6a93SThomas Gleixner 
6732ffd8bea8SSebastian Andrzej Siewior 	cpus_read_lock();
67330e8d6a93SThomas Gleixner 	if (cpu_online(cpu))
6734265f3ed0SFrederic Weisbecker 		ret = work_on_cpu_key(cpu, fn, arg, key);
6735ffd8bea8SSebastian Andrzej Siewior 	cpus_read_unlock();
67360e8d6a93SThomas Gleixner 	return ret;
67370e8d6a93SThomas Gleixner }
6738265f3ed0SFrederic Weisbecker EXPORT_SYMBOL_GPL(work_on_cpu_safe_key);
67392d3854a3SRusty Russell #endif /* CONFIG_SMP */
67402d3854a3SRusty Russell 
6741a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
6742e7577c50SRusty Russell 
6743a0a1a5fdSTejun Heo /**
6744a0a1a5fdSTejun Heo  * freeze_workqueues_begin - begin freezing workqueues
6745a0a1a5fdSTejun Heo  *
674658a69cb4STejun Heo  * Start freezing workqueues.  After this function returns, all freezable
6747f97a4a1aSLai Jiangshan  * workqueues will queue new works to their inactive_works list instead of
6748706026c2STejun Heo  * pool->worklist.
6749a0a1a5fdSTejun Heo  *
6750a0a1a5fdSTejun Heo  * CONTEXT:
6751a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
6752a0a1a5fdSTejun Heo  */
6753a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
6754a0a1a5fdSTejun Heo {
675524b8a847STejun Heo 	struct workqueue_struct *wq;
6756a0a1a5fdSTejun Heo 
675768e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
6758a0a1a5fdSTejun Heo 
67596183c009STejun Heo 	WARN_ON_ONCE(workqueue_freezing);
6760a0a1a5fdSTejun Heo 	workqueue_freezing = true;
6761a0a1a5fdSTejun Heo 
676224b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
6763a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
6764a045a272STejun Heo 		wq_adjust_max_active(wq);
6765a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
6766a1056305STejun Heo 	}
67675bcab335STejun Heo 
676868e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
6769a0a1a5fdSTejun Heo }
6770a0a1a5fdSTejun Heo 
6771a0a1a5fdSTejun Heo /**
677258a69cb4STejun Heo  * freeze_workqueues_busy - are freezable workqueues still busy?
6773a0a1a5fdSTejun Heo  *
6774a0a1a5fdSTejun Heo  * Check whether freezing is complete.  This function must be called
6775a0a1a5fdSTejun Heo  * between freeze_workqueues_begin() and thaw_workqueues().
6776a0a1a5fdSTejun Heo  *
6777a0a1a5fdSTejun Heo  * CONTEXT:
677868e13a67SLai Jiangshan  * Grabs and releases wq_pool_mutex.
6779a0a1a5fdSTejun Heo  *
6780d185af30SYacine Belkadi  * Return:
678158a69cb4STejun Heo  * %true if some freezable workqueues are still busy.  %false if freezing
678258a69cb4STejun Heo  * is complete.
6783a0a1a5fdSTejun Heo  */
6784a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
6785a0a1a5fdSTejun Heo {
6786a0a1a5fdSTejun Heo 	bool busy = false;
678724b8a847STejun Heo 	struct workqueue_struct *wq;
678824b8a847STejun Heo 	struct pool_workqueue *pwq;
6789a0a1a5fdSTejun Heo 
679068e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
6791a0a1a5fdSTejun Heo 
67926183c009STejun Heo 	WARN_ON_ONCE(!workqueue_freezing);
6793a0a1a5fdSTejun Heo 
679424b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
679524b8a847STejun Heo 		if (!(wq->flags & WQ_FREEZABLE))
679624b8a847STejun Heo 			continue;
6797a0a1a5fdSTejun Heo 		/*
6798a0a1a5fdSTejun Heo 		 * nr_active is monotonically decreasing.  It's safe
6799a0a1a5fdSTejun Heo 		 * to peek without lock.
6800a0a1a5fdSTejun Heo 		 */
680124acfb71SThomas Gleixner 		rcu_read_lock();
680224b8a847STejun Heo 		for_each_pwq(pwq, wq) {
68036183c009STejun Heo 			WARN_ON_ONCE(pwq->nr_active < 0);
6804112202d9STejun Heo 			if (pwq->nr_active) {
6805a0a1a5fdSTejun Heo 				busy = true;
680624acfb71SThomas Gleixner 				rcu_read_unlock();
6807a0a1a5fdSTejun Heo 				goto out_unlock;
6808a0a1a5fdSTejun Heo 			}
6809a0a1a5fdSTejun Heo 		}
681024acfb71SThomas Gleixner 		rcu_read_unlock();
6811a0a1a5fdSTejun Heo 	}
6812a0a1a5fdSTejun Heo out_unlock:
681368e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
6814a0a1a5fdSTejun Heo 	return busy;
6815a0a1a5fdSTejun Heo }
6816a0a1a5fdSTejun Heo 
6817a0a1a5fdSTejun Heo /**
6818a0a1a5fdSTejun Heo  * thaw_workqueues - thaw workqueues
6819a0a1a5fdSTejun Heo  *
6820a0a1a5fdSTejun Heo  * Thaw workqueues.  Normal queueing is restored and all collected
6821706026c2STejun Heo  * frozen works are transferred to their respective pool worklists.
6822a0a1a5fdSTejun Heo  *
6823a0a1a5fdSTejun Heo  * CONTEXT:
6824a357fc03SLai Jiangshan  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
6825a0a1a5fdSTejun Heo  */
6826a0a1a5fdSTejun Heo void thaw_workqueues(void)
6827a0a1a5fdSTejun Heo {
682824b8a847STejun Heo 	struct workqueue_struct *wq;
6829a0a1a5fdSTejun Heo 
683068e13a67SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
6831a0a1a5fdSTejun Heo 
6832a0a1a5fdSTejun Heo 	if (!workqueue_freezing)
6833a0a1a5fdSTejun Heo 		goto out_unlock;
6834a0a1a5fdSTejun Heo 
683574b414eaSLai Jiangshan 	workqueue_freezing = false;
683624b8a847STejun Heo 
683724b8a847STejun Heo 	/* restore max_active and repopulate worklist */
683824b8a847STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
6839a357fc03SLai Jiangshan 		mutex_lock(&wq->mutex);
6840a045a272STejun Heo 		wq_adjust_max_active(wq);
6841a357fc03SLai Jiangshan 		mutex_unlock(&wq->mutex);
684224b8a847STejun Heo 	}
684324b8a847STejun Heo 
6844a0a1a5fdSTejun Heo out_unlock:
684568e13a67SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
6846a0a1a5fdSTejun Heo }
6847a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
6848a0a1a5fdSTejun Heo 
684999c621efSLai Jiangshan static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
6850042f7df1SLai Jiangshan {
6851042f7df1SLai Jiangshan 	LIST_HEAD(ctxs);
6852042f7df1SLai Jiangshan 	int ret = 0;
6853042f7df1SLai Jiangshan 	struct workqueue_struct *wq;
6854042f7df1SLai Jiangshan 	struct apply_wqattrs_ctx *ctx, *n;
6855042f7df1SLai Jiangshan 
6856042f7df1SLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
6857042f7df1SLai Jiangshan 
6858042f7df1SLai Jiangshan 	list_for_each_entry(wq, &workqueues, list) {
68598eb17dc1SWaiman Long 		if (!(wq->flags & WQ_UNBOUND) || (wq->flags & __WQ_DESTROYING))
6860042f7df1SLai Jiangshan 			continue;
6861042f7df1SLai Jiangshan 
686299c621efSLai Jiangshan 		ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
686384193c07STejun Heo 		if (IS_ERR(ctx)) {
686484193c07STejun Heo 			ret = PTR_ERR(ctx);
6865042f7df1SLai Jiangshan 			break;
6866042f7df1SLai Jiangshan 		}
6867042f7df1SLai Jiangshan 
6868042f7df1SLai Jiangshan 		list_add_tail(&ctx->list, &ctxs);
6869042f7df1SLai Jiangshan 	}
6870042f7df1SLai Jiangshan 
6871042f7df1SLai Jiangshan 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
6872042f7df1SLai Jiangshan 		if (!ret)
6873042f7df1SLai Jiangshan 			apply_wqattrs_commit(ctx);
6874042f7df1SLai Jiangshan 		apply_wqattrs_cleanup(ctx);
6875042f7df1SLai Jiangshan 	}
6876042f7df1SLai Jiangshan 
687799c621efSLai Jiangshan 	if (!ret) {
687899c621efSLai Jiangshan 		mutex_lock(&wq_pool_attach_mutex);
687999c621efSLai Jiangshan 		cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
688099c621efSLai Jiangshan 		mutex_unlock(&wq_pool_attach_mutex);
688199c621efSLai Jiangshan 	}
6882042f7df1SLai Jiangshan 	return ret;
6883042f7df1SLai Jiangshan }
6884042f7df1SLai Jiangshan 
6885042f7df1SLai Jiangshan /**
6886fe28f631SWaiman Long  * workqueue_unbound_exclude_cpumask - Exclude given CPUs from unbound cpumask
6887fe28f631SWaiman Long  * @exclude_cpumask: the cpumask to be excluded from wq_unbound_cpumask
6888fe28f631SWaiman Long  *
6889fe28f631SWaiman Long  * This function can be called from cpuset code to provide a set of isolated
6890fe28f631SWaiman Long  * CPUs that should be excluded from wq_unbound_cpumask. The caller must hold
6891fe28f631SWaiman Long  * either cpus_read_lock or cpus_write_lock.
6892fe28f631SWaiman Long  */
6893fe28f631SWaiman Long int workqueue_unbound_exclude_cpumask(cpumask_var_t exclude_cpumask)
6894fe28f631SWaiman Long {
6895fe28f631SWaiman Long 	cpumask_var_t cpumask;
6896fe28f631SWaiman Long 	int ret = 0;
6897fe28f631SWaiman Long 
6898fe28f631SWaiman Long 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
6899fe28f631SWaiman Long 		return -ENOMEM;
6900fe28f631SWaiman Long 
6901fe28f631SWaiman Long 	lockdep_assert_cpus_held();
6902fe28f631SWaiman Long 	mutex_lock(&wq_pool_mutex);
6903fe28f631SWaiman Long 
6904fe28f631SWaiman Long 	/* Save the current isolated cpumask & export it via sysfs */
6905fe28f631SWaiman Long 	cpumask_copy(wq_isolated_cpumask, exclude_cpumask);
6906fe28f631SWaiman Long 
6907fe28f631SWaiman Long 	/*
6908fe28f631SWaiman Long 	 * If the operation fails, it will fall back to
6909fe28f631SWaiman Long 	 * wq_requested_unbound_cpumask which is initially set to
6910fe28f631SWaiman Long 	 * (HK_TYPE_WQ ∩ HK_TYPE_DOMAIN) house keeping mask and rewritten
6911fe28f631SWaiman Long 	 * by any subsequent write to workqueue/cpumask sysfs file.
6912fe28f631SWaiman Long 	 */
6913fe28f631SWaiman Long 	if (!cpumask_andnot(cpumask, wq_requested_unbound_cpumask, exclude_cpumask))
6914fe28f631SWaiman Long 		cpumask_copy(cpumask, wq_requested_unbound_cpumask);
6915fe28f631SWaiman Long 	if (!cpumask_equal(cpumask, wq_unbound_cpumask))
6916fe28f631SWaiman Long 		ret = workqueue_apply_unbound_cpumask(cpumask);
6917fe28f631SWaiman Long 
6918fe28f631SWaiman Long 	mutex_unlock(&wq_pool_mutex);
6919fe28f631SWaiman Long 	free_cpumask_var(cpumask);
6920fe28f631SWaiman Long 	return ret;
6921fe28f631SWaiman Long }
6922fe28f631SWaiman Long 
692363c5484eSTejun Heo static int parse_affn_scope(const char *val)
692463c5484eSTejun Heo {
692563c5484eSTejun Heo 	int i;
692663c5484eSTejun Heo 
692763c5484eSTejun Heo 	for (i = 0; i < ARRAY_SIZE(wq_affn_names); i++) {
692863c5484eSTejun Heo 		if (!strncasecmp(val, wq_affn_names[i], strlen(wq_affn_names[i])))
692963c5484eSTejun Heo 			return i;
693063c5484eSTejun Heo 	}
693163c5484eSTejun Heo 	return -EINVAL;
693263c5484eSTejun Heo }
693363c5484eSTejun Heo 
693463c5484eSTejun Heo static int wq_affn_dfl_set(const char *val, const struct kernel_param *kp)
693563c5484eSTejun Heo {
6936523a301eSTejun Heo 	struct workqueue_struct *wq;
6937523a301eSTejun Heo 	int affn, cpu;
693863c5484eSTejun Heo 
693963c5484eSTejun Heo 	affn = parse_affn_scope(val);
694063c5484eSTejun Heo 	if (affn < 0)
694163c5484eSTejun Heo 		return affn;
6942523a301eSTejun Heo 	if (affn == WQ_AFFN_DFL)
6943523a301eSTejun Heo 		return -EINVAL;
6944523a301eSTejun Heo 
6945523a301eSTejun Heo 	cpus_read_lock();
6946523a301eSTejun Heo 	mutex_lock(&wq_pool_mutex);
694763c5484eSTejun Heo 
694863c5484eSTejun Heo 	wq_affn_dfl = affn;
6949523a301eSTejun Heo 
6950523a301eSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
6951523a301eSTejun Heo 		for_each_online_cpu(cpu) {
6952523a301eSTejun Heo 			wq_update_pod(wq, cpu, cpu, true);
6953523a301eSTejun Heo 		}
6954523a301eSTejun Heo 	}
6955523a301eSTejun Heo 
6956523a301eSTejun Heo 	mutex_unlock(&wq_pool_mutex);
6957523a301eSTejun Heo 	cpus_read_unlock();
6958523a301eSTejun Heo 
695963c5484eSTejun Heo 	return 0;
696063c5484eSTejun Heo }
696163c5484eSTejun Heo 
696263c5484eSTejun Heo static int wq_affn_dfl_get(char *buffer, const struct kernel_param *kp)
696363c5484eSTejun Heo {
696463c5484eSTejun Heo 	return scnprintf(buffer, PAGE_SIZE, "%s\n", wq_affn_names[wq_affn_dfl]);
696563c5484eSTejun Heo }
696663c5484eSTejun Heo 
696763c5484eSTejun Heo static const struct kernel_param_ops wq_affn_dfl_ops = {
696863c5484eSTejun Heo 	.set	= wq_affn_dfl_set,
696963c5484eSTejun Heo 	.get	= wq_affn_dfl_get,
697063c5484eSTejun Heo };
697163c5484eSTejun Heo 
697263c5484eSTejun Heo module_param_cb(default_affinity_scope, &wq_affn_dfl_ops, NULL, 0644);
697363c5484eSTejun Heo 
69746ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
69756ba94429SFrederic Weisbecker /*
69766ba94429SFrederic Weisbecker  * Workqueues with WQ_SYSFS flag set is visible to userland via
69776ba94429SFrederic Weisbecker  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
69786ba94429SFrederic Weisbecker  * following attributes.
69796ba94429SFrederic Weisbecker  *
69806ba94429SFrederic Weisbecker  *  per_cpu		RO bool	: whether the workqueue is per-cpu or unbound
69816ba94429SFrederic Weisbecker  *  max_active		RW int	: maximum number of in-flight work items
69826ba94429SFrederic Weisbecker  *
69836ba94429SFrederic Weisbecker  * Unbound workqueues have the following extra attributes.
69846ba94429SFrederic Weisbecker  *
69856ba94429SFrederic Weisbecker  *  nice		RW int	: nice value of the workers
69866ba94429SFrederic Weisbecker  *  cpumask		RW mask	: bitmask of allowed CPUs for the workers
698763c5484eSTejun Heo  *  affinity_scope	RW str  : worker CPU affinity scope (cache, numa, none)
69888639ecebSTejun Heo  *  affinity_strict	RW bool : worker CPU affinity is strict
69896ba94429SFrederic Weisbecker  */
69906ba94429SFrederic Weisbecker struct wq_device {
69916ba94429SFrederic Weisbecker 	struct workqueue_struct		*wq;
69926ba94429SFrederic Weisbecker 	struct device			dev;
69936ba94429SFrederic Weisbecker };
69946ba94429SFrederic Weisbecker 
69956ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
69966ba94429SFrederic Weisbecker {
69976ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
69986ba94429SFrederic Weisbecker 
69996ba94429SFrederic Weisbecker 	return wq_dev->wq;
70006ba94429SFrederic Weisbecker }
70016ba94429SFrederic Weisbecker 
70026ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
70036ba94429SFrederic Weisbecker 			    char *buf)
70046ba94429SFrederic Weisbecker {
70056ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
70066ba94429SFrederic Weisbecker 
70076ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
70086ba94429SFrederic Weisbecker }
70096ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
70106ba94429SFrederic Weisbecker 
70116ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
70126ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
70136ba94429SFrederic Weisbecker {
70146ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
70156ba94429SFrederic Weisbecker 
70166ba94429SFrederic Weisbecker 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
70176ba94429SFrederic Weisbecker }
70186ba94429SFrederic Weisbecker 
70196ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
70206ba94429SFrederic Weisbecker 				struct device_attribute *attr, const char *buf,
70216ba94429SFrederic Weisbecker 				size_t count)
70226ba94429SFrederic Weisbecker {
70236ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
70246ba94429SFrederic Weisbecker 	int val;
70256ba94429SFrederic Weisbecker 
70266ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
70276ba94429SFrederic Weisbecker 		return -EINVAL;
70286ba94429SFrederic Weisbecker 
70296ba94429SFrederic Weisbecker 	workqueue_set_max_active(wq, val);
70306ba94429SFrederic Weisbecker 	return count;
70316ba94429SFrederic Weisbecker }
70326ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
70336ba94429SFrederic Weisbecker 
70346ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
70356ba94429SFrederic Weisbecker 	&dev_attr_per_cpu.attr,
70366ba94429SFrederic Weisbecker 	&dev_attr_max_active.attr,
70376ba94429SFrederic Weisbecker 	NULL,
70386ba94429SFrederic Weisbecker };
70396ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
70406ba94429SFrederic Weisbecker 
704149277a5bSWaiman Long static void apply_wqattrs_lock(void)
704249277a5bSWaiman Long {
704349277a5bSWaiman Long 	/* CPUs should stay stable across pwq creations and installations */
704449277a5bSWaiman Long 	cpus_read_lock();
704549277a5bSWaiman Long 	mutex_lock(&wq_pool_mutex);
704649277a5bSWaiman Long }
704749277a5bSWaiman Long 
704849277a5bSWaiman Long static void apply_wqattrs_unlock(void)
704949277a5bSWaiman Long {
705049277a5bSWaiman Long 	mutex_unlock(&wq_pool_mutex);
705149277a5bSWaiman Long 	cpus_read_unlock();
705249277a5bSWaiman Long }
705349277a5bSWaiman Long 
70546ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
70556ba94429SFrederic Weisbecker 			    char *buf)
70566ba94429SFrederic Weisbecker {
70576ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
70586ba94429SFrederic Weisbecker 	int written;
70596ba94429SFrederic Weisbecker 
70606ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
70616ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
70626ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
70636ba94429SFrederic Weisbecker 
70646ba94429SFrederic Weisbecker 	return written;
70656ba94429SFrederic Weisbecker }
70666ba94429SFrederic Weisbecker 
70676ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
70686ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
70696ba94429SFrederic Weisbecker {
70706ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
70716ba94429SFrederic Weisbecker 
7072899a94feSLai Jiangshan 	lockdep_assert_held(&wq_pool_mutex);
7073899a94feSLai Jiangshan 
7074be69d00dSThomas Gleixner 	attrs = alloc_workqueue_attrs();
70756ba94429SFrederic Weisbecker 	if (!attrs)
70766ba94429SFrederic Weisbecker 		return NULL;
70776ba94429SFrederic Weisbecker 
70786ba94429SFrederic Weisbecker 	copy_workqueue_attrs(attrs, wq->unbound_attrs);
70796ba94429SFrederic Weisbecker 	return attrs;
70806ba94429SFrederic Weisbecker }
70816ba94429SFrederic Weisbecker 
70826ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
70836ba94429SFrederic Weisbecker 			     const char *buf, size_t count)
70846ba94429SFrederic Weisbecker {
70856ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
70866ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
7087d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
7088d4d3e257SLai Jiangshan 
7089d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
70906ba94429SFrederic Weisbecker 
70916ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
70926ba94429SFrederic Weisbecker 	if (!attrs)
7093d4d3e257SLai Jiangshan 		goto out_unlock;
70946ba94429SFrederic Weisbecker 
70956ba94429SFrederic Weisbecker 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
70966ba94429SFrederic Weisbecker 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
7097d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
70986ba94429SFrederic Weisbecker 	else
70996ba94429SFrederic Weisbecker 		ret = -EINVAL;
71006ba94429SFrederic Weisbecker 
7101d4d3e257SLai Jiangshan out_unlock:
7102d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
71036ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
71046ba94429SFrederic Weisbecker 	return ret ?: count;
71056ba94429SFrederic Weisbecker }
71066ba94429SFrederic Weisbecker 
71076ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
71086ba94429SFrederic Weisbecker 			       struct device_attribute *attr, char *buf)
71096ba94429SFrederic Weisbecker {
71106ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
71116ba94429SFrederic Weisbecker 	int written;
71126ba94429SFrederic Weisbecker 
71136ba94429SFrederic Weisbecker 	mutex_lock(&wq->mutex);
71146ba94429SFrederic Weisbecker 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
71156ba94429SFrederic Weisbecker 			    cpumask_pr_args(wq->unbound_attrs->cpumask));
71166ba94429SFrederic Weisbecker 	mutex_unlock(&wq->mutex);
71176ba94429SFrederic Weisbecker 	return written;
71186ba94429SFrederic Weisbecker }
71196ba94429SFrederic Weisbecker 
71206ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
71216ba94429SFrederic Weisbecker 				struct device_attribute *attr,
71226ba94429SFrederic Weisbecker 				const char *buf, size_t count)
71236ba94429SFrederic Weisbecker {
71246ba94429SFrederic Weisbecker 	struct workqueue_struct *wq = dev_to_wq(dev);
71256ba94429SFrederic Weisbecker 	struct workqueue_attrs *attrs;
7126d4d3e257SLai Jiangshan 	int ret = -ENOMEM;
7127d4d3e257SLai Jiangshan 
7128d4d3e257SLai Jiangshan 	apply_wqattrs_lock();
71296ba94429SFrederic Weisbecker 
71306ba94429SFrederic Weisbecker 	attrs = wq_sysfs_prep_attrs(wq);
71316ba94429SFrederic Weisbecker 	if (!attrs)
7132d4d3e257SLai Jiangshan 		goto out_unlock;
71336ba94429SFrederic Weisbecker 
71346ba94429SFrederic Weisbecker 	ret = cpumask_parse(buf, attrs->cpumask);
71356ba94429SFrederic Weisbecker 	if (!ret)
7136d4d3e257SLai Jiangshan 		ret = apply_workqueue_attrs_locked(wq, attrs);
71376ba94429SFrederic Weisbecker 
7138d4d3e257SLai Jiangshan out_unlock:
7139d4d3e257SLai Jiangshan 	apply_wqattrs_unlock();
71406ba94429SFrederic Weisbecker 	free_workqueue_attrs(attrs);
71416ba94429SFrederic Weisbecker 	return ret ?: count;
71426ba94429SFrederic Weisbecker }
71436ba94429SFrederic Weisbecker 
714463c5484eSTejun Heo static ssize_t wq_affn_scope_show(struct device *dev,
714563c5484eSTejun Heo 				  struct device_attribute *attr, char *buf)
714663c5484eSTejun Heo {
714763c5484eSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
714863c5484eSTejun Heo 	int written;
714963c5484eSTejun Heo 
715063c5484eSTejun Heo 	mutex_lock(&wq->mutex);
7151523a301eSTejun Heo 	if (wq->unbound_attrs->affn_scope == WQ_AFFN_DFL)
7152523a301eSTejun Heo 		written = scnprintf(buf, PAGE_SIZE, "%s (%s)\n",
7153523a301eSTejun Heo 				    wq_affn_names[WQ_AFFN_DFL],
7154523a301eSTejun Heo 				    wq_affn_names[wq_affn_dfl]);
7155523a301eSTejun Heo 	else
715663c5484eSTejun Heo 		written = scnprintf(buf, PAGE_SIZE, "%s\n",
715763c5484eSTejun Heo 				    wq_affn_names[wq->unbound_attrs->affn_scope]);
715863c5484eSTejun Heo 	mutex_unlock(&wq->mutex);
715963c5484eSTejun Heo 
716063c5484eSTejun Heo 	return written;
716163c5484eSTejun Heo }
716263c5484eSTejun Heo 
716363c5484eSTejun Heo static ssize_t wq_affn_scope_store(struct device *dev,
716463c5484eSTejun Heo 				   struct device_attribute *attr,
716563c5484eSTejun Heo 				   const char *buf, size_t count)
716663c5484eSTejun Heo {
716763c5484eSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
716863c5484eSTejun Heo 	struct workqueue_attrs *attrs;
716963c5484eSTejun Heo 	int affn, ret = -ENOMEM;
717063c5484eSTejun Heo 
717163c5484eSTejun Heo 	affn = parse_affn_scope(buf);
717263c5484eSTejun Heo 	if (affn < 0)
717363c5484eSTejun Heo 		return affn;
717463c5484eSTejun Heo 
717563c5484eSTejun Heo 	apply_wqattrs_lock();
717663c5484eSTejun Heo 	attrs = wq_sysfs_prep_attrs(wq);
717763c5484eSTejun Heo 	if (attrs) {
717863c5484eSTejun Heo 		attrs->affn_scope = affn;
717963c5484eSTejun Heo 		ret = apply_workqueue_attrs_locked(wq, attrs);
718063c5484eSTejun Heo 	}
718163c5484eSTejun Heo 	apply_wqattrs_unlock();
718263c5484eSTejun Heo 	free_workqueue_attrs(attrs);
718363c5484eSTejun Heo 	return ret ?: count;
718463c5484eSTejun Heo }
718563c5484eSTejun Heo 
71868639ecebSTejun Heo static ssize_t wq_affinity_strict_show(struct device *dev,
71878639ecebSTejun Heo 				       struct device_attribute *attr, char *buf)
71888639ecebSTejun Heo {
71898639ecebSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
71908639ecebSTejun Heo 
71918639ecebSTejun Heo 	return scnprintf(buf, PAGE_SIZE, "%d\n",
71928639ecebSTejun Heo 			 wq->unbound_attrs->affn_strict);
71938639ecebSTejun Heo }
71948639ecebSTejun Heo 
71958639ecebSTejun Heo static ssize_t wq_affinity_strict_store(struct device *dev,
71968639ecebSTejun Heo 					struct device_attribute *attr,
71978639ecebSTejun Heo 					const char *buf, size_t count)
71988639ecebSTejun Heo {
71998639ecebSTejun Heo 	struct workqueue_struct *wq = dev_to_wq(dev);
72008639ecebSTejun Heo 	struct workqueue_attrs *attrs;
72018639ecebSTejun Heo 	int v, ret = -ENOMEM;
72028639ecebSTejun Heo 
72038639ecebSTejun Heo 	if (sscanf(buf, "%d", &v) != 1)
72048639ecebSTejun Heo 		return -EINVAL;
72058639ecebSTejun Heo 
72068639ecebSTejun Heo 	apply_wqattrs_lock();
72078639ecebSTejun Heo 	attrs = wq_sysfs_prep_attrs(wq);
72088639ecebSTejun Heo 	if (attrs) {
72098639ecebSTejun Heo 		attrs->affn_strict = (bool)v;
72108639ecebSTejun Heo 		ret = apply_workqueue_attrs_locked(wq, attrs);
72118639ecebSTejun Heo 	}
72128639ecebSTejun Heo 	apply_wqattrs_unlock();
72138639ecebSTejun Heo 	free_workqueue_attrs(attrs);
72148639ecebSTejun Heo 	return ret ?: count;
72158639ecebSTejun Heo }
72168639ecebSTejun Heo 
72176ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
72186ba94429SFrederic Weisbecker 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
72196ba94429SFrederic Weisbecker 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
722063c5484eSTejun Heo 	__ATTR(affinity_scope, 0644, wq_affn_scope_show, wq_affn_scope_store),
72218639ecebSTejun Heo 	__ATTR(affinity_strict, 0644, wq_affinity_strict_show, wq_affinity_strict_store),
72226ba94429SFrederic Weisbecker 	__ATTR_NULL,
72236ba94429SFrederic Weisbecker };
72246ba94429SFrederic Weisbecker 
72255df9197eSRicardo B. Marliere static const struct bus_type wq_subsys = {
72266ba94429SFrederic Weisbecker 	.name				= "workqueue",
72276ba94429SFrederic Weisbecker 	.dev_groups			= wq_sysfs_groups,
72286ba94429SFrederic Weisbecker };
72296ba94429SFrederic Weisbecker 
723049277a5bSWaiman Long /**
723149277a5bSWaiman Long  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
723249277a5bSWaiman Long  *  @cpumask: the cpumask to set
723349277a5bSWaiman Long  *
723449277a5bSWaiman Long  *  The low-level workqueues cpumask is a global cpumask that limits
723549277a5bSWaiman Long  *  the affinity of all unbound workqueues.  This function check the @cpumask
723649277a5bSWaiman Long  *  and apply it to all unbound workqueues and updates all pwqs of them.
723749277a5bSWaiman Long  *
723849277a5bSWaiman Long  *  Return:	0	- Success
723949277a5bSWaiman Long  *		-EINVAL	- Invalid @cpumask
724049277a5bSWaiman Long  *		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
724149277a5bSWaiman Long  */
724249277a5bSWaiman Long static int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
724349277a5bSWaiman Long {
724449277a5bSWaiman Long 	int ret = -EINVAL;
724549277a5bSWaiman Long 
724649277a5bSWaiman Long 	/*
724749277a5bSWaiman Long 	 * Not excluding isolated cpus on purpose.
724849277a5bSWaiman Long 	 * If the user wishes to include them, we allow that.
724949277a5bSWaiman Long 	 */
725049277a5bSWaiman Long 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
725149277a5bSWaiman Long 	if (!cpumask_empty(cpumask)) {
725249277a5bSWaiman Long 		apply_wqattrs_lock();
725349277a5bSWaiman Long 		cpumask_copy(wq_requested_unbound_cpumask, cpumask);
725449277a5bSWaiman Long 		if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
725549277a5bSWaiman Long 			ret = 0;
725649277a5bSWaiman Long 			goto out_unlock;
725749277a5bSWaiman Long 		}
725849277a5bSWaiman Long 
725949277a5bSWaiman Long 		ret = workqueue_apply_unbound_cpumask(cpumask);
726049277a5bSWaiman Long 
726149277a5bSWaiman Long out_unlock:
726249277a5bSWaiman Long 		apply_wqattrs_unlock();
726349277a5bSWaiman Long 	}
726449277a5bSWaiman Long 
726549277a5bSWaiman Long 	return ret;
726649277a5bSWaiman Long }
726749277a5bSWaiman Long 
7268fe28f631SWaiman Long static ssize_t __wq_cpumask_show(struct device *dev,
7269fe28f631SWaiman Long 		struct device_attribute *attr, char *buf, cpumask_var_t mask)
7270b05a7928SFrederic Weisbecker {
7271b05a7928SFrederic Weisbecker 	int written;
7272b05a7928SFrederic Weisbecker 
7273042f7df1SLai Jiangshan 	mutex_lock(&wq_pool_mutex);
7274fe28f631SWaiman Long 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n", cpumask_pr_args(mask));
7275042f7df1SLai Jiangshan 	mutex_unlock(&wq_pool_mutex);
7276b05a7928SFrederic Weisbecker 
7277b05a7928SFrederic Weisbecker 	return written;
7278b05a7928SFrederic Weisbecker }
7279b05a7928SFrederic Weisbecker 
728079202591SDan Williams static ssize_t cpumask_requested_show(struct device *dev,
728179202591SDan Williams 		struct device_attribute *attr, char *buf)
728279202591SDan Williams {
728379202591SDan Williams 	return __wq_cpumask_show(dev, attr, buf, wq_requested_unbound_cpumask);
728479202591SDan Williams }
728579202591SDan Williams static DEVICE_ATTR_RO(cpumask_requested);
728679202591SDan Williams 
728779202591SDan Williams static ssize_t cpumask_isolated_show(struct device *dev,
728879202591SDan Williams 		struct device_attribute *attr, char *buf)
728979202591SDan Williams {
729079202591SDan Williams 	return __wq_cpumask_show(dev, attr, buf, wq_isolated_cpumask);
729179202591SDan Williams }
729279202591SDan Williams static DEVICE_ATTR_RO(cpumask_isolated);
729379202591SDan Williams 
729479202591SDan Williams static ssize_t cpumask_show(struct device *dev,
7295fe28f631SWaiman Long 		struct device_attribute *attr, char *buf)
7296fe28f631SWaiman Long {
7297fe28f631SWaiman Long 	return __wq_cpumask_show(dev, attr, buf, wq_unbound_cpumask);
7298fe28f631SWaiman Long }
7299fe28f631SWaiman Long 
730079202591SDan Williams static ssize_t cpumask_store(struct device *dev,
7301042f7df1SLai Jiangshan 		struct device_attribute *attr, const char *buf, size_t count)
7302042f7df1SLai Jiangshan {
7303042f7df1SLai Jiangshan 	cpumask_var_t cpumask;
7304042f7df1SLai Jiangshan 	int ret;
7305042f7df1SLai Jiangshan 
7306042f7df1SLai Jiangshan 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
7307042f7df1SLai Jiangshan 		return -ENOMEM;
7308042f7df1SLai Jiangshan 
7309042f7df1SLai Jiangshan 	ret = cpumask_parse(buf, cpumask);
7310042f7df1SLai Jiangshan 	if (!ret)
7311042f7df1SLai Jiangshan 		ret = workqueue_set_unbound_cpumask(cpumask);
7312042f7df1SLai Jiangshan 
7313042f7df1SLai Jiangshan 	free_cpumask_var(cpumask);
7314042f7df1SLai Jiangshan 	return ret ? ret : count;
7315042f7df1SLai Jiangshan }
731679202591SDan Williams static DEVICE_ATTR_RW(cpumask);
7317042f7df1SLai Jiangshan 
731879202591SDan Williams static struct attribute *wq_sysfs_cpumask_attrs[] = {
731979202591SDan Williams 	&dev_attr_cpumask.attr,
732079202591SDan Williams 	&dev_attr_cpumask_requested.attr,
732179202591SDan Williams 	&dev_attr_cpumask_isolated.attr,
732279202591SDan Williams 	NULL,
7323fe28f631SWaiman Long };
732479202591SDan Williams ATTRIBUTE_GROUPS(wq_sysfs_cpumask);
7325b05a7928SFrederic Weisbecker 
73266ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
73276ba94429SFrederic Weisbecker {
732879202591SDan Williams 	return subsys_virtual_register(&wq_subsys, wq_sysfs_cpumask_groups);
73296ba94429SFrederic Weisbecker }
73306ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
73316ba94429SFrederic Weisbecker 
73326ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
73336ba94429SFrederic Weisbecker {
73346ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
73356ba94429SFrederic Weisbecker 
73366ba94429SFrederic Weisbecker 	kfree(wq_dev);
73376ba94429SFrederic Weisbecker }
73386ba94429SFrederic Weisbecker 
73396ba94429SFrederic Weisbecker /**
73406ba94429SFrederic Weisbecker  * workqueue_sysfs_register - make a workqueue visible in sysfs
73416ba94429SFrederic Weisbecker  * @wq: the workqueue to register
73426ba94429SFrederic Weisbecker  *
73436ba94429SFrederic Weisbecker  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
73446ba94429SFrederic Weisbecker  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
73456ba94429SFrederic Weisbecker  * which is the preferred method.
73466ba94429SFrederic Weisbecker  *
73476ba94429SFrederic Weisbecker  * Workqueue user should use this function directly iff it wants to apply
73486ba94429SFrederic Weisbecker  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
73496ba94429SFrederic Weisbecker  * apply_workqueue_attrs() may race against userland updating the
73506ba94429SFrederic Weisbecker  * attributes.
73516ba94429SFrederic Weisbecker  *
73526ba94429SFrederic Weisbecker  * Return: 0 on success, -errno on failure.
73536ba94429SFrederic Weisbecker  */
73546ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
73556ba94429SFrederic Weisbecker {
73566ba94429SFrederic Weisbecker 	struct wq_device *wq_dev;
73576ba94429SFrederic Weisbecker 	int ret;
73586ba94429SFrederic Weisbecker 
73596ba94429SFrederic Weisbecker 	/*
73604c065dbcSWaiman Long 	 * Adjusting max_active breaks ordering guarantee.  Disallow exposing
73614c065dbcSWaiman Long 	 * ordered workqueues.
73626ba94429SFrederic Weisbecker 	 */
73633bc1e711STejun Heo 	if (WARN_ON(wq->flags & __WQ_ORDERED))
73646ba94429SFrederic Weisbecker 		return -EINVAL;
73656ba94429SFrederic Weisbecker 
73666ba94429SFrederic Weisbecker 	wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
73676ba94429SFrederic Weisbecker 	if (!wq_dev)
73686ba94429SFrederic Weisbecker 		return -ENOMEM;
73696ba94429SFrederic Weisbecker 
73706ba94429SFrederic Weisbecker 	wq_dev->wq = wq;
73716ba94429SFrederic Weisbecker 	wq_dev->dev.bus = &wq_subsys;
73726ba94429SFrederic Weisbecker 	wq_dev->dev.release = wq_device_release;
737323217b44SLars-Peter Clausen 	dev_set_name(&wq_dev->dev, "%s", wq->name);
73746ba94429SFrederic Weisbecker 
73756ba94429SFrederic Weisbecker 	/*
73766ba94429SFrederic Weisbecker 	 * unbound_attrs are created separately.  Suppress uevent until
73776ba94429SFrederic Weisbecker 	 * everything is ready.
73786ba94429SFrederic Weisbecker 	 */
73796ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, true);
73806ba94429SFrederic Weisbecker 
73816ba94429SFrederic Weisbecker 	ret = device_register(&wq_dev->dev);
73826ba94429SFrederic Weisbecker 	if (ret) {
7383537f4146SArvind Yadav 		put_device(&wq_dev->dev);
73846ba94429SFrederic Weisbecker 		wq->wq_dev = NULL;
73856ba94429SFrederic Weisbecker 		return ret;
73866ba94429SFrederic Weisbecker 	}
73876ba94429SFrederic Weisbecker 
73886ba94429SFrederic Weisbecker 	if (wq->flags & WQ_UNBOUND) {
73896ba94429SFrederic Weisbecker 		struct device_attribute *attr;
73906ba94429SFrederic Weisbecker 
73916ba94429SFrederic Weisbecker 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
73926ba94429SFrederic Weisbecker 			ret = device_create_file(&wq_dev->dev, attr);
73936ba94429SFrederic Weisbecker 			if (ret) {
73946ba94429SFrederic Weisbecker 				device_unregister(&wq_dev->dev);
73956ba94429SFrederic Weisbecker 				wq->wq_dev = NULL;
73966ba94429SFrederic Weisbecker 				return ret;
73976ba94429SFrederic Weisbecker 			}
73986ba94429SFrederic Weisbecker 		}
73996ba94429SFrederic Weisbecker 	}
74006ba94429SFrederic Weisbecker 
74016ba94429SFrederic Weisbecker 	dev_set_uevent_suppress(&wq_dev->dev, false);
74026ba94429SFrederic Weisbecker 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
74036ba94429SFrederic Weisbecker 	return 0;
74046ba94429SFrederic Weisbecker }
74056ba94429SFrederic Weisbecker 
74066ba94429SFrederic Weisbecker /**
74076ba94429SFrederic Weisbecker  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
74086ba94429SFrederic Weisbecker  * @wq: the workqueue to unregister
74096ba94429SFrederic Weisbecker  *
74106ba94429SFrederic Weisbecker  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
74116ba94429SFrederic Weisbecker  */
74126ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
74136ba94429SFrederic Weisbecker {
74146ba94429SFrederic Weisbecker 	struct wq_device *wq_dev = wq->wq_dev;
74156ba94429SFrederic Weisbecker 
74166ba94429SFrederic Weisbecker 	if (!wq->wq_dev)
74176ba94429SFrederic Weisbecker 		return;
74186ba94429SFrederic Weisbecker 
74196ba94429SFrederic Weisbecker 	wq->wq_dev = NULL;
74206ba94429SFrederic Weisbecker 	device_unregister(&wq_dev->dev);
74216ba94429SFrederic Weisbecker }
74226ba94429SFrederic Weisbecker #else	/* CONFIG_SYSFS */
74236ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
74246ba94429SFrederic Weisbecker #endif	/* CONFIG_SYSFS */
74256ba94429SFrederic Weisbecker 
742682607adcSTejun Heo /*
742782607adcSTejun Heo  * Workqueue watchdog.
742882607adcSTejun Heo  *
742982607adcSTejun Heo  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
743082607adcSTejun Heo  * flush dependency, a concurrency managed work item which stays RUNNING
743182607adcSTejun Heo  * indefinitely.  Workqueue stalls can be very difficult to debug as the
743282607adcSTejun Heo  * usual warning mechanisms don't trigger and internal workqueue state is
743382607adcSTejun Heo  * largely opaque.
743482607adcSTejun Heo  *
743582607adcSTejun Heo  * Workqueue watchdog monitors all worker pools periodically and dumps
743682607adcSTejun Heo  * state if some pools failed to make forward progress for a while where
743782607adcSTejun Heo  * forward progress is defined as the first item on ->worklist changing.
743882607adcSTejun Heo  *
743982607adcSTejun Heo  * This mechanism is controlled through the kernel parameter
744082607adcSTejun Heo  * "workqueue.watchdog_thresh" which can be updated at runtime through the
744182607adcSTejun Heo  * corresponding sysfs parameter file.
744282607adcSTejun Heo  */
744382607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
744482607adcSTejun Heo 
744582607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
74465cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
744782607adcSTejun Heo 
744882607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
744982607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
745082607adcSTejun Heo 
7451cd2440d6SPetr Mladek /*
7452cd2440d6SPetr Mladek  * Show workers that might prevent the processing of pending work items.
7453cd2440d6SPetr Mladek  * The only candidates are CPU-bound workers in the running state.
7454cd2440d6SPetr Mladek  * Pending work items should be handled by another idle worker
7455cd2440d6SPetr Mladek  * in all other situations.
7456cd2440d6SPetr Mladek  */
7457cd2440d6SPetr Mladek static void show_cpu_pool_hog(struct worker_pool *pool)
7458cd2440d6SPetr Mladek {
7459cd2440d6SPetr Mladek 	struct worker *worker;
7460c26e2f2eSTejun Heo 	unsigned long irq_flags;
7461cd2440d6SPetr Mladek 	int bkt;
7462cd2440d6SPetr Mladek 
7463c26e2f2eSTejun Heo 	raw_spin_lock_irqsave(&pool->lock, irq_flags);
7464cd2440d6SPetr Mladek 
7465cd2440d6SPetr Mladek 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
7466cd2440d6SPetr Mladek 		if (task_is_running(worker->task)) {
7467cd2440d6SPetr Mladek 			/*
7468cd2440d6SPetr Mladek 			 * Defer printing to avoid deadlocks in console
7469cd2440d6SPetr Mladek 			 * drivers that queue work while holding locks
7470cd2440d6SPetr Mladek 			 * also taken in their write paths.
7471cd2440d6SPetr Mladek 			 */
7472cd2440d6SPetr Mladek 			printk_deferred_enter();
7473cd2440d6SPetr Mladek 
7474cd2440d6SPetr Mladek 			pr_info("pool %d:\n", pool->id);
7475cd2440d6SPetr Mladek 			sched_show_task(worker->task);
7476cd2440d6SPetr Mladek 
7477cd2440d6SPetr Mladek 			printk_deferred_exit();
7478cd2440d6SPetr Mladek 		}
7479cd2440d6SPetr Mladek 	}
7480cd2440d6SPetr Mladek 
7481c26e2f2eSTejun Heo 	raw_spin_unlock_irqrestore(&pool->lock, irq_flags);
7482cd2440d6SPetr Mladek }
7483cd2440d6SPetr Mladek 
7484cd2440d6SPetr Mladek static void show_cpu_pools_hogs(void)
7485cd2440d6SPetr Mladek {
7486cd2440d6SPetr Mladek 	struct worker_pool *pool;
7487cd2440d6SPetr Mladek 	int pi;
7488cd2440d6SPetr Mladek 
7489cd2440d6SPetr Mladek 	pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
7490cd2440d6SPetr Mladek 
7491cd2440d6SPetr Mladek 	rcu_read_lock();
7492cd2440d6SPetr Mladek 
7493cd2440d6SPetr Mladek 	for_each_pool(pool, pi) {
7494cd2440d6SPetr Mladek 		if (pool->cpu_stall)
7495cd2440d6SPetr Mladek 			show_cpu_pool_hog(pool);
7496cd2440d6SPetr Mladek 
7497cd2440d6SPetr Mladek 	}
7498cd2440d6SPetr Mladek 
7499cd2440d6SPetr Mladek 	rcu_read_unlock();
7500cd2440d6SPetr Mladek }
7501cd2440d6SPetr Mladek 
750282607adcSTejun Heo static void wq_watchdog_reset_touched(void)
750382607adcSTejun Heo {
750482607adcSTejun Heo 	int cpu;
750582607adcSTejun Heo 
750682607adcSTejun Heo 	wq_watchdog_touched = jiffies;
750782607adcSTejun Heo 	for_each_possible_cpu(cpu)
750882607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
750982607adcSTejun Heo }
751082607adcSTejun Heo 
75115cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
751282607adcSTejun Heo {
751382607adcSTejun Heo 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
751482607adcSTejun Heo 	bool lockup_detected = false;
7515cd2440d6SPetr Mladek 	bool cpu_pool_stall = false;
7516940d71c6SSergey Senozhatsky 	unsigned long now = jiffies;
751782607adcSTejun Heo 	struct worker_pool *pool;
751882607adcSTejun Heo 	int pi;
751982607adcSTejun Heo 
752082607adcSTejun Heo 	if (!thresh)
752182607adcSTejun Heo 		return;
752282607adcSTejun Heo 
752382607adcSTejun Heo 	rcu_read_lock();
752482607adcSTejun Heo 
752582607adcSTejun Heo 	for_each_pool(pool, pi) {
752682607adcSTejun Heo 		unsigned long pool_ts, touched, ts;
752782607adcSTejun Heo 
7528cd2440d6SPetr Mladek 		pool->cpu_stall = false;
752982607adcSTejun Heo 		if (list_empty(&pool->worklist))
753082607adcSTejun Heo 			continue;
753182607adcSTejun Heo 
7532940d71c6SSergey Senozhatsky 		/*
7533940d71c6SSergey Senozhatsky 		 * If a virtual machine is stopped by the host it can look to
7534940d71c6SSergey Senozhatsky 		 * the watchdog like a stall.
7535940d71c6SSergey Senozhatsky 		 */
7536940d71c6SSergey Senozhatsky 		kvm_check_and_clear_guest_paused();
7537940d71c6SSergey Senozhatsky 
753882607adcSTejun Heo 		/* get the latest of pool and touched timestamps */
753989e28ce6SWang Qing 		if (pool->cpu >= 0)
754089e28ce6SWang Qing 			touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
754189e28ce6SWang Qing 		else
754282607adcSTejun Heo 			touched = READ_ONCE(wq_watchdog_touched);
754389e28ce6SWang Qing 		pool_ts = READ_ONCE(pool->watchdog_ts);
754482607adcSTejun Heo 
754582607adcSTejun Heo 		if (time_after(pool_ts, touched))
754682607adcSTejun Heo 			ts = pool_ts;
754782607adcSTejun Heo 		else
754882607adcSTejun Heo 			ts = touched;
754982607adcSTejun Heo 
755082607adcSTejun Heo 		/* did we stall? */
7551940d71c6SSergey Senozhatsky 		if (time_after(now, ts + thresh)) {
755282607adcSTejun Heo 			lockup_detected = true;
75534cb1ef64STejun Heo 			if (pool->cpu >= 0 && !(pool->flags & POOL_BH)) {
7554cd2440d6SPetr Mladek 				pool->cpu_stall = true;
7555cd2440d6SPetr Mladek 				cpu_pool_stall = true;
7556cd2440d6SPetr Mladek 			}
755782607adcSTejun Heo 			pr_emerg("BUG: workqueue lockup - pool");
755882607adcSTejun Heo 			pr_cont_pool_info(pool);
755982607adcSTejun Heo 			pr_cont(" stuck for %us!\n",
7560940d71c6SSergey Senozhatsky 				jiffies_to_msecs(now - pool_ts) / 1000);
756182607adcSTejun Heo 		}
7562cd2440d6SPetr Mladek 
7563cd2440d6SPetr Mladek 
756482607adcSTejun Heo 	}
756582607adcSTejun Heo 
756682607adcSTejun Heo 	rcu_read_unlock();
756782607adcSTejun Heo 
756882607adcSTejun Heo 	if (lockup_detected)
756955df0933SImran Khan 		show_all_workqueues();
757082607adcSTejun Heo 
7571cd2440d6SPetr Mladek 	if (cpu_pool_stall)
7572cd2440d6SPetr Mladek 		show_cpu_pools_hogs();
7573cd2440d6SPetr Mladek 
757482607adcSTejun Heo 	wq_watchdog_reset_touched();
757582607adcSTejun Heo 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
757682607adcSTejun Heo }
757782607adcSTejun Heo 
7578cb9d7fd5SVincent Whitchurch notrace void wq_watchdog_touch(int cpu)
757982607adcSTejun Heo {
758082607adcSTejun Heo 	if (cpu >= 0)
758182607adcSTejun Heo 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
758289e28ce6SWang Qing 
758382607adcSTejun Heo 	wq_watchdog_touched = jiffies;
758482607adcSTejun Heo }
758582607adcSTejun Heo 
758682607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
758782607adcSTejun Heo {
758882607adcSTejun Heo 	wq_watchdog_thresh = 0;
758982607adcSTejun Heo 	del_timer_sync(&wq_watchdog_timer);
759082607adcSTejun Heo 
759182607adcSTejun Heo 	if (thresh) {
759282607adcSTejun Heo 		wq_watchdog_thresh = thresh;
759382607adcSTejun Heo 		wq_watchdog_reset_touched();
759482607adcSTejun Heo 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
759582607adcSTejun Heo 	}
759682607adcSTejun Heo }
759782607adcSTejun Heo 
759882607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
759982607adcSTejun Heo 					const struct kernel_param *kp)
760082607adcSTejun Heo {
760182607adcSTejun Heo 	unsigned long thresh;
760282607adcSTejun Heo 	int ret;
760382607adcSTejun Heo 
760482607adcSTejun Heo 	ret = kstrtoul(val, 0, &thresh);
760582607adcSTejun Heo 	if (ret)
760682607adcSTejun Heo 		return ret;
760782607adcSTejun Heo 
760882607adcSTejun Heo 	if (system_wq)
760982607adcSTejun Heo 		wq_watchdog_set_thresh(thresh);
761082607adcSTejun Heo 	else
761182607adcSTejun Heo 		wq_watchdog_thresh = thresh;
761282607adcSTejun Heo 
761382607adcSTejun Heo 	return 0;
761482607adcSTejun Heo }
761582607adcSTejun Heo 
761682607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
761782607adcSTejun Heo 	.set	= wq_watchdog_param_set_thresh,
761882607adcSTejun Heo 	.get	= param_get_ulong,
761982607adcSTejun Heo };
762082607adcSTejun Heo 
762182607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
762282607adcSTejun Heo 		0644);
762382607adcSTejun Heo 
762482607adcSTejun Heo static void wq_watchdog_init(void)
762582607adcSTejun Heo {
76265cd79d6aSKees Cook 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
762782607adcSTejun Heo 	wq_watchdog_set_thresh(wq_watchdog_thresh);
762882607adcSTejun Heo }
762982607adcSTejun Heo 
763082607adcSTejun Heo #else	/* CONFIG_WQ_WATCHDOG */
763182607adcSTejun Heo 
763282607adcSTejun Heo static inline void wq_watchdog_init(void) { }
763382607adcSTejun Heo 
763482607adcSTejun Heo #endif	/* CONFIG_WQ_WATCHDOG */
763582607adcSTejun Heo 
76362f34d733STejun Heo static void bh_pool_kick_normal(struct irq_work *irq_work)
76372f34d733STejun Heo {
76382f34d733STejun Heo 	raise_softirq_irqoff(TASKLET_SOFTIRQ);
76392f34d733STejun Heo }
76402f34d733STejun Heo 
76412f34d733STejun Heo static void bh_pool_kick_highpri(struct irq_work *irq_work)
76422f34d733STejun Heo {
76432f34d733STejun Heo 	raise_softirq_irqoff(HI_SOFTIRQ);
76442f34d733STejun Heo }
76452f34d733STejun Heo 
76464a6c5607STejun Heo static void __init restrict_unbound_cpumask(const char *name, const struct cpumask *mask)
76474a6c5607STejun Heo {
76484a6c5607STejun Heo 	if (!cpumask_intersects(wq_unbound_cpumask, mask)) {
76494a6c5607STejun Heo 		pr_warn("workqueue: Restricting unbound_cpumask (%*pb) with %s (%*pb) leaves no CPU, ignoring\n",
76504a6c5607STejun Heo 			cpumask_pr_args(wq_unbound_cpumask), name, cpumask_pr_args(mask));
76514a6c5607STejun Heo 		return;
76524a6c5607STejun Heo 	}
76534a6c5607STejun Heo 
76544a6c5607STejun Heo 	cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, mask);
76554a6c5607STejun Heo }
76564a6c5607STejun Heo 
76572fcdb1b4STejun Heo static void __init init_cpu_worker_pool(struct worker_pool *pool, int cpu, int nice)
76582fcdb1b4STejun Heo {
76592fcdb1b4STejun Heo 	BUG_ON(init_worker_pool(pool));
76602fcdb1b4STejun Heo 	pool->cpu = cpu;
76612fcdb1b4STejun Heo 	cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
76622fcdb1b4STejun Heo 	cpumask_copy(pool->attrs->__pod_cpumask, cpumask_of(cpu));
76632fcdb1b4STejun Heo 	pool->attrs->nice = nice;
76642fcdb1b4STejun Heo 	pool->attrs->affn_strict = true;
76652fcdb1b4STejun Heo 	pool->node = cpu_to_node(cpu);
76662fcdb1b4STejun Heo 
76672fcdb1b4STejun Heo 	/* alloc pool ID */
76682fcdb1b4STejun Heo 	mutex_lock(&wq_pool_mutex);
76692fcdb1b4STejun Heo 	BUG_ON(worker_pool_assign_id(pool));
76702fcdb1b4STejun Heo 	mutex_unlock(&wq_pool_mutex);
76712fcdb1b4STejun Heo }
76722fcdb1b4STejun Heo 
76733347fa09STejun Heo /**
76743347fa09STejun Heo  * workqueue_init_early - early init for workqueue subsystem
76753347fa09STejun Heo  *
76762930155bSTejun Heo  * This is the first step of three-staged workqueue subsystem initialization and
76772930155bSTejun Heo  * invoked as soon as the bare basics - memory allocation, cpumasks and idr are
76782930155bSTejun Heo  * up. It sets up all the data structures and system workqueues and allows early
76792930155bSTejun Heo  * boot code to create workqueues and queue/cancel work items. Actual work item
76802930155bSTejun Heo  * execution starts only after kthreads can be created and scheduled right
76812930155bSTejun Heo  * before early initcalls.
76823347fa09STejun Heo  */
76832333e829SYu Chen void __init workqueue_init_early(void)
76841da177e4SLinus Torvalds {
768584193c07STejun Heo 	struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_SYSTEM];
76867a4e344cSTejun Heo 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
76872f34d733STejun Heo 	void (*irq_work_fns[2])(struct irq_work *) = { bh_pool_kick_normal,
76882f34d733STejun Heo 						       bh_pool_kick_highpri };
76897a4e344cSTejun Heo 	int i, cpu;
7690c34056a3STejun Heo 
769110cdb157SLai Jiangshan 	BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
7692e904e6c2STejun Heo 
7693b05a7928SFrederic Weisbecker 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
7694fe28f631SWaiman Long 	BUG_ON(!alloc_cpumask_var(&wq_requested_unbound_cpumask, GFP_KERNEL));
7695fe28f631SWaiman Long 	BUG_ON(!zalloc_cpumask_var(&wq_isolated_cpumask, GFP_KERNEL));
7696b05a7928SFrederic Weisbecker 
76974a6c5607STejun Heo 	cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
76984a6c5607STejun Heo 	restrict_unbound_cpumask("HK_TYPE_WQ", housekeeping_cpumask(HK_TYPE_WQ));
76994a6c5607STejun Heo 	restrict_unbound_cpumask("HK_TYPE_DOMAIN", housekeeping_cpumask(HK_TYPE_DOMAIN));
7700ace3c549Stiozhang 	if (!cpumask_empty(&wq_cmdline_cpumask))
77014a6c5607STejun Heo 		restrict_unbound_cpumask("workqueue.unbound_cpus", &wq_cmdline_cpumask);
7702ace3c549Stiozhang 
7703fe28f631SWaiman Long 	cpumask_copy(wq_requested_unbound_cpumask, wq_unbound_cpumask);
77048b03ae3cSTejun Heo 
77058b03ae3cSTejun Heo 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
7706e22bee78STejun Heo 
77072930155bSTejun Heo 	wq_update_pod_attrs_buf = alloc_workqueue_attrs();
77082930155bSTejun Heo 	BUG_ON(!wq_update_pod_attrs_buf);
77092930155bSTejun Heo 
77107bd20b6bSMarcelo Tosatti 	/*
77117bd20b6bSMarcelo Tosatti 	 * If nohz_full is enabled, set power efficient workqueue as unbound.
77127bd20b6bSMarcelo Tosatti 	 * This allows workqueue items to be moved to HK CPUs.
77137bd20b6bSMarcelo Tosatti 	 */
77147bd20b6bSMarcelo Tosatti 	if (housekeeping_enabled(HK_TYPE_TICK))
77157bd20b6bSMarcelo Tosatti 		wq_power_efficient = true;
77167bd20b6bSMarcelo Tosatti 
771784193c07STejun Heo 	/* initialize WQ_AFFN_SYSTEM pods */
771884193c07STejun Heo 	pt->pod_cpus = kcalloc(1, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
771984193c07STejun Heo 	pt->pod_node = kcalloc(1, sizeof(pt->pod_node[0]), GFP_KERNEL);
772084193c07STejun Heo 	pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
772184193c07STejun Heo 	BUG_ON(!pt->pod_cpus || !pt->pod_node || !pt->cpu_pod);
772284193c07STejun Heo 
772384193c07STejun Heo 	BUG_ON(!zalloc_cpumask_var_node(&pt->pod_cpus[0], GFP_KERNEL, NUMA_NO_NODE));
772484193c07STejun Heo 
772584193c07STejun Heo 	pt->nr_pods = 1;
772684193c07STejun Heo 	cpumask_copy(pt->pod_cpus[0], cpu_possible_mask);
772784193c07STejun Heo 	pt->pod_node[0] = NUMA_NO_NODE;
772884193c07STejun Heo 	pt->cpu_pod[0] = 0;
772984193c07STejun Heo 
77304cb1ef64STejun Heo 	/* initialize BH and CPU pools */
77311da177e4SLinus Torvalds 	for_each_possible_cpu(cpu) {
77321da177e4SLinus Torvalds 		struct worker_pool *pool;
77331da177e4SLinus Torvalds 
77341da177e4SLinus Torvalds 		i = 0;
77354cb1ef64STejun Heo 		for_each_bh_worker_pool(pool, cpu) {
77362f34d733STejun Heo 			init_cpu_worker_pool(pool, cpu, std_nice[i]);
77374cb1ef64STejun Heo 			pool->flags |= POOL_BH;
77382f34d733STejun Heo 			init_irq_work(bh_pool_irq_work(pool), irq_work_fns[i]);
77392f34d733STejun Heo 			i++;
77404cb1ef64STejun Heo 		}
77414cb1ef64STejun Heo 
77424cb1ef64STejun Heo 		i = 0;
77432fcdb1b4STejun Heo 		for_each_cpu_worker_pool(pool, cpu)
77442fcdb1b4STejun Heo 			init_cpu_worker_pool(pool, cpu, std_nice[i++]);
77451da177e4SLinus Torvalds 	}
77461da177e4SLinus Torvalds 
77478a2b7538STejun Heo 	/* create default unbound and ordered wq attrs */
774829c91e99STejun Heo 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
774929c91e99STejun Heo 		struct workqueue_attrs *attrs;
775029c91e99STejun Heo 
7751be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
775229c91e99STejun Heo 		attrs->nice = std_nice[i];
775329c91e99STejun Heo 		unbound_std_wq_attrs[i] = attrs;
77548a2b7538STejun Heo 
77558a2b7538STejun Heo 		/*
77568a2b7538STejun Heo 		 * An ordered wq should have only one pwq as ordering is
77578a2b7538STejun Heo 		 * guaranteed by max_active which is enforced by pwqs.
77588a2b7538STejun Heo 		 */
7759be69d00dSThomas Gleixner 		BUG_ON(!(attrs = alloc_workqueue_attrs()));
77608a2b7538STejun Heo 		attrs->nice = std_nice[i];
7761af73f5c9STejun Heo 		attrs->ordered = true;
77628a2b7538STejun Heo 		ordered_wq_attrs[i] = attrs;
776329c91e99STejun Heo 	}
776429c91e99STejun Heo 
7765d320c038STejun Heo 	system_wq = alloc_workqueue("events", 0, 0);
77661aabe902SJoonsoo Kim 	system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
7767d320c038STejun Heo 	system_long_wq = alloc_workqueue("events_long", 0, 0);
7768f3421797STejun Heo 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
7769636b927eSTejun Heo 					    WQ_MAX_ACTIVE);
777024d51addSTejun Heo 	system_freezable_wq = alloc_workqueue("events_freezable",
777124d51addSTejun Heo 					      WQ_FREEZABLE, 0);
77720668106cSViresh Kumar 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
77730668106cSViresh Kumar 					      WQ_POWER_EFFICIENT, 0);
77748318d6a6SAudra Mitchell 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_pwr_efficient",
77750668106cSViresh Kumar 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT,
77760668106cSViresh Kumar 					      0);
77774cb1ef64STejun Heo 	system_bh_wq = alloc_workqueue("events_bh", WQ_BH, 0);
77784cb1ef64STejun Heo 	system_bh_highpri_wq = alloc_workqueue("events_bh_highpri",
77794cb1ef64STejun Heo 					       WQ_BH | WQ_HIGHPRI, 0);
77801aabe902SJoonsoo Kim 	BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
77810668106cSViresh Kumar 	       !system_unbound_wq || !system_freezable_wq ||
77820668106cSViresh Kumar 	       !system_power_efficient_wq ||
77834cb1ef64STejun Heo 	       !system_freezable_power_efficient_wq ||
77844cb1ef64STejun Heo 	       !system_bh_wq || !system_bh_highpri_wq);
77853347fa09STejun Heo }
77863347fa09STejun Heo 
7787aa6fde93STejun Heo static void __init wq_cpu_intensive_thresh_init(void)
7788aa6fde93STejun Heo {
7789aa6fde93STejun Heo 	unsigned long thresh;
7790aa6fde93STejun Heo 	unsigned long bogo;
7791aa6fde93STejun Heo 
7792dd64c873SZqiang 	pwq_release_worker = kthread_create_worker(0, "pool_workqueue_release");
7793dd64c873SZqiang 	BUG_ON(IS_ERR(pwq_release_worker));
7794dd64c873SZqiang 
7795aa6fde93STejun Heo 	/* if the user set it to a specific value, keep it */
7796aa6fde93STejun Heo 	if (wq_cpu_intensive_thresh_us != ULONG_MAX)
7797aa6fde93STejun Heo 		return;
7798aa6fde93STejun Heo 
7799aa6fde93STejun Heo 	/*
7800aa6fde93STejun Heo 	 * The default of 10ms is derived from the fact that most modern (as of
7801aa6fde93STejun Heo 	 * 2023) processors can do a lot in 10ms and that it's just below what
7802aa6fde93STejun Heo 	 * most consider human-perceivable. However, the kernel also runs on a
7803aa6fde93STejun Heo 	 * lot slower CPUs including microcontrollers where the threshold is way
7804aa6fde93STejun Heo 	 * too low.
7805aa6fde93STejun Heo 	 *
7806aa6fde93STejun Heo 	 * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
7807aa6fde93STejun Heo 	 * This is by no means accurate but it doesn't have to be. The mechanism
7808aa6fde93STejun Heo 	 * is still useful even when the threshold is fully scaled up. Also, as
7809aa6fde93STejun Heo 	 * the reports would usually be applicable to everyone, some machines
7810aa6fde93STejun Heo 	 * operating on longer thresholds won't significantly diminish their
7811aa6fde93STejun Heo 	 * usefulness.
7812aa6fde93STejun Heo 	 */
7813aa6fde93STejun Heo 	thresh = 10 * USEC_PER_MSEC;
7814aa6fde93STejun Heo 
7815aa6fde93STejun Heo 	/* see init/calibrate.c for lpj -> BogoMIPS calculation */
7816aa6fde93STejun Heo 	bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
7817aa6fde93STejun Heo 	if (bogo < 4000)
7818aa6fde93STejun Heo 		thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
7819aa6fde93STejun Heo 
7820aa6fde93STejun Heo 	pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
7821aa6fde93STejun Heo 		 loops_per_jiffy, bogo, thresh);
7822aa6fde93STejun Heo 
7823aa6fde93STejun Heo 	wq_cpu_intensive_thresh_us = thresh;
7824aa6fde93STejun Heo }
7825aa6fde93STejun Heo 
78263347fa09STejun Heo /**
78273347fa09STejun Heo  * workqueue_init - bring workqueue subsystem fully online
78283347fa09STejun Heo  *
78292930155bSTejun Heo  * This is the second step of three-staged workqueue subsystem initialization
78302930155bSTejun Heo  * and invoked as soon as kthreads can be created and scheduled. Workqueues have
78312930155bSTejun Heo  * been created and work items queued on them, but there are no kworkers
78322930155bSTejun Heo  * executing the work items yet. Populate the worker pools with the initial
78332930155bSTejun Heo  * workers and enable future kworker creations.
78343347fa09STejun Heo  */
78352333e829SYu Chen void __init workqueue_init(void)
78363347fa09STejun Heo {
78372186d9f9STejun Heo 	struct workqueue_struct *wq;
78383347fa09STejun Heo 	struct worker_pool *pool;
78393347fa09STejun Heo 	int cpu, bkt;
78403347fa09STejun Heo 
7841aa6fde93STejun Heo 	wq_cpu_intensive_thresh_init();
7842aa6fde93STejun Heo 
78432186d9f9STejun Heo 	mutex_lock(&wq_pool_mutex);
78442186d9f9STejun Heo 
78452930155bSTejun Heo 	/*
78462930155bSTejun Heo 	 * Per-cpu pools created earlier could be missing node hint. Fix them
78472930155bSTejun Heo 	 * up. Also, create a rescuer for workqueues that requested it.
78482930155bSTejun Heo 	 */
78492186d9f9STejun Heo 	for_each_possible_cpu(cpu) {
78504cb1ef64STejun Heo 		for_each_bh_worker_pool(pool, cpu)
78512186d9f9STejun Heo 			pool->node = cpu_to_node(cpu);
78524cb1ef64STejun Heo 		for_each_cpu_worker_pool(pool, cpu)
78534cb1ef64STejun Heo 			pool->node = cpu_to_node(cpu);
78542186d9f9STejun Heo 	}
78552186d9f9STejun Heo 
785640c17f75STejun Heo 	list_for_each_entry(wq, &workqueues, list) {
785740c17f75STejun Heo 		WARN(init_rescuer(wq),
785840c17f75STejun Heo 		     "workqueue: failed to create early rescuer for %s",
785940c17f75STejun Heo 		     wq->name);
786040c17f75STejun Heo 	}
78612186d9f9STejun Heo 
78622186d9f9STejun Heo 	mutex_unlock(&wq_pool_mutex);
78632186d9f9STejun Heo 
78644cb1ef64STejun Heo 	/*
78654cb1ef64STejun Heo 	 * Create the initial workers. A BH pool has one pseudo worker that
78664cb1ef64STejun Heo 	 * represents the shared BH execution context and thus doesn't get
78674cb1ef64STejun Heo 	 * affected by hotplug events. Create the BH pseudo workers for all
78684cb1ef64STejun Heo 	 * possible CPUs here.
78694cb1ef64STejun Heo 	 */
78704cb1ef64STejun Heo 	for_each_possible_cpu(cpu)
78714cb1ef64STejun Heo 		for_each_bh_worker_pool(pool, cpu)
78724cb1ef64STejun Heo 			BUG_ON(!create_worker(pool));
78734cb1ef64STejun Heo 
78743347fa09STejun Heo 	for_each_online_cpu(cpu) {
78753347fa09STejun Heo 		for_each_cpu_worker_pool(pool, cpu) {
78763347fa09STejun Heo 			pool->flags &= ~POOL_DISASSOCIATED;
78773347fa09STejun Heo 			BUG_ON(!create_worker(pool));
78783347fa09STejun Heo 		}
78793347fa09STejun Heo 	}
78803347fa09STejun Heo 
78813347fa09STejun Heo 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
78823347fa09STejun Heo 		BUG_ON(!create_worker(pool));
78833347fa09STejun Heo 
78843347fa09STejun Heo 	wq_online = true;
788582607adcSTejun Heo 	wq_watchdog_init();
78861da177e4SLinus Torvalds }
7887c4f135d6STetsuo Handa 
7888025e1684STejun Heo /*
7889025e1684STejun Heo  * Initialize @pt by first initializing @pt->cpu_pod[] with pod IDs according to
7890025e1684STejun Heo  * @cpu_shares_pod(). Each subset of CPUs that share a pod is assigned a unique
7891025e1684STejun Heo  * and consecutive pod ID. The rest of @pt is initialized accordingly.
7892025e1684STejun Heo  */
7893025e1684STejun Heo static void __init init_pod_type(struct wq_pod_type *pt,
7894025e1684STejun Heo 				 bool (*cpus_share_pod)(int, int))
7895025e1684STejun Heo {
7896025e1684STejun Heo 	int cur, pre, cpu, pod;
7897025e1684STejun Heo 
7898025e1684STejun Heo 	pt->nr_pods = 0;
7899025e1684STejun Heo 
7900025e1684STejun Heo 	/* init @pt->cpu_pod[] according to @cpus_share_pod() */
7901025e1684STejun Heo 	pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
7902025e1684STejun Heo 	BUG_ON(!pt->cpu_pod);
7903025e1684STejun Heo 
7904025e1684STejun Heo 	for_each_possible_cpu(cur) {
7905025e1684STejun Heo 		for_each_possible_cpu(pre) {
7906025e1684STejun Heo 			if (pre >= cur) {
7907025e1684STejun Heo 				pt->cpu_pod[cur] = pt->nr_pods++;
7908025e1684STejun Heo 				break;
7909025e1684STejun Heo 			}
7910025e1684STejun Heo 			if (cpus_share_pod(cur, pre)) {
7911025e1684STejun Heo 				pt->cpu_pod[cur] = pt->cpu_pod[pre];
7912025e1684STejun Heo 				break;
7913025e1684STejun Heo 			}
7914025e1684STejun Heo 		}
7915025e1684STejun Heo 	}
7916025e1684STejun Heo 
7917025e1684STejun Heo 	/* init the rest to match @pt->cpu_pod[] */
7918025e1684STejun Heo 	pt->pod_cpus = kcalloc(pt->nr_pods, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
7919025e1684STejun Heo 	pt->pod_node = kcalloc(pt->nr_pods, sizeof(pt->pod_node[0]), GFP_KERNEL);
7920025e1684STejun Heo 	BUG_ON(!pt->pod_cpus || !pt->pod_node);
7921025e1684STejun Heo 
7922025e1684STejun Heo 	for (pod = 0; pod < pt->nr_pods; pod++)
7923025e1684STejun Heo 		BUG_ON(!zalloc_cpumask_var(&pt->pod_cpus[pod], GFP_KERNEL));
7924025e1684STejun Heo 
7925025e1684STejun Heo 	for_each_possible_cpu(cpu) {
7926025e1684STejun Heo 		cpumask_set_cpu(cpu, pt->pod_cpus[pt->cpu_pod[cpu]]);
7927025e1684STejun Heo 		pt->pod_node[pt->cpu_pod[cpu]] = cpu_to_node(cpu);
7928025e1684STejun Heo 	}
7929025e1684STejun Heo }
7930025e1684STejun Heo 
793163c5484eSTejun Heo static bool __init cpus_dont_share(int cpu0, int cpu1)
793263c5484eSTejun Heo {
793363c5484eSTejun Heo 	return false;
793463c5484eSTejun Heo }
793563c5484eSTejun Heo 
793663c5484eSTejun Heo static bool __init cpus_share_smt(int cpu0, int cpu1)
793763c5484eSTejun Heo {
793863c5484eSTejun Heo #ifdef CONFIG_SCHED_SMT
793963c5484eSTejun Heo 	return cpumask_test_cpu(cpu0, cpu_smt_mask(cpu1));
794063c5484eSTejun Heo #else
794163c5484eSTejun Heo 	return false;
794263c5484eSTejun Heo #endif
794363c5484eSTejun Heo }
794463c5484eSTejun Heo 
7945025e1684STejun Heo static bool __init cpus_share_numa(int cpu0, int cpu1)
7946025e1684STejun Heo {
7947025e1684STejun Heo 	return cpu_to_node(cpu0) == cpu_to_node(cpu1);
7948025e1684STejun Heo }
7949025e1684STejun Heo 
79502930155bSTejun Heo /**
79512930155bSTejun Heo  * workqueue_init_topology - initialize CPU pods for unbound workqueues
79522930155bSTejun Heo  *
795396068b60SWang Jinchao  * This is the third step of three-staged workqueue subsystem initialization and
79542930155bSTejun Heo  * invoked after SMP and topology information are fully initialized. It
79552930155bSTejun Heo  * initializes the unbound CPU pods accordingly.
79562930155bSTejun Heo  */
79572930155bSTejun Heo void __init workqueue_init_topology(void)
7958a86feae6STejun Heo {
79592930155bSTejun Heo 	struct workqueue_struct *wq;
7960025e1684STejun Heo 	int cpu;
7961a86feae6STejun Heo 
796263c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_CPU], cpus_dont_share);
796363c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_SMT], cpus_share_smt);
796463c5484eSTejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_CACHE], cpus_share_cache);
7965025e1684STejun Heo 	init_pod_type(&wq_pod_types[WQ_AFFN_NUMA], cpus_share_numa);
7966a86feae6STejun Heo 
7967c5f8cd6cSTejun Heo 	wq_topo_initialized = true;
7968c5f8cd6cSTejun Heo 
79692930155bSTejun Heo 	mutex_lock(&wq_pool_mutex);
7970a86feae6STejun Heo 
7971a86feae6STejun Heo 	/*
79722930155bSTejun Heo 	 * Workqueues allocated earlier would have all CPUs sharing the default
79732930155bSTejun Heo 	 * worker pool. Explicitly call wq_update_pod() on all workqueue and CPU
79742930155bSTejun Heo 	 * combinations to apply per-pod sharing.
79752930155bSTejun Heo 	 */
79762930155bSTejun Heo 	list_for_each_entry(wq, &workqueues, list) {
79775797b1c1STejun Heo 		for_each_online_cpu(cpu)
79782930155bSTejun Heo 			wq_update_pod(wq, cpu, cpu, true);
79795797b1c1STejun Heo 		if (wq->flags & WQ_UNBOUND) {
79805797b1c1STejun Heo 			mutex_lock(&wq->mutex);
79815797b1c1STejun Heo 			wq_update_node_max_active(wq, -1);
79825797b1c1STejun Heo 			mutex_unlock(&wq->mutex);
79832930155bSTejun Heo 		}
79842930155bSTejun Heo 	}
79852930155bSTejun Heo 
79862930155bSTejun Heo 	mutex_unlock(&wq_pool_mutex);
7987a86feae6STejun Heo }
7988a86feae6STejun Heo 
798920bdedafSTetsuo Handa void __warn_flushing_systemwide_wq(void)
799020bdedafSTetsuo Handa {
799120bdedafSTetsuo Handa 	pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
799220bdedafSTetsuo Handa 	dump_stack();
799320bdedafSTetsuo Handa }
7994c4f135d6STetsuo Handa EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
7995ace3c549Stiozhang 
7996ace3c549Stiozhang static int __init workqueue_unbound_cpus_setup(char *str)
7997ace3c549Stiozhang {
7998ace3c549Stiozhang 	if (cpulist_parse(str, &wq_cmdline_cpumask) < 0) {
7999ace3c549Stiozhang 		cpumask_clear(&wq_cmdline_cpumask);
8000ace3c549Stiozhang 		pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
8001ace3c549Stiozhang 	}
8002ace3c549Stiozhang 
8003ace3c549Stiozhang 	return 1;
8004ace3c549Stiozhang }
8005ace3c549Stiozhang __setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup);
8006