xref: /linux/kernel/workqueue.c (revision 7a0622004b9ea92900be33c0f21da0a2c0f29d5c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * kernel/workqueue.c - generic async execution with shared worker pool
4  *
5  * Copyright (C) 2002		Ingo Molnar
6  *
7  *   Derived from the taskqueue/keventd code by:
8  *     David Woodhouse <dwmw2@infradead.org>
9  *     Andrew Morton
10  *     Kai Petzke <wpp@marie.physik.tu-berlin.de>
11  *     Theodore Ts'o <tytso@mit.edu>
12  *
13  * Made to use alloc_percpu by Christoph Lameter.
14  *
15  * Copyright (C) 2010		SUSE Linux Products GmbH
16  * Copyright (C) 2010		Tejun Heo <tj@kernel.org>
17  *
18  * This is the generic async execution mechanism.  Work items as are
19  * executed in process context.  The worker pool is shared and
20  * automatically managed.  There are two worker pools for each CPU (one for
21  * normal work items and the other for high priority ones) and some extra
22  * pools for workqueues which are not bound to any specific CPU - the
23  * number of these backing pools is dynamic.
24  *
25  * Please read Documentation/core-api/workqueue.rst for details.
26  */
27 
28 #include <linux/export.h>
29 #include <linux/kernel.h>
30 #include <linux/sched.h>
31 #include <linux/init.h>
32 #include <linux/interrupt.h>
33 #include <linux/signal.h>
34 #include <linux/completion.h>
35 #include <linux/workqueue.h>
36 #include <linux/slab.h>
37 #include <linux/cpu.h>
38 #include <linux/notifier.h>
39 #include <linux/kthread.h>
40 #include <linux/hardirq.h>
41 #include <linux/mempolicy.h>
42 #include <linux/freezer.h>
43 #include <linux/debug_locks.h>
44 #include <linux/device/devres.h>
45 #include <linux/lockdep.h>
46 #include <linux/idr.h>
47 #include <linux/jhash.h>
48 #include <linux/hashtable.h>
49 #include <linux/rculist.h>
50 #include <linux/nodemask.h>
51 #include <linux/moduleparam.h>
52 #include <linux/uaccess.h>
53 #include <linux/sched/isolation.h>
54 #include <linux/sched/debug.h>
55 #include <linux/nmi.h>
56 #include <linux/kvm_para.h>
57 #include <linux/delay.h>
58 #include <linux/irq_work.h>
59 #include <linux/math64.h>
60 
61 #include "workqueue_internal.h"
62 
63 enum worker_pool_flags {
64 	/*
65 	 * worker_pool flags
66 	 *
67 	 * A bound pool is either associated or disassociated with its CPU.
68 	 * While associated (!DISASSOCIATED), all workers are bound to the
69 	 * CPU and none has %WORKER_UNBOUND set and concurrency management
70 	 * is in effect.
71 	 *
72 	 * While DISASSOCIATED, the cpu may be offline and all workers have
73 	 * %WORKER_UNBOUND set and concurrency management disabled, and may
74 	 * be executing on any CPU.  The pool behaves as an unbound one.
75 	 *
76 	 * Note that DISASSOCIATED should be flipped only while holding
77 	 * wq_pool_attach_mutex to avoid changing binding state while
78 	 * worker_attach_to_pool() is in progress.
79 	 *
80 	 * As there can only be one concurrent BH execution context per CPU, a
81 	 * BH pool is per-CPU and always DISASSOCIATED.
82 	 */
83 	POOL_BH			= 1 << 0,	/* is a BH pool */
84 	POOL_MANAGER_ACTIVE	= 1 << 1,	/* being managed */
85 	POOL_DISASSOCIATED	= 1 << 2,	/* cpu can't serve workers */
86 	POOL_BH_DRAINING	= 1 << 3,	/* draining after CPU offline */
87 };
88 
89 enum worker_flags {
90 	/* worker flags */
91 	WORKER_DIE		= 1 << 1,	/* die die die */
92 	WORKER_IDLE		= 1 << 2,	/* is idle */
93 	WORKER_PREP		= 1 << 3,	/* preparing to run works */
94 	WORKER_CPU_INTENSIVE	= 1 << 6,	/* cpu intensive */
95 	WORKER_UNBOUND		= 1 << 7,	/* worker is unbound */
96 	WORKER_REBOUND		= 1 << 8,	/* worker was rebound */
97 
98 	WORKER_NOT_RUNNING	= WORKER_PREP | WORKER_CPU_INTENSIVE |
99 				  WORKER_UNBOUND | WORKER_REBOUND,
100 };
101 
102 enum work_cancel_flags {
103 	WORK_CANCEL_DELAYED	= 1 << 0,	/* canceling a delayed_work */
104 	WORK_CANCEL_DISABLE	= 1 << 1,	/* canceling to disable */
105 };
106 
107 enum wq_internal_consts {
108 	NR_STD_WORKER_POOLS	= 2,		/* # standard pools per cpu */
109 
110 	UNBOUND_POOL_HASH_ORDER	= 6,		/* hashed by pool->attrs */
111 	BUSY_WORKER_HASH_ORDER	= 6,		/* 64 pointers */
112 
113 	MAX_IDLE_WORKERS_RATIO	= 4,		/* 1/4 of busy can be idle */
114 	IDLE_WORKER_TIMEOUT	= 300 * HZ,	/* keep idle ones for 5 mins */
115 
116 	MAYDAY_INITIAL_TIMEOUT  = HZ / 100 >= 2 ? HZ / 100 : 2,
117 						/* call for help after 10ms
118 						   (min two ticks) */
119 	MAYDAY_INTERVAL		= HZ / 10,	/* and then every 100ms */
120 	CREATE_COOLDOWN		= HZ,		/* time to breath after fail */
121 
122 	RESCUER_BATCH		= 16,		/* process items per turn */
123 
124 	/*
125 	 * Rescue workers are used only on emergencies and shared by
126 	 * all cpus.  Give MIN_NICE.
127 	 */
128 	RESCUER_NICE_LEVEL	= MIN_NICE,
129 	HIGHPRI_NICE_LEVEL	= MIN_NICE,
130 
131 	WQ_NAME_LEN		= 32,
132 	WORKER_ID_LEN		= 10 + WQ_NAME_LEN, /* "kworker/R-" + WQ_NAME_LEN */
133 };
134 
135 /* Layout of shards within one LLC pod */
136 struct llc_shard_layout {
137 	int nr_large_shards;	/* number of large shards (cores_per_shard + 1) */
138 	int cores_per_shard;	/* base number of cores per default shard */
139 	int nr_shards;		/* total number of shards */
140 	/* nr_default shards = (nr_shards - nr_large_shards) */
141 };
142 
143 /*
144  * We don't want to trap softirq for too long. See MAX_SOFTIRQ_TIME and
145  * MAX_SOFTIRQ_RESTART in kernel/softirq.c. These are macros because
146  * msecs_to_jiffies() can't be an initializer.
147  */
148 #define BH_WORKER_JIFFIES	msecs_to_jiffies(2)
149 #define BH_WORKER_RESTARTS	10
150 
151 /*
152  * Structure fields follow one of the following exclusion rules.
153  *
154  * I: Modifiable by initialization/destruction paths and read-only for
155  *    everyone else.
156  *
157  * P: Preemption protected.  Disabling preemption is enough and should
158  *    only be modified and accessed from the local cpu.
159  *
160  * L: pool->lock protected.  Access with pool->lock held.
161  *
162  * LN: pool->lock and wq_node_nr_active->lock protected for writes. Either for
163  *     reads.
164  *
165  * FN: wq_flush_pnode->lock protected. list_empty(&pwq->flush_node) can also be
166  *     tested with only pool->lock held.
167  *
168  * K: Only modified by worker while holding pool->lock. Can be safely read by
169  *    self, while holding pool->lock or from IRQ context if %current is the
170  *    kworker.
171  *
172  * S: Only modified by worker self.
173  *
174  * A: wq_pool_attach_mutex protected.
175  *
176  * PL: wq_pool_mutex protected.
177  *
178  * PR: wq_pool_mutex protected for writes.  RCU protected for reads.
179  *
180  * PW: wq_pool_mutex and wq->mutex protected for writes.  Either for reads.
181  *
182  * PWR: wq_pool_mutex and wq->mutex protected for writes.  Either or
183  *      RCU for reads.
184  *
185  * WQ: wq->mutex protected.
186  *
187  * WR: wq->mutex protected for writes.  RCU protected for reads.
188  *
189  * WO: wq->mutex protected for writes. Updated with WRITE_ONCE() and can be read
190  *     with READ_ONCE() without locking.
191  *
192  * MD: wq_mayday_lock protected.
193  *
194  * WD: Used internally by the watchdog.
195  */
196 
197 /* struct worker is defined in workqueue_internal.h */
198 
199 struct worker_pool {
200 	raw_spinlock_t		lock;		/* the pool lock */
201 	int			cpu;		/* I: the associated cpu */
202 	int			node;		/* I: the associated node ID */
203 	int			id;		/* I: pool ID */
204 	unsigned int		flags;		/* L: flags */
205 
206 	unsigned long		last_progress_ts;	/* L: last forward progress timestamp */
207 	bool			cpu_stall;	/* WD: stalled cpu bound pool */
208 
209 	/*
210 	 * The counter is incremented in a process context on the associated CPU
211 	 * w/ preemption disabled, and decremented or reset in the same context
212 	 * but w/ pool->lock held. The readers grab pool->lock and are
213 	 * guaranteed to see if the counter reached zero.
214 	 */
215 	int __data_racy nr_running;
216 
217 	struct list_head	worklist;	/* L: list of pending works */
218 
219 	int			nr_workers;	/* L: total number of workers */
220 	int			nr_idle;	/* L: currently idle workers */
221 
222 	struct list_head	idle_list;	/* L: list of idle workers */
223 	struct timer_list	idle_timer;	/* L: worker idle timeout */
224 	struct work_struct      idle_cull_work; /* L: worker idle cleanup */
225 
226 	struct timer_list	mayday_timer;	  /* L: SOS timer for workers */
227 
228 	/* a workers is either on busy_hash or idle_list, or the manager */
229 	DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
230 						/* L: hash of busy workers */
231 
232 	struct worker		*manager;	/* L: purely informational */
233 	/* L: last worker woken by kick_pool() */
234 	struct worker		*last_woken_worker;
235 	struct list_head	workers;	/* A: attached workers */
236 
237 	struct ida		worker_ida;	/* worker IDs for task name */
238 
239 	struct workqueue_attrs	*attrs;		/* I: worker attributes */
240 	struct hlist_node	hash_node;	/* PL: unbound_pool_hash node */
241 	int			refcnt;		/* PL: refcnt for unbound pools */
242 #ifdef CONFIG_PREEMPT_RT
243 	spinlock_t		cb_lock;	/* BH worker cancel lock */
244 #endif
245 	/*
246 	 * Destruction of pool is RCU protected to allow dereferences
247 	 * from get_work_pool().
248 	 */
249 	struct rcu_head		rcu;
250 };
251 
252 /*
253  * Per-pool_workqueue statistics. These can be monitored using
254  * tools/workqueue/wq_monitor.py.
255  */
256 enum pool_workqueue_stats {
257 	PWQ_STAT_STARTED,	/* work items started execution */
258 	PWQ_STAT_COMPLETED,	/* work items completed execution */
259 	PWQ_STAT_CPU_TIME,	/* total CPU time consumed */
260 	PWQ_STAT_CPU_INTENSIVE,	/* wq_cpu_intensive_thresh_us violations */
261 	PWQ_STAT_CM_WAKEUP,	/* concurrency-management worker wakeups */
262 	PWQ_STAT_REPATRIATED,	/* unbound workers brought back into scope */
263 	PWQ_STAT_MAYDAY,	/* maydays to rescuer */
264 	PWQ_STAT_RESCUED,	/* linked work items executed by rescuer */
265 
266 	PWQ_NR_STATS,
267 };
268 
269 /*
270  * The per-pool workqueue.  While queued, bits below WORK_PWQ_SHIFT
271  * of work_struct->data are used for flags and the remaining high bits
272  * point to the pwq; thus, pwqs need to be aligned at two's power of the
273  * number of flag bits.
274  */
275 struct pool_workqueue {
276 	struct worker_pool	*pool;		/* I: the associated pool */
277 	struct workqueue_struct *wq;		/* I: the owning workqueue */
278 	int			work_color;	/* L: current color */
279 	int			flush_color;	/* L: flushing color */
280 	int			refcnt;		/* L: reference count */
281 	int			total_in_flight; /* L: sum of nr_in_flight[] */
282 	int			nr_in_flight[WORK_NR_COLORS];
283 						/* L: nr of in_flight works */
284 	unsigned long		nr_started;	/* L: see drain_workqueue() */
285 	struct list_head	flush_node;	/* FN: node on wq_flush_pnode->pwqs */
286 	bool			plugged;	/* L: execution suspended */
287 
288 	/*
289 	 * nr_active management and WORK_STRUCT_INACTIVE:
290 	 *
291 	 * When pwq->nr_active >= max_active, new work item is queued to
292 	 * pwq->inactive_works instead of pool->worklist and marked with
293 	 * WORK_STRUCT_INACTIVE.
294 	 *
295 	 * All work items marked with WORK_STRUCT_INACTIVE do not participate in
296 	 * nr_active and all work items in pwq->inactive_works are marked with
297 	 * WORK_STRUCT_INACTIVE. But not all WORK_STRUCT_INACTIVE work items are
298 	 * in pwq->inactive_works. Some of them are ready to run in
299 	 * pool->worklist or worker->scheduled. Those work itmes are only struct
300 	 * wq_barrier which is used for flush_work() and should not participate
301 	 * in nr_active. For non-barrier work item, it is marked with
302 	 * WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
303 	 */
304 	int			nr_active;	/* L: nr of active works */
305 	struct list_head	inactive_works;	/* L: inactive works */
306 	struct list_head	pending_node;	/* LN: node on wq_node_nr_active->pending_pwqs */
307 	struct list_head	pwqs_node;	/* WR: node on wq->pwqs */
308 	struct list_head	mayday_node;	/* MD: node on wq->maydays */
309 	struct work_struct	mayday_cursor;	/* L: cursor on pool->worklist */
310 
311 	u64			stats[PWQ_NR_STATS];
312 
313 	/*
314 	 * Release of unbound pwq is punted to a kthread_worker. See put_pwq()
315 	 * and pwq_release_workfn() for details. pool_workqueue itself is also
316 	 * RCU protected so that the first pwq can be determined without
317 	 * grabbing wq->mutex.
318 	 */
319 	struct kthread_work	release_work;
320 	struct rcu_head		rcu;
321 } __aligned(1 << WORK_STRUCT_PWQ_SHIFT);
322 
323 /*
324  * Structure used to wait for workqueue flush.
325  */
326 struct wq_flusher {
327 	struct list_head	list;		/* WQ: list of flushers */
328 	int			flush_color;	/* WQ: flush color waiting for */
329 	struct completion	done;		/* flush completion */
330 };
331 
332 struct wq_device;
333 
334 /*
335  * Unlike in a per-cpu workqueue where max_active limits its concurrency level
336  * on each CPU, in an unbound workqueue, max_active applies to the whole system.
337  * As sharing a single nr_active across multiple sockets can be very expensive,
338  * the counting and enforcement is per NUMA node.
339  *
340  * The following struct is used to enforce per-node max_active. When a pwq wants
341  * to start executing a work item, it should increment ->nr using
342  * tryinc_node_nr_active(). If acquisition fails due to ->nr already being over
343  * ->max, the pwq is queued on ->pending_pwqs. As in-flight work items finish
344  * and decrement ->nr, node_activate_pending_pwq() activates the pending pwqs in
345  * round-robin order.
346  */
347 struct wq_node_nr_active {
348 	int			max;		/* per-node max_active */
349 	atomic_t		nr;		/* per-node nr_active */
350 	raw_spinlock_t		lock;		/* nests inside pool locks */
351 	struct list_head	pending_pwqs;	/* LN: pwqs with inactive works */
352 };
353 
354 /*
355  * Per-node list of pwqs active since the last flush so that flushes visit only
356  * those. One per possible node plus the NUMA_NO_NODE fallback at nr_node_ids,
357  * each allocated on its node. A pwq is added when a work item is queued to it
358  * while off the list and removed by a flush which finds it with nothing in
359  * flight. ->work_color mirrors wq->work_color. Reading it and adding the pwq in
360  * one ->lock section keeps queueing coherent against flushing: a work item is
361  * either stamped with the new color or its pwq is visible to the flusher.
362  */
363 struct wq_flush_pnode {
364 	raw_spinlock_t		lock;		/* nests inside pool locks */
365 	int			work_color;	/* FN: mirrors wq->work_color */
366 	struct list_head	pwqs;		/* FN: pwqs active since last flush */
367 };
368 
369 /*
370  * The externally visible workqueue.  It relays the issued work items to
371  * the appropriate worker_pool through its pool_workqueues.
372  */
373 struct workqueue_struct {
374 	struct list_head	pwqs;		/* WR: all pwqs of this wq */
375 	struct list_head	list;		/* PR: list of all workqueues */
376 
377 	struct mutex		mutex;		/* protects this wq */
378 	int			work_color;	/* WQ: current work color */
379 	int			flush_color;	/* WQ: current flush color */
380 	atomic_t		nr_pwqs_to_flush; /* flush in progress */
381 	struct wq_flusher	*first_flusher;	/* WQ: first flusher */
382 	struct list_head	flusher_queue;	/* WQ: flush waiters */
383 	struct list_head	flusher_overflow; /* WQ: flush overflow list */
384 	struct wq_flush_pnode	**flush_pnodes; /* I: per-node flush membership */
385 
386 	struct list_head	maydays;	/* MD: pwqs requesting rescue */
387 	struct worker		*rescuer;	/* MD: rescue worker */
388 
389 	int			nr_drainers;	/* WQ: drain in progress */
390 
391 	/* See alloc_workqueue() function comment for info on min/max_active */
392 	int			max_active;	/* WO: max active works */
393 	int			percpu_max_active; /* WO: max active works per cpu */
394 	int			min_active;	/* WO: min active works */
395 	int			saved_max_active; /* WQ: saved max_active */
396 	int			saved_min_active; /* WQ: saved min_active */
397 
398 	struct workqueue_attrs	*attrs;	/* PW: workqueue attributes */
399 	struct pool_workqueue __rcu *dfl_pwq;   /* PW: only for unbound wqs */
400 
401 #ifdef CONFIG_SYSFS
402 	struct wq_device	*wq_dev;	/* I: for sysfs interface */
403 #endif
404 #ifdef CONFIG_LOCKDEP
405 	char			*lock_name;
406 	struct lock_class_key	key;
407 	struct lockdep_map	__lockdep_map;
408 	struct lockdep_map	*lockdep_map;
409 #endif
410 	char			name[WQ_NAME_LEN]; /* I: workqueue name */
411 
412 	/*
413 	 * Destruction of workqueue_struct is RCU protected to allow walking
414 	 * the workqueues list without grabbing wq_pool_mutex.
415 	 * This is used to dump all workqueues from sysrq.
416 	 */
417 	struct rcu_head		rcu;
418 
419 	/* hot fields used during command issue, aligned to cacheline */
420 	unsigned int		flags ____cacheline_aligned; /* WQ: WQ_* flags */
421 	struct pool_workqueue __rcu * __percpu *cpu_pwq; /* I: per-cpu pwqs */
422 	struct wq_node_nr_active *node_nr_active[]; /* I: per-node nr_active */
423 };
424 
425 /*
426  * Each pod type describes how CPUs should be grouped for unbound workqueues.
427  * See the comment above workqueue_attrs->affn_scope.
428  */
429 struct wq_pod_type {
430 	int			nr_pods;	/* number of pods */
431 	cpumask_var_t		*pod_cpus;	/* pod -> cpus */
432 	int			*pod_node;	/* pod -> node */
433 	int			*cpu_pod;	/* cpu -> pod */
434 };
435 
436 struct work_offq_data {
437 	u32			pool_id;
438 	u32			disable;
439 	u32			flags;
440 };
441 
442 static const char * const wq_affn_names[WQ_AFFN_NR_TYPES] = {
443 	[WQ_AFFN_DFL]		= "default",
444 	[WQ_AFFN_CPU]		= "cpu",
445 	[WQ_AFFN_SMT]		= "smt",
446 	[WQ_AFFN_CACHE]		= "cache",
447 	[WQ_AFFN_CACHE_SHARD]	= "cache_shard",
448 	[WQ_AFFN_NUMA]		= "numa",
449 	[WQ_AFFN_SYSTEM]	= "system",
450 };
451 
452 /*
453  * Per-cpu work items which run for longer than the following threshold are
454  * automatically considered CPU intensive and excluded from concurrency
455  * management to prevent them from noticeably delaying other per-cpu work items.
456  * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
457  * The actual value is initialized in wq_cpu_intensive_thresh_init().
458  */
459 static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
460 module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
461 #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
462 static unsigned int wq_cpu_intensive_warning_thresh = 4;
463 module_param_named(cpu_intensive_warning_thresh, wq_cpu_intensive_warning_thresh, uint, 0644);
464 #endif
465 
466 /* see the comment above the definition of WQ_POWER_EFFICIENT */
467 static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
468 module_param_named(power_efficient, wq_power_efficient, bool, 0444);
469 
470 static unsigned int wq_cache_shard_size = 8;
471 module_param_named(cache_shard_size, wq_cache_shard_size, uint, 0444);
472 
473 static bool wq_online;			/* can kworkers be created yet? */
474 static bool wq_topo_initialized __read_mostly = false;
475 
476 static struct kmem_cache *pwq_cache;
477 
478 static struct wq_pod_type wq_pod_types[WQ_AFFN_NR_TYPES];
479 static enum wq_affn_scope wq_affn_dfl = WQ_AFFN_CACHE_SHARD;
480 
481 /* buf for wq_update_unbound_pod_attrs(), protected by CPU hotplug exclusion */
482 static struct workqueue_attrs *unbound_wq_update_pwq_attrs_buf;
483 
484 static DEFINE_MUTEX(wq_pool_mutex);	/* protects pools and workqueues list */
485 static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
486 static DEFINE_RAW_SPINLOCK(wq_mayday_lock);	/* protects wq->maydays list */
487 /* wait for manager to go away */
488 static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
489 
490 static LIST_HEAD(workqueues);		/* PR: list of all workqueues */
491 static bool workqueue_freezing;		/* PL: have wqs started freezing? */
492 
493 /* PL: mirror the cpu_online_mask excluding the CPU in the midst of hotplugging */
494 static cpumask_var_t wq_online_cpumask;
495 
496 /* PL&A: allowable cpus for unbound wqs and work items */
497 static cpumask_var_t wq_unbound_cpumask;
498 
499 /* PL: user requested unbound cpumask via sysfs */
500 static cpumask_var_t wq_requested_unbound_cpumask;
501 
502 /* PL: isolated cpumask to be excluded from unbound cpumask */
503 static cpumask_var_t wq_isolated_cpumask;
504 
505 /* for further constrain wq_unbound_cpumask by cmdline parameter*/
506 static struct cpumask wq_cmdline_cpumask __initdata;
507 
508 /* CPU where unbound work was last round robin scheduled from this CPU */
509 static DEFINE_PER_CPU(int, wq_rr_cpu_last);
510 
511 /*
512  * Local execution of unbound work items is no longer guaranteed.  The
513  * following always forces round-robin CPU selection on unbound work items
514  * to uncover usages which depend on it.
515  */
516 #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
517 static bool wq_debug_force_rr_cpu = true;
518 #else
519 static bool wq_debug_force_rr_cpu = false;
520 #endif
521 module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
522 
523 /* to raise softirq for the BH worker pools on other CPUs */
524 static DEFINE_PER_CPU_SHARED_ALIGNED(struct irq_work [NR_STD_WORKER_POOLS], bh_pool_irq_works);
525 
526 /* the BH worker pools */
527 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], bh_worker_pools);
528 
529 /* the per-cpu worker pools */
530 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
531 
532 static DEFINE_IDR(worker_pool_idr);	/* PR: idr of all pools */
533 
534 /* PL: hash of all unbound pools keyed by pool->attrs */
535 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
536 
537 /*
538  * I: kthread_worker to release pwq's. pwq release needs to be bounced to a
539  * process context while holding a pool lock. Bounce to a dedicated kthread
540  * worker to avoid A-A deadlocks.
541  */
542 static struct kthread_worker *pwq_release_worker __ro_after_init;
543 
544 struct workqueue_struct *system_wq __ro_after_init;
545 EXPORT_SYMBOL(system_wq);
546 struct workqueue_struct *system_percpu_wq __ro_after_init;
547 EXPORT_SYMBOL(system_percpu_wq);
548 struct workqueue_struct *system_highpri_wq __ro_after_init;
549 EXPORT_SYMBOL_GPL(system_highpri_wq);
550 struct workqueue_struct *system_long_wq __ro_after_init;
551 EXPORT_SYMBOL_GPL(system_long_wq);
552 struct workqueue_struct *system_unbound_wq __ro_after_init;
553 EXPORT_SYMBOL_GPL(system_unbound_wq);
554 struct workqueue_struct *system_dfl_wq __ro_after_init;
555 EXPORT_SYMBOL_GPL(system_dfl_wq);
556 struct workqueue_struct *system_freezable_wq __ro_after_init;
557 EXPORT_SYMBOL_GPL(system_freezable_wq);
558 struct workqueue_struct *system_power_efficient_wq __ro_after_init;
559 EXPORT_SYMBOL_GPL(system_power_efficient_wq);
560 struct workqueue_struct *system_freezable_power_efficient_wq __ro_after_init;
561 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
562 struct workqueue_struct *system_bh_wq;
563 EXPORT_SYMBOL_GPL(system_bh_wq);
564 struct workqueue_struct *system_bh_highpri_wq;
565 EXPORT_SYMBOL_GPL(system_bh_highpri_wq);
566 struct workqueue_struct *system_dfl_long_wq __ro_after_init;
567 EXPORT_SYMBOL_GPL(system_dfl_long_wq);
568 
569 static int worker_thread(void *__worker);
570 static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
571 static void show_pwq(struct pool_workqueue *pwq);
572 static void show_one_worker_pool(struct worker_pool *pool);
573 
574 #define CREATE_TRACE_POINTS
575 #include <trace/events/workqueue.h>
576 
577 #define assert_rcu_or_pool_mutex()					\
578 	RCU_LOCKDEP_WARN(!rcu_read_lock_any_held() &&			\
579 			 !lockdep_is_held(&wq_pool_mutex),		\
580 			 "RCU or wq_pool_mutex should be held")
581 
582 #define for_each_bh_worker_pool(pool, cpu)				\
583 	for ((pool) = &per_cpu(bh_worker_pools, cpu)[0];		\
584 	     (pool) < &per_cpu(bh_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
585 	     (pool)++)
586 
587 #define for_each_cpu_worker_pool(pool, cpu)				\
588 	for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0];		\
589 	     (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
590 	     (pool)++)
591 
592 /**
593  * for_each_pool - iterate through all worker_pools in the system
594  * @pool: iteration cursor
595  * @pi: integer used for iteration
596  *
597  * This must be called either with wq_pool_mutex held or RCU read
598  * locked.  If the pool needs to be used beyond the locking in effect, the
599  * caller is responsible for guaranteeing that the pool stays online.
600  *
601  * The if/else clause exists only for the lockdep assertion and can be
602  * ignored.
603  */
604 #define for_each_pool(pool, pi)						\
605 	idr_for_each_entry(&worker_pool_idr, pool, pi)			\
606 		if (({ assert_rcu_or_pool_mutex(); false; })) { }	\
607 		else
608 
609 /**
610  * for_each_pool_worker - iterate through all workers of a worker_pool
611  * @worker: iteration cursor
612  * @pool: worker_pool to iterate workers of
613  *
614  * This must be called with wq_pool_attach_mutex.
615  *
616  * The if/else clause exists only for the lockdep assertion and can be
617  * ignored.
618  */
619 #define for_each_pool_worker(worker, pool)				\
620 	list_for_each_entry((worker), &(pool)->workers, node)		\
621 		if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
622 		else
623 
624 /**
625  * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
626  * @pwq: iteration cursor
627  * @wq: the target workqueue
628  *
629  * This must be called either with wq->mutex held or RCU read locked.
630  * If the pwq needs to be used beyond the locking in effect, the caller is
631  * responsible for guaranteeing that the pwq stays online.
632  *
633  * The if/else clause exists only for the lockdep assertion and can be
634  * ignored.
635  */
636 #define for_each_pwq(pwq, wq)						\
637 	list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node,		\
638 				 lockdep_is_held(&(wq->mutex)))
639 
640 /*
641  * Per-node arrays in this file carry an extra slot at nr_node_ids serving
642  * NUMA_NO_NODE. Return the slot after all nodes.
643  */
644 static int next_node_with_fallback(int node)
645 {
646 	if (node >= nr_node_ids)
647 		return nr_node_ids + 1;
648 
649 	node = next_node(node, node_possible_map);
650 	if (node >= nr_node_ids)
651 		return nr_node_ids;
652 	return node;
653 }
654 
655 #define for_each_node_with_fallback(node)				\
656 	for ((node) = first_node(node_possible_map);			\
657 	     (node) <= nr_node_ids;					\
658 	     (node) = next_node_with_fallback(node))
659 
660 #ifdef CONFIG_DEBUG_OBJECTS_WORK
661 
662 static const struct debug_obj_descr work_debug_descr;
663 
664 static void *work_debug_hint(void *addr)
665 {
666 	return ((struct work_struct *) addr)->func;
667 }
668 
669 static bool work_is_static_object(void *addr)
670 {
671 	struct work_struct *work = addr;
672 
673 	return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
674 }
675 
676 /*
677  * fixup_init is called when:
678  * - an active object is initialized
679  */
680 static bool work_fixup_init(void *addr, enum debug_obj_state state)
681 {
682 	struct work_struct *work = addr;
683 
684 	switch (state) {
685 	case ODEBUG_STATE_ACTIVE:
686 		cancel_work_sync(work);
687 		debug_object_init(work, &work_debug_descr);
688 		return true;
689 	default:
690 		return false;
691 	}
692 }
693 
694 /*
695  * fixup_free is called when:
696  * - an active object is freed
697  */
698 static bool work_fixup_free(void *addr, enum debug_obj_state state)
699 {
700 	struct work_struct *work = addr;
701 
702 	switch (state) {
703 	case ODEBUG_STATE_ACTIVE:
704 		cancel_work_sync(work);
705 		debug_object_free(work, &work_debug_descr);
706 		return true;
707 	default:
708 		return false;
709 	}
710 }
711 
712 static const struct debug_obj_descr work_debug_descr = {
713 	.name		= "work_struct",
714 	.debug_hint	= work_debug_hint,
715 	.is_static_object = work_is_static_object,
716 	.fixup_init	= work_fixup_init,
717 	.fixup_free	= work_fixup_free,
718 };
719 
720 static inline void debug_work_activate(struct work_struct *work)
721 {
722 	debug_object_activate(work, &work_debug_descr);
723 }
724 
725 static inline void debug_work_deactivate(struct work_struct *work)
726 {
727 	debug_object_deactivate(work, &work_debug_descr);
728 }
729 
730 void __init_work(struct work_struct *work, int onstack)
731 {
732 	if (onstack)
733 		debug_object_init_on_stack(work, &work_debug_descr);
734 	else
735 		debug_object_init(work, &work_debug_descr);
736 }
737 EXPORT_SYMBOL_GPL(__init_work);
738 
739 void destroy_work_on_stack(struct work_struct *work)
740 {
741 	debug_object_free(work, &work_debug_descr);
742 }
743 EXPORT_SYMBOL_GPL(destroy_work_on_stack);
744 
745 void destroy_delayed_work_on_stack(struct delayed_work *work)
746 {
747 	timer_destroy_on_stack(&work->timer);
748 	debug_object_free(&work->work, &work_debug_descr);
749 }
750 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
751 
752 #else
753 static inline void debug_work_activate(struct work_struct *work) { }
754 static inline void debug_work_deactivate(struct work_struct *work) { }
755 #endif
756 
757 /**
758  * worker_pool_assign_id - allocate ID and assign it to @pool
759  * @pool: the pool pointer of interest
760  *
761  * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
762  * successfully, -errno on failure.
763  */
764 static int worker_pool_assign_id(struct worker_pool *pool)
765 {
766 	int ret;
767 
768 	lockdep_assert_held(&wq_pool_mutex);
769 
770 	ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
771 			GFP_KERNEL);
772 	if (ret >= 0) {
773 		pool->id = ret;
774 		return 0;
775 	}
776 	return ret;
777 }
778 
779 static struct pool_workqueue __rcu **
780 pwq_slot(struct workqueue_struct *wq, int cpu)
781 {
782        if (cpu >= 0)
783                return per_cpu_ptr(wq->cpu_pwq, cpu);
784        else
785                return &wq->dfl_pwq;
786 }
787 
788 /* @cpu < 0 for dfl_pwq */
789 static struct pool_workqueue *installed_pwq(struct workqueue_struct *wq, int cpu)
790 {
791 	return rcu_dereference_check(*pwq_slot(wq, cpu),
792 				     lockdep_is_held(&wq_pool_mutex) ||
793 				     lockdep_is_held(&wq->mutex));
794 }
795 
796 /**
797  * unbound_effective_cpumask - effective cpumask of an unbound workqueue
798  * @wq: workqueue of interest
799  *
800  * @wq->attrs->cpumask contains the cpumask requested by the user which
801  * is masked with wq_unbound_cpumask to determine the effective cpumask. The
802  * default pwq is always mapped to the pool with the current effective cpumask.
803  */
804 static struct cpumask *unbound_effective_cpumask(struct workqueue_struct *wq)
805 {
806 	return installed_pwq(wq, -1)->pool->attrs->__pod_cpumask;
807 }
808 
809 static unsigned int work_color_to_flags(int color)
810 {
811 	return color << WORK_STRUCT_COLOR_SHIFT;
812 }
813 
814 static int get_work_color(unsigned long work_data)
815 {
816 	return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
817 		((1 << WORK_STRUCT_COLOR_BITS) - 1);
818 }
819 
820 static int work_next_color(int color)
821 {
822 	return (color + 1) % WORK_NR_COLORS;
823 }
824 
825 static unsigned long pool_offq_flags(struct worker_pool *pool)
826 {
827 	return (pool->flags & POOL_BH) ? WORK_OFFQ_BH : 0;
828 }
829 
830 /*
831  * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
832  * contain the pointer to the queued pwq.  Once execution starts, the flag
833  * is cleared and the high bits contain OFFQ flags and pool ID.
834  *
835  * set_work_pwq(), set_work_pool_and_clear_pending() and mark_work_canceling()
836  * can be used to set the pwq, pool or clear work->data. These functions should
837  * only be called while the work is owned - ie. while the PENDING bit is set.
838  *
839  * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
840  * corresponding to a work.  Pool is available once the work has been
841  * queued anywhere after initialization until it is sync canceled.  pwq is
842  * available only while the work item is queued.
843  */
844 static inline void set_work_data(struct work_struct *work, unsigned long data)
845 {
846 	WARN_ON_ONCE(!work_pending(work));
847 	atomic_long_set(&work->data, data | work_static(work));
848 }
849 
850 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
851 			 unsigned long flags)
852 {
853 	set_work_data(work, (unsigned long)pwq | WORK_STRUCT_PENDING |
854 		      WORK_STRUCT_PWQ | flags);
855 }
856 
857 static void set_work_pool_and_keep_pending(struct work_struct *work,
858 					   int pool_id, unsigned long flags)
859 {
860 	set_work_data(work, ((unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT) |
861 		      WORK_STRUCT_PENDING | flags);
862 }
863 
864 static void set_work_pool_and_clear_pending(struct work_struct *work,
865 					    int pool_id, unsigned long flags)
866 {
867 	/*
868 	 * The following wmb is paired with the implied mb in
869 	 * test_and_set_bit(PENDING) and ensures all updates to @work made
870 	 * here are visible to and precede any updates by the next PENDING
871 	 * owner.
872 	 */
873 	smp_wmb();
874 	set_work_data(work, ((unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT) |
875 		      flags);
876 	/*
877 	 * The following mb guarantees that previous clear of a PENDING bit
878 	 * will not be reordered with any speculative LOADS or STORES from
879 	 * work->current_func, which is executed afterwards.  This possible
880 	 * reordering can lead to a missed execution on attempt to queue
881 	 * the same @work.  E.g. consider this case:
882 	 *
883 	 *   CPU#0                         CPU#1
884 	 *   ----------------------------  --------------------------------
885 	 *
886 	 * 1  STORE event_indicated
887 	 * 2  queue_work_on() {
888 	 * 3    test_and_set_bit(PENDING)
889 	 * 4 }                             set_..._and_clear_pending() {
890 	 * 5                                 set_work_data() # clear bit
891 	 * 6                                 smp_mb()
892 	 * 7                               work->current_func() {
893 	 * 8				      LOAD event_indicated
894 	 *				   }
895 	 *
896 	 * Without an explicit full barrier speculative LOAD on line 8 can
897 	 * be executed before CPU#0 does STORE on line 1.  If that happens,
898 	 * CPU#0 observes the PENDING bit is still set and new execution of
899 	 * a @work is not queued in a hope, that CPU#1 will eventually
900 	 * finish the queued @work.  Meanwhile CPU#1 does not see
901 	 * event_indicated is set, because speculative LOAD was executed
902 	 * before actual STORE.
903 	 */
904 	smp_mb();
905 }
906 
907 static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
908 {
909 	return (struct pool_workqueue *)(data & WORK_STRUCT_PWQ_MASK);
910 }
911 
912 static struct pool_workqueue *get_work_pwq(struct work_struct *work)
913 {
914 	unsigned long data = atomic_long_read(&work->data);
915 
916 	if (data & WORK_STRUCT_PWQ)
917 		return work_struct_pwq(data);
918 	else
919 		return NULL;
920 }
921 
922 /**
923  * get_work_pool - return the worker_pool a given work was associated with
924  * @work: the work item of interest
925  *
926  * Pools are created and destroyed under wq_pool_mutex, and allows read
927  * access under RCU read lock.  As such, this function should be
928  * called under wq_pool_mutex or inside of a rcu_read_lock() region.
929  *
930  * All fields of the returned pool are accessible as long as the above
931  * mentioned locking is in effect.  If the returned pool needs to be used
932  * beyond the critical section, the caller is responsible for ensuring the
933  * returned pool is and stays online.
934  *
935  * Return: The worker_pool @work was last associated with.  %NULL if none.
936  */
937 static struct worker_pool *get_work_pool(struct work_struct *work)
938 {
939 	unsigned long data = atomic_long_read(&work->data);
940 	int pool_id;
941 
942 	assert_rcu_or_pool_mutex();
943 
944 	if (data & WORK_STRUCT_PWQ)
945 		return work_struct_pwq(data)->pool;
946 
947 	pool_id = data >> WORK_OFFQ_POOL_SHIFT;
948 	if (pool_id == WORK_OFFQ_POOL_NONE)
949 		return NULL;
950 
951 	return idr_find(&worker_pool_idr, pool_id);
952 }
953 
954 static unsigned long shift_and_mask(unsigned long v, u32 shift, u32 bits)
955 {
956 	return (v >> shift) & ((1U << bits) - 1);
957 }
958 
959 static void work_offqd_unpack(struct work_offq_data *offqd, unsigned long data)
960 {
961 	WARN_ON_ONCE(data & WORK_STRUCT_PWQ);
962 
963 	offqd->pool_id = shift_and_mask(data, WORK_OFFQ_POOL_SHIFT,
964 					WORK_OFFQ_POOL_BITS);
965 	offqd->disable = shift_and_mask(data, WORK_OFFQ_DISABLE_SHIFT,
966 					WORK_OFFQ_DISABLE_BITS);
967 	offqd->flags = data & WORK_OFFQ_FLAG_MASK;
968 }
969 
970 static unsigned long work_offqd_pack_flags(struct work_offq_data *offqd)
971 {
972 	return ((unsigned long)offqd->disable << WORK_OFFQ_DISABLE_SHIFT) |
973 		((unsigned long)offqd->flags);
974 }
975 
976 /*
977  * Policy functions.  These define the policies on how the global worker
978  * pools are managed.  Unless noted otherwise, these functions assume that
979  * they're being called with pool->lock held.
980  */
981 
982 /*
983  * Need to wake up a worker?  Called from anything but currently
984  * running workers.
985  *
986  * Note that, because unbound workers never contribute to nr_running, this
987  * function will always return %true for unbound pools as long as the
988  * worklist isn't empty.
989  */
990 static bool need_more_worker(struct worker_pool *pool)
991 {
992 	return !list_empty(&pool->worklist) && !pool->nr_running;
993 }
994 
995 /* Can I start working?  Called from busy but !running workers. */
996 static bool may_start_working(struct worker_pool *pool)
997 {
998 	return pool->nr_idle;
999 }
1000 
1001 /* Do I need to keep working?  Called from currently running workers. */
1002 static bool keep_working(struct worker_pool *pool)
1003 {
1004 	return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
1005 }
1006 
1007 /* Do we need a new worker?  Called from manager. */
1008 static bool need_to_create_worker(struct worker_pool *pool)
1009 {
1010 	return need_more_worker(pool) && !may_start_working(pool);
1011 }
1012 
1013 /* Do we have too many workers and should some go away? */
1014 static bool too_many_workers(struct worker_pool *pool)
1015 {
1016 	bool managing = pool->flags & POOL_MANAGER_ACTIVE;
1017 	int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
1018 	int nr_busy = pool->nr_workers - nr_idle;
1019 
1020 	return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
1021 }
1022 
1023 /**
1024  * worker_set_flags - set worker flags and adjust nr_running accordingly
1025  * @worker: self
1026  * @flags: flags to set
1027  *
1028  * Set @flags in @worker->flags and adjust nr_running accordingly.
1029  */
1030 static inline void worker_set_flags(struct worker *worker, unsigned int flags)
1031 {
1032 	struct worker_pool *pool = worker->pool;
1033 
1034 	lockdep_assert_held(&pool->lock);
1035 
1036 	/* If transitioning into NOT_RUNNING, adjust nr_running. */
1037 	if ((flags & WORKER_NOT_RUNNING) &&
1038 	    !(worker->flags & WORKER_NOT_RUNNING)) {
1039 		pool->nr_running--;
1040 	}
1041 
1042 	worker->flags |= flags;
1043 }
1044 
1045 /**
1046  * worker_clr_flags - clear worker flags and adjust nr_running accordingly
1047  * @worker: self
1048  * @flags: flags to clear
1049  *
1050  * Clear @flags in @worker->flags and adjust nr_running accordingly.
1051  */
1052 static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
1053 {
1054 	struct worker_pool *pool = worker->pool;
1055 	unsigned int oflags = worker->flags;
1056 
1057 	lockdep_assert_held(&pool->lock);
1058 
1059 	worker->flags &= ~flags;
1060 
1061 	/*
1062 	 * If transitioning out of NOT_RUNNING, increment nr_running.  Note
1063 	 * that the nested NOT_RUNNING is not a noop.  NOT_RUNNING is mask
1064 	 * of multiple flags, not a single flag.
1065 	 */
1066 	if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
1067 		if (!(worker->flags & WORKER_NOT_RUNNING))
1068 			pool->nr_running++;
1069 }
1070 
1071 /* Return the first idle worker.  Called with pool->lock held. */
1072 static struct worker *first_idle_worker(struct worker_pool *pool)
1073 {
1074 	if (unlikely(list_empty(&pool->idle_list)))
1075 		return NULL;
1076 
1077 	return list_first_entry(&pool->idle_list, struct worker, entry);
1078 }
1079 
1080 /**
1081  * worker_enter_idle - enter idle state
1082  * @worker: worker which is entering idle state
1083  *
1084  * @worker is entering idle state.  Update stats and idle timer if
1085  * necessary.
1086  *
1087  * LOCKING:
1088  * raw_spin_lock_irq(pool->lock).
1089  */
1090 static void worker_enter_idle(struct worker *worker)
1091 {
1092 	struct worker_pool *pool = worker->pool;
1093 
1094 	if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
1095 	    WARN_ON_ONCE(!list_empty(&worker->entry) &&
1096 			 (worker->hentry.next || worker->hentry.pprev)))
1097 		return;
1098 
1099 	/* can't use worker_set_flags(), also called from create_worker() */
1100 	worker->flags |= WORKER_IDLE;
1101 	pool->nr_idle++;
1102 	worker->last_active = jiffies;
1103 
1104 	/* idle_list is LIFO */
1105 	list_add(&worker->entry, &pool->idle_list);
1106 
1107 	if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
1108 		mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
1109 
1110 	/* Sanity check nr_running. */
1111 	WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
1112 }
1113 
1114 /**
1115  * worker_leave_idle - leave idle state
1116  * @worker: worker which is leaving idle state
1117  *
1118  * @worker is leaving idle state.  Update stats.
1119  *
1120  * LOCKING:
1121  * raw_spin_lock_irq(pool->lock).
1122  */
1123 static void worker_leave_idle(struct worker *worker)
1124 {
1125 	struct worker_pool *pool = worker->pool;
1126 
1127 	if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
1128 		return;
1129 	worker_clr_flags(worker, WORKER_IDLE);
1130 	pool->nr_idle--;
1131 	list_del_init(&worker->entry);
1132 }
1133 
1134 /**
1135  * find_worker_executing_work - find worker which is executing a work
1136  * @pool: pool of interest
1137  * @work: work to find worker for
1138  *
1139  * Find a worker which is executing @work on @pool by searching
1140  * @pool->busy_hash which is keyed by the address of @work.  For a worker
1141  * to match, its current execution should match the address of @work and
1142  * its work function.  This is to avoid unwanted dependency between
1143  * unrelated work executions through a work item being recycled while still
1144  * being executed.
1145  *
1146  * This is a bit tricky.  A work item may be freed once its execution
1147  * starts and nothing prevents the freed area from being recycled for
1148  * another work item.  If the same work item address ends up being reused
1149  * before the original execution finishes, workqueue will identify the
1150  * recycled work item as currently executing and make it wait until the
1151  * current execution finishes, introducing an unwanted dependency.
1152  *
1153  * This function checks the work item address and work function to avoid
1154  * false positives.  Note that this isn't complete as one may construct a
1155  * work function which can introduce dependency onto itself through a
1156  * recycled work item.  Well, if somebody wants to shoot oneself in the
1157  * foot that badly, there's only so much we can do, and if such deadlock
1158  * actually occurs, it should be easy to locate the culprit work function.
1159  *
1160  * CONTEXT:
1161  * raw_spin_lock_irq(pool->lock).
1162  *
1163  * Return:
1164  * Pointer to worker which is executing @work if found, %NULL
1165  * otherwise.
1166  */
1167 static struct worker *find_worker_executing_work(struct worker_pool *pool,
1168 						 struct work_struct *work)
1169 {
1170 	struct worker *worker;
1171 
1172 	hash_for_each_possible(pool->busy_hash, worker, hentry,
1173 			       (unsigned long)work)
1174 		if (worker->current_work == work &&
1175 		    worker->current_func == work->func)
1176 			return worker;
1177 
1178 	return NULL;
1179 }
1180 
1181 static void mayday_cursor_func(struct work_struct *work)
1182 {
1183 	/* should not be processed, only for marking position */
1184 	BUG();
1185 }
1186 
1187 /**
1188  * move_linked_works - move linked works to a list
1189  * @work: start of series of works to be scheduled
1190  * @head: target list to append @work to
1191  * @nextp: out parameter for nested worklist walking
1192  *
1193  * Schedule linked works starting from @work to @head. Work series to be
1194  * scheduled starts at @work and includes any consecutive work with
1195  * WORK_STRUCT_LINKED set in its predecessor. See assign_work() for details on
1196  * @nextp.
1197  *
1198  * CONTEXT:
1199  * raw_spin_lock_irq(pool->lock).
1200  */
1201 static void move_linked_works(struct work_struct *work, struct list_head *head,
1202 			      struct work_struct **nextp)
1203 {
1204 	struct work_struct *n;
1205 
1206 	/*
1207 	 * Linked worklist will always end before the end of the list,
1208 	 * use NULL for list head.
1209 	 */
1210 	list_for_each_entry_safe_from(work, n, NULL, entry) {
1211 		list_move_tail(&work->entry, head);
1212 		if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1213 			break;
1214 	}
1215 
1216 	/*
1217 	 * If we're already inside safe list traversal and have moved
1218 	 * multiple works to the scheduled queue, the next position
1219 	 * needs to be updated.
1220 	 */
1221 	if (nextp)
1222 		*nextp = n;
1223 }
1224 
1225 /**
1226  * assign_work - assign a work item and its linked work items to a worker
1227  * @work: work to assign
1228  * @worker: worker to assign to
1229  * @nextp: out parameter for nested worklist walking
1230  *
1231  * Assign @work and its linked work items to @worker. If @work is already being
1232  * executed by another worker in the same pool, it'll be punted there.
1233  *
1234  * If @nextp is not NULL, it's updated to point to the next work of the last
1235  * scheduled work. This allows assign_work() to be nested inside
1236  * list_for_each_entry_safe().
1237  *
1238  * Returns %true if @work was successfully assigned to @worker. %false if @work
1239  * was punted to another worker already executing it.
1240  */
1241 static bool assign_work(struct work_struct *work, struct worker *worker,
1242 			struct work_struct **nextp)
1243 {
1244 	struct worker_pool *pool = worker->pool;
1245 	struct worker *collision;
1246 
1247 	lockdep_assert_held(&pool->lock);
1248 
1249 	/* The cursor work should not be processed */
1250 	if (unlikely(work->func == mayday_cursor_func)) {
1251 		/* only worker_thread() can possibly take this branch */
1252 		WARN_ON_ONCE(worker->rescue_wq);
1253 		if (nextp)
1254 			*nextp = list_next_entry(work, entry);
1255 		list_del_init(&work->entry);
1256 		return false;
1257 	}
1258 
1259 	/*
1260 	 * A single work shouldn't be executed concurrently by multiple workers.
1261 	 * __queue_work() ensures that @work doesn't jump to a different pool
1262 	 * while still running in the previous pool. Here, we should ensure that
1263 	 * @work is not executed concurrently by multiple workers from the same
1264 	 * pool. Check whether anyone is already processing the work. If so,
1265 	 * defer the work to the currently executing one.
1266 	 */
1267 	collision = find_worker_executing_work(pool, work);
1268 	if (unlikely(collision)) {
1269 		move_linked_works(work, &collision->scheduled, nextp);
1270 		return false;
1271 	}
1272 
1273 	move_linked_works(work, &worker->scheduled, nextp);
1274 	return true;
1275 }
1276 
1277 static struct irq_work *bh_pool_irq_work(struct worker_pool *pool)
1278 {
1279 	int high = pool->attrs->nice == HIGHPRI_NICE_LEVEL ? 1 : 0;
1280 
1281 	return &per_cpu(bh_pool_irq_works, pool->cpu)[high];
1282 }
1283 
1284 static void kick_bh_pool(struct worker_pool *pool)
1285 {
1286 #ifdef CONFIG_SMP
1287 	/* see drain_dead_softirq_workfn() for BH_DRAINING */
1288 	if (unlikely(pool->cpu != smp_processor_id() &&
1289 		     !(pool->flags & POOL_BH_DRAINING))) {
1290 		irq_work_queue_on(bh_pool_irq_work(pool), pool->cpu);
1291 		return;
1292 	}
1293 #endif
1294 	if (pool->attrs->nice == HIGHPRI_NICE_LEVEL)
1295 		raise_softirq_irqoff(HI_SOFTIRQ);
1296 	else
1297 		raise_softirq_irqoff(TASKLET_SOFTIRQ);
1298 }
1299 
1300 /**
1301  * kick_pool_pick - select an idle worker to kick, deferring the wakeup
1302  * @pool: pool to kick
1303  * @wakep: out-param, set to the task to wake after pool->lock is dropped
1304  *
1305  * Like kick_pool() but, for a regular (non-BH) pool, returns the picked
1306  * worker's task via @wakep instead of waking it, so the caller can issue the
1307  * wakeup after dropping pool->lock (the wakeup takes rq->lock). Worker
1308  * selection, wake_cpu setup and the BH kick still happen under the lock.
1309  * Returns whether a worker was selected or kicked.
1310  *
1311  * Must be called with @pool->lock held.
1312  */
1313 static bool kick_pool_pick(struct worker_pool *pool, struct task_struct **wakep)
1314 {
1315 	struct worker *worker = first_idle_worker(pool);
1316 	struct task_struct *p;
1317 
1318 	lockdep_assert_held(&pool->lock);
1319 
1320 	*wakep = NULL;
1321 
1322 	if (!need_more_worker(pool) || !worker)
1323 		return false;
1324 
1325 	if (pool->flags & POOL_BH) {
1326 		kick_bh_pool(pool);
1327 		return true;
1328 	}
1329 
1330 	p = worker->task;
1331 
1332 #ifdef CONFIG_SMP
1333 	/*
1334 	 * Idle @worker is about to execute @work and waking up provides an
1335 	 * opportunity to migrate @worker at a lower cost by setting the task's
1336 	 * wake_cpu field. Let's see if we want to move @worker to improve
1337 	 * execution locality.
1338 	 *
1339 	 * We're waking the worker that went idle the latest and there's some
1340 	 * chance that @worker is marked idle but hasn't gone off CPU yet. If
1341 	 * so, setting the wake_cpu won't do anything. As this is a best-effort
1342 	 * optimization and the race window is narrow, let's leave as-is for
1343 	 * now. If this becomes pronounced, we can skip over workers which are
1344 	 * still on cpu when picking an idle worker.
1345 	 *
1346 	 * If @pool has non-strict affinity, @worker might have ended up outside
1347 	 * its affinity scope. Repatriate.
1348 	 */
1349 	if (!pool->attrs->affn_strict &&
1350 	    !cpumask_test_cpu(READ_ONCE(p->wake_cpu),
1351 			      pool->attrs->__pod_cpumask)) {
1352 		struct work_struct *work = list_first_entry(&pool->worklist,
1353 						struct work_struct, entry);
1354 		int wake_cpu = cpumask_any_and_distribute(pool->attrs->__pod_cpumask,
1355 							  cpu_online_mask);
1356 		if (wake_cpu < nr_cpu_ids) {
1357 			WRITE_ONCE(p->wake_cpu, wake_cpu);
1358 			get_work_pwq(work)->stats[PWQ_STAT_REPATRIATED]++;
1359 		}
1360 	}
1361 #endif
1362 	/* Track the last idle worker woken, used for stall diagnostics. */
1363 	pool->last_woken_worker = worker;
1364 
1365 	*wakep = p;
1366 	return true;
1367 }
1368 
1369 /**
1370  * kick_pool - wake up an idle worker if necessary
1371  * @pool: pool to kick
1372  *
1373  * @pool may have pending work items. Wake up worker if necessary. Returns
1374  * whether a worker was woken up.
1375  */
1376 static bool kick_pool(struct worker_pool *pool)
1377 {
1378 	struct task_struct *p;
1379 	bool kicked = kick_pool_pick(pool, &p);
1380 
1381 	if (p)
1382 		wake_up_process(p);
1383 	return kicked;
1384 }
1385 
1386 #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
1387 
1388 /*
1389  * Concurrency-managed per-cpu work items that hog CPU for longer than
1390  * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
1391  * which prevents them from stalling other concurrency-managed work items. If a
1392  * work function keeps triggering this mechanism, it's likely that the work item
1393  * should be using an unbound workqueue instead.
1394  *
1395  * wq_cpu_intensive_report() tracks work functions which trigger such conditions
1396  * and report them so that they can be examined and converted to use unbound
1397  * workqueues as appropriate. To avoid flooding the console, each violating work
1398  * function is tracked and reported with exponential backoff.
1399  */
1400 #define WCI_MAX_ENTS 128
1401 
1402 struct wci_ent {
1403 	work_func_t		func;
1404 	atomic64_t		cnt;
1405 	struct hlist_node	hash_node;
1406 };
1407 
1408 static struct wci_ent wci_ents[WCI_MAX_ENTS];
1409 static int wci_nr_ents;
1410 static DEFINE_RAW_SPINLOCK(wci_lock);
1411 static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
1412 
1413 static struct wci_ent *wci_find_ent(work_func_t func)
1414 {
1415 	struct wci_ent *ent;
1416 
1417 	hash_for_each_possible_rcu(wci_hash, ent, hash_node,
1418 				   (unsigned long)func) {
1419 		if (ent->func == func)
1420 			return ent;
1421 	}
1422 	return NULL;
1423 }
1424 
1425 static void wq_cpu_intensive_report(work_func_t func)
1426 {
1427 	struct wci_ent *ent;
1428 
1429 restart:
1430 	ent = wci_find_ent(func);
1431 	if (ent) {
1432 		u64 cnt;
1433 
1434 		/*
1435 		 * Start reporting from the warning_thresh and back off
1436 		 * exponentially.
1437 		 */
1438 		cnt = atomic64_inc_return_relaxed(&ent->cnt);
1439 		if (wq_cpu_intensive_warning_thresh &&
1440 		    cnt >= wq_cpu_intensive_warning_thresh &&
1441 		    is_power_of_2(cnt + 1 - wq_cpu_intensive_warning_thresh))
1442 			printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
1443 					ent->func, wq_cpu_intensive_thresh_us,
1444 					atomic64_read(&ent->cnt));
1445 		return;
1446 	}
1447 
1448 	/*
1449 	 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
1450 	 * is exhausted, something went really wrong and we probably made enough
1451 	 * noise already.
1452 	 */
1453 	if (wci_nr_ents >= WCI_MAX_ENTS)
1454 		return;
1455 
1456 	raw_spin_lock(&wci_lock);
1457 
1458 	if (wci_nr_ents >= WCI_MAX_ENTS) {
1459 		raw_spin_unlock(&wci_lock);
1460 		return;
1461 	}
1462 
1463 	if (wci_find_ent(func)) {
1464 		raw_spin_unlock(&wci_lock);
1465 		goto restart;
1466 	}
1467 
1468 	ent = &wci_ents[wci_nr_ents++];
1469 	ent->func = func;
1470 	atomic64_set(&ent->cnt, 0);
1471 	hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
1472 
1473 	raw_spin_unlock(&wci_lock);
1474 
1475 	goto restart;
1476 }
1477 
1478 #else	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1479 static void wq_cpu_intensive_report(work_func_t func) {}
1480 #endif	/* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1481 
1482 /**
1483  * wq_worker_running - a worker is running again
1484  * @task: task waking up
1485  *
1486  * This function is called when a worker returns from schedule()
1487  */
1488 void wq_worker_running(struct task_struct *task)
1489 {
1490 	struct worker *worker = kthread_data(task);
1491 
1492 	if (!READ_ONCE(worker->sleeping))
1493 		return;
1494 
1495 	/*
1496 	 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
1497 	 * and the nr_running increment below, we may ruin the nr_running reset
1498 	 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
1499 	 * pool. Protect against such race.
1500 	 */
1501 	preempt_disable();
1502 	if (!(worker->flags & WORKER_NOT_RUNNING))
1503 		worker->pool->nr_running++;
1504 	preempt_enable();
1505 
1506 	/*
1507 	 * CPU intensive auto-detection cares about how long a work item hogged
1508 	 * CPU without sleeping. Reset the starting timestamp on wakeup.
1509 	 */
1510 	worker->current_at = READ_ONCE(worker->task->se.sum_exec_runtime);
1511 
1512 	WRITE_ONCE(worker->sleeping, 0);
1513 }
1514 
1515 /**
1516  * wq_worker_sleeping - a worker is going to sleep
1517  * @task: task going to sleep
1518  *
1519  * This function is called from schedule() when a busy worker is
1520  * going to sleep.
1521  */
1522 void wq_worker_sleeping(struct task_struct *task)
1523 {
1524 	struct worker *worker = kthread_data(task);
1525 	struct worker_pool *pool;
1526 
1527 	/*
1528 	 * Rescuers, which may not have all the fields set up like normal
1529 	 * workers, also reach here, let's not access anything before
1530 	 * checking NOT_RUNNING.
1531 	 */
1532 	if (worker->flags & WORKER_NOT_RUNNING)
1533 		return;
1534 
1535 	pool = worker->pool;
1536 
1537 	/* Return if preempted before wq_worker_running() was reached */
1538 	if (READ_ONCE(worker->sleeping))
1539 		return;
1540 
1541 	WRITE_ONCE(worker->sleeping, 1);
1542 	raw_spin_lock_irq(&pool->lock);
1543 
1544 	/*
1545 	 * Recheck in case unbind_workers() preempted us. We don't
1546 	 * want to decrement nr_running after the worker is unbound
1547 	 * and nr_running has been reset.
1548 	 */
1549 	if (worker->flags & WORKER_NOT_RUNNING) {
1550 		raw_spin_unlock_irq(&pool->lock);
1551 		return;
1552 	}
1553 
1554 	pool->nr_running--;
1555 	if (kick_pool(pool))
1556 		worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1557 
1558 	raw_spin_unlock_irq(&pool->lock);
1559 }
1560 
1561 /**
1562  * wq_worker_tick - a scheduler tick occurred while a kworker is running
1563  * @task: task currently running
1564  *
1565  * Called from sched_tick(). We're in the IRQ context and the current
1566  * worker's fields which follow the 'K' locking rule can be accessed safely.
1567  */
1568 void wq_worker_tick(struct task_struct *task)
1569 {
1570 	struct worker *worker = kthread_data(task);
1571 	struct pool_workqueue *pwq = worker->current_pwq;
1572 	struct worker_pool *pool = worker->pool;
1573 	u64 delta;
1574 
1575 	if (!pwq)
1576 		return;
1577 
1578 	/*
1579 	 * @pwq is shared across CPUs for unbound wqs and this advisory stat is
1580 	 * bumped outside pool->lock, so the update is intentionally racy.
1581 	 */
1582 	data_race(pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC);
1583 
1584 	if (!wq_cpu_intensive_thresh_us)
1585 		return;
1586 
1587 	/*
1588 	 * If the current worker is concurrency managed and hogged the CPU for
1589 	 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1590 	 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1591 	 *
1592 	 * Set @worker->sleeping means that @worker is in the process of
1593 	 * switching out voluntarily and won't be contributing to
1594 	 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1595 	 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1596 	 * double decrements. The task is releasing the CPU anyway. Let's skip.
1597 	 * We probably want to make this prettier in the future.
1598 	 */
1599 	if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1600 	    READ_ONCE(worker->task->se.sum_exec_runtime) - worker->current_at <
1601 	    wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1602 		return;
1603 
1604 	raw_spin_lock(&pool->lock);
1605 
1606 	worker_set_flags(worker, WORKER_CPU_INTENSIVE);
1607 	wq_cpu_intensive_report(worker->current_func);
1608 	pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1609 
1610 	if (kick_pool(pool))
1611 		pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1612 
1613 	raw_spin_unlock(&pool->lock);
1614 
1615 	delta = READ_ONCE(worker->task->se.sum_exec_runtime) - worker->current_at;
1616 	trace_workqueue_cpu_intensive(pwq, worker->current_work,
1617 				      worker->current_func,
1618 				      div_u64(delta, NSEC_PER_USEC));
1619 }
1620 
1621 /**
1622  * wq_worker_last_func - retrieve worker's last work function
1623  * @task: Task to retrieve last work function of.
1624  *
1625  * Determine the last function a worker executed. This is called from
1626  * the scheduler to get a worker's last known identity.
1627  *
1628  * CONTEXT:
1629  * raw_spin_lock_irq(rq->lock)
1630  *
1631  * This function is called during schedule() when a kworker is going
1632  * to sleep. It's used by psi to identify aggregation workers during
1633  * dequeuing, to allow periodic aggregation to shut-off when that
1634  * worker is the last task in the system or cgroup to go to sleep.
1635  *
1636  * As this function doesn't involve any workqueue-related locking, it
1637  * only returns stable values when called from inside the scheduler's
1638  * queuing and dequeuing paths, when @task, which must be a kworker,
1639  * is guaranteed to not be processing any works.
1640  *
1641  * Return:
1642  * The last work function %current executed as a worker, NULL if it
1643  * hasn't executed any work yet.
1644  */
1645 work_func_t wq_worker_last_func(struct task_struct *task)
1646 {
1647 	struct worker *worker = kthread_data(task);
1648 
1649 	return worker->last_func;
1650 }
1651 
1652 /* True if @pool is a static per-cpu pool rather than an unbound one. */
1653 static bool is_percpu_pool(struct worker_pool *pool)
1654 {
1655 	return pool->cpu >= 0;
1656 }
1657 
1658 /**
1659  * wq_node_nr_active - Determine wq_node_nr_active to use
1660  * @wq: workqueue of interest
1661  * @node: NUMA node, can be %NUMA_NO_NODE
1662  *
1663  * Determine wq_node_nr_active to use for @wq on @node. @wq must be unbound.
1664  * Returns:
1665  *
1666  * - node_nr_active[nr_node_ids] if @node is %NUMA_NO_NODE.
1667  *
1668  * - Otherwise, node_nr_active[@node].
1669  */
1670 static struct wq_node_nr_active *wq_node_nr_active(struct workqueue_struct *wq,
1671 						   int node)
1672 {
1673 	BUG_ON(!(wq->flags & WQ_UNBOUND));
1674 
1675 	if (node == NUMA_NO_NODE)
1676 		node = nr_node_ids;
1677 
1678 	return wq->node_nr_active[node];
1679 }
1680 
1681 /**
1682  * wq_flush_pnode - Determine wq_flush_pnode to use
1683  * @wq: workqueue of interest
1684  * @node: NUMA node, can be %NUMA_NO_NODE
1685  *
1686  * Return @wq's wq_flush_pnode for @node, the nr_node_ids fallback if @node is
1687  * %NUMA_NO_NODE.
1688  */
1689 static struct wq_flush_pnode *wq_flush_pnode(struct workqueue_struct *wq, int node)
1690 {
1691 	if (node == NUMA_NO_NODE)
1692 		node = nr_node_ids;
1693 
1694 	return wq->flush_pnodes[node];
1695 }
1696 
1697 /**
1698  * wq_update_node_max_active - Update per-node max_actives to use
1699  * @wq: workqueue to update
1700  * @off_cpu: CPU that's going down, -1 if a CPU is not going down
1701  *
1702  * Update @wq->node_nr_active[]->max. @wq must be unbound. max_active is
1703  * distributed among nodes according to the proportions of numbers of online
1704  * cpus. The result is always between @wq->min_active and max_active.
1705  */
1706 static void wq_update_node_max_active(struct workqueue_struct *wq, int off_cpu)
1707 {
1708 	struct cpumask *effective = unbound_effective_cpumask(wq);
1709 	int min_active = READ_ONCE(wq->min_active);
1710 	int max_active = READ_ONCE(wq->max_active);
1711 	int total_cpus, node;
1712 
1713 	lockdep_assert_held(&wq->mutex);
1714 
1715 	if (!wq_topo_initialized)
1716 		return;
1717 
1718 	if (off_cpu >= 0 && !cpumask_test_cpu(off_cpu, effective))
1719 		off_cpu = -1;
1720 
1721 	total_cpus = cpumask_weight_and(effective, cpu_online_mask);
1722 	if (off_cpu >= 0)
1723 		total_cpus--;
1724 
1725 	/* If all CPUs of the wq get offline, use the default values */
1726 	if (unlikely(!total_cpus)) {
1727 		for_each_node(node)
1728 			wq_node_nr_active(wq, node)->max = min_active;
1729 
1730 		wq_node_nr_active(wq, NUMA_NO_NODE)->max = max_active;
1731 		return;
1732 	}
1733 
1734 	for_each_node(node) {
1735 		int node_cpus;
1736 
1737 		node_cpus = cpumask_weight_and(effective, cpumask_of_node(node));
1738 		if (off_cpu >= 0 && cpu_to_node(off_cpu) == node)
1739 			node_cpus--;
1740 
1741 		wq_node_nr_active(wq, node)->max =
1742 			clamp(DIV_ROUND_UP(max_active * node_cpus, total_cpus),
1743 			      min_active, max_active);
1744 	}
1745 
1746 	wq_node_nr_active(wq, NUMA_NO_NODE)->max = max_active;
1747 }
1748 
1749 /**
1750  * get_pwq - get an extra reference on the specified pool_workqueue
1751  * @pwq: pool_workqueue to get
1752  *
1753  * Obtain an extra reference on @pwq.  The caller should guarantee that
1754  * @pwq has positive refcnt and be holding the matching pool->lock.
1755  */
1756 static void get_pwq(struct pool_workqueue *pwq)
1757 {
1758 	lockdep_assert_held(&pwq->pool->lock);
1759 	WARN_ON_ONCE(pwq->refcnt <= 0);
1760 	pwq->refcnt++;
1761 }
1762 
1763 /**
1764  * put_pwq - put a pool_workqueue reference
1765  * @pwq: pool_workqueue to put
1766  *
1767  * Drop a reference of @pwq.  If its refcnt reaches zero, schedule its
1768  * destruction.  The caller should be holding the matching pool->lock.
1769  */
1770 static void put_pwq(struct pool_workqueue *pwq)
1771 {
1772 	lockdep_assert_held(&pwq->pool->lock);
1773 	if (likely(--pwq->refcnt))
1774 		return;
1775 
1776 	/*
1777 	 * pwq_release_worker is only created in workqueue_init(). Getting
1778 	 * here before that means an early workqueue allocation failed, which
1779 	 * is fatal anyway.
1780 	 */
1781 	BUG_ON(!pwq_release_worker);
1782 
1783 	/*
1784 	 * @pwq can't be released under pool->lock, bounce to a dedicated
1785 	 * kthread_worker to avoid A-A deadlocks.
1786 	 */
1787 	kthread_queue_work(pwq_release_worker, &pwq->release_work);
1788 }
1789 
1790 /**
1791  * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1792  * @pwq: pool_workqueue to put (can be %NULL)
1793  *
1794  * put_pwq() with locking.  This function also allows %NULL @pwq.
1795  */
1796 static void put_pwq_unlocked(struct pool_workqueue *pwq)
1797 {
1798 	if (pwq) {
1799 		/*
1800 		 * As both pwqs and pools are RCU protected, the
1801 		 * following lock operations are safe.
1802 		 */
1803 		raw_spin_lock_irq(&pwq->pool->lock);
1804 		put_pwq(pwq);
1805 		raw_spin_unlock_irq(&pwq->pool->lock);
1806 	}
1807 }
1808 
1809 static bool pwq_is_empty(struct pool_workqueue *pwq)
1810 {
1811 	return !pwq->nr_active && list_empty(&pwq->inactive_works);
1812 }
1813 
1814 static void __pwq_activate_work(struct pool_workqueue *pwq,
1815 				struct work_struct *work)
1816 {
1817 	unsigned long *wdb = work_data_bits(work);
1818 
1819 	WARN_ON_ONCE(!(*wdb & WORK_STRUCT_INACTIVE));
1820 	trace_workqueue_activate_work(work);
1821 	if (list_empty(&pwq->pool->worklist))
1822 		pwq->pool->last_progress_ts = jiffies;
1823 	move_linked_works(work, &pwq->pool->worklist, NULL);
1824 	__clear_bit(WORK_STRUCT_INACTIVE_BIT, wdb);
1825 }
1826 
1827 static bool tryinc_node_nr_active(struct wq_node_nr_active *nna)
1828 {
1829 	int max = READ_ONCE(nna->max);
1830 	int old = atomic_read(&nna->nr);
1831 
1832 	do {
1833 		if (old >= max)
1834 			return false;
1835 	} while (!atomic_try_cmpxchg_relaxed(&nna->nr, &old, old + 1));
1836 
1837 	return true;
1838 }
1839 
1840 /**
1841  * pwq_tryinc_nr_active - Try to increment nr_active for a pwq
1842  * @pwq: pool_workqueue of interest
1843  * @fill: max_active may have increased, try to increase concurrency level
1844  *
1845  * Try to increment nr_active for @pwq. Returns %true if an nr_active count is
1846  * successfully obtained. %false otherwise.
1847  */
1848 static bool pwq_tryinc_nr_active(struct pool_workqueue *pwq, bool fill)
1849 {
1850 	struct workqueue_struct *wq = pwq->wq;
1851 	struct worker_pool *pool = pwq->pool;
1852 	struct wq_node_nr_active *nna;
1853 	bool obtained = false;
1854 
1855 	lockdep_assert_held(&pool->lock);
1856 
1857 	/*
1858 	 * A concurrency-managed per-cpu pool accounts nr_active per pwq, so
1859 	 * pwq->nr_active against wq->percpu_max_active is sufficient.
1860 	 */
1861 	if (is_percpu_pool(pool)) {
1862 		obtained = pwq->nr_active < READ_ONCE(wq->percpu_max_active);
1863 		goto out;
1864 	}
1865 
1866 	if (unlikely(pwq->plugged))
1867 		return false;
1868 
1869 	nna = wq_node_nr_active(wq, pool->node);
1870 
1871 	/*
1872 	 * Unbound workqueue uses per-node shared nr_active $nna. If @pwq is
1873 	 * already waiting on $nna, pwq_dec_nr_active() will maintain the
1874 	 * concurrency level. Don't jump the line.
1875 	 *
1876 	 * We need to ignore the pending test after max_active has increased as
1877 	 * pwq_dec_nr_active() can only maintain the concurrency level but not
1878 	 * increase it. This is indicated by @fill.
1879 	 */
1880 	if (!list_empty(&pwq->pending_node) && likely(!fill))
1881 		goto out;
1882 
1883 	obtained = tryinc_node_nr_active(nna);
1884 	if (obtained)
1885 		goto out;
1886 
1887 	/*
1888 	 * Lockless acquisition failed. Lock, add ourself to $nna->pending_pwqs
1889 	 * and try again. The smp_mb() is paired with the implied memory barrier
1890 	 * of atomic_dec_return() in pwq_dec_nr_active() to ensure that either
1891 	 * we see the decremented $nna->nr or they see non-empty
1892 	 * $nna->pending_pwqs.
1893 	 */
1894 	raw_spin_lock(&nna->lock);
1895 
1896 	if (list_empty(&pwq->pending_node))
1897 		list_add_tail(&pwq->pending_node, &nna->pending_pwqs);
1898 	else if (likely(!fill))
1899 		goto out_unlock;
1900 
1901 	smp_mb();
1902 
1903 	obtained = tryinc_node_nr_active(nna);
1904 
1905 	/*
1906 	 * If @fill, @pwq might have already been pending. Being spuriously
1907 	 * pending in cold paths doesn't affect anything. Let's leave it be.
1908 	 */
1909 	if (obtained && likely(!fill))
1910 		list_del_init(&pwq->pending_node);
1911 
1912 out_unlock:
1913 	raw_spin_unlock(&nna->lock);
1914 out:
1915 	if (obtained)
1916 		pwq->nr_active++;
1917 	return obtained;
1918 }
1919 
1920 /**
1921  * pwq_activate_first_inactive - Activate the first inactive work item on a pwq
1922  * @pwq: pool_workqueue of interest
1923  * @fill: max_active may have increased, try to increase concurrency level
1924  *
1925  * Activate the first inactive work item of @pwq if available and allowed by
1926  * max_active limit.
1927  *
1928  * Returns %true if an inactive work item has been activated. %false if no
1929  * inactive work item is found or max_active limit is reached.
1930  */
1931 static bool pwq_activate_first_inactive(struct pool_workqueue *pwq, bool fill)
1932 {
1933 	struct work_struct *work =
1934 		list_first_entry_or_null(&pwq->inactive_works,
1935 					 struct work_struct, entry);
1936 
1937 	if (work && pwq_tryinc_nr_active(pwq, fill)) {
1938 		__pwq_activate_work(pwq, work);
1939 		return true;
1940 	} else {
1941 		return false;
1942 	}
1943 }
1944 
1945 /**
1946  * unplug_oldest_pwq - unplug the oldest pool_workqueue
1947  * @wq: workqueue_struct where its oldest pwq is to be unplugged
1948  *
1949  * This function should only be called for ordered workqueues where only the
1950  * oldest pwq is unplugged, the others are plugged to suspend execution to
1951  * ensure proper work item ordering::
1952  *
1953  *    dfl_pwq --------------+     [P] - plugged
1954  *                          |
1955  *                          v
1956  *    pwqs -> A -> B [P] -> C [P] (newest)
1957  *            |    |        |
1958  *            1    3        5
1959  *            |    |        |
1960  *            2    4        6
1961  *
1962  * When the oldest pwq is drained and removed, this function should be called
1963  * to unplug the next oldest one to start its work item execution. Note that
1964  * pwq's are linked into wq->pwqs with the oldest first, so the first one in
1965  * the list is the oldest.
1966  */
1967 static void unplug_oldest_pwq(struct workqueue_struct *wq)
1968 {
1969 	struct pool_workqueue *pwq;
1970 
1971 	lockdep_assert_held(&wq->mutex);
1972 
1973 	/* Caller should make sure that pwqs isn't empty before calling */
1974 	pwq = list_first_entry_or_null(&wq->pwqs, struct pool_workqueue,
1975 				       pwqs_node);
1976 	raw_spin_lock_irq(&pwq->pool->lock);
1977 	if (pwq->plugged) {
1978 		pwq->plugged = false;
1979 		if (pwq_activate_first_inactive(pwq, true)) {
1980 			/*
1981 			 * While plugged, queueing skips activation which
1982 			 * includes bumping the nr_active count and adding the
1983 			 * pwq to nna->pending_pwqs if the count can't be
1984 			 * obtained. We need to restore both for the pwq being
1985 			 * unplugged. The first call activates the first
1986 			 * inactive work item and the second, if there are more
1987 			 * inactive, puts the pwq on pending_pwqs.
1988 			 */
1989 			pwq_activate_first_inactive(pwq, false);
1990 
1991 			kick_pool(pwq->pool);
1992 		}
1993 	}
1994 	raw_spin_unlock_irq(&pwq->pool->lock);
1995 }
1996 
1997 /**
1998  * node_activate_pending_pwq - Activate a pending pwq on a wq_node_nr_active
1999  * @nna: wq_node_nr_active to activate a pending pwq for
2000  * @caller_pool: worker_pool the caller is locking
2001  *
2002  * Activate a pwq in @nna->pending_pwqs. Called with @caller_pool locked.
2003  * @caller_pool may be unlocked and relocked to lock other worker_pools.
2004  */
2005 static void node_activate_pending_pwq(struct wq_node_nr_active *nna,
2006 				      struct worker_pool *caller_pool)
2007 {
2008 	struct worker_pool *locked_pool = caller_pool;
2009 	struct pool_workqueue *pwq;
2010 	struct work_struct *work;
2011 
2012 	lockdep_assert_held(&caller_pool->lock);
2013 
2014 	raw_spin_lock(&nna->lock);
2015 retry:
2016 	pwq = list_first_entry_or_null(&nna->pending_pwqs,
2017 				       struct pool_workqueue, pending_node);
2018 	if (!pwq)
2019 		goto out_unlock;
2020 
2021 	/*
2022 	 * If @pwq is for a different pool than @locked_pool, we need to lock
2023 	 * @pwq->pool->lock. Let's trylock first. If unsuccessful, do the unlock
2024 	 * / lock dance. For that, we also need to release @nna->lock as it's
2025 	 * nested inside pool locks.
2026 	 */
2027 	if (pwq->pool != locked_pool) {
2028 		raw_spin_unlock(&locked_pool->lock);
2029 		locked_pool = pwq->pool;
2030 		if (!raw_spin_trylock(&locked_pool->lock)) {
2031 			raw_spin_unlock(&nna->lock);
2032 			raw_spin_lock(&locked_pool->lock);
2033 			raw_spin_lock(&nna->lock);
2034 			goto retry;
2035 		}
2036 	}
2037 
2038 	/*
2039 	 * $pwq may not have any inactive work items due to e.g. cancellations.
2040 	 * Drop it from pending_pwqs and see if there's another one.
2041 	 */
2042 	work = list_first_entry_or_null(&pwq->inactive_works,
2043 					struct work_struct, entry);
2044 	if (!work) {
2045 		list_del_init(&pwq->pending_node);
2046 		goto retry;
2047 	}
2048 
2049 	/*
2050 	 * Acquire an nr_active count and activate the inactive work item. If
2051 	 * $pwq still has inactive work items, rotate it to the end of the
2052 	 * pending_pwqs so that we round-robin through them. This means that
2053 	 * inactive work items are not activated in queueing order which is fine
2054 	 * given that there has never been any ordering across different pwqs.
2055 	 */
2056 	if (likely(tryinc_node_nr_active(nna))) {
2057 		pwq->nr_active++;
2058 		__pwq_activate_work(pwq, work);
2059 
2060 		if (list_empty(&pwq->inactive_works))
2061 			list_del_init(&pwq->pending_node);
2062 		else
2063 			list_move_tail(&pwq->pending_node, &nna->pending_pwqs);
2064 
2065 		/* if activating a foreign pool, make sure it's running */
2066 		if (pwq->pool != caller_pool)
2067 			kick_pool(pwq->pool);
2068 	}
2069 
2070 out_unlock:
2071 	raw_spin_unlock(&nna->lock);
2072 	if (locked_pool != caller_pool) {
2073 		raw_spin_unlock(&locked_pool->lock);
2074 		raw_spin_lock(&caller_pool->lock);
2075 	}
2076 }
2077 
2078 /**
2079  * pwq_dec_nr_active - Retire an active count
2080  * @pwq: pool_workqueue of interest
2081  *
2082  * Decrement @pwq's nr_active and try to activate the first inactive work item.
2083  * For unbound workqueues, this function may temporarily drop @pwq->pool->lock.
2084  */
2085 static void pwq_dec_nr_active(struct pool_workqueue *pwq)
2086 {
2087 	struct worker_pool *pool = pwq->pool;
2088 	struct wq_node_nr_active *nna;
2089 
2090 	lockdep_assert_held(&pool->lock);
2091 
2092 	/*
2093 	 * @pwq->nr_active should be decremented for both percpu and unbound
2094 	 * workqueues.
2095 	 */
2096 	pwq->nr_active--;
2097 
2098 	/*
2099 	 * A concurrency-managed per-cpu pool only needs to kick the first
2100 	 * inactive work item on @pwq itself.
2101 	 */
2102 	if (is_percpu_pool(pool)) {
2103 		pwq_activate_first_inactive(pwq, false);
2104 		return;
2105 	}
2106 
2107 	nna = wq_node_nr_active(pwq->wq, pool->node);
2108 
2109 	/*
2110 	 * If @pwq is for an unbound workqueue, it's more complicated because
2111 	 * multiple pwqs and pools may be sharing the nr_active count. When a
2112 	 * pwq needs to wait for an nr_active count, it puts itself on
2113 	 * $nna->pending_pwqs. The following atomic_dec_return()'s implied
2114 	 * memory barrier is paired with smp_mb() in pwq_tryinc_nr_active() to
2115 	 * guarantee that either we see non-empty pending_pwqs or they see
2116 	 * decremented $nna->nr.
2117 	 *
2118 	 * $nna->max may change as CPUs come online/offline and @pwq->wq's
2119 	 * max_active gets updated. However, it is guaranteed to be equal to or
2120 	 * larger than @pwq->wq->min_active which is above zero unless freezing.
2121 	 * This maintains the forward progress guarantee.
2122 	 */
2123 	if (atomic_dec_return(&nna->nr) >= READ_ONCE(nna->max))
2124 		return;
2125 
2126 	if (!list_empty(&nna->pending_pwqs))
2127 		node_activate_pending_pwq(nna, pool);
2128 }
2129 
2130 /**
2131  * pwq_inc_nr_in_flight - increment pwq's nr_in_flight
2132  * @pwq: pwq of interest
2133  * @work_color: color of the work item being queued
2134  *
2135  * A work item or a barrier with @work_color is being queued to @pwq.
2136  *
2137  * CONTEXT:
2138  * raw_spin_lock_irq(pool->lock).
2139  */
2140 static void pwq_inc_nr_in_flight(struct pool_workqueue *pwq, int work_color)
2141 {
2142 	pwq->nr_in_flight[work_color]++;
2143 	pwq->total_in_flight++;
2144 }
2145 
2146 /**
2147  * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
2148  * @pwq: pwq of interest
2149  * @work_data: work_data of work which left the queue
2150  *
2151  * A work either has completed or is removed from pending queue,
2152  * decrement nr_in_flight of its pwq and handle workqueue flushing.
2153  *
2154  * NOTE:
2155  * For unbound workqueues, this function may temporarily drop @pwq->pool->lock
2156  * and thus should be called after all other state updates for the in-flight
2157  * work item is complete.
2158  *
2159  * CONTEXT:
2160  * raw_spin_lock_irq(pool->lock).
2161  */
2162 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
2163 {
2164 	int color = get_work_color(work_data);
2165 
2166 	if (!(work_data & WORK_STRUCT_INACTIVE))
2167 		pwq_dec_nr_active(pwq);
2168 
2169 	pwq->nr_in_flight[color]--;
2170 	pwq->total_in_flight--;
2171 
2172 	/* is flush in progress and are we at the flushing tip? */
2173 	if (likely(pwq->flush_color != color))
2174 		goto out_put;
2175 
2176 	/* are there still in-flight works? */
2177 	if (pwq->nr_in_flight[color])
2178 		goto out_put;
2179 
2180 	/* this pwq is done, clear flush_color */
2181 	pwq->flush_color = -1;
2182 
2183 	/*
2184 	 * If this was the last pwq, wake up the first flusher.  It
2185 	 * will handle the rest.
2186 	 */
2187 	if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
2188 		complete(&pwq->wq->first_flusher->done);
2189 out_put:
2190 	put_pwq(pwq);
2191 }
2192 
2193 /**
2194  * try_to_grab_pending - steal work item from worklist and disable irq
2195  * @work: work item to steal
2196  * @cflags: %WORK_CANCEL_ flags
2197  * @irq_flags: place to store irq state
2198  *
2199  * Try to grab PENDING bit of @work.  This function can handle @work in any
2200  * stable state - idle, on timer or on worklist.
2201  *
2202  * Return:
2203  *
2204  *  ========	================================================================
2205  *  1		if @work was pending and we successfully stole PENDING
2206  *  0		if @work was idle and we claimed PENDING
2207  *  -EAGAIN	if PENDING couldn't be grabbed at the moment, safe to busy-retry
2208  *  ========	================================================================
2209  *
2210  * Note:
2211  * On >= 0 return, the caller owns @work's PENDING bit.  To avoid getting
2212  * interrupted while holding PENDING and @work off queue, irq must be
2213  * disabled on entry.  This, combined with delayed_work->timer being
2214  * irqsafe, ensures that we return -EAGAIN for finite short period of time.
2215  *
2216  * On successful return, >= 0, irq is disabled and the caller is
2217  * responsible for releasing it using local_irq_restore(*@irq_flags).
2218  *
2219  * This function is safe to call from any context including IRQ handler.
2220  */
2221 static int try_to_grab_pending(struct work_struct *work, u32 cflags,
2222 			       unsigned long *irq_flags)
2223 {
2224 	struct worker_pool *pool;
2225 	struct pool_workqueue *pwq;
2226 
2227 	local_irq_save(*irq_flags);
2228 
2229 	/* try to steal the timer if it exists */
2230 	if (cflags & WORK_CANCEL_DELAYED) {
2231 		struct delayed_work *dwork = to_delayed_work(work);
2232 
2233 		/*
2234 		 * dwork->timer is irqsafe.  If timer_delete() fails, it's
2235 		 * guaranteed that the timer is not queued anywhere and not
2236 		 * running on the local CPU.
2237 		 */
2238 		if (likely(timer_delete(&dwork->timer)))
2239 			return 1;
2240 	}
2241 
2242 	/* try to claim PENDING the normal way */
2243 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
2244 		return 0;
2245 
2246 	rcu_read_lock();
2247 	/*
2248 	 * The queueing is in progress, or it is already queued. Try to
2249 	 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
2250 	 */
2251 	pool = get_work_pool(work);
2252 	if (!pool)
2253 		goto fail;
2254 
2255 	raw_spin_lock(&pool->lock);
2256 	/*
2257 	 * work->data is guaranteed to point to pwq only while the work
2258 	 * item is queued on pwq->wq, and both updating work->data to point
2259 	 * to pwq on queueing and to pool on dequeueing are done under
2260 	 * pwq->pool->lock.  This in turn guarantees that, if work->data
2261 	 * points to pwq which is associated with a locked pool, the work
2262 	 * item is currently queued on that pool.
2263 	 */
2264 	pwq = get_work_pwq(work);
2265 	if (pwq && pwq->pool == pool) {
2266 		unsigned long work_data = *work_data_bits(work);
2267 		struct worker_pool *offq_pool = pool;
2268 
2269 		debug_work_deactivate(work);
2270 
2271 		/*
2272 		 * A cancelable inactive work item must be in the
2273 		 * pwq->inactive_works since a queued barrier can't be
2274 		 * canceled (see the comments in insert_wq_barrier()).
2275 		 *
2276 		 * An inactive work item cannot be deleted directly because
2277 		 * it might have linked barrier work items which, if left
2278 		 * on the inactive_works list, will confuse pwq->nr_active
2279 		 * management later on and cause stall.  Move the linked
2280 		 * barrier work items to the worklist when deleting the grabbed
2281 		 * item. Also keep WORK_STRUCT_INACTIVE in work_data, so that
2282 		 * it doesn't participate in nr_active management in later
2283 		 * pwq_dec_nr_in_flight().
2284 		 */
2285 		if (work_data & WORK_STRUCT_INACTIVE)
2286 			move_linked_works(work, &pwq->pool->worklist, NULL);
2287 
2288 		list_del_init(&work->entry);
2289 
2290 		/*
2291 		 * work->data points to pwq iff queued. Let's point to pool. As
2292 		 * this destroys work->data needed by the next step, stash it.
2293 		 *
2294 		 * For ordered workqueues, __queue_work() skips last_pool
2295 		 * redirection so @pwq may be plugged while @work is still
2296 		 * executing on the oldest pwq after a cpumask update. Only the
2297 		 * oldest pwq is unplugged and can be executing @work, so record
2298 		 * its pool instead.
2299 		 */
2300 		if (unlikely(pwq->wq->flags & __WQ_ORDERED))
2301 			offq_pool = list_entry_rcu(pwq->wq->pwqs.next, struct pool_workqueue,
2302 						   pwqs_node)->pool;
2303 		set_work_pool_and_keep_pending(work, offq_pool->id,
2304 					       pool_offq_flags(offq_pool));
2305 
2306 		/* must be the last step, see the function comment */
2307 		pwq_dec_nr_in_flight(pwq, work_data);
2308 
2309 		raw_spin_unlock(&pool->lock);
2310 		rcu_read_unlock();
2311 		return 1;
2312 	}
2313 	raw_spin_unlock(&pool->lock);
2314 fail:
2315 	rcu_read_unlock();
2316 	local_irq_restore(*irq_flags);
2317 	return -EAGAIN;
2318 }
2319 
2320 /**
2321  * work_grab_pending - steal work item from worklist and disable irq
2322  * @work: work item to steal
2323  * @cflags: %WORK_CANCEL_ flags
2324  * @irq_flags: place to store IRQ state
2325  *
2326  * Grab PENDING bit of @work. @work can be in any stable state - idle, on timer
2327  * or on worklist.
2328  *
2329  * Can be called from any context. IRQ is disabled on return with IRQ state
2330  * stored in *@irq_flags. The caller is responsible for re-enabling it using
2331  * local_irq_restore().
2332  *
2333  * Returns %true if @work was pending. %false if idle.
2334  */
2335 static bool work_grab_pending(struct work_struct *work, u32 cflags,
2336 			      unsigned long *irq_flags)
2337 {
2338 	int ret;
2339 
2340 	while (true) {
2341 		ret = try_to_grab_pending(work, cflags, irq_flags);
2342 		if (ret >= 0)
2343 			return ret;
2344 		cpu_relax();
2345 	}
2346 }
2347 
2348 /**
2349  * insert_work - insert a work into a pool
2350  * @pwq: pwq @work belongs to
2351  * @work: work to insert
2352  * @head: insertion point
2353  * @extra_flags: extra WORK_STRUCT_* flags to set
2354  *
2355  * Insert @work which belongs to @pwq after @head.  @extra_flags is or'd to
2356  * work_struct flags.
2357  *
2358  * CONTEXT:
2359  * raw_spin_lock_irq(pool->lock).
2360  */
2361 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
2362 			struct list_head *head, unsigned int extra_flags)
2363 {
2364 	debug_work_activate(work);
2365 
2366 	/* record the work call stack in order to print it in KASAN reports */
2367 	kasan_record_aux_stack(work);
2368 
2369 	/* we own @work, set data and link */
2370 	set_work_pwq(work, pwq, extra_flags);
2371 	list_add_tail(&work->entry, head);
2372 	get_pwq(pwq);
2373 }
2374 
2375 /*
2376  * Test whether @work is being queued from another work executing on the
2377  * same workqueue.
2378  */
2379 static bool is_chained_work(struct workqueue_struct *wq)
2380 {
2381 	struct worker *worker;
2382 
2383 	worker = current_wq_worker();
2384 	/*
2385 	 * Return %true iff I'm a worker executing a work item on @wq.  If
2386 	 * I'm @worker, it's safe to dereference it without locking.
2387 	 */
2388 	return worker && worker->current_pwq && worker->current_pwq->wq == wq;
2389 }
2390 
2391 /*
2392  * When queueing an unbound work item to a wq, prefer local CPU if allowed
2393  * by wq_unbound_cpumask.  Otherwise, round robin among the allowed ones to
2394  * avoid perturbing sensitive tasks.
2395  */
2396 static int wq_select_unbound_cpu(int cpu)
2397 {
2398 	int new_cpu;
2399 
2400 	if (likely(!wq_debug_force_rr_cpu)) {
2401 		if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
2402 			return cpu;
2403 	} else {
2404 		pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
2405 	}
2406 
2407 	new_cpu = __this_cpu_read(wq_rr_cpu_last);
2408 	new_cpu = cpumask_next_and_wrap(new_cpu, wq_unbound_cpumask, cpu_online_mask);
2409 	if (unlikely(new_cpu >= nr_cpu_ids))
2410 		return cpu;
2411 	__this_cpu_write(wq_rr_cpu_last, new_cpu);
2412 
2413 	return new_cpu;
2414 }
2415 
2416 static void __queue_work(int cpu, struct workqueue_struct *wq,
2417 			 struct work_struct *work)
2418 {
2419 	struct pool_workqueue *pwq;
2420 	struct worker_pool *last_pool, *pool;
2421 	struct task_struct *wake_task = NULL;
2422 	unsigned int work_flags;
2423 	unsigned int req_cpu = cpu;
2424 
2425 	/*
2426 	 * NOTE: Check whether the used workqueue is deprecated and warn
2427 	 */
2428 	if (unlikely(wq->flags & __WQ_DEPRECATED))
2429 		pr_warn_once("workqueue: work func %ps enqueued on deprecated workqueue. "
2430 			"Use system_{percpu|dfl}_wq instead.\n",
2431 			work->func);
2432 
2433 	/*
2434 	 * While a work item is PENDING && off queue, a task trying to
2435 	 * steal the PENDING will busy-loop waiting for it to either get
2436 	 * queued or lose PENDING.  Grabbing PENDING and queueing should
2437 	 * happen with IRQ disabled.
2438 	 */
2439 	lockdep_assert_irqs_disabled();
2440 
2441 	/*
2442 	 * For a draining wq, only works from the same workqueue are
2443 	 * allowed. The __WQ_DESTROYING helps to spot the issue that
2444 	 * queues a new work item to a wq after destroy_workqueue(wq).
2445 	 */
2446 	if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
2447 		     WARN_ONCE(!is_chained_work(wq), "workqueue: cannot queue %ps on wq %s\n",
2448 			       work->func, wq->name))) {
2449 		struct work_offq_data offqd;
2450 
2451 		/*
2452 		 * State on entry: PENDING is set, work is off-queue (no
2453 		 * insert_work() has run).
2454 		 *
2455 		 * Returning without clearing PENDING would leave the work
2456 		 * in a weird state (PENDING=1, PWQ=0, entry empty)
2457 		 */
2458 		work_offqd_unpack(&offqd, *work_data_bits(work));
2459 		set_work_pool_and_clear_pending(work, offqd.pool_id,
2460 						work_offqd_pack_flags(&offqd));
2461 		return;
2462 	}
2463 	rcu_read_lock();
2464 retry:
2465 	/* pwq which will be used unless @work is executing elsewhere */
2466 	if (req_cpu == WORK_CPU_UNBOUND) {
2467 		if (wq->flags & WQ_UNBOUND)
2468 			cpu = wq_select_unbound_cpu(raw_smp_processor_id());
2469 		else
2470 			cpu = raw_smp_processor_id();
2471 	}
2472 
2473 	pwq = rcu_dereference(*per_cpu_ptr(wq->cpu_pwq, cpu));
2474 	pool = pwq->pool;
2475 
2476 	/*
2477 	 * If @work was previously on a different pool, it might still be
2478 	 * running there, in which case the work needs to be queued on that
2479 	 * pool to guarantee non-reentrancy.
2480 	 *
2481 	 * For ordered workqueue, work items must be queued on the newest pwq
2482 	 * for accurate order management.  Guaranteed order also guarantees
2483 	 * non-reentrancy.  See the comments above unplug_oldest_pwq().
2484 	 */
2485 	last_pool = get_work_pool(work);
2486 	if (last_pool && last_pool != pool && !(wq->flags & __WQ_ORDERED)) {
2487 		struct worker *worker;
2488 
2489 		raw_spin_lock(&last_pool->lock);
2490 
2491 		worker = find_worker_executing_work(last_pool, work);
2492 
2493 		if (worker && worker->current_pwq->wq == wq) {
2494 			pwq = worker->current_pwq;
2495 			pool = pwq->pool;
2496 			WARN_ON_ONCE(pool != last_pool);
2497 		} else {
2498 			/* meh... not running there, queue here */
2499 			raw_spin_unlock(&last_pool->lock);
2500 			raw_spin_lock(&pool->lock);
2501 		}
2502 	} else {
2503 		raw_spin_lock(&pool->lock);
2504 	}
2505 
2506 	/*
2507 	 * pwq is determined and locked. For unbound pools, we could have raced
2508 	 * with pwq release and it could already be dead. If its refcnt is zero,
2509 	 * repeat pwq selection. Note that unbound pwqs never die without
2510 	 * another pwq replacing it in cpu_pwq or while work items are executing
2511 	 * on it, so the retrying is guaranteed to make forward-progress.
2512 	 */
2513 	if (unlikely(!pwq->refcnt)) {
2514 		if (wq->flags & WQ_UNBOUND) {
2515 			raw_spin_unlock(&pool->lock);
2516 			cpu_relax();
2517 			goto retry;
2518 		}
2519 		/* oops */
2520 		WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
2521 			  wq->name, cpu);
2522 	}
2523 
2524 	/* pwq determined, queue */
2525 	trace_workqueue_queue_work(req_cpu, pwq, work);
2526 
2527 	if (WARN_ON(!list_empty(&work->entry)))
2528 		goto out;
2529 
2530 	/*
2531 	 * Add @pwq to its wq_flush_pnode list if off it. Syncing ->work_color
2532 	 * in the same fpn->lock section is what keeps a concurrent flush from
2533 	 * missing @work, see wq_flush_pnode.
2534 	 */
2535 	if (unlikely(list_empty(&pwq->flush_node))) {
2536 		struct wq_flush_pnode *fpn = wq_flush_pnode(wq, pool->node);
2537 
2538 		raw_spin_lock(&fpn->lock);
2539 		pwq->work_color = fpn->work_color;
2540 		list_add_tail(&pwq->flush_node, &fpn->pwqs);
2541 		raw_spin_unlock(&fpn->lock);
2542 	}
2543 
2544 	pwq_inc_nr_in_flight(pwq, pwq->work_color);
2545 	work_flags = work_color_to_flags(pwq->work_color);
2546 
2547 	/*
2548 	 * Limit the number of concurrently active work items to max_active.
2549 	 * @work must also queue behind existing inactive work items to maintain
2550 	 * ordering when max_active changes. See wq_adjust_max_active().
2551 	 */
2552 	if (list_empty(&pwq->inactive_works) && pwq_tryinc_nr_active(pwq, false)) {
2553 		if (list_empty(&pool->worklist))
2554 			pool->last_progress_ts = jiffies;
2555 
2556 		trace_workqueue_activate_work(work);
2557 		insert_work(pwq, work, &pool->worklist, work_flags);
2558 		kick_pool_pick(pool, &wake_task);
2559 	} else {
2560 		work_flags |= WORK_STRUCT_INACTIVE;
2561 		insert_work(pwq, work, &pwq->inactive_works, work_flags);
2562 	}
2563 
2564 out:
2565 	raw_spin_unlock(&pool->lock);
2566 	if (wake_task)
2567 		wake_up_process(wake_task);
2568 	rcu_read_unlock();
2569 }
2570 
2571 static bool clear_pending_if_disabled(struct work_struct *work)
2572 {
2573 	unsigned long data = *work_data_bits(work);
2574 	struct work_offq_data offqd;
2575 
2576 	if (likely((data & WORK_STRUCT_PWQ) ||
2577 		   !(data & WORK_OFFQ_DISABLE_MASK)))
2578 		return false;
2579 
2580 	work_offqd_unpack(&offqd, data);
2581 	set_work_pool_and_clear_pending(work, offqd.pool_id,
2582 					work_offqd_pack_flags(&offqd));
2583 	return true;
2584 }
2585 
2586 /**
2587  * queue_work_on - queue work on specific cpu
2588  * @cpu: CPU number to execute work on
2589  * @wq: workqueue to use
2590  * @work: work to queue
2591  *
2592  * We queue the work to a specific CPU, the caller must ensure it
2593  * can't go away.  Callers that fail to ensure that the specified
2594  * CPU cannot go away will execute on a randomly chosen CPU.
2595  * But note well that callers specifying a CPU that never has been
2596  * online will get a splat.
2597  *
2598  * Return: %false if @work was already on a queue, %true otherwise.
2599  */
2600 bool queue_work_on(int cpu, struct workqueue_struct *wq,
2601 		   struct work_struct *work)
2602 {
2603 	bool ret = false;
2604 	unsigned long irq_flags;
2605 
2606 	local_irq_save(irq_flags);
2607 
2608 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)) &&
2609 	    !clear_pending_if_disabled(work)) {
2610 		__queue_work(cpu, wq, work);
2611 		ret = true;
2612 	}
2613 
2614 	local_irq_restore(irq_flags);
2615 	return ret;
2616 }
2617 EXPORT_SYMBOL(queue_work_on);
2618 
2619 /**
2620  * select_numa_node_cpu - Select a CPU based on NUMA node
2621  * @node: NUMA node ID that we want to select a CPU from
2622  *
2623  * This function will attempt to find a "random" cpu available on a given
2624  * node. If there are no CPUs available on the given node it will return
2625  * WORK_CPU_UNBOUND indicating that we should just schedule to any
2626  * available CPU if we need to schedule this work.
2627  */
2628 static int select_numa_node_cpu(int node)
2629 {
2630 	int cpu;
2631 
2632 	/* Delay binding to CPU if node is not valid or online */
2633 	if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
2634 		return WORK_CPU_UNBOUND;
2635 
2636 	/* Use local node/cpu if we are already there */
2637 	cpu = raw_smp_processor_id();
2638 	if (node == cpu_to_node(cpu))
2639 		return cpu;
2640 
2641 	/* Use "random" otherwise know as "first" online CPU of node */
2642 	cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
2643 
2644 	/* If CPU is valid return that, otherwise just defer */
2645 	return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
2646 }
2647 
2648 /**
2649  * queue_work_node - queue work on a "random" cpu for a given NUMA node
2650  * @node: NUMA node that we are targeting the work for
2651  * @wq: workqueue to use
2652  * @work: work to queue
2653  *
2654  * We queue the work to a "random" CPU within a given NUMA node. The basic
2655  * idea here is to provide a way to somehow associate work with a given
2656  * NUMA node.
2657  *
2658  * This function will only make a best effort attempt at getting this onto
2659  * the right NUMA node. If no node is requested or the requested node is
2660  * offline then we just fall back to standard queue_work behavior.
2661  *
2662  * Currently the "random" CPU ends up being the first available CPU in the
2663  * intersection of cpu_online_mask and the cpumask of the node, unless we
2664  * are running on the node. In that case we just use the current CPU.
2665  *
2666  * Return: %false if @work was already on a queue, %true otherwise.
2667  */
2668 bool queue_work_node(int node, struct workqueue_struct *wq,
2669 		     struct work_struct *work)
2670 {
2671 	unsigned long irq_flags;
2672 	bool ret = false;
2673 
2674 	/*
2675 	 * This current implementation is specific to unbound workqueues.
2676 	 * Specifically we only return the first available CPU for a given
2677 	 * node instead of cycling through individual CPUs within the node.
2678 	 *
2679 	 * If this is used with a per-cpu workqueue then the logic in
2680 	 * workqueue_select_cpu_near would need to be updated to allow for
2681 	 * some round robin type logic.
2682 	 */
2683 	WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
2684 
2685 	local_irq_save(irq_flags);
2686 
2687 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)) &&
2688 	    !clear_pending_if_disabled(work)) {
2689 		int cpu = select_numa_node_cpu(node);
2690 
2691 		__queue_work(cpu, wq, work);
2692 		ret = true;
2693 	}
2694 
2695 	local_irq_restore(irq_flags);
2696 	return ret;
2697 }
2698 EXPORT_SYMBOL_GPL(queue_work_node);
2699 
2700 void delayed_work_timer_fn(struct timer_list *t)
2701 {
2702 	struct delayed_work *dwork = timer_container_of(dwork, t, timer);
2703 
2704 	/* should have been called from irqsafe timer with irq already off */
2705 	__queue_work(dwork->cpu, dwork->wq, &dwork->work);
2706 }
2707 EXPORT_SYMBOL(delayed_work_timer_fn);
2708 
2709 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
2710 				struct delayed_work *dwork, unsigned long delay)
2711 {
2712 	struct timer_list *timer = &dwork->timer;
2713 	struct work_struct *work = &dwork->work;
2714 
2715 	WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
2716 	WARN_ON_ONCE(timer_pending(timer));
2717 	WARN_ON_ONCE(!list_empty(&work->entry));
2718 
2719 	/*
2720 	 * If @delay is 0, queue @dwork->work immediately.  This is for
2721 	 * both optimization and correctness.  The earliest @timer can
2722 	 * expire is on the closest next tick and delayed_work users depend
2723 	 * on that there's no such delay when @delay is 0.
2724 	 */
2725 	if (!delay) {
2726 		__queue_work(cpu, wq, &dwork->work);
2727 		return;
2728 	}
2729 
2730 	WARN_ON_ONCE(cpu != WORK_CPU_UNBOUND && !cpu_online(cpu));
2731 	dwork->wq = wq;
2732 	dwork->cpu = cpu;
2733 	timer->expires = jiffies + delay;
2734 
2735 	if (housekeeping_enabled(HK_TYPE_TIMER)) {
2736 		/* If the current cpu is a housekeeping cpu, use it. */
2737 		cpu = smp_processor_id();
2738 		if (!housekeeping_test_cpu(cpu, HK_TYPE_TIMER))
2739 			cpu = housekeeping_any_cpu(HK_TYPE_TIMER);
2740 		add_timer_on(timer, cpu);
2741 	} else {
2742 		if (likely(cpu == WORK_CPU_UNBOUND))
2743 			add_timer_global(timer);
2744 		else
2745 			add_timer_on(timer, cpu);
2746 	}
2747 }
2748 
2749 /**
2750  * queue_delayed_work_on - queue work on specific CPU after delay
2751  * @cpu: CPU number to execute work on
2752  * @wq: workqueue to use
2753  * @dwork: work to queue
2754  * @delay: number of jiffies to wait before queueing
2755  *
2756  * We queue the delayed_work to a specific CPU, for non-zero delays the
2757  * caller must ensure it is online and can't go away. Callers that fail
2758  * to ensure this, may get @dwork->timer queued to an offlined CPU and
2759  * this will prevent queueing of @dwork->work unless the offlined CPU
2760  * becomes online again.
2761  *
2762  * Return: %false if @work was already on a queue, %true otherwise.  If
2763  * @delay is zero and @dwork is idle, it will be scheduled for immediate
2764  * execution.
2765  */
2766 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
2767 			   struct delayed_work *dwork, unsigned long delay)
2768 {
2769 	struct work_struct *work = &dwork->work;
2770 	bool ret = false;
2771 	unsigned long irq_flags;
2772 
2773 	/* read the comment in __queue_work() */
2774 	local_irq_save(irq_flags);
2775 
2776 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)) &&
2777 	    !clear_pending_if_disabled(work)) {
2778 		__queue_delayed_work(cpu, wq, dwork, delay);
2779 		ret = true;
2780 	}
2781 
2782 	local_irq_restore(irq_flags);
2783 	return ret;
2784 }
2785 EXPORT_SYMBOL(queue_delayed_work_on);
2786 
2787 /**
2788  * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
2789  * @cpu: CPU number to execute work on
2790  * @wq: workqueue to use
2791  * @dwork: work to queue
2792  * @delay: number of jiffies to wait before queueing
2793  *
2794  * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
2795  * modify @dwork's timer so that it expires after @delay.  If @delay is
2796  * zero, @work is guaranteed to be scheduled immediately regardless of its
2797  * current state.
2798  *
2799  * Return: %false if @dwork was idle and queued, %true if @dwork was
2800  * pending and its timer was modified.
2801  *
2802  * This function is safe to call from any context including IRQ handler.
2803  * See try_to_grab_pending() for details.
2804  */
2805 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
2806 			 struct delayed_work *dwork, unsigned long delay)
2807 {
2808 	unsigned long irq_flags;
2809 	bool ret;
2810 
2811 	ret = work_grab_pending(&dwork->work, WORK_CANCEL_DELAYED, &irq_flags);
2812 
2813 	if (!clear_pending_if_disabled(&dwork->work))
2814 		__queue_delayed_work(cpu, wq, dwork, delay);
2815 
2816 	local_irq_restore(irq_flags);
2817 	return ret;
2818 }
2819 EXPORT_SYMBOL_GPL(mod_delayed_work_on);
2820 
2821 static void rcu_work_rcufn(struct rcu_head *rcu)
2822 {
2823 	struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
2824 
2825 	/* read the comment in __queue_work() */
2826 	local_irq_disable();
2827 	__queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
2828 	local_irq_enable();
2829 }
2830 
2831 /**
2832  * queue_rcu_work - queue work after a RCU grace period
2833  * @wq: workqueue to use
2834  * @rwork: work to queue
2835  *
2836  * Return: %false if @rwork was already pending, %true otherwise.  Note
2837  * that a full RCU grace period is guaranteed only after a %true return.
2838  * While @rwork is guaranteed to be executed after a %false return, the
2839  * execution may happen before a full RCU grace period has passed.
2840  */
2841 bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
2842 {
2843 	struct work_struct *work = &rwork->work;
2844 
2845 	/*
2846 	 * rcu_work can't be canceled or disabled. Warn if the user reached
2847 	 * inside @rwork and disabled the inner work.
2848 	 */
2849 	if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)) &&
2850 	    !WARN_ON_ONCE(clear_pending_if_disabled(work))) {
2851 		rwork->wq = wq;
2852 		call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
2853 		return true;
2854 	}
2855 
2856 	return false;
2857 }
2858 EXPORT_SYMBOL(queue_rcu_work);
2859 
2860 static struct worker *alloc_worker(int node)
2861 {
2862 	struct worker *worker;
2863 
2864 	worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
2865 	if (worker) {
2866 		INIT_LIST_HEAD(&worker->entry);
2867 		INIT_LIST_HEAD(&worker->scheduled);
2868 		INIT_LIST_HEAD(&worker->node);
2869 		/* on creation a worker is in !idle && prep state */
2870 		worker->flags = WORKER_PREP;
2871 	}
2872 	return worker;
2873 }
2874 
2875 static cpumask_t *pool_allowed_cpus(struct worker_pool *pool)
2876 {
2877 	if (!is_percpu_pool(pool) && pool->attrs->affn_strict)
2878 		return pool->attrs->__pod_cpumask;
2879 	else
2880 		return pool->attrs->cpumask;
2881 }
2882 
2883 /**
2884  * worker_attach_to_pool() - attach a worker to a pool
2885  * @worker: worker to be attached
2886  * @pool: the target pool
2887  *
2888  * Attach @worker to @pool.  Once attached, the %WORKER_UNBOUND flag and
2889  * cpu-binding of @worker are kept coordinated with the pool across
2890  * cpu-[un]hotplugs.
2891  */
2892 static void worker_attach_to_pool(struct worker *worker,
2893 				  struct worker_pool *pool)
2894 {
2895 	mutex_lock(&wq_pool_attach_mutex);
2896 
2897 	/*
2898 	 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains stable
2899 	 * across this function. See the comments above the flag definition for
2900 	 * details. BH workers are, while per-CPU, always DISASSOCIATED.
2901 	 */
2902 	if (pool->flags & POOL_DISASSOCIATED) {
2903 		worker->flags |= WORKER_UNBOUND;
2904 	} else {
2905 		WARN_ON_ONCE(pool->flags & POOL_BH);
2906 		kthread_set_per_cpu(worker->task, pool->cpu);
2907 	}
2908 
2909 	if (worker->rescue_wq)
2910 		set_cpus_allowed_ptr(worker->task, pool_allowed_cpus(pool));
2911 
2912 	list_add_tail(&worker->node, &pool->workers);
2913 	worker->pool = pool;
2914 
2915 	mutex_unlock(&wq_pool_attach_mutex);
2916 }
2917 
2918 static void unbind_worker(struct worker *worker)
2919 {
2920 	lockdep_assert_held(&wq_pool_attach_mutex);
2921 
2922 	kthread_set_per_cpu(worker->task, -1);
2923 	if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2924 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2925 	else
2926 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2927 }
2928 
2929 
2930 static void detach_worker(struct worker *worker)
2931 {
2932 	lockdep_assert_held(&wq_pool_attach_mutex);
2933 
2934 	unbind_worker(worker);
2935 	list_del(&worker->node);
2936 }
2937 
2938 /**
2939  * worker_detach_from_pool() - detach a worker from its pool
2940  * @worker: worker which is attached to its pool
2941  *
2942  * Undo the attaching which had been done in worker_attach_to_pool().  The
2943  * caller worker shouldn't access to the pool after detached except it has
2944  * other reference to the pool.
2945  */
2946 static void worker_detach_from_pool(struct worker *worker)
2947 {
2948 	struct worker_pool *pool = worker->pool;
2949 
2950 	/* there is one permanent BH worker per CPU which should never detach */
2951 	WARN_ON_ONCE(pool->flags & POOL_BH);
2952 
2953 	mutex_lock(&wq_pool_attach_mutex);
2954 	detach_worker(worker);
2955 	worker->pool = NULL;
2956 	mutex_unlock(&wq_pool_attach_mutex);
2957 
2958 	/* clear leftover flags without pool->lock after it is detached */
2959 	worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2960 }
2961 
2962 static int format_worker_id(char *buf, size_t size, struct worker *worker,
2963 			    struct worker_pool *pool)
2964 {
2965 	if (worker->rescue_wq)
2966 		return scnprintf(buf, size, "kworker/R-%s",
2967 				 worker->rescue_wq->name);
2968 
2969 	if (pool) {
2970 		if (pool->cpu >= 0)
2971 			return scnprintf(buf, size, "kworker/%d:%d%s",
2972 					 pool->cpu, worker->id,
2973 					 pool->attrs->nice < 0  ? "H" : "");
2974 		else
2975 			return scnprintf(buf, size, "kworker/u%d:%d",
2976 					 pool->id, worker->id);
2977 	} else {
2978 		return scnprintf(buf, size, "kworker/dying");
2979 	}
2980 }
2981 
2982 /**
2983  * create_worker - create a new workqueue worker
2984  * @pool: pool the new worker will belong to
2985  *
2986  * Create and start a new worker which is attached to @pool.
2987  *
2988  * CONTEXT:
2989  * Might sleep.  Does GFP_KERNEL allocations.
2990  *
2991  * Return:
2992  * Pointer to the newly created worker.
2993  */
2994 static struct worker *create_worker(struct worker_pool *pool)
2995 {
2996 	struct worker *worker;
2997 	int id;
2998 
2999 	/* ID is needed to determine kthread name */
3000 	id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
3001 	if (id < 0) {
3002 		pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
3003 			    ERR_PTR(id));
3004 		return NULL;
3005 	}
3006 
3007 	worker = alloc_worker(pool->node);
3008 	if (!worker) {
3009 		pr_err_once("workqueue: Failed to allocate a worker\n");
3010 		goto fail;
3011 	}
3012 
3013 	worker->id = id;
3014 
3015 	if (!(pool->flags & POOL_BH)) {
3016 		char id_buf[WORKER_ID_LEN];
3017 
3018 		format_worker_id(id_buf, sizeof(id_buf), worker, pool);
3019 		worker->task = kthread_create_on_node(worker_thread, worker,
3020 						      pool->node, "%s", id_buf);
3021 		if (IS_ERR(worker->task)) {
3022 			if (PTR_ERR(worker->task) == -EINTR) {
3023 				pr_err("workqueue: Interrupted when creating a worker thread \"%s\"\n",
3024 				       id_buf);
3025 			} else {
3026 				pr_err_once("workqueue: Failed to create a worker thread: %pe",
3027 					    worker->task);
3028 			}
3029 			goto fail;
3030 		}
3031 
3032 		set_user_nice(worker->task, pool->attrs->nice);
3033 		kthread_bind_mask(worker->task, pool_allowed_cpus(pool));
3034 	}
3035 
3036 	/* successful, attach the worker to the pool */
3037 	worker_attach_to_pool(worker, pool);
3038 
3039 	/* start the newly created worker */
3040 	raw_spin_lock_irq(&pool->lock);
3041 
3042 	worker->pool->nr_workers++;
3043 	worker_enter_idle(worker);
3044 
3045 	/*
3046 	 * @worker is waiting on a completion in kthread() and will trigger hung
3047 	 * check if not woken up soon. As kick_pool() is noop if @pool is empty,
3048 	 * wake it up explicitly.
3049 	 */
3050 	if (worker->task)
3051 		wake_up_process(worker->task);
3052 
3053 	raw_spin_unlock_irq(&pool->lock);
3054 
3055 	return worker;
3056 
3057 fail:
3058 	ida_free(&pool->worker_ida, id);
3059 	kfree(worker);
3060 	return NULL;
3061 }
3062 
3063 static void detach_dying_workers(struct list_head *cull_list)
3064 {
3065 	struct worker *worker;
3066 
3067 	list_for_each_entry(worker, cull_list, entry)
3068 		detach_worker(worker);
3069 }
3070 
3071 static void reap_dying_workers(struct list_head *cull_list)
3072 {
3073 	struct worker *worker, *tmp;
3074 
3075 	list_for_each_entry_safe(worker, tmp, cull_list, entry) {
3076 		list_del_init(&worker->entry);
3077 		kthread_stop_put(worker->task);
3078 		kfree(worker);
3079 	}
3080 }
3081 
3082 /**
3083  * set_worker_dying - Tag a worker for destruction
3084  * @worker: worker to be destroyed
3085  * @list: transfer worker away from its pool->idle_list and into list
3086  *
3087  * Tag @worker for destruction and adjust @pool stats accordingly.  The worker
3088  * should be idle.
3089  *
3090  * CONTEXT:
3091  * raw_spin_lock_irq(pool->lock).
3092  */
3093 static void set_worker_dying(struct worker *worker, struct list_head *list)
3094 {
3095 	struct worker_pool *pool = worker->pool;
3096 
3097 	lockdep_assert_held(&pool->lock);
3098 	lockdep_assert_held(&wq_pool_attach_mutex);
3099 
3100 	/* sanity check frenzy */
3101 	if (WARN_ON(worker->current_work) ||
3102 	    WARN_ON(!list_empty(&worker->scheduled)) ||
3103 	    WARN_ON(!(worker->flags & WORKER_IDLE)))
3104 		return;
3105 
3106 	pool->nr_workers--;
3107 	pool->nr_idle--;
3108 
3109 	/*
3110 	 * Clear last_woken_worker if it points to this worker, so that
3111 	 * show_cpu_pool_busy_workers() cannot dereference a freed worker.
3112 	 */
3113 	if (pool->last_woken_worker == worker)
3114 		pool->last_woken_worker = NULL;
3115 
3116 	worker->flags |= WORKER_DIE;
3117 
3118 	list_move(&worker->entry, list);
3119 
3120 	/* get an extra task struct reference for later kthread_stop_put() */
3121 	get_task_struct(worker->task);
3122 }
3123 
3124 /**
3125  * idle_worker_timeout - check if some idle workers can now be deleted.
3126  * @t: The pool's idle_timer that just expired
3127  *
3128  * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
3129  * worker_leave_idle(), as a worker flicking between idle and active while its
3130  * pool is at the too_many_workers() tipping point would cause too much timer
3131  * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
3132  * it expire and re-evaluate things from there.
3133  */
3134 static void idle_worker_timeout(struct timer_list *t)
3135 {
3136 	struct worker_pool *pool = timer_container_of(pool, t, idle_timer);
3137 	bool do_cull = false;
3138 
3139 	if (work_pending(&pool->idle_cull_work))
3140 		return;
3141 
3142 	raw_spin_lock_irq(&pool->lock);
3143 
3144 	if (too_many_workers(pool)) {
3145 		struct worker *worker;
3146 		unsigned long expires;
3147 
3148 		/* idle_list is kept in LIFO order, check the last one */
3149 		worker = list_last_entry(&pool->idle_list, struct worker, entry);
3150 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
3151 		do_cull = !time_before(jiffies, expires);
3152 
3153 		if (!do_cull)
3154 			mod_timer(&pool->idle_timer, expires);
3155 	}
3156 	raw_spin_unlock_irq(&pool->lock);
3157 
3158 	if (do_cull)
3159 		queue_work(system_dfl_wq, &pool->idle_cull_work);
3160 }
3161 
3162 /**
3163  * idle_cull_fn - cull workers that have been idle for too long.
3164  * @work: the pool's work for handling these idle workers
3165  *
3166  * This goes through a pool's idle workers and gets rid of those that have been
3167  * idle for at least IDLE_WORKER_TIMEOUT seconds.
3168  *
3169  * We don't want to disturb isolated CPUs because of a pcpu kworker being
3170  * culled, so this also resets worker affinity. This requires a sleepable
3171  * context, hence the split between timer callback and work item.
3172  */
3173 static void idle_cull_fn(struct work_struct *work)
3174 {
3175 	struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
3176 	LIST_HEAD(cull_list);
3177 
3178 	/*
3179 	 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
3180 	 * cannot proceed beyong set_pf_worker() in its self-destruct path.
3181 	 * This is required as a previously-preempted worker could run after
3182 	 * set_worker_dying() has happened but before detach_dying_workers() did.
3183 	 */
3184 	mutex_lock(&wq_pool_attach_mutex);
3185 	raw_spin_lock_irq(&pool->lock);
3186 
3187 	while (too_many_workers(pool)) {
3188 		struct worker *worker;
3189 		unsigned long expires;
3190 
3191 		worker = list_last_entry(&pool->idle_list, struct worker, entry);
3192 		expires = worker->last_active + IDLE_WORKER_TIMEOUT;
3193 
3194 		if (time_before(jiffies, expires)) {
3195 			mod_timer(&pool->idle_timer, expires);
3196 			break;
3197 		}
3198 
3199 		set_worker_dying(worker, &cull_list);
3200 	}
3201 
3202 	raw_spin_unlock_irq(&pool->lock);
3203 	detach_dying_workers(&cull_list);
3204 	mutex_unlock(&wq_pool_attach_mutex);
3205 
3206 	reap_dying_workers(&cull_list);
3207 }
3208 
3209 static void send_mayday(struct pool_workqueue *pwq)
3210 {
3211 	struct workqueue_struct *wq = pwq->wq;
3212 
3213 	lockdep_assert_held(&wq_mayday_lock);
3214 
3215 	if (!wq->rescuer)
3216 		return;
3217 
3218 	/* mayday mayday mayday */
3219 	if (list_empty(&pwq->mayday_node)) {
3220 		/*
3221 		 * If @pwq is for an unbound wq, its base ref may be put at
3222 		 * any time due to an attribute change.  Pin @pwq until the
3223 		 * rescuer is done with it.
3224 		 */
3225 		get_pwq(pwq);
3226 		list_add_tail(&pwq->mayday_node, &wq->maydays);
3227 		wake_up_process(wq->rescuer->task);
3228 		pwq->stats[PWQ_STAT_MAYDAY]++;
3229 		trace_workqueue_mayday(pwq);
3230 	}
3231 }
3232 
3233 static void pool_mayday_timeout(struct timer_list *t)
3234 {
3235 	struct worker_pool *pool = timer_container_of(pool, t, mayday_timer);
3236 	struct work_struct *work;
3237 
3238 	raw_spin_lock_irq(&pool->lock);
3239 	raw_spin_lock(&wq_mayday_lock);		/* for wq->maydays */
3240 
3241 	if (need_to_create_worker(pool)) {
3242 		/*
3243 		 * We've been trying to create a new worker but
3244 		 * haven't been successful.  We might be hitting an
3245 		 * allocation deadlock.  Send distress signals to
3246 		 * rescuers.
3247 		 */
3248 		list_for_each_entry(work, &pool->worklist, entry)
3249 			send_mayday(get_work_pwq(work));
3250 	}
3251 
3252 	raw_spin_unlock(&wq_mayday_lock);
3253 	raw_spin_unlock_irq(&pool->lock);
3254 
3255 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
3256 }
3257 
3258 /**
3259  * maybe_create_worker - create a new worker if necessary
3260  * @pool: pool to create a new worker for
3261  *
3262  * Create a new worker for @pool if necessary.  @pool is guaranteed to
3263  * have at least one idle worker on return from this function.  If
3264  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
3265  * sent to all rescuers with works scheduled on @pool to resolve
3266  * possible allocation deadlock.
3267  *
3268  * On return, need_to_create_worker() is guaranteed to be %false and
3269  * may_start_working() %true.
3270  *
3271  * LOCKING:
3272  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3273  * multiple times.  Does GFP_KERNEL allocations.  Called only from
3274  * manager.
3275  */
3276 static void maybe_create_worker(struct worker_pool *pool)
3277 __releases(&pool->lock)
3278 __acquires(&pool->lock)
3279 {
3280 restart:
3281 	raw_spin_unlock_irq(&pool->lock);
3282 
3283 	/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
3284 	mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
3285 
3286 	while (true) {
3287 		if (create_worker(pool) || !need_to_create_worker(pool))
3288 			break;
3289 
3290 		schedule_timeout_interruptible(CREATE_COOLDOWN);
3291 
3292 		if (!need_to_create_worker(pool))
3293 			break;
3294 	}
3295 
3296 	timer_delete_sync(&pool->mayday_timer);
3297 	raw_spin_lock_irq(&pool->lock);
3298 	/*
3299 	 * This is necessary even after a new worker was just successfully
3300 	 * created as @pool->lock was dropped and the new worker might have
3301 	 * already become busy.
3302 	 */
3303 	if (need_to_create_worker(pool))
3304 		goto restart;
3305 }
3306 
3307 #ifdef CONFIG_PREEMPT_RT
3308 static void worker_lock_callback(struct worker_pool *pool)
3309 {
3310 	/*
3311 	 * SINGLE_DEPTH_NESTING is for a dead pool's bh_worker() running from
3312 	 * drain_dead_softirq_workfn() inside a live pool's bh_worker(). The
3313 	 * unlocked read is stable: the flag is only set while @pool's CPU is
3314 	 * dead, inside a serialized hotplug operation. data_race() as the value
3315 	 * only affects the lockdep annotation and the read can be elided when
3316 	 * lockdep is disabled.
3317 	 */
3318 	spin_lock_nested(&pool->cb_lock,
3319 			 data_race(pool->flags) & POOL_BH_DRAINING ? SINGLE_DEPTH_NESTING : 0);
3320 }
3321 
3322 static void worker_unlock_callback(struct worker_pool *pool)
3323 {
3324 	spin_unlock(&pool->cb_lock);
3325 }
3326 
3327 static void workqueue_callback_cancel_wait_running(struct worker_pool *pool)
3328 {
3329 	spin_lock(&pool->cb_lock);
3330 	spin_unlock(&pool->cb_lock);
3331 }
3332 
3333 #else
3334 
3335 static void worker_lock_callback(struct worker_pool *pool) { }
3336 static void worker_unlock_callback(struct worker_pool *pool) { }
3337 static void workqueue_callback_cancel_wait_running(struct worker_pool *pool) { }
3338 
3339 #endif
3340 
3341 /**
3342  * manage_workers - manage worker pool
3343  * @worker: self
3344  *
3345  * Assume the manager role and manage the worker pool @worker belongs
3346  * to.  At any given time, there can be only zero or one manager per
3347  * pool.  The exclusion is handled automatically by this function.
3348  *
3349  * The caller can safely start processing works on false return.  On
3350  * true return, it's guaranteed that need_to_create_worker() is false
3351  * and may_start_working() is true.
3352  *
3353  * CONTEXT:
3354  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3355  * multiple times.  Does GFP_KERNEL allocations.
3356  *
3357  * Return:
3358  * %false if the pool doesn't need management and the caller can safely
3359  * start processing works, %true if management function was performed and
3360  * the conditions that the caller verified before calling the function may
3361  * no longer be true.
3362  */
3363 static bool manage_workers(struct worker *worker)
3364 {
3365 	struct worker_pool *pool = worker->pool;
3366 
3367 	if (pool->flags & POOL_MANAGER_ACTIVE)
3368 		return false;
3369 
3370 	pool->flags |= POOL_MANAGER_ACTIVE;
3371 	pool->manager = worker;
3372 
3373 	maybe_create_worker(pool);
3374 
3375 	pool->manager = NULL;
3376 	pool->flags &= ~POOL_MANAGER_ACTIVE;
3377 	rcuwait_wake_up(&manager_wait);
3378 	return true;
3379 }
3380 
3381 /**
3382  * process_one_work - process single work
3383  * @worker: self
3384  * @work: work to process
3385  *
3386  * Process @work.  This function contains all the logics necessary to
3387  * process a single work including synchronization against and
3388  * interaction with other workers on the same cpu, queueing and
3389  * flushing.  As long as context requirement is met, any worker can
3390  * call this function to process a work.
3391  *
3392  * CONTEXT:
3393  * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
3394  */
3395 static void process_one_work(struct worker *worker, struct work_struct *work)
3396 __releases(&pool->lock)
3397 __acquires(&pool->lock)
3398 {
3399 	struct pool_workqueue *pwq = get_work_pwq(work);
3400 	struct worker_pool *pool = worker->pool;
3401 	struct task_struct *wake_task = NULL;
3402 	unsigned long work_data;
3403 	int lockdep_start_depth, rcu_start_depth;
3404 	bool bh_draining = pool->flags & POOL_BH_DRAINING;
3405 #ifdef CONFIG_LOCKDEP
3406 	/*
3407 	 * It is permissible to free the struct work_struct from
3408 	 * inside the function that is called from it, this we need to
3409 	 * take into account for lockdep too.  To avoid bogus "held
3410 	 * lock freed" warnings as well as problems when looking into
3411 	 * work->lockdep_map, make a copy and use that here.
3412 	 */
3413 	struct lockdep_map lockdep_map;
3414 
3415 	lockdep_copy_map(&lockdep_map, &work->lockdep_map);
3416 #endif
3417 	/* ensure we're on the correct CPU */
3418 	WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
3419 		     raw_smp_processor_id() != pool->cpu);
3420 
3421 	/* claim and dequeue */
3422 	debug_work_deactivate(work);
3423 	hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
3424 	worker->current_work = work;
3425 	worker->current_func = work->func;
3426 	worker->current_pwq = pwq;
3427 	if (worker->task)
3428 		worker->current_at = READ_ONCE(worker->task->se.sum_exec_runtime);
3429 	worker->current_start = jiffies;
3430 	work_data = *work_data_bits(work);
3431 	worker->current_color = get_work_color(work_data);
3432 
3433 	/*
3434 	 * Record wq name for cmdline and debug reporting, may get
3435 	 * overridden through set_worker_desc().
3436 	 */
3437 	strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
3438 
3439 	list_del_init(&work->entry);
3440 
3441 	/*
3442 	 * CPU intensive works don't participate in concurrency management.
3443 	 * They're the scheduler's responsibility.  This takes @worker out
3444 	 * of concurrency management and the next code block will chain
3445 	 * execution of the pending work items.
3446 	 */
3447 	if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
3448 		worker_set_flags(worker, WORKER_CPU_INTENSIVE);
3449 
3450 	/*
3451 	 * Kick @pool if necessary. It's always noop for per-cpu worker pools
3452 	 * since nr_running would always be >= 1 at this point. This is used to
3453 	 * chain execution of the pending work items for WORKER_NOT_RUNNING
3454 	 * workers such as the UNBOUND and CPU_INTENSIVE ones.
3455 	 *
3456 	 * Select the worker under pool->lock; the wakeup is deferred until
3457 	 * after the lock is dropped, guarded by the rcu_read_lock() below.
3458 	 */
3459 	kick_pool_pick(pool, &wake_task);
3460 
3461 	/*
3462 	 * Record the last pool and clear PENDING which should be the last
3463 	 * update to @work.  Also, do this inside @pool->lock so that
3464 	 * PENDING and queued state changes happen together while IRQ is
3465 	 * disabled.
3466 	 */
3467 	set_work_pool_and_clear_pending(work, pool->id, pool_offq_flags(pool));
3468 
3469 	pwq->nr_started++;
3470 	pwq->stats[PWQ_STAT_STARTED]++;
3471 
3472 	rcu_read_lock();
3473 	raw_spin_unlock_irq(&pool->lock);
3474 	if (wake_task)
3475 		wake_up_process(wake_task);
3476 	rcu_read_unlock();
3477 
3478 	rcu_start_depth = rcu_preempt_depth();
3479 	lockdep_start_depth = lockdep_depth(current);
3480 	/* see drain_dead_softirq_workfn() */
3481 	if (!bh_draining)
3482 		lock_map_acquire(pwq->wq->lockdep_map);
3483 	lock_map_acquire(&lockdep_map);
3484 	/*
3485 	 * Strictly speaking we should mark the invariant state without holding
3486 	 * any locks, that is, before these two lock_map_acquire()'s.
3487 	 *
3488 	 * However, that would result in:
3489 	 *
3490 	 *   A(W1)
3491 	 *   WFC(C)
3492 	 *		A(W1)
3493 	 *		C(C)
3494 	 *
3495 	 * Which would create W1->C->W1 dependencies, even though there is no
3496 	 * actual deadlock possible. There are two solutions, using a
3497 	 * read-recursive acquire on the work(queue) 'locks', but this will then
3498 	 * hit the lockdep limitation on recursive locks, or simply discard
3499 	 * these locks.
3500 	 *
3501 	 * AFAICT there is no possible deadlock scenario between the
3502 	 * flush_work() and complete() primitives (except for single-threaded
3503 	 * workqueues), so hiding them isn't a problem.
3504 	 */
3505 	lockdep_invariant_state(true);
3506 	trace_workqueue_execute_start(work);
3507 	worker->current_func(work);
3508 	/*
3509 	 * While we must be careful to not use "work" after this, the trace
3510 	 * point will only record its address.
3511 	 */
3512 	trace_workqueue_execute_end(work, worker->current_func);
3513 
3514 	lock_map_release(&lockdep_map);
3515 	if (!bh_draining)
3516 		lock_map_release(pwq->wq->lockdep_map);
3517 
3518 	if (unlikely((worker->task && in_atomic()) ||
3519 		     lockdep_depth(current) != lockdep_start_depth ||
3520 		     rcu_preempt_depth() != rcu_start_depth)) {
3521 		pr_err("BUG: workqueue leaked atomic, lock or RCU: %s[%d]\n"
3522 		       "     preempt=0x%08x lock=%d->%d RCU=%d->%d workfn=%ps\n",
3523 		       current->comm, task_pid_nr(current), preempt_count(),
3524 		       lockdep_start_depth, lockdep_depth(current),
3525 		       rcu_start_depth, rcu_preempt_depth(),
3526 		       worker->current_func);
3527 		debug_show_held_locks(current);
3528 		dump_stack();
3529 	}
3530 
3531 	/*
3532 	 * The following prevents a kworker from hogging CPU on !PREEMPTION
3533 	 * kernels, where a requeueing work item waiting for something to
3534 	 * happen could deadlock with stop_machine as such work item could
3535 	 * indefinitely requeue itself while all other CPUs are trapped in
3536 	 * stop_machine. At the same time, report a quiescent RCU state so
3537 	 * the same condition doesn't freeze RCU.
3538 	 */
3539 	if (worker->task)
3540 		cond_resched();
3541 
3542 	raw_spin_lock_irq(&pool->lock);
3543 
3544 	pwq->stats[PWQ_STAT_COMPLETED]++;
3545 
3546 	/*
3547 	 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
3548 	 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
3549 	 * wq_cpu_intensive_thresh_us. Clear it.
3550 	 */
3551 	worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
3552 
3553 	/* tag the worker for identification in schedule() */
3554 	worker->last_func = worker->current_func;
3555 
3556 	/* we're done with it, release */
3557 	hash_del(&worker->hentry);
3558 	worker->current_work = NULL;
3559 	worker->current_func = NULL;
3560 	worker->current_pwq = NULL;
3561 	worker->current_color = INT_MAX;
3562 
3563 	/* must be the last step, see the function comment */
3564 	pwq_dec_nr_in_flight(pwq, work_data);
3565 }
3566 
3567 /**
3568  * process_scheduled_works - process scheduled works
3569  * @worker: self
3570  *
3571  * Process all scheduled works.  Please note that the scheduled list
3572  * may change while processing a work, so this function repeatedly
3573  * fetches a work from the top and executes it.
3574  *
3575  * CONTEXT:
3576  * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3577  * multiple times.
3578  */
3579 static void process_scheduled_works(struct worker *worker)
3580 {
3581 	struct work_struct *work;
3582 	bool first = true;
3583 
3584 	while ((work = list_first_entry_or_null(&worker->scheduled,
3585 						struct work_struct, entry))) {
3586 		if (first) {
3587 			worker->pool->last_progress_ts = jiffies;
3588 			first = false;
3589 		}
3590 		process_one_work(worker, work);
3591 	}
3592 }
3593 
3594 static void set_pf_worker(bool val)
3595 {
3596 	mutex_lock(&wq_pool_attach_mutex);
3597 	if (val)
3598 		current->flags |= PF_WQ_WORKER;
3599 	else
3600 		current->flags &= ~PF_WQ_WORKER;
3601 	mutex_unlock(&wq_pool_attach_mutex);
3602 }
3603 
3604 /**
3605  * worker_thread - the worker thread function
3606  * @__worker: self
3607  *
3608  * The worker thread function.  All workers belong to a worker_pool -
3609  * either a per-cpu one or dynamic unbound one.  These workers process all
3610  * work items regardless of their specific target workqueue.  The only
3611  * exception is work items which belong to workqueues with a rescuer which
3612  * will be explained in rescuer_thread().
3613  *
3614  * Return: 0
3615  */
3616 static int worker_thread(void *__worker)
3617 {
3618 	struct worker *worker = __worker;
3619 	struct worker_pool *pool = worker->pool;
3620 
3621 	/* tell the scheduler that this is a workqueue worker */
3622 	set_pf_worker(true);
3623 woke_up:
3624 	raw_spin_lock_irq(&pool->lock);
3625 
3626 	/* am I supposed to die? */
3627 	if (unlikely(worker->flags & WORKER_DIE)) {
3628 		raw_spin_unlock_irq(&pool->lock);
3629 		set_pf_worker(false);
3630 		/*
3631 		 * The worker is dead and PF_WQ_WORKER is cleared, worker->pool
3632 		 * shouldn't be accessed, reset it to NULL in case otherwise.
3633 		 */
3634 		worker->pool = NULL;
3635 		ida_free(&pool->worker_ida, worker->id);
3636 		return 0;
3637 	}
3638 
3639 	worker_leave_idle(worker);
3640 recheck:
3641 	/* no more worker necessary? */
3642 	if (!need_more_worker(pool))
3643 		goto sleep;
3644 
3645 	/* do we need to manage? */
3646 	if (unlikely(!may_start_working(pool)) && manage_workers(worker))
3647 		goto recheck;
3648 
3649 	/*
3650 	 * ->scheduled list can only be filled while a worker is
3651 	 * preparing to process a work or actually processing it.
3652 	 * Make sure nobody diddled with it while I was sleeping.
3653 	 */
3654 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
3655 
3656 	/*
3657 	 * Finish PREP stage.  We're guaranteed to have at least one idle
3658 	 * worker or that someone else has already assumed the manager
3659 	 * role.  This is where @worker starts participating in concurrency
3660 	 * management if applicable and concurrency management is restored
3661 	 * after being rebound.  See rebind_workers() for details.
3662 	 */
3663 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
3664 
3665 	do {
3666 		struct work_struct *work =
3667 			list_first_entry(&pool->worklist,
3668 					 struct work_struct, entry);
3669 
3670 		if (assign_work(work, worker, NULL))
3671 			process_scheduled_works(worker);
3672 	} while (keep_working(pool));
3673 
3674 	worker_set_flags(worker, WORKER_PREP);
3675 sleep:
3676 	/*
3677 	 * pool->lock is held and there's no work to process and no need to
3678 	 * manage, sleep.  Workers are woken up only while holding
3679 	 * pool->lock or from local cpu, so setting the current state
3680 	 * before releasing pool->lock is enough to prevent losing any
3681 	 * event.
3682 	 */
3683 	worker_enter_idle(worker);
3684 	__set_current_state(TASK_IDLE);
3685 	raw_spin_unlock_irq(&pool->lock);
3686 	schedule();
3687 	goto woke_up;
3688 }
3689 
3690 static bool assign_rescuer_work(struct pool_workqueue *pwq, struct worker *rescuer)
3691 {
3692 	struct worker_pool *pool = pwq->pool;
3693 	struct work_struct *cursor = &pwq->mayday_cursor;
3694 	struct work_struct *work, *n;
3695 
3696 	/* have work items to rescue? */
3697 	if (!pwq->nr_active)
3698 		return false;
3699 
3700 	/* need rescue? */
3701 	if (!need_to_create_worker(pool)) {
3702 		/*
3703 		 * The pool has idle workers and doesn't need the rescuer, so it
3704 		 * could simply return false here.
3705 		 *
3706 		 * However, the memory pressure might not be fully relieved.
3707 		 * In PERCPU pool with concurrency enabled, having idle workers
3708 		 * does not necessarily mean memory pressure is gone; it may
3709 		 * simply mean regular workers have woken up, completed their
3710 		 * work, and gone idle again due to concurrency limits.
3711 		 *
3712 		 * In this case, those working workers may later sleep again,
3713 		 * the pool may run out of idle workers, and it will have to
3714 		 * allocate new ones and wait for the timer to send mayday,
3715 		 * causing unnecessary delay - especially if memory pressure
3716 		 * was never resolved throughout.
3717 		 *
3718 		 * Do more work if memory pressure is still on to reduce
3719 		 * relapse, using (pool->flags & POOL_MANAGER_ACTIVE), though
3720 		 * not precisely, unless there are other PWQs needing help.
3721 		 */
3722 		if (!(pool->flags & POOL_MANAGER_ACTIVE) ||
3723 		    !list_empty(&pwq->wq->maydays))
3724 			return false;
3725 	}
3726 
3727 	/* search from the start or cursor if available */
3728 	if (list_empty(&cursor->entry))
3729 		work = list_first_entry(&pool->worklist, struct work_struct, entry);
3730 	else
3731 		work = list_next_entry(cursor, entry);
3732 
3733 	/* find the next work item to rescue */
3734 	list_for_each_entry_safe_from(work, n, &pool->worklist, entry) {
3735 		if (get_work_pwq(work) == pwq && assign_work(work, rescuer, &n)) {
3736 			pwq->stats[PWQ_STAT_RESCUED]++;
3737 			trace_workqueue_rescued(pwq, work, work->func);
3738 			/* put the cursor for next search */
3739 			list_move_tail(&cursor->entry, &n->entry);
3740 			return true;
3741 		}
3742 	}
3743 
3744 	return false;
3745 }
3746 
3747 /**
3748  * rescuer_thread - the rescuer thread function
3749  * @__rescuer: self
3750  *
3751  * Workqueue rescuer thread function.  There's one rescuer for each
3752  * workqueue which has WQ_MEM_RECLAIM set.
3753  *
3754  * Regular work processing on a pool may block trying to create a new
3755  * worker which uses GFP_KERNEL allocation which has slight chance of
3756  * developing into deadlock if some works currently on the same queue
3757  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
3758  * the problem rescuer solves.
3759  *
3760  * When such condition is possible, the pool summons rescuers of all
3761  * workqueues which have works queued on the pool and let them process
3762  * those works so that forward progress can be guaranteed.
3763  *
3764  * This should happen rarely.
3765  *
3766  * Return: 0
3767  */
3768 static int rescuer_thread(void *__rescuer)
3769 {
3770 	struct worker *rescuer = __rescuer;
3771 	struct workqueue_struct *wq = rescuer->rescue_wq;
3772 	bool should_stop;
3773 
3774 	set_user_nice(current, RESCUER_NICE_LEVEL);
3775 
3776 	/*
3777 	 * Mark rescuer as worker too.  As WORKER_PREP is never cleared, it
3778 	 * doesn't participate in concurrency management.
3779 	 */
3780 	set_pf_worker(true);
3781 repeat:
3782 	set_current_state(TASK_IDLE);
3783 
3784 	/*
3785 	 * By the time the rescuer is requested to stop, the workqueue
3786 	 * shouldn't have any work pending, but @wq->maydays may still have
3787 	 * pwq(s) queued.  This can happen by non-rescuer workers consuming
3788 	 * all the work items before the rescuer got to them.  Go through
3789 	 * @wq->maydays processing before acting on should_stop so that the
3790 	 * list is always empty on exit.
3791 	 */
3792 	should_stop = kthread_should_stop();
3793 
3794 	/* see whether any pwq is asking for help */
3795 	raw_spin_lock_irq(&wq_mayday_lock);
3796 
3797 	while (!list_empty(&wq->maydays)) {
3798 		struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
3799 					struct pool_workqueue, mayday_node);
3800 		struct worker_pool *pool = pwq->pool;
3801 		unsigned int count = 0;
3802 
3803 		__set_current_state(TASK_RUNNING);
3804 		list_del_init(&pwq->mayday_node);
3805 
3806 		raw_spin_unlock_irq(&wq_mayday_lock);
3807 
3808 		worker_attach_to_pool(rescuer, pool);
3809 
3810 		raw_spin_lock_irq(&pool->lock);
3811 
3812 		WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
3813 
3814 		while (assign_rescuer_work(pwq, rescuer)) {
3815 			process_scheduled_works(rescuer);
3816 
3817 			/*
3818 			 * If the per-turn work item limit is reached and other
3819 			 * PWQs are in mayday, requeue mayday for this PWQ and
3820 			 * let the rescuer handle the other PWQs first.
3821 			 */
3822 			if (++count > RESCUER_BATCH && !list_empty(&pwq->wq->maydays) &&
3823 			    pwq->nr_active && need_to_create_worker(pool)) {
3824 				raw_spin_lock(&wq_mayday_lock);
3825 				send_mayday(pwq);
3826 				raw_spin_unlock(&wq_mayday_lock);
3827 				break;
3828 			}
3829 		}
3830 
3831 		/* The cursor can not be left behind without the rescuer watching it. */
3832 		if (!list_empty(&pwq->mayday_cursor.entry) && list_empty(&pwq->mayday_node))
3833 			list_del_init(&pwq->mayday_cursor.entry);
3834 
3835 		/*
3836 		 * Leave this pool. Notify regular workers; otherwise, we end up
3837 		 * with 0 concurrency and stalling the execution.
3838 		 */
3839 		kick_pool(pool);
3840 
3841 		raw_spin_unlock_irq(&pool->lock);
3842 
3843 		worker_detach_from_pool(rescuer);
3844 
3845 		/*
3846 		 * Put the reference grabbed by send_mayday().  @pool might
3847 		 * go away any time after it.
3848 		 */
3849 		put_pwq_unlocked(pwq);
3850 
3851 		raw_spin_lock_irq(&wq_mayday_lock);
3852 	}
3853 
3854 	raw_spin_unlock_irq(&wq_mayday_lock);
3855 
3856 	if (should_stop) {
3857 		__set_current_state(TASK_RUNNING);
3858 		set_pf_worker(false);
3859 		return 0;
3860 	}
3861 
3862 	/* rescuers should never participate in concurrency management */
3863 	WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
3864 	schedule();
3865 	goto repeat;
3866 }
3867 
3868 static void bh_worker(struct worker *worker)
3869 {
3870 	struct worker_pool *pool = worker->pool;
3871 	int nr_restarts = BH_WORKER_RESTARTS;
3872 	unsigned long end = jiffies + BH_WORKER_JIFFIES;
3873 	bool budget_exhausted = false;
3874 	bool timeout = false;
3875 	int restarts = 0;
3876 
3877 	worker_lock_callback(pool);
3878 	raw_spin_lock_irq(&pool->lock);
3879 	worker_leave_idle(worker);
3880 
3881 	/*
3882 	 * This function follows the structure of worker_thread(). See there for
3883 	 * explanations on each step.
3884 	 */
3885 	if (!need_more_worker(pool))
3886 		goto done;
3887 
3888 	WARN_ON_ONCE(!list_empty(&worker->scheduled));
3889 	worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
3890 
3891 	do {
3892 		struct work_struct *work =
3893 			list_first_entry(&pool->worklist,
3894 					 struct work_struct, entry);
3895 
3896 		if (assign_work(work, worker, NULL))
3897 			process_scheduled_works(worker);
3898 
3899 		if (!keep_working(pool))
3900 			break;
3901 
3902 		if (!--nr_restarts) {
3903 			budget_exhausted = true;
3904 			break;
3905 		}
3906 
3907 		if (!time_before(jiffies, end)) {
3908 			budget_exhausted = true;
3909 			timeout = true;
3910 			break;
3911 		}
3912 
3913 		restarts++;
3914 	} while (1);
3915 
3916 	worker_set_flags(worker, WORKER_PREP);
3917 done:
3918 	worker_enter_idle(worker);
3919 	kick_pool(pool);
3920 	raw_spin_unlock_irq(&pool->lock);
3921 	worker_unlock_callback(pool);
3922 
3923 	if (budget_exhausted)
3924 		trace_workqueue_bh_budget_yield(pool, restarts, timeout,
3925 						pool->attrs->nice == HIGHPRI_NICE_LEVEL);
3926 }
3927 
3928 /*
3929  * TODO: Convert all tasklet users to workqueue and use softirq directly.
3930  *
3931  * This is currently called from tasklet[_hi]action() and thus is also called
3932  * whenever there are tasklets to run. Let's do an early exit if there's nothing
3933  * queued. Once conversion from tasklet is complete, the need_more_worker() test
3934  * can be dropped.
3935  *
3936  * After full conversion, we'll add worker->softirq_action, directly use the
3937  * softirq action and obtain the worker pointer from the softirq_action pointer.
3938  */
3939 void workqueue_softirq_action(bool highpri)
3940 {
3941 	struct worker_pool *pool =
3942 		&per_cpu(bh_worker_pools, smp_processor_id())[highpri];
3943 	if (need_more_worker(pool))
3944 		bh_worker(list_first_entry(&pool->workers, struct worker, node));
3945 }
3946 
3947 struct wq_drain_dead_softirq_work {
3948 	struct work_struct	work;
3949 	struct worker_pool	*pool;
3950 	struct completion	done;
3951 };
3952 
3953 static void drain_dead_softirq_workfn(struct work_struct *work)
3954 {
3955 	struct wq_drain_dead_softirq_work *dead_work =
3956 		container_of(work, struct wq_drain_dead_softirq_work, work);
3957 	struct worker_pool *pool = dead_work->pool;
3958 	bool repeat;
3959 
3960 	/*
3961 	 * @pool's CPU is dead and we want to execute its still pending work
3962 	 * items from this BH work item which is running on a different CPU. As
3963 	 * its CPU is dead, @pool can't be kicked and, as work execution path
3964 	 * will be nested, a lockdep annotation needs to be suppressed. Mark
3965 	 * @pool with %POOL_BH_DRAINING for the special treatments.
3966 	 */
3967 	raw_spin_lock_irq(&pool->lock);
3968 	pool->flags |= POOL_BH_DRAINING;
3969 	raw_spin_unlock_irq(&pool->lock);
3970 
3971 	bh_worker(list_first_entry(&pool->workers, struct worker, node));
3972 
3973 	raw_spin_lock_irq(&pool->lock);
3974 	pool->flags &= ~POOL_BH_DRAINING;
3975 	repeat = need_more_worker(pool);
3976 	raw_spin_unlock_irq(&pool->lock);
3977 
3978 	/*
3979 	 * bh_worker() might hit consecutive execution limit and bail. If there
3980 	 * still are pending work items, reschedule self and return so that we
3981 	 * don't hog this CPU's BH.
3982 	 */
3983 	if (repeat) {
3984 		if (pool->attrs->nice == HIGHPRI_NICE_LEVEL)
3985 			queue_work(system_bh_highpri_wq, work);
3986 		else
3987 			queue_work(system_bh_wq, work);
3988 	} else {
3989 		complete(&dead_work->done);
3990 	}
3991 }
3992 
3993 /*
3994  * @cpu is dead. Drain the remaining BH work items on the current CPU. It's
3995  * possible to allocate dead_work per CPU and avoid flushing. However, then we
3996  * have to worry about draining overlapping with CPU coming back online or
3997  * nesting (one CPU's dead_work queued on another CPU which is also dead and so
3998  * on). Let's keep it simple and drain them synchronously. These are BH work
3999  * items which shouldn't be requeued on the same pool. Shouldn't take long.
4000  */
4001 void workqueue_softirq_dead(unsigned int cpu)
4002 {
4003 	int i;
4004 
4005 	for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
4006 		struct worker_pool *pool = &per_cpu(bh_worker_pools, cpu)[i];
4007 		struct wq_drain_dead_softirq_work dead_work;
4008 
4009 		if (!need_more_worker(pool))
4010 			continue;
4011 
4012 		INIT_WORK_ONSTACK(&dead_work.work, drain_dead_softirq_workfn);
4013 		dead_work.pool = pool;
4014 		init_completion(&dead_work.done);
4015 
4016 		if (pool->attrs->nice == HIGHPRI_NICE_LEVEL)
4017 			queue_work(system_bh_highpri_wq, &dead_work.work);
4018 		else
4019 			queue_work(system_bh_wq, &dead_work.work);
4020 
4021 		wait_for_completion(&dead_work.done);
4022 		destroy_work_on_stack(&dead_work.work);
4023 	}
4024 }
4025 
4026 /**
4027  * check_flush_dependency - check for flush dependency sanity
4028  * @target_wq: workqueue being flushed
4029  * @target_work: work item being flushed (NULL for workqueue flushes)
4030  * @from_cancel: are we called from the work cancel path
4031  *
4032  * %current is trying to flush the whole @target_wq or @target_work on it.
4033  * If this is not the cancel path (which implies work being flushed is either
4034  * already running, or will not be at all), check if @target_wq doesn't have
4035  * %WQ_MEM_RECLAIM and verify that %current is not reclaiming memory or running
4036  * on a workqueue which doesn't have %WQ_MEM_RECLAIM as that can break forward-
4037  * progress guarantee leading to a deadlock.
4038  */
4039 static void check_flush_dependency(struct workqueue_struct *target_wq,
4040 				   struct work_struct *target_work,
4041 				   bool from_cancel)
4042 {
4043 	work_func_t target_func;
4044 	struct worker *worker;
4045 
4046 	if (from_cancel || target_wq->flags & WQ_MEM_RECLAIM)
4047 		return;
4048 
4049 	worker = current_wq_worker();
4050 	target_func = target_work ? target_work->func : NULL;
4051 
4052 	WARN_ONCE(current->flags & PF_MEMALLOC,
4053 		  "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
4054 		  current->pid, current->comm, target_wq->name, target_func);
4055 	WARN_ONCE(worker && worker->current_pwq && ((worker->current_pwq->wq->flags &
4056 			      (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
4057 		  "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
4058 		  worker->current_pwq->wq->name, worker->current_func,
4059 		  target_wq->name, target_func);
4060 }
4061 
4062 struct wq_barrier {
4063 	struct work_struct	work;
4064 	struct completion	done;
4065 	struct task_struct	*task;	/* purely informational */
4066 };
4067 
4068 static void wq_barrier_func(struct work_struct *work)
4069 {
4070 	struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
4071 	complete(&barr->done);
4072 }
4073 
4074 /**
4075  * insert_wq_barrier - insert a barrier work
4076  * @pwq: pwq to insert barrier into
4077  * @barr: wq_barrier to insert
4078  * @target: target work to attach @barr to
4079  * @worker: worker currently executing @target, NULL if @target is not executing
4080  *
4081  * @barr is linked to @target such that @barr is completed only after
4082  * @target finishes execution.  Please note that the ordering
4083  * guarantee is observed only with respect to @target and on the local
4084  * cpu.
4085  *
4086  * Currently, a queued barrier can't be canceled.  This is because
4087  * try_to_grab_pending() can't determine whether the work to be
4088  * grabbed is at the head of the queue and thus can't clear LINKED
4089  * flag of the previous work while there must be a valid next work
4090  * after a work with LINKED flag set.
4091  *
4092  * Note that when @worker is non-NULL, @target may be modified
4093  * underneath us, so we can't reliably determine pwq from @target.
4094  *
4095  * CONTEXT:
4096  * raw_spin_lock_irq(pool->lock).
4097  */
4098 static void insert_wq_barrier(struct pool_workqueue *pwq,
4099 			      struct wq_barrier *barr,
4100 			      struct work_struct *target, struct worker *worker)
4101 {
4102 	static __maybe_unused struct lock_class_key bh_key, thr_key;
4103 	unsigned int work_flags = 0;
4104 	unsigned int work_color;
4105 	struct list_head *head;
4106 
4107 	/*
4108 	 * debugobject calls are safe here even with pool->lock locked
4109 	 * as we know for sure that this will not trigger any of the
4110 	 * checks and call back into the fixup functions where we
4111 	 * might deadlock.
4112 	 *
4113 	 * BH and threaded workqueues need separate lockdep keys to avoid
4114 	 * spuriously triggering "inconsistent {SOFTIRQ-ON-W} -> {IN-SOFTIRQ-W}
4115 	 * usage".
4116 	 */
4117 	INIT_WORK_ONSTACK_KEY(&barr->work, wq_barrier_func,
4118 			      (pwq->wq->flags & WQ_BH) ? &bh_key : &thr_key);
4119 	__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
4120 
4121 	init_completion_map(&barr->done, &target->lockdep_map);
4122 
4123 	barr->task = current;
4124 
4125 	/* The barrier work item does not participate in nr_active. */
4126 	work_flags |= WORK_STRUCT_INACTIVE;
4127 
4128 	/*
4129 	 * If @target is currently being executed, schedule the
4130 	 * barrier to the worker; otherwise, put it after @target.
4131 	 */
4132 	if (worker) {
4133 		head = worker->scheduled.next;
4134 		work_color = worker->current_color;
4135 	} else {
4136 		unsigned long *bits = work_data_bits(target);
4137 
4138 		head = target->entry.next;
4139 		/* there can already be other linked works, inherit and set */
4140 		work_flags |= *bits & WORK_STRUCT_LINKED;
4141 		work_color = get_work_color(*bits);
4142 		__set_bit(WORK_STRUCT_LINKED_BIT, bits);
4143 	}
4144 
4145 	/*
4146 	 * Flushes must wait for barriers too as a barrier pins @pwq and a
4147 	 * worker until it runs and destroy_workqueue()'s drain relies on that.
4148 	 * @target being in flight keeps @pwq on its wq_flush_pnode list, so no
4149 	 * need to add it here.
4150 	 */
4151 	WARN_ON_ONCE(list_empty(&pwq->flush_node));
4152 
4153 	pwq_inc_nr_in_flight(pwq, work_color);
4154 	work_flags |= work_color_to_flags(work_color);
4155 
4156 	insert_work(pwq, &barr->work, head, work_flags);
4157 }
4158 
4159 /**
4160  * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
4161  * @wq: workqueue being flushed
4162  * @flush_color: new flush color, < 0 for no-op
4163  * @work_color: new work color, < 0 for no-op
4164  *
4165  * Prepare pwqs for workqueue flushing. Only the pwqs on @wq's wq_flush_pnode
4166  * lists, which have been active since the last flush, are visited.
4167  *
4168  * If @flush_color >= 0, flush_color on all visited pwqs should be -1. If no
4169  * visited pwq has in-flight work items at the specified color, all
4170  * pwq->flush_color's stay at -1 and return %false. If any visited pwq has
4171  * in-flight work items, set its pwq->flush_color to @flush_color, update
4172  * @wq->nr_pwqs_to_flush accordingly, arm pwq wakeup logic and return %true.
4173  *
4174  * The caller should have initialized @wq->first_flusher prior to calling this
4175  * function with non-negative @flush_color. If @flush_color < 0, no flush color
4176  * update is done and %false is returned.
4177  *
4178  * If @work_color >= 0, all visited pwqs and every wq_flush_pnode's work color
4179  * mirror are advanced to @work_color. The mirrors of nodes with no active pwqs
4180  * must be advanced too as a pwq added to a list later stamps the color it reads
4181  * from the mirror.
4182  *
4183  * CONTEXT:
4184  * mutex_lock(wq->mutex).
4185  *
4186  * Return:
4187  * %true if @flush_color >= 0 and there's something to flush.  %false
4188  * otherwise.
4189  */
4190 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
4191 				      int flush_color, int work_color)
4192 {
4193 	struct pool_workqueue *pwq, *next;
4194 	bool wait = false;
4195 	int node;
4196 
4197 	if (flush_color >= 0) {
4198 		WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
4199 		atomic_set(&wq->nr_pwqs_to_flush, 1);
4200 	}
4201 
4202 	for_each_node_with_fallback(node) {
4203 		struct wq_flush_pnode *fpn = wq->flush_pnodes[node];
4204 		struct worker_pool *current_pool = NULL;
4205 		LIST_HEAD(to_visit);
4206 		LIST_HEAD(to_keep);
4207 
4208 		/*
4209 		 * Advance the node's color mirror and take its active pwqs.
4210 		 * Work items queued to off-list pwqs afterwards carry the new
4211 		 * color and don't need visiting.
4212 		 */
4213 		raw_spin_lock_irq(&fpn->lock);
4214 		if (work_color >= 0) {
4215 			WARN_ON_ONCE(work_color != work_next_color(fpn->work_color));
4216 			fpn->work_color = work_color;
4217 		}
4218 		list_splice_init(&fpn->pwqs, &to_visit);
4219 		raw_spin_unlock_irq(&fpn->lock);
4220 
4221 		/*
4222 		 * Unbound workqueues map multiple pwqs to one pool. Only cycle
4223 		 * pool->lock when the pool changes.
4224 		 */
4225 		list_for_each_entry_safe(pwq, next, &to_visit, flush_node) {
4226 			if (current_pool != pwq->pool) {
4227 				if (likely(current_pool))
4228 					raw_spin_unlock_irq(&current_pool->lock);
4229 				current_pool = pwq->pool;
4230 				raw_spin_lock_irq(&current_pool->lock);
4231 			}
4232 
4233 			if (flush_color >= 0) {
4234 				WARN_ON_ONCE(pwq->flush_color != -1);
4235 
4236 				if (pwq->nr_in_flight[flush_color]) {
4237 					pwq->flush_color = flush_color;
4238 					atomic_inc(&wq->nr_pwqs_to_flush);
4239 					wait = true;
4240 				}
4241 			}
4242 
4243 			if (work_color >= 0) {
4244 				WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
4245 				pwq->work_color = work_color;
4246 			}
4247 
4248 			/*
4249 			 * A cascade can arm a color retired several advances
4250 			 * ago, so keep a pwq listed while any color has work
4251 			 * items in flight.
4252 			 */
4253 			if (pwq->total_in_flight)
4254 				list_move_tail(&pwq->flush_node, &to_keep);
4255 			else
4256 				list_del_init(&pwq->flush_node);
4257 		}
4258 
4259 		if (current_pool)
4260 			raw_spin_unlock_irq(&current_pool->lock);
4261 
4262 		if (!list_empty(&to_keep)) {
4263 			raw_spin_lock_irq(&fpn->lock);
4264 			list_splice_tail(&to_keep, &fpn->pwqs);
4265 			raw_spin_unlock_irq(&fpn->lock);
4266 		}
4267 	}
4268 
4269 	if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
4270 		complete(&wq->first_flusher->done);
4271 
4272 	return wait;
4273 }
4274 
4275 static void touch_wq_lockdep_map(struct workqueue_struct *wq)
4276 {
4277 #ifdef CONFIG_LOCKDEP
4278 	if (unlikely(!wq->lockdep_map))
4279 		return;
4280 
4281 	if (wq->flags & WQ_BH)
4282 		local_bh_disable();
4283 
4284 	lock_map_acquire(wq->lockdep_map);
4285 	lock_map_release(wq->lockdep_map);
4286 
4287 	if (wq->flags & WQ_BH)
4288 		local_bh_enable();
4289 #endif
4290 }
4291 
4292 static void touch_work_lockdep_map(struct work_struct *work,
4293 				   struct workqueue_struct *wq)
4294 {
4295 #ifdef CONFIG_LOCKDEP
4296 	if (wq->flags & WQ_BH)
4297 		local_bh_disable();
4298 
4299 	lock_map_acquire(&work->lockdep_map);
4300 	lock_map_release(&work->lockdep_map);
4301 
4302 	if (wq->flags & WQ_BH)
4303 		local_bh_enable();
4304 #endif
4305 }
4306 
4307 /**
4308  * __flush_workqueue - ensure that any scheduled work has run to completion.
4309  * @wq: workqueue to flush
4310  *
4311  * This function sleeps until all work items which were queued on entry
4312  * have finished execution, but it is not livelocked by new incoming ones.
4313  */
4314 void __flush_workqueue(struct workqueue_struct *wq)
4315 {
4316 	struct wq_flusher this_flusher = {
4317 		.list = LIST_HEAD_INIT(this_flusher.list),
4318 		.flush_color = -1,
4319 		.done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, (*wq->lockdep_map)),
4320 	};
4321 	int next_color;
4322 
4323 	if (WARN_ON(!wq_online))
4324 		return;
4325 
4326 	touch_wq_lockdep_map(wq);
4327 
4328 	mutex_lock(&wq->mutex);
4329 
4330 	/*
4331 	 * Start-to-wait phase
4332 	 */
4333 	next_color = work_next_color(wq->work_color);
4334 
4335 	if (next_color != wq->flush_color) {
4336 		/*
4337 		 * Color space is not full.  The current work_color
4338 		 * becomes our flush_color and work_color is advanced
4339 		 * by one.
4340 		 */
4341 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
4342 		this_flusher.flush_color = wq->work_color;
4343 		wq->work_color = next_color;
4344 
4345 		if (!wq->first_flusher) {
4346 			/* no flush in progress, become the first flusher */
4347 			WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
4348 
4349 			wq->first_flusher = &this_flusher;
4350 
4351 			if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
4352 						       wq->work_color)) {
4353 				/* nothing to flush, done */
4354 				wq->flush_color = next_color;
4355 				wq->first_flusher = NULL;
4356 				goto out_unlock;
4357 			}
4358 		} else {
4359 			/* wait in queue */
4360 			WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
4361 			list_add_tail(&this_flusher.list, &wq->flusher_queue);
4362 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
4363 		}
4364 	} else {
4365 		/*
4366 		 * Oops, color space is full, wait on overflow queue.
4367 		 * The next flush completion will assign us
4368 		 * flush_color and transfer to flusher_queue.
4369 		 */
4370 		list_add_tail(&this_flusher.list, &wq->flusher_overflow);
4371 	}
4372 
4373 	check_flush_dependency(wq, NULL, false);
4374 
4375 	mutex_unlock(&wq->mutex);
4376 
4377 	wait_for_completion(&this_flusher.done);
4378 
4379 	/*
4380 	 * Wake-up-and-cascade phase
4381 	 *
4382 	 * First flushers are responsible for cascading flushes and
4383 	 * handling overflow.  Non-first flushers can simply return.
4384 	 */
4385 	if (READ_ONCE(wq->first_flusher) != &this_flusher)
4386 		return;
4387 
4388 	mutex_lock(&wq->mutex);
4389 
4390 	/* we might have raced, check again with mutex held */
4391 	if (wq->first_flusher != &this_flusher)
4392 		goto out_unlock;
4393 
4394 	WRITE_ONCE(wq->first_flusher, NULL);
4395 
4396 	WARN_ON_ONCE(!list_empty(&this_flusher.list));
4397 	WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
4398 
4399 	while (true) {
4400 		struct wq_flusher *next, *tmp;
4401 
4402 		/* complete all the flushers sharing the current flush color */
4403 		list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
4404 			if (next->flush_color != wq->flush_color)
4405 				break;
4406 			list_del_init(&next->list);
4407 			complete(&next->done);
4408 		}
4409 
4410 		WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
4411 			     wq->flush_color != work_next_color(wq->work_color));
4412 
4413 		/* this flush_color is finished, advance by one */
4414 		wq->flush_color = work_next_color(wq->flush_color);
4415 
4416 		/* one color has been freed, handle overflow queue */
4417 		if (!list_empty(&wq->flusher_overflow)) {
4418 			/*
4419 			 * Assign the same color to all overflowed
4420 			 * flushers, advance work_color and append to
4421 			 * flusher_queue.  This is the start-to-wait
4422 			 * phase for these overflowed flushers.
4423 			 */
4424 			list_for_each_entry(tmp, &wq->flusher_overflow, list)
4425 				tmp->flush_color = wq->work_color;
4426 
4427 			wq->work_color = work_next_color(wq->work_color);
4428 
4429 			list_splice_tail_init(&wq->flusher_overflow,
4430 					      &wq->flusher_queue);
4431 			flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
4432 		}
4433 
4434 		if (list_empty(&wq->flusher_queue)) {
4435 			WARN_ON_ONCE(wq->flush_color != wq->work_color);
4436 			break;
4437 		}
4438 
4439 		/*
4440 		 * Need to flush more colors.  Make the next flusher
4441 		 * the new first flusher and arm pwqs.
4442 		 */
4443 		WARN_ON_ONCE(wq->flush_color == wq->work_color);
4444 		WARN_ON_ONCE(wq->flush_color != next->flush_color);
4445 
4446 		list_del_init(&next->list);
4447 		wq->first_flusher = next;
4448 
4449 		if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
4450 			break;
4451 
4452 		/*
4453 		 * Meh... this color is already done, clear first
4454 		 * flusher and repeat cascading.
4455 		 */
4456 		wq->first_flusher = NULL;
4457 	}
4458 
4459 out_unlock:
4460 	mutex_unlock(&wq->mutex);
4461 }
4462 EXPORT_SYMBOL(__flush_workqueue);
4463 
4464 /*
4465  * Return 0 if any pwq of @wq is busy. Otherwise, return the sum of nr_started
4466  * of all pwqs encoded as 2 * sum + 1, which is always odd, so that 0 can only
4467  * mean busy.
4468  */
4469 static unsigned long pwqs_nr_started(struct workqueue_struct *wq)
4470 {
4471 	struct pool_workqueue *pwq;
4472 	unsigned long sum = 0;
4473 
4474 	lockdep_assert_held(&wq->mutex);
4475 
4476 	for_each_pwq(pwq, wq) {
4477 		bool empty;
4478 
4479 		raw_spin_lock_irq(&pwq->pool->lock);
4480 		empty = pwq_is_empty(pwq);
4481 		sum += pwq->nr_started;
4482 		raw_spin_unlock_irq(&pwq->pool->lock);
4483 
4484 		if (!empty)
4485 			return 0;
4486 	}
4487 
4488 	return 2 * sum + 1;
4489 }
4490 
4491 /**
4492  * drain_workqueue - drain a workqueue
4493  * @wq: workqueue to drain
4494  *
4495  * Wait until the workqueue becomes empty.  While draining is in progress,
4496  * only chain queueing is allowed.  IOW, only currently pending or running
4497  * work items on @wq can queue further work items on it.  @wq is flushed
4498  * repeatedly until it becomes empty.  The number of flushing is determined
4499  * by the depth of chaining and should be relatively short.  Whine if it
4500  * takes too long.
4501  */
4502 void drain_workqueue(struct workqueue_struct *wq)
4503 {
4504 	unsigned long started;
4505 	unsigned int flush_cnt = 0;
4506 
4507 	/*
4508 	 * __queue_work() needs to test whether there are drainers, is much
4509 	 * hotter than drain_workqueue() and already looks at @wq->flags.
4510 	 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
4511 	 */
4512 	mutex_lock(&wq->mutex);
4513 	if (!wq->nr_drainers++)
4514 		wq->flags |= __WQ_DRAINING;
4515 	mutex_unlock(&wq->mutex);
4516 reflush:
4517 	__flush_workqueue(wq);
4518 
4519 	mutex_lock(&wq->mutex);
4520 
4521 	/*
4522 	 * A pass isn't atomic across pwqs, so a chained work item can land on
4523 	 * a pwq it already found empty. Anything slipping past the second pass
4524 	 * needs a work item that was in flight at its pwq's first check, or
4525 	 * that started between its pwq's two checks. The first makes the first
4526 	 * pass fail, the second changes nr_started. wq->mutex keeps the set of
4527 	 * pwqs stable across both passes.
4528 	 */
4529 	started = pwqs_nr_started(wq);
4530 	if (!started || pwqs_nr_started(wq) != started) {
4531 		if (++flush_cnt == 10 ||
4532 		    (flush_cnt % 100 == 0 && flush_cnt <= 1000))
4533 			pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
4534 				wq->name, __func__, flush_cnt);
4535 
4536 		mutex_unlock(&wq->mutex);
4537 		goto reflush;
4538 	}
4539 
4540 	if (!--wq->nr_drainers)
4541 		wq->flags &= ~__WQ_DRAINING;
4542 	mutex_unlock(&wq->mutex);
4543 }
4544 EXPORT_SYMBOL_GPL(drain_workqueue);
4545 
4546 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
4547 			     bool from_cancel)
4548 {
4549 	struct worker *worker = NULL;
4550 	struct worker_pool *pool;
4551 	struct pool_workqueue *pwq;
4552 	struct workqueue_struct *wq;
4553 
4554 	rcu_read_lock();
4555 	pool = get_work_pool(work);
4556 	if (!pool) {
4557 		rcu_read_unlock();
4558 		return false;
4559 	}
4560 
4561 	raw_spin_lock_irq(&pool->lock);
4562 	/* see the comment in try_to_grab_pending() with the same code */
4563 	pwq = get_work_pwq(work);
4564 	if (pwq) {
4565 		if (unlikely(pwq->pool != pool))
4566 			goto already_gone;
4567 	} else {
4568 		worker = find_worker_executing_work(pool, work);
4569 		if (!worker)
4570 			goto already_gone;
4571 		pwq = worker->current_pwq;
4572 	}
4573 
4574 	wq = pwq->wq;
4575 	check_flush_dependency(wq, work, from_cancel);
4576 
4577 	insert_wq_barrier(pwq, barr, work, worker);
4578 	raw_spin_unlock_irq(&pool->lock);
4579 
4580 	touch_work_lockdep_map(work, wq);
4581 
4582 	/*
4583 	 * Force a lock recursion deadlock when using flush_work() inside a
4584 	 * single-threaded or rescuer equipped workqueue.
4585 	 *
4586 	 * For single threaded workqueues the deadlock happens when the work
4587 	 * is after the work issuing the flush_work(). For rescuer equipped
4588 	 * workqueues the deadlock happens when the rescuer stalls, blocking
4589 	 * forward progress.
4590 	 */
4591 	if (!from_cancel && (wq->saved_max_active == 1 || wq->rescuer))
4592 		touch_wq_lockdep_map(wq);
4593 
4594 	rcu_read_unlock();
4595 	return true;
4596 already_gone:
4597 	raw_spin_unlock_irq(&pool->lock);
4598 	rcu_read_unlock();
4599 	return false;
4600 }
4601 
4602 static bool __flush_work(struct work_struct *work, bool from_cancel)
4603 {
4604 	struct wq_barrier barr;
4605 
4606 	if (WARN_ON(!wq_online))
4607 		return false;
4608 
4609 	if (WARN_ON(!work->func))
4610 		return false;
4611 
4612 	if (!start_flush_work(work, &barr, from_cancel))
4613 		return false;
4614 
4615 	/*
4616 	 * start_flush_work() returned %true. If @from_cancel is set, we know
4617 	 * that @work must have been executing during start_flush_work() and
4618 	 * can't currently be queued. Its data must contain OFFQ bits. If @work
4619 	 * was queued on a BH workqueue, we also know that it was running in the
4620 	 * BH context and thus can be busy-waited.
4621 	 */
4622 	if (from_cancel) {
4623 		unsigned long data = *work_data_bits(work);
4624 
4625 		if (!WARN_ON_ONCE(data & WORK_STRUCT_PWQ) &&
4626 		    (data & WORK_OFFQ_BH)) {
4627 			/*
4628 			 * On RT, prevent a live lock when %current preempted
4629 			 * soft interrupt processing by blocking on lock which
4630 			 * is owned by the thread invoking the callback.
4631 			 */
4632 			while (!try_wait_for_completion(&barr.done)) {
4633 				if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
4634 					struct worker_pool *pool;
4635 
4636 					guard(rcu)();
4637 					pool = get_work_pool(work);
4638 					if (pool)
4639 						workqueue_callback_cancel_wait_running(pool);
4640 				} else {
4641 					cpu_relax();
4642 				}
4643 			}
4644 			goto out_destroy;
4645 		}
4646 	}
4647 
4648 	wait_for_completion(&barr.done);
4649 
4650 out_destroy:
4651 	destroy_work_on_stack(&barr.work);
4652 	return true;
4653 }
4654 
4655 /**
4656  * flush_work - wait for a work to finish executing the last queueing instance
4657  * @work: the work to flush
4658  *
4659  * Wait until @work has finished execution.  @work is guaranteed to be idle
4660  * on return if it hasn't been requeued since flush started.
4661  *
4662  * Return:
4663  * %true if flush_work() waited for the work to finish execution,
4664  * %false if it was already idle.
4665  */
4666 bool flush_work(struct work_struct *work)
4667 {
4668 	might_sleep();
4669 	return __flush_work(work, false);
4670 }
4671 EXPORT_SYMBOL_GPL(flush_work);
4672 
4673 /**
4674  * flush_delayed_work - wait for a dwork to finish executing the last queueing
4675  * @dwork: the delayed work to flush
4676  *
4677  * Delayed timer is cancelled and the pending work is queued for
4678  * immediate execution.  Like flush_work(), this function only
4679  * considers the last queueing instance of @dwork.
4680  *
4681  * Return:
4682  * %true if flush_work() waited for the work to finish execution,
4683  * %false if it was already idle.
4684  */
4685 bool flush_delayed_work(struct delayed_work *dwork)
4686 {
4687 	local_irq_disable();
4688 	if (timer_delete_sync(&dwork->timer))
4689 		__queue_work(dwork->cpu, dwork->wq, &dwork->work);
4690 	local_irq_enable();
4691 	return flush_work(&dwork->work);
4692 }
4693 EXPORT_SYMBOL(flush_delayed_work);
4694 
4695 /**
4696  * flush_rcu_work - wait for a rwork to finish executing the last queueing
4697  * @rwork: the rcu work to flush
4698  *
4699  * Return:
4700  * %true if flush_rcu_work() waited for the work to finish execution,
4701  * %false if it was already idle.
4702  */
4703 bool flush_rcu_work(struct rcu_work *rwork)
4704 {
4705 	if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
4706 		rcu_barrier();
4707 		flush_work(&rwork->work);
4708 		return true;
4709 	} else {
4710 		return flush_work(&rwork->work);
4711 	}
4712 }
4713 EXPORT_SYMBOL(flush_rcu_work);
4714 
4715 static void work_offqd_disable(struct work_offq_data *offqd)
4716 {
4717 	const unsigned long max = (1lu << WORK_OFFQ_DISABLE_BITS) - 1;
4718 
4719 	if (likely(offqd->disable < max))
4720 		offqd->disable++;
4721 	else
4722 		WARN_ONCE(true, "workqueue: work disable count overflowed\n");
4723 }
4724 
4725 static void work_offqd_enable(struct work_offq_data *offqd)
4726 {
4727 	if (likely(offqd->disable > 0))
4728 		offqd->disable--;
4729 	else
4730 		WARN_ONCE(true, "workqueue: work disable count underflowed\n");
4731 }
4732 
4733 static bool __cancel_work(struct work_struct *work, u32 cflags)
4734 {
4735 	struct work_offq_data offqd;
4736 	unsigned long irq_flags;
4737 	int ret;
4738 
4739 	ret = work_grab_pending(work, cflags, &irq_flags);
4740 
4741 	work_offqd_unpack(&offqd, *work_data_bits(work));
4742 
4743 	if (cflags & WORK_CANCEL_DISABLE)
4744 		work_offqd_disable(&offqd);
4745 
4746 	set_work_pool_and_clear_pending(work, offqd.pool_id,
4747 					work_offqd_pack_flags(&offqd));
4748 	local_irq_restore(irq_flags);
4749 	return ret;
4750 }
4751 
4752 static bool __cancel_work_sync(struct work_struct *work, u32 cflags)
4753 {
4754 	bool ret;
4755 
4756 	ret = __cancel_work(work, cflags | WORK_CANCEL_DISABLE);
4757 
4758 	if (*work_data_bits(work) & WORK_OFFQ_BH)
4759 		WARN_ON_ONCE(in_hardirq());
4760 	else
4761 		might_sleep();
4762 
4763 	/*
4764 	 * Skip __flush_work() during early boot when we know that @work isn't
4765 	 * executing. This allows canceling during early boot.
4766 	 */
4767 	if (wq_online)
4768 		__flush_work(work, true);
4769 
4770 	if (!(cflags & WORK_CANCEL_DISABLE))
4771 		enable_work(work);
4772 
4773 	return ret;
4774 }
4775 
4776 /*
4777  * See cancel_delayed_work()
4778  */
4779 bool cancel_work(struct work_struct *work)
4780 {
4781 	return __cancel_work(work, 0);
4782 }
4783 EXPORT_SYMBOL(cancel_work);
4784 
4785 /**
4786  * cancel_work_sync - cancel a work and wait for it to finish
4787  * @work: the work to cancel
4788  *
4789  * Cancel @work and wait for its execution to finish. This function can be used
4790  * even if the work re-queues itself or migrates to another workqueue. On return
4791  * from this function, @work is guaranteed to be not pending or executing on any
4792  * CPU as long as there aren't racing enqueues.
4793  *
4794  * cancel_work_sync(&delayed_work->work) must not be used for delayed_work's.
4795  * Use cancel_delayed_work_sync() instead.
4796  *
4797  * Must be called from a sleepable context if @work was last queued on a non-BH
4798  * workqueue. Can also be called from non-hardirq atomic contexts including BH
4799  * if @work was last queued on a BH workqueue.
4800  *
4801  * Returns %true if @work was pending, %false otherwise.
4802  */
4803 bool cancel_work_sync(struct work_struct *work)
4804 {
4805 	return __cancel_work_sync(work, 0);
4806 }
4807 EXPORT_SYMBOL_GPL(cancel_work_sync);
4808 
4809 /**
4810  * cancel_delayed_work - cancel a delayed work
4811  * @dwork: delayed_work to cancel
4812  *
4813  * Kill off a pending delayed_work.
4814  *
4815  * Return: %true if @dwork was pending and canceled; %false if it wasn't
4816  * pending.
4817  *
4818  * Note:
4819  * The work callback function may still be running on return, unless
4820  * it returns %true and the work doesn't re-arm itself.  Explicitly flush or
4821  * use cancel_delayed_work_sync() to wait on it.
4822  *
4823  * This function is safe to call from any context including IRQ handler.
4824  */
4825 bool cancel_delayed_work(struct delayed_work *dwork)
4826 {
4827 	return __cancel_work(&dwork->work, WORK_CANCEL_DELAYED);
4828 }
4829 EXPORT_SYMBOL(cancel_delayed_work);
4830 
4831 /**
4832  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
4833  * @dwork: the delayed work cancel
4834  *
4835  * This is cancel_work_sync() for delayed works.
4836  *
4837  * Return:
4838  * %true if @dwork was pending, %false otherwise.
4839  */
4840 bool cancel_delayed_work_sync(struct delayed_work *dwork)
4841 {
4842 	return __cancel_work_sync(&dwork->work, WORK_CANCEL_DELAYED);
4843 }
4844 EXPORT_SYMBOL(cancel_delayed_work_sync);
4845 
4846 /**
4847  * disable_work - Disable and cancel a work item
4848  * @work: work item to disable
4849  *
4850  * Disable @work by incrementing its disable count and cancel it if currently
4851  * pending. As long as the disable count is non-zero, any attempt to queue @work
4852  * will fail and return %false. The maximum supported disable depth is 2 to the
4853  * power of %WORK_OFFQ_DISABLE_BITS, currently 65536.
4854  *
4855  * Can be called from any context. Returns %true if @work was pending, %false
4856  * otherwise.
4857  */
4858 bool disable_work(struct work_struct *work)
4859 {
4860 	return __cancel_work(work, WORK_CANCEL_DISABLE);
4861 }
4862 EXPORT_SYMBOL_GPL(disable_work);
4863 
4864 /**
4865  * disable_work_sync - Disable, cancel and drain a work item
4866  * @work: work item to disable
4867  *
4868  * Similar to disable_work() but also wait for @work to finish if currently
4869  * executing.
4870  *
4871  * Must be called from a sleepable context if @work was last queued on a non-BH
4872  * workqueue. Can also be called from non-hardirq atomic contexts including BH
4873  * if @work was last queued on a BH workqueue.
4874  *
4875  * Returns %true if @work was pending, %false otherwise.
4876  */
4877 bool disable_work_sync(struct work_struct *work)
4878 {
4879 	return __cancel_work_sync(work, WORK_CANCEL_DISABLE);
4880 }
4881 EXPORT_SYMBOL_GPL(disable_work_sync);
4882 
4883 /**
4884  * enable_work - Enable a work item
4885  * @work: work item to enable
4886  *
4887  * Undo disable_work[_sync]() by decrementing @work's disable count. @work can
4888  * only be queued if its disable count is 0.
4889  *
4890  * Can be called from any context. Returns %true if the disable count reached 0.
4891  * Otherwise, %false.
4892  */
4893 bool enable_work(struct work_struct *work)
4894 {
4895 	struct work_offq_data offqd;
4896 	unsigned long irq_flags;
4897 
4898 	work_grab_pending(work, 0, &irq_flags);
4899 
4900 	work_offqd_unpack(&offqd, *work_data_bits(work));
4901 	work_offqd_enable(&offqd);
4902 	set_work_pool_and_clear_pending(work, offqd.pool_id,
4903 					work_offqd_pack_flags(&offqd));
4904 	local_irq_restore(irq_flags);
4905 
4906 	return !offqd.disable;
4907 }
4908 EXPORT_SYMBOL_GPL(enable_work);
4909 
4910 /**
4911  * disable_delayed_work - Disable and cancel a delayed work item
4912  * @dwork: delayed work item to disable
4913  *
4914  * disable_work() for delayed work items.
4915  */
4916 bool disable_delayed_work(struct delayed_work *dwork)
4917 {
4918 	return __cancel_work(&dwork->work,
4919 			     WORK_CANCEL_DELAYED | WORK_CANCEL_DISABLE);
4920 }
4921 EXPORT_SYMBOL_GPL(disable_delayed_work);
4922 
4923 /**
4924  * disable_delayed_work_sync - Disable, cancel and drain a delayed work item
4925  * @dwork: delayed work item to disable
4926  *
4927  * disable_work_sync() for delayed work items.
4928  */
4929 bool disable_delayed_work_sync(struct delayed_work *dwork)
4930 {
4931 	return __cancel_work_sync(&dwork->work,
4932 				  WORK_CANCEL_DELAYED | WORK_CANCEL_DISABLE);
4933 }
4934 EXPORT_SYMBOL_GPL(disable_delayed_work_sync);
4935 
4936 /**
4937  * enable_delayed_work - Enable a delayed work item
4938  * @dwork: delayed work item to enable
4939  *
4940  * enable_work() for delayed work items.
4941  */
4942 bool enable_delayed_work(struct delayed_work *dwork)
4943 {
4944 	return enable_work(&dwork->work);
4945 }
4946 EXPORT_SYMBOL_GPL(enable_delayed_work);
4947 
4948 /**
4949  * schedule_on_each_cpu - execute a function synchronously on each online CPU
4950  * @func: the function to call
4951  *
4952  * schedule_on_each_cpu() executes @func on each online CPU using the
4953  * system workqueue and blocks until all CPUs have completed.
4954  * schedule_on_each_cpu() is very slow.
4955  *
4956  * Return:
4957  * 0 on success, -errno on failure.
4958  */
4959 int schedule_on_each_cpu(work_func_t func)
4960 {
4961 	int cpu;
4962 	struct work_struct __percpu *works;
4963 
4964 	works = alloc_percpu(struct work_struct);
4965 	if (!works)
4966 		return -ENOMEM;
4967 
4968 	cpus_read_lock();
4969 
4970 	for_each_online_cpu(cpu) {
4971 		struct work_struct *work = per_cpu_ptr(works, cpu);
4972 
4973 		INIT_WORK(work, func);
4974 		schedule_work_on(cpu, work);
4975 	}
4976 
4977 	for_each_online_cpu(cpu)
4978 		flush_work(per_cpu_ptr(works, cpu));
4979 
4980 	cpus_read_unlock();
4981 	free_percpu(works);
4982 	return 0;
4983 }
4984 
4985 /**
4986  * execute_in_process_context - reliably execute the routine with user context
4987  * @fn:		the function to execute
4988  * @ew:		guaranteed storage for the execute work structure (must
4989  *		be available when the work executes)
4990  *
4991  * Executes the function immediately if process context is available,
4992  * otherwise schedules the function for delayed execution.
4993  *
4994  * Return:	0 - function was executed
4995  *		1 - function was scheduled for execution
4996  */
4997 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
4998 {
4999 	if (!in_interrupt()) {
5000 		fn(&ew->work);
5001 		return 0;
5002 	}
5003 
5004 	INIT_WORK(&ew->work, fn);
5005 	schedule_work(&ew->work);
5006 
5007 	return 1;
5008 }
5009 EXPORT_SYMBOL_GPL(execute_in_process_context);
5010 
5011 /**
5012  * free_workqueue_attrs - free a workqueue_attrs
5013  * @attrs: workqueue_attrs to free
5014  *
5015  * Undo alloc_workqueue_attrs().
5016  */
5017 void free_workqueue_attrs(struct workqueue_attrs *attrs)
5018 {
5019 	if (attrs) {
5020 		free_cpumask_var(attrs->cpumask);
5021 		free_cpumask_var(attrs->__pod_cpumask);
5022 		kfree(attrs);
5023 	}
5024 }
5025 
5026 /**
5027  * alloc_workqueue_attrs - allocate a workqueue_attrs
5028  *
5029  * Allocate a new workqueue_attrs, initialize with default settings and
5030  * return it.
5031  *
5032  * Return: The allocated new workqueue_attr on success. %NULL on failure.
5033  */
5034 struct workqueue_attrs *alloc_workqueue_attrs_noprof(void)
5035 {
5036 	struct workqueue_attrs *attrs;
5037 
5038 	attrs = kzalloc_obj(*attrs);
5039 	if (!attrs)
5040 		goto fail;
5041 	if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
5042 		goto fail;
5043 	if (!alloc_cpumask_var(&attrs->__pod_cpumask, GFP_KERNEL))
5044 		goto fail;
5045 
5046 	cpumask_copy(attrs->cpumask, cpu_possible_mask);
5047 	attrs->affn_scope = WQ_AFFN_DFL;
5048 	return attrs;
5049 fail:
5050 	free_workqueue_attrs(attrs);
5051 	return NULL;
5052 }
5053 
5054 static void copy_workqueue_attrs(struct workqueue_attrs *to,
5055 				 const struct workqueue_attrs *from)
5056 {
5057 	to->nice = from->nice;
5058 	cpumask_copy(to->cpumask, from->cpumask);
5059 	cpumask_copy(to->__pod_cpumask, from->__pod_cpumask);
5060 	to->affn_strict = from->affn_strict;
5061 
5062 	/*
5063 	 * Unlike hash and equality test, copying shouldn't ignore wq-only
5064 	 * fields as copying is used for both pool and wq attrs. Instead,
5065 	 * get_unbound_pool() explicitly clears the fields.
5066 	 */
5067 	to->affn_scope = from->affn_scope;
5068 	to->ordered = from->ordered;
5069 }
5070 
5071 /*
5072  * Some attrs fields are workqueue-only. Clear them for worker_pool's. See the
5073  * comments in 'struct workqueue_attrs' definition.
5074  */
5075 static void wqattrs_clear_for_pool(struct workqueue_attrs *attrs)
5076 {
5077 	attrs->affn_scope = WQ_AFFN_NR_TYPES;
5078 	attrs->ordered = false;
5079 	if (attrs->affn_strict)
5080 		cpumask_copy(attrs->cpumask, cpu_possible_mask);
5081 }
5082 
5083 /* hash value of the content of @attr */
5084 static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
5085 {
5086 	u32 hash = 0;
5087 
5088 	hash = jhash_1word(attrs->nice, hash);
5089 	hash = jhash_1word(attrs->affn_strict, hash);
5090 	hash = jhash(cpumask_bits(attrs->__pod_cpumask),
5091 		     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
5092 	if (!attrs->affn_strict)
5093 		hash = jhash(cpumask_bits(attrs->cpumask),
5094 			     BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
5095 	return hash;
5096 }
5097 
5098 /* content equality test */
5099 static bool wqattrs_equal(const struct workqueue_attrs *a,
5100 			  const struct workqueue_attrs *b)
5101 {
5102 	if (a->nice != b->nice)
5103 		return false;
5104 	if (a->affn_strict != b->affn_strict)
5105 		return false;
5106 	if (!cpumask_equal(a->__pod_cpumask, b->__pod_cpumask))
5107 		return false;
5108 	if (!a->affn_strict && !cpumask_equal(a->cpumask, b->cpumask))
5109 		return false;
5110 	return true;
5111 }
5112 
5113 /* Update @attrs with actually available CPUs */
5114 static void wqattrs_actualize_cpumask(struct workqueue_attrs *attrs,
5115 				      const cpumask_t *unbound_cpumask)
5116 {
5117 	/*
5118 	 * Calculate the effective CPU mask of @attrs given @unbound_cpumask. If
5119 	 * @attrs->cpumask doesn't overlap with @unbound_cpumask, we fallback to
5120 	 * @unbound_cpumask.
5121 	 */
5122 	cpumask_and(attrs->cpumask, attrs->cpumask, unbound_cpumask);
5123 	if (unlikely(cpumask_empty(attrs->cpumask)))
5124 		cpumask_copy(attrs->cpumask, unbound_cpumask);
5125 }
5126 
5127 /* find wq_pod_type to use for @attrs */
5128 static const struct wq_pod_type *
5129 wqattrs_pod_type(const struct workqueue_attrs *attrs)
5130 {
5131 	enum wq_affn_scope scope;
5132 	struct wq_pod_type *pt;
5133 
5134 	/* to synchronize access to wq_affn_dfl */
5135 	lockdep_assert_held(&wq_pool_mutex);
5136 
5137 	if (attrs->affn_scope == WQ_AFFN_DFL)
5138 		scope = wq_affn_dfl;
5139 	else
5140 		scope = attrs->affn_scope;
5141 
5142 	pt = &wq_pod_types[scope];
5143 
5144 	if (!WARN_ON_ONCE(attrs->affn_scope == WQ_AFFN_NR_TYPES) &&
5145 	    likely(pt->nr_pods))
5146 		return pt;
5147 
5148 	/*
5149 	 * Before workqueue_init_topology(), only SYSTEM is available which is
5150 	 * initialized in workqueue_init_early().
5151 	 */
5152 	pt = &wq_pod_types[WQ_AFFN_SYSTEM];
5153 	BUG_ON(!pt->nr_pods);
5154 	return pt;
5155 }
5156 
5157 /**
5158  * init_worker_pool - initialize a newly zalloc'd worker_pool
5159  * @pool: worker_pool to initialize
5160  *
5161  * Initialize a newly zalloc'd @pool.  It also allocates @pool->attrs.
5162  *
5163  * Return: 0 on success, -errno on failure.  Even on failure, all fields
5164  * inside @pool proper are initialized and put_unbound_pool() can be called
5165  * on @pool safely to release it.
5166  */
5167 static int init_worker_pool(struct worker_pool *pool)
5168 {
5169 	raw_spin_lock_init(&pool->lock);
5170 	pool->id = -1;
5171 	pool->cpu = -1;
5172 	pool->node = NUMA_NO_NODE;
5173 	pool->flags |= POOL_DISASSOCIATED;
5174 	pool->last_progress_ts = jiffies;
5175 	INIT_LIST_HEAD(&pool->worklist);
5176 	INIT_LIST_HEAD(&pool->idle_list);
5177 	hash_init(pool->busy_hash);
5178 
5179 	timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
5180 	INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
5181 
5182 	timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
5183 
5184 	INIT_LIST_HEAD(&pool->workers);
5185 
5186 	ida_init(&pool->worker_ida);
5187 	INIT_HLIST_NODE(&pool->hash_node);
5188 	pool->refcnt = 1;
5189 #ifdef CONFIG_PREEMPT_RT
5190 	spin_lock_init(&pool->cb_lock);
5191 #endif
5192 
5193 	/* shouldn't fail above this point */
5194 	pool->attrs = alloc_workqueue_attrs();
5195 	if (!pool->attrs)
5196 		return -ENOMEM;
5197 
5198 	wqattrs_clear_for_pool(pool->attrs);
5199 
5200 	return 0;
5201 }
5202 
5203 #ifdef CONFIG_LOCKDEP
5204 static void wq_init_lockdep(struct workqueue_struct *wq)
5205 {
5206 	char *lock_name;
5207 
5208 	lockdep_register_key(&wq->key);
5209 	lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
5210 	if (!lock_name)
5211 		lock_name = wq->name;
5212 
5213 	wq->lock_name = lock_name;
5214 	wq->lockdep_map = &wq->__lockdep_map;
5215 	lockdep_init_map(wq->lockdep_map, lock_name, &wq->key, 0);
5216 }
5217 
5218 static void wq_unregister_lockdep(struct workqueue_struct *wq)
5219 {
5220 	if (wq->lockdep_map != &wq->__lockdep_map)
5221 		return;
5222 
5223 	lockdep_unregister_key(&wq->key);
5224 }
5225 
5226 static void wq_free_lockdep(struct workqueue_struct *wq)
5227 {
5228 	if (wq->lockdep_map != &wq->__lockdep_map)
5229 		return;
5230 
5231 	if (wq->lock_name != wq->name)
5232 		kfree(wq->lock_name);
5233 }
5234 #else
5235 static void wq_init_lockdep(struct workqueue_struct *wq)
5236 {
5237 }
5238 
5239 static void wq_unregister_lockdep(struct workqueue_struct *wq)
5240 {
5241 }
5242 
5243 static void wq_free_lockdep(struct workqueue_struct *wq)
5244 {
5245 }
5246 #endif
5247 
5248 static void free_node_nr_active(struct wq_node_nr_active **nna_ar)
5249 {
5250 	int node;
5251 
5252 	for_each_node_with_fallback(node) {
5253 		kfree(nna_ar[node]);
5254 		nna_ar[node] = NULL;
5255 	}
5256 }
5257 
5258 static void init_node_nr_active(struct wq_node_nr_active *nna)
5259 {
5260 	nna->max = WQ_DFL_MIN_ACTIVE;
5261 	atomic_set(&nna->nr, 0);
5262 	raw_spin_lock_init(&nna->lock);
5263 	INIT_LIST_HEAD(&nna->pending_pwqs);
5264 }
5265 
5266 /*
5267  * Each node's nr_active counter will be accessed mostly from its own node and
5268  * should be allocated in the node.
5269  */
5270 static int alloc_node_nr_active(struct wq_node_nr_active **nna_ar)
5271 {
5272 	struct wq_node_nr_active *nna;
5273 	int node;
5274 
5275 	for_each_node_with_fallback(node) {
5276 		nna = kzalloc_node(sizeof(*nna), GFP_KERNEL,
5277 				   node < nr_node_ids ? node : NUMA_NO_NODE);
5278 		if (!nna)
5279 			goto err_free;
5280 		init_node_nr_active(nna);
5281 		nna_ar[node] = nna;
5282 	}
5283 
5284 	return 0;
5285 
5286 err_free:
5287 	free_node_nr_active(nna_ar);
5288 	return -ENOMEM;
5289 }
5290 
5291 static void free_flush_pnodes(struct workqueue_struct *wq)
5292 {
5293 	int node;
5294 
5295 	if (!wq->flush_pnodes)
5296 		return;
5297 
5298 	for_each_node_with_fallback(node)
5299 		kfree(wq->flush_pnodes[node]);
5300 	kfree(wq->flush_pnodes);
5301 	wq->flush_pnodes = NULL;
5302 }
5303 
5304 static int alloc_flush_pnodes(struct workqueue_struct *wq)
5305 {
5306 	struct wq_flush_pnode *fpn;
5307 	int node;
5308 
5309 	wq->flush_pnodes = kzalloc_objs(*wq->flush_pnodes, nr_node_ids + 1);
5310 	if (!wq->flush_pnodes)
5311 		return -ENOMEM;
5312 
5313 	for_each_node_with_fallback(node) {
5314 		fpn = kzalloc_node(sizeof(*fpn), GFP_KERNEL,
5315 				   node < nr_node_ids ? node : NUMA_NO_NODE);
5316 		if (!fpn)
5317 			goto err_free;
5318 
5319 		raw_spin_lock_init(&fpn->lock);
5320 		fpn->work_color = wq->work_color;
5321 		INIT_LIST_HEAD(&fpn->pwqs);
5322 		wq->flush_pnodes[node] = fpn;
5323 	}
5324 
5325 	return 0;
5326 
5327 err_free:
5328 	free_flush_pnodes(wq);
5329 	return -ENOMEM;
5330 }
5331 
5332 static void rcu_free_wq(struct rcu_head *rcu)
5333 {
5334 	struct workqueue_struct *wq =
5335 		container_of(rcu, struct workqueue_struct, rcu);
5336 
5337 	if (wq->flags & WQ_UNBOUND)
5338 		free_node_nr_active(wq->node_nr_active);
5339 
5340 	free_flush_pnodes(wq);
5341 	wq_free_lockdep(wq);
5342 	free_percpu(wq->cpu_pwq);
5343 	free_workqueue_attrs(wq->attrs);
5344 	kfree(wq);
5345 }
5346 
5347 static void rcu_free_pool(struct rcu_head *rcu)
5348 {
5349 	struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
5350 
5351 	ida_destroy(&pool->worker_ida);
5352 	free_workqueue_attrs(pool->attrs);
5353 	kfree(pool);
5354 }
5355 
5356 /**
5357  * put_unbound_pool - put a worker_pool
5358  * @pool: worker_pool to put
5359  *
5360  * Put @pool.  If its refcnt reaches zero, it gets destroyed in RCU
5361  * safe manner.  get_unbound_pool() calls this function on its failure path
5362  * and this function should be able to release pools which went through,
5363  * successfully or not, init_worker_pool().
5364  *
5365  * Should be called with wq_pool_mutex held.
5366  */
5367 static void put_unbound_pool(struct worker_pool *pool)
5368 {
5369 	struct worker *worker;
5370 	LIST_HEAD(cull_list);
5371 
5372 	lockdep_assert_held(&wq_pool_mutex);
5373 
5374 	if (--pool->refcnt)
5375 		return;
5376 
5377 	/* sanity checks */
5378 	if (WARN_ON(is_percpu_pool(pool)) ||
5379 	    WARN_ON(!list_empty(&pool->worklist)))
5380 		return;
5381 
5382 	/* release id and unhash */
5383 	if (pool->id >= 0)
5384 		idr_remove(&worker_pool_idr, pool->id);
5385 	hash_del(&pool->hash_node);
5386 
5387 	/*
5388 	 * Become the manager and destroy all workers.  This prevents
5389 	 * @pool's workers from blocking on attach_mutex.  We're the last
5390 	 * manager and @pool gets freed with the flag set.
5391 	 *
5392 	 * Having a concurrent manager is quite unlikely to happen as we can
5393 	 * only get here with
5394 	 *   pwq->refcnt == pool->refcnt == 0
5395 	 * which implies no work queued to the pool, which implies no worker can
5396 	 * become the manager. However a worker could have taken the role of
5397 	 * manager before the refcnts dropped to 0, since maybe_create_worker()
5398 	 * drops pool->lock
5399 	 */
5400 	while (true) {
5401 		rcuwait_wait_event(&manager_wait,
5402 				   !(pool->flags & POOL_MANAGER_ACTIVE),
5403 				   TASK_UNINTERRUPTIBLE);
5404 
5405 		mutex_lock(&wq_pool_attach_mutex);
5406 		raw_spin_lock_irq(&pool->lock);
5407 		if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
5408 			pool->flags |= POOL_MANAGER_ACTIVE;
5409 			break;
5410 		}
5411 		raw_spin_unlock_irq(&pool->lock);
5412 		mutex_unlock(&wq_pool_attach_mutex);
5413 	}
5414 
5415 	while ((worker = first_idle_worker(pool)))
5416 		set_worker_dying(worker, &cull_list);
5417 	WARN_ON(pool->nr_workers || pool->nr_idle);
5418 	raw_spin_unlock_irq(&pool->lock);
5419 
5420 	detach_dying_workers(&cull_list);
5421 
5422 	mutex_unlock(&wq_pool_attach_mutex);
5423 
5424 	reap_dying_workers(&cull_list);
5425 
5426 	/* shut down the timers */
5427 	timer_delete_sync(&pool->idle_timer);
5428 	cancel_work_sync(&pool->idle_cull_work);
5429 	timer_delete_sync(&pool->mayday_timer);
5430 
5431 	/* RCU protected to allow dereferences from get_work_pool() */
5432 	call_rcu(&pool->rcu, rcu_free_pool);
5433 }
5434 
5435 /**
5436  * get_unbound_pool - get a worker_pool with the specified attributes
5437  * @attrs: the attributes of the worker_pool to get
5438  *
5439  * Obtain a worker_pool which has the same attributes as @attrs, bump the
5440  * reference count and return it.  If there already is a matching
5441  * worker_pool, it will be used; otherwise, this function attempts to
5442  * create a new one.
5443  *
5444  * Should be called with wq_pool_mutex held.
5445  *
5446  * Return: On success, a worker_pool with the same attributes as @attrs.
5447  * On failure, %NULL.
5448  */
5449 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
5450 {
5451 	struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_NUMA];
5452 	u32 hash = wqattrs_hash(attrs);
5453 	struct worker_pool *pool;
5454 	int pod, node = NUMA_NO_NODE;
5455 
5456 	lockdep_assert_held(&wq_pool_mutex);
5457 
5458 	/* do we already have a matching pool? */
5459 	hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
5460 		if (wqattrs_equal(pool->attrs, attrs)) {
5461 			pool->refcnt++;
5462 			return pool;
5463 		}
5464 	}
5465 
5466 	/* If __pod_cpumask is contained inside a NUMA pod, that's our node */
5467 	for (pod = 0; pod < pt->nr_pods; pod++) {
5468 		if (cpumask_subset(attrs->__pod_cpumask, pt->pod_cpus[pod])) {
5469 			node = pt->pod_node[pod];
5470 			break;
5471 		}
5472 	}
5473 
5474 	/* nope, create a new one */
5475 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, node);
5476 	if (!pool || init_worker_pool(pool) < 0)
5477 		goto fail;
5478 
5479 	pool->node = node;
5480 	copy_workqueue_attrs(pool->attrs, attrs);
5481 	wqattrs_clear_for_pool(pool->attrs);
5482 
5483 	if (worker_pool_assign_id(pool) < 0)
5484 		goto fail;
5485 
5486 	/* create and start the initial worker */
5487 	if (wq_online && !create_worker(pool))
5488 		goto fail;
5489 
5490 	/* install */
5491 	hash_add(unbound_pool_hash, &pool->hash_node, hash);
5492 
5493 	return pool;
5494 fail:
5495 	if (pool)
5496 		put_unbound_pool(pool);
5497 	return NULL;
5498 }
5499 
5500 /*
5501  * Scheduled on pwq_release_worker by put_pwq() when an unbound pwq hits zero
5502  * refcnt and needs to be destroyed.
5503  */
5504 static void pwq_release_workfn(struct kthread_work *work)
5505 {
5506 	struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
5507 						  release_work);
5508 	struct workqueue_struct *wq = pwq->wq;
5509 	struct worker_pool *pool = pwq->pool;
5510 	bool is_last = false;
5511 
5512 	/*
5513 	 * When @pwq is not linked, it doesn't hold any reference to the
5514 	 * @wq, and @wq is invalid to access.
5515 	 */
5516 	if (!list_empty(&pwq->pwqs_node)) {
5517 		mutex_lock(&wq->mutex);
5518 		list_del_rcu(&pwq->pwqs_node);
5519 		is_last = list_empty(&wq->pwqs);
5520 
5521 		/*
5522 		 * An idle pwq can linger on its wq_flush_pnode list until the
5523 		 * next flush. wq->mutex excludes flushers, which never drop it
5524 		 * with pwqs on their private lists.
5525 		 */
5526 		if (!list_empty(&pwq->flush_node)) {
5527 			struct wq_flush_pnode *fpn = wq_flush_pnode(wq, pool->node);
5528 
5529 			raw_spin_lock_irq(&fpn->lock);
5530 			list_del_init(&pwq->flush_node);
5531 			raw_spin_unlock_irq(&fpn->lock);
5532 		}
5533 
5534 		/*
5535 		 * For ordered workqueue with a plugged dfl_pwq, restart it now.
5536 		 */
5537 		if (!is_last && (wq->flags & __WQ_ORDERED))
5538 			unplug_oldest_pwq(wq);
5539 
5540 		mutex_unlock(&wq->mutex);
5541 	}
5542 
5543 	if (!list_empty(&pwq->pending_node)) {
5544 		struct wq_node_nr_active *nna =
5545 			wq_node_nr_active(pwq->wq, pwq->pool->node);
5546 
5547 		raw_spin_lock_irq(&nna->lock);
5548 		list_del_init(&pwq->pending_node);
5549 		raw_spin_unlock_irq(&nna->lock);
5550 	}
5551 
5552 	if (!is_percpu_pool(pool)) {
5553 		mutex_lock(&wq_pool_mutex);
5554 		put_unbound_pool(pool);
5555 		mutex_unlock(&wq_pool_mutex);
5556 	}
5557 
5558 	kfree_rcu(pwq, rcu);
5559 
5560 	/*
5561 	 * If we're the last pwq going away, @wq is already dead and no one
5562 	 * is gonna access it anymore.  Schedule RCU free.
5563 	 */
5564 	if (is_last) {
5565 		wq_unregister_lockdep(wq);
5566 		call_rcu(&wq->rcu, rcu_free_wq);
5567 	}
5568 }
5569 
5570 /* initialize newly allocated @pwq which is associated with @wq and @pool */
5571 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
5572 		     struct worker_pool *pool)
5573 {
5574 	BUG_ON((unsigned long)pwq & ~WORK_STRUCT_PWQ_MASK);
5575 
5576 	memset(pwq, 0, sizeof(*pwq));
5577 
5578 	pwq->pool = pool;
5579 	pwq->wq = wq;
5580 	pwq->flush_color = -1;
5581 	pwq->refcnt = 1;
5582 	INIT_LIST_HEAD(&pwq->inactive_works);
5583 	INIT_LIST_HEAD(&pwq->pending_node);
5584 	INIT_LIST_HEAD(&pwq->flush_node);
5585 	INIT_LIST_HEAD(&pwq->pwqs_node);
5586 	INIT_LIST_HEAD(&pwq->mayday_node);
5587 	kthread_init_work(&pwq->release_work, pwq_release_workfn);
5588 
5589 	/*
5590 	 * Set the dummy cursor work with valid function and get_work_pwq().
5591 	 *
5592 	 * The cursor work should only be in the pwq->pool->worklist, and
5593 	 * should not be treated as a processable work item.
5594 	 *
5595 	 * WORK_STRUCT_PENDING and WORK_STRUCT_INACTIVE just make it less
5596 	 * surprise for kernel debugging tools and reviewers.
5597 	 */
5598 	INIT_WORK(&pwq->mayday_cursor, mayday_cursor_func);
5599 	atomic_long_set(&pwq->mayday_cursor.data, (unsigned long)pwq |
5600 			WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | WORK_STRUCT_INACTIVE);
5601 }
5602 
5603 /* sync @pwq with the current state of its associated wq and link it */
5604 static void link_pwq(struct pool_workqueue *pwq)
5605 {
5606 	struct workqueue_struct *wq = pwq->wq;
5607 
5608 	lockdep_assert_held(&wq->mutex);
5609 
5610 	/* may be called multiple times, ignore if already linked */
5611 	if (!list_empty(&pwq->pwqs_node))
5612 		return;
5613 
5614 	/* set the matching work_color */
5615 	pwq->work_color = wq->work_color;
5616 
5617 	/* link in @pwq */
5618 	list_add_tail_rcu(&pwq->pwqs_node, &wq->pwqs);
5619 }
5620 
5621 /* Return the static per-cpu worker_pool that backs @wq on @cpu. */
5622 static struct worker_pool *get_percpu_pool(struct workqueue_struct *wq, int cpu)
5623 {
5624 	struct worker_pool __percpu *pools;
5625 	bool highpri = wq->flags & WQ_HIGHPRI;
5626 
5627 	if (wq->flags & WQ_BH)
5628 		pools = bh_worker_pools;
5629 	else
5630 		pools = cpu_worker_pools;
5631 
5632 	return &per_cpu_ptr(pools, cpu)[highpri];
5633 }
5634 
5635 /*
5636  * Obtain the pool backing @wq on @cpu and create a pwq associating the two.
5637  * A WQ_PERCPU workqueue is backed by the static per-cpu pool of @cpu,
5638  * everything else by a pool matching @attrs. @cpu < 0 is always unbound.
5639  */
5640 static struct pool_workqueue *alloc_pwq(struct workqueue_struct *wq,
5641 					const struct workqueue_attrs *attrs,
5642 					int cpu)
5643 {
5644 	struct worker_pool *pool;
5645 	struct pool_workqueue *pwq;
5646 
5647 	lockdep_assert_held(&wq_pool_mutex);
5648 
5649 	WARN_ON_ONCE((wq->flags & WQ_PERCPU) && cpu < 0);
5650 
5651 	if (cpu >= 0 && (wq->flags & WQ_PERCPU)) {
5652 		pool = get_percpu_pool(wq, cpu);
5653 	} else {
5654 		pool = get_unbound_pool(attrs);
5655 		if (!pool)
5656 			return NULL;
5657 	}
5658 
5659 	pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
5660 	if (!pwq) {
5661 		if (!is_percpu_pool(pool))
5662 			put_unbound_pool(pool);
5663 		return NULL;
5664 	}
5665 
5666 	init_pwq(pwq, wq, pool);
5667 	return pwq;
5668 }
5669 
5670 /* create a pwq backed by an unbound pool matching @attrs */
5671 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
5672 						const struct workqueue_attrs *attrs)
5673 {
5674 	return alloc_pwq(wq, attrs, -1);
5675 }
5676 
5677 /**
5678  * wq_calc_pod_cpumask - calculate a wq_attrs' cpumask for a pod
5679  * @attrs: the wq_attrs of the default pwq of the target workqueue
5680  * @cpu: the target CPU
5681  *
5682  * Calculate the cpumask a workqueue with @attrs should use on @pod.
5683  * The result is stored in @attrs->__pod_cpumask.
5684  *
5685  * If pod affinity is not enabled, @attrs->cpumask is always used. If enabled
5686  * and @pod has online CPUs requested by @attrs, the returned cpumask is the
5687  * intersection of the possible CPUs of @pod and @attrs->cpumask.
5688  *
5689  * The caller is responsible for ensuring that the cpumask of @pod stays stable.
5690  */
5691 static void wq_calc_pod_cpumask(struct workqueue_attrs *attrs, int cpu)
5692 {
5693 	const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
5694 	int pod = pt->cpu_pod[cpu];
5695 
5696 	/* calculate possible CPUs in @pod that @attrs wants */
5697 	cpumask_and(attrs->__pod_cpumask, pt->pod_cpus[pod], attrs->cpumask);
5698 	/* does @pod have any online CPUs @attrs wants? */
5699 	if (!cpumask_intersects(attrs->__pod_cpumask, wq_online_cpumask)) {
5700 		cpumask_copy(attrs->__pod_cpumask, attrs->cpumask);
5701 		return;
5702 	}
5703 }
5704 
5705 /* install @pwq into @wq and return the old pwq, @cpu < 0 for dfl_pwq */
5706 static struct pool_workqueue *install_pwq(struct workqueue_struct *wq,
5707 					  int cpu, struct pool_workqueue *pwq)
5708 {
5709 	struct pool_workqueue __rcu **slot = pwq_slot(wq, cpu);
5710 	struct pool_workqueue *old_pwq;
5711 
5712 	lockdep_assert_held(&wq_pool_mutex);
5713 	lockdep_assert_held(&wq->mutex);
5714 
5715 	/* link_pwq() can handle duplicate calls */
5716 	link_pwq(pwq);
5717 
5718 	old_pwq = rcu_access_pointer(*slot);
5719 	rcu_assign_pointer(*slot, pwq);
5720 	return old_pwq;
5721 }
5722 
5723 /* context to store the prepared attrs & pwqs before applying */
5724 struct apply_wqattrs_ctx {
5725 	struct workqueue_struct	*wq;		/* target workqueue */
5726 	struct workqueue_attrs	*attrs;		/* attrs to apply */
5727 	struct list_head	list;		/* queued for batching commit */
5728 	struct pool_workqueue	*dfl_pwq;
5729 	struct pool_workqueue	*pwq_tbl[];
5730 };
5731 
5732 /* free the resources after success or abort */
5733 static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
5734 {
5735 	if (ctx) {
5736 		int cpu;
5737 
5738 		for_each_possible_cpu(cpu)
5739 			put_pwq_unlocked(ctx->pwq_tbl[cpu]);
5740 		put_pwq_unlocked(ctx->dfl_pwq);
5741 
5742 		free_workqueue_attrs(ctx->attrs);
5743 
5744 		kfree(ctx);
5745 	}
5746 }
5747 
5748 /* allocate the attrs and pwqs for later installation */
5749 static struct apply_wqattrs_ctx *
5750 apply_wqattrs_prepare(struct workqueue_struct *wq,
5751 		      const struct workqueue_attrs *attrs,
5752 		      const cpumask_var_t unbound_cpumask)
5753 {
5754 	struct apply_wqattrs_ctx *ctx;
5755 	struct workqueue_attrs *new_attrs;
5756 	int cpu;
5757 
5758 	lockdep_assert_held(&wq_pool_mutex);
5759 
5760 	if (WARN_ON(attrs->affn_scope < 0 ||
5761 		    attrs->affn_scope >= WQ_AFFN_NR_TYPES))
5762 		return ERR_PTR(-EINVAL);
5763 
5764 	ctx = kzalloc_flex(*ctx, pwq_tbl, nr_cpu_ids);
5765 
5766 	new_attrs = alloc_workqueue_attrs();
5767 	if (!ctx || !new_attrs)
5768 		goto out_free;
5769 
5770 	/*
5771 	 * If something goes wrong during CPU up/down, we'll fall back to
5772 	 * the default pwq covering whole @attrs->cpumask.  Create it even
5773 	 * if we don't use it immediately.  A percpu workqueue has a pwq on
5774 	 * every possible CPU and never falls back, so it has no default.
5775 	 */
5776 	copy_workqueue_attrs(new_attrs, attrs);
5777 	wqattrs_actualize_cpumask(new_attrs, unbound_cpumask);
5778 	cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
5779 	if (!(wq->flags & WQ_PERCPU)) {
5780 		ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
5781 		if (!ctx->dfl_pwq)
5782 			goto out_free;
5783 	}
5784 
5785 	for_each_possible_cpu(cpu) {
5786 		if (new_attrs->ordered) {
5787 			ctx->dfl_pwq->refcnt++;
5788 			ctx->pwq_tbl[cpu] = ctx->dfl_pwq;
5789 		} else {
5790 			wq_calc_pod_cpumask(new_attrs, cpu);
5791 			ctx->pwq_tbl[cpu] = alloc_pwq(wq, new_attrs, cpu);
5792 			if (!ctx->pwq_tbl[cpu])
5793 				goto out_free;
5794 		}
5795 	}
5796 
5797 	/* save the user configured attrs and sanitize it. */
5798 	copy_workqueue_attrs(new_attrs, attrs);
5799 	cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
5800 	cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
5801 	ctx->attrs = new_attrs;
5802 
5803 	/*
5804 	 * For initialized ordered workqueues, there should only be one pwq
5805 	 * (dfl_pwq). Set the plugged flag of ctx->dfl_pwq to suspend execution
5806 	 * of newly queued work items until execution of older work items in
5807 	 * the old pwq's have completed.
5808 	 */
5809 	if ((wq->flags & __WQ_ORDERED) && !list_empty(&wq->pwqs))
5810 		ctx->dfl_pwq->plugged = true;
5811 
5812 	ctx->wq = wq;
5813 	return ctx;
5814 
5815 out_free:
5816 	free_workqueue_attrs(new_attrs);
5817 	apply_wqattrs_cleanup(ctx);
5818 	return ERR_PTR(-ENOMEM);
5819 }
5820 
5821 /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
5822 static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
5823 {
5824 	int cpu;
5825 
5826 	/* all pwqs have been created successfully, let's install'em */
5827 	mutex_lock(&ctx->wq->mutex);
5828 
5829 	copy_workqueue_attrs(ctx->wq->attrs, ctx->attrs);
5830 
5831 	/* save the previous pwqs and install the new ones */
5832 	for_each_possible_cpu(cpu)
5833 		ctx->pwq_tbl[cpu] = install_pwq(ctx->wq, cpu,
5834 						ctx->pwq_tbl[cpu]);
5835 	if (ctx->dfl_pwq)
5836 		ctx->dfl_pwq = install_pwq(ctx->wq, -1, ctx->dfl_pwq);
5837 
5838 	/* update node_nr_active->max, which only unbound workqueues have */
5839 	if (ctx->wq->flags & WQ_UNBOUND)
5840 		wq_update_node_max_active(ctx->wq, -1);
5841 
5842 	mutex_unlock(&ctx->wq->mutex);
5843 }
5844 
5845 static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
5846 					const struct workqueue_attrs *attrs)
5847 {
5848 	struct apply_wqattrs_ctx *ctx;
5849 
5850 	ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
5851 	if (IS_ERR(ctx))
5852 		return PTR_ERR(ctx);
5853 
5854 	/* the ctx has been prepared successfully, let's commit it */
5855 	apply_wqattrs_commit(ctx);
5856 	apply_wqattrs_cleanup(ctx);
5857 
5858 	return 0;
5859 }
5860 
5861 /**
5862  * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
5863  * @wq: the target workqueue
5864  * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
5865  *
5866  * Apply @attrs to an unbound workqueue @wq. Unless disabled, this function maps
5867  * a separate pwq to each CPU pod with possibles CPUs in @attrs->cpumask so that
5868  * work items are affine to the pod it was issued on. Older pwqs are released as
5869  * in-flight work items finish. Note that a work item which repeatedly requeues
5870  * itself back-to-back will stay on its current pwq.
5871  *
5872  * Performs GFP_KERNEL allocations.
5873  *
5874  * Return: 0 on success and -errno on failure.
5875  */
5876 int apply_workqueue_attrs(struct workqueue_struct *wq,
5877 			  const struct workqueue_attrs *attrs)
5878 {
5879 	int ret;
5880 
5881 	/* only unbound workqueues can change attributes */
5882 	if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
5883 		return -EINVAL;
5884 
5885 	mutex_lock(&wq_pool_mutex);
5886 	ret = apply_workqueue_attrs_locked(wq, attrs);
5887 	mutex_unlock(&wq_pool_mutex);
5888 
5889 	return ret;
5890 }
5891 
5892 /**
5893  * unbound_wq_update_pwq - update a pwq slot for CPU hot[un]plug
5894  * @wq: the target workqueue
5895  * @cpu: the CPU to update the pwq slot for
5896  *
5897  * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
5898  * %CPU_DOWN_FAILED.  @cpu is in the same pod of the CPU being hot[un]plugged.
5899  *
5900  *
5901  * If pod affinity can't be adjusted due to memory allocation failure, it falls
5902  * back to @wq->dfl_pwq which may not be optimal but is always correct.
5903  *
5904  * Note that when the last allowed CPU of a pod goes offline for a workqueue
5905  * with a cpumask spanning multiple pods, the workers which were already
5906  * executing the work items for the workqueue will lose their CPU affinity and
5907  * may execute on any CPU. This is similar to how per-cpu workqueues behave on
5908  * CPU_DOWN. If a workqueue user wants strict affinity, it's the user's
5909  * responsibility to flush the work item from CPU_DOWN_PREPARE.
5910  */
5911 static void unbound_wq_update_pwq(struct workqueue_struct *wq, int cpu)
5912 {
5913 	struct pool_workqueue *old_pwq = NULL, *pwq;
5914 	struct workqueue_attrs *target_attrs;
5915 
5916 	lockdep_assert_held(&wq_pool_mutex);
5917 
5918 	if (!(wq->flags & WQ_UNBOUND) || wq->attrs->ordered)
5919 		return;
5920 
5921 	/*
5922 	 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
5923 	 * Let's use a preallocated one.  The following buf is protected by
5924 	 * CPU hotplug exclusion.
5925 	 */
5926 	target_attrs = unbound_wq_update_pwq_attrs_buf;
5927 
5928 	copy_workqueue_attrs(target_attrs, wq->attrs);
5929 	wqattrs_actualize_cpumask(target_attrs, wq_unbound_cpumask);
5930 
5931 	/* nothing to do if the target cpumask matches the current pwq */
5932 	wq_calc_pod_cpumask(target_attrs, cpu);
5933 	if (wqattrs_equal(target_attrs, installed_pwq(wq, cpu)->pool->attrs))
5934 		return;
5935 
5936 	/* create a new pwq */
5937 	pwq = alloc_unbound_pwq(wq, target_attrs);
5938 	if (!pwq) {
5939 		pr_warn("workqueue: allocation failed while updating CPU pod affinity of \"%s\"\n",
5940 			wq->name);
5941 		goto use_dfl_pwq;
5942 	}
5943 
5944 	/* Install the new pwq. */
5945 	mutex_lock(&wq->mutex);
5946 	old_pwq = install_pwq(wq, cpu, pwq);
5947 	goto out_unlock;
5948 
5949 use_dfl_pwq:
5950 	mutex_lock(&wq->mutex);
5951 	pwq = installed_pwq(wq, -1);
5952 	raw_spin_lock_irq(&pwq->pool->lock);
5953 	get_pwq(pwq);
5954 	raw_spin_unlock_irq(&pwq->pool->lock);
5955 	old_pwq = install_pwq(wq, cpu, pwq);
5956 out_unlock:
5957 	mutex_unlock(&wq->mutex);
5958 	put_pwq_unlocked(old_pwq);
5959 }
5960 
5961 /* the attrs @wq asked for, as spelled by its flags */
5962 static struct workqueue_attrs *alloc_wq_std_attrs(struct workqueue_struct *wq)
5963 {
5964 	struct workqueue_attrs *attrs;
5965 
5966 	attrs = alloc_workqueue_attrs();
5967 	if (!attrs)
5968 		return NULL;
5969 
5970 	if (wq->flags & WQ_HIGHPRI)
5971 		attrs->nice = HIGHPRI_NICE_LEVEL;
5972 
5973 	if (wq->flags & __WQ_ORDERED)
5974 		attrs->ordered = true;
5975 
5976 	return attrs;
5977 }
5978 
5979 static int alloc_and_link_pwqs(struct workqueue_struct *wq)
5980 {
5981 	struct workqueue_attrs *attrs;
5982 	int ret;
5983 
5984 	lockdep_assert_held(&wq_pool_mutex);
5985 
5986 	wq->cpu_pwq = alloc_percpu(struct pool_workqueue __rcu *);
5987 	if (!wq->cpu_pwq)
5988 		goto enomem;
5989 
5990 	attrs = alloc_wq_std_attrs(wq);
5991 	if (!attrs)
5992 		goto enomem;
5993 
5994 	ret = apply_workqueue_attrs_locked(wq, attrs);
5995 	free_workqueue_attrs(attrs);
5996 	if (ret)
5997 		goto enomem;
5998 
5999 	if (wq->flags & __WQ_ORDERED) {
6000 		struct pool_workqueue *dfl_pwq = rcu_access_pointer(wq->dfl_pwq);
6001 
6002 		/* there should only be single pwq for ordering guarantee */
6003 		WARN(wq->pwqs.next != &dfl_pwq->pwqs_node ||
6004 		     wq->pwqs.prev != &dfl_pwq->pwqs_node,
6005 		     "ordering guarantee broken for workqueue %s\n", wq->name);
6006 	}
6007 
6008 	return 0;
6009 
6010 enomem:
6011 	free_percpu(wq->cpu_pwq);
6012 	wq->cpu_pwq = NULL;
6013 	return -ENOMEM;
6014 }
6015 
6016 static int wq_clamp_max_active(int max_active, unsigned int flags,
6017 			       const char *name)
6018 {
6019 	if (max_active < 1 || max_active > WQ_MAX_ACTIVE)
6020 		pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
6021 			max_active, name, 1, WQ_MAX_ACTIVE);
6022 
6023 	return clamp_val(max_active, 1, WQ_MAX_ACTIVE);
6024 }
6025 
6026 /*
6027  * Workqueues which may be used during memory reclaim should have a rescuer
6028  * to guarantee forward progress.
6029  */
6030 static int init_rescuer(struct workqueue_struct *wq)
6031 {
6032 	struct worker *rescuer;
6033 	char id_buf[WORKER_ID_LEN];
6034 	int ret;
6035 
6036 	lockdep_assert_held(&wq_pool_mutex);
6037 
6038 	if (!(wq->flags & WQ_MEM_RECLAIM))
6039 		return 0;
6040 
6041 	rescuer = alloc_worker(NUMA_NO_NODE);
6042 	if (!rescuer) {
6043 		pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
6044 		       wq->name);
6045 		return -ENOMEM;
6046 	}
6047 
6048 	rescuer->rescue_wq = wq;
6049 	format_worker_id(id_buf, sizeof(id_buf), rescuer, NULL);
6050 
6051 	rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", id_buf);
6052 	if (IS_ERR(rescuer->task)) {
6053 		ret = PTR_ERR(rescuer->task);
6054 		pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
6055 		       wq->name, ERR_PTR(ret));
6056 		kfree(rescuer);
6057 		return ret;
6058 	}
6059 
6060 	wq->rescuer = rescuer;
6061 
6062 	/* initial cpumask is consistent with the detached rescuer and unbind_worker() */
6063 	if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
6064 		kthread_bind_mask(rescuer->task, wq_unbound_cpumask);
6065 	else
6066 		kthread_bind_mask(rescuer->task, cpu_possible_mask);
6067 
6068 	wake_up_process(rescuer->task);
6069 
6070 	return 0;
6071 }
6072 
6073 /**
6074  * wq_adjust_max_active - update a wq's max_active to the current setting
6075  * @wq: target workqueue
6076  *
6077  * If @wq isn't freezing, set the limit that applies to @wq's backing to the
6078  * saved_max_active and activate inactive work items accordingly. If @wq is
6079  * freezing, clear it to zero.
6080  */
6081 static void wq_adjust_max_active(struct workqueue_struct *wq)
6082 {
6083 	bool activated;
6084 	int new_max, new_min;
6085 
6086 	lockdep_assert_held(&wq->mutex);
6087 
6088 	if ((wq->flags & WQ_FREEZABLE) && workqueue_freezing) {
6089 		new_max = 0;
6090 		new_min = 0;
6091 	} else {
6092 		new_max = wq->saved_max_active;
6093 		new_min = wq->saved_min_active;
6094 	}
6095 
6096 	/*
6097 	 * Update the limit and then kick inactive work items if more active
6098 	 * work items are allowed. This doesn't break work item ordering
6099 	 * because new work items are always queued behind existing inactive
6100 	 * work items if there are any.
6101 	 */
6102 	if (wq->flags & WQ_UNBOUND) {
6103 		if (wq->max_active == new_max && wq->min_active == new_min)
6104 			return;
6105 
6106 		WRITE_ONCE(wq->max_active, new_max);
6107 		WRITE_ONCE(wq->min_active, new_min);
6108 		wq_update_node_max_active(wq, -1);
6109 	} else {
6110 		if (wq->percpu_max_active == new_max)
6111 			return;
6112 
6113 		WRITE_ONCE(wq->percpu_max_active, new_max);
6114 	}
6115 
6116 	if (new_max == 0)
6117 		return;
6118 
6119 	/*
6120 	 * Round-robin through pwq's activating the first inactive work item
6121 	 * until max_active is filled.
6122 	 */
6123 	do {
6124 		struct pool_workqueue *pwq;
6125 
6126 		activated = false;
6127 		for_each_pwq(pwq, wq) {
6128 			unsigned long irq_flags;
6129 
6130 			/* can be called during early boot w/ irq disabled */
6131 			raw_spin_lock_irqsave(&pwq->pool->lock, irq_flags);
6132 			if (pwq_activate_first_inactive(pwq, true)) {
6133 				activated = true;
6134 				kick_pool(pwq->pool);
6135 			}
6136 			raw_spin_unlock_irqrestore(&pwq->pool->lock, irq_flags);
6137 		}
6138 	} while (activated);
6139 }
6140 
6141 __printf(1, 0)
6142 static struct workqueue_struct *__alloc_workqueue(const char *fmt,
6143 						  unsigned int flags,
6144 						  int max_active, va_list args)
6145 {
6146 	struct workqueue_struct *wq;
6147 	size_t wq_size;
6148 	int name_len;
6149 
6150 	if (flags & WQ_BH) {
6151 		if (WARN_ON_ONCE(flags & ~__WQ_BH_ALLOWS))
6152 			return NULL;
6153 		if (WARN_ON_ONCE(max_active))
6154 			return NULL;
6155 	}
6156 
6157 	/* see the comment above the definition of WQ_POWER_EFFICIENT */
6158 	if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
6159 		flags = (flags & ~WQ_PERCPU) | WQ_UNBOUND;
6160 
6161 	/* allocate wq and format name */
6162 	if (flags & WQ_UNBOUND)
6163 		wq_size = struct_size(wq, node_nr_active, nr_node_ids + 1);
6164 	else
6165 		wq_size = sizeof(*wq);
6166 
6167 	wq = kzalloc_noprof(wq_size, GFP_KERNEL);
6168 	if (!wq)
6169 		return NULL;
6170 
6171 	wq->attrs = alloc_workqueue_attrs_noprof();
6172 	if (!wq->attrs)
6173 		goto err_free_wq;
6174 
6175 	name_len = vsnprintf(wq->name, sizeof(wq->name), fmt, args);
6176 
6177 	if (name_len >= WQ_NAME_LEN)
6178 		pr_warn_once("workqueue: name exceeds WQ_NAME_LEN. Truncating to: %s\n",
6179 			     wq->name);
6180 
6181 	/*
6182 	 * One among WQ_PERCPU and WQ_UNBOUND must be set, but not both.
6183 	 * - If neither is set, default to WQ_PERCPU
6184 	 * - If both are set, default to WQ_UNBOUND
6185 	 *
6186 	 * This code can be removed after workqueue are unbound by default
6187 	 */
6188 	if (unlikely(!(flags & (WQ_UNBOUND | WQ_PERCPU)))) {
6189 		WARN_ONCE(1, "workqueue: %s is using neither WQ_PERCPU or WQ_UNBOUND. "
6190 			  "Setting WQ_PERCPU.\n", wq->name);
6191 		flags |= WQ_PERCPU;
6192 	} else if (unlikely((flags & WQ_PERCPU) && (flags & WQ_UNBOUND))) {
6193 		WARN_ONCE(1, "workqueue: %s uses both WQ_PERCPU and WQ_UNBOUND. "
6194 			  "Dropped WQ_PERCPU, keeping WQ_UNBOUND.\n", wq->name);
6195 		flags &= ~WQ_PERCPU;
6196 	}
6197 
6198 	if (flags & WQ_BH) {
6199 		/*
6200 		 * BH workqueues always share a single execution context per CPU
6201 		 * and don't impose any max_active limit.
6202 		 */
6203 		max_active = INT_MAX;
6204 	} else {
6205 		max_active = max_active ?: WQ_DFL_ACTIVE;
6206 		max_active = wq_clamp_max_active(max_active, flags, wq->name);
6207 	}
6208 
6209 	/* init wq */
6210 	wq->flags = flags;
6211 	if (flags & WQ_UNBOUND) {
6212 		wq->max_active = max_active;
6213 		wq->min_active = min(max_active, WQ_DFL_MIN_ACTIVE);
6214 		wq->saved_min_active = wq->min_active;
6215 	} else {
6216 		wq->percpu_max_active = max_active;
6217 	}
6218 	wq->saved_max_active = max_active;
6219 	mutex_init(&wq->mutex);
6220 	atomic_set(&wq->nr_pwqs_to_flush, 0);
6221 	INIT_LIST_HEAD(&wq->pwqs);
6222 	INIT_LIST_HEAD(&wq->flusher_queue);
6223 	INIT_LIST_HEAD(&wq->flusher_overflow);
6224 	INIT_LIST_HEAD(&wq->maydays);
6225 
6226 	INIT_LIST_HEAD(&wq->list);
6227 
6228 	if (alloc_flush_pnodes(wq) < 0)
6229 		goto err_free_wq;
6230 
6231 	if (flags & WQ_UNBOUND) {
6232 		if (alloc_node_nr_active(wq->node_nr_active) < 0)
6233 			goto err_free_wq;
6234 	}
6235 
6236 	/*
6237 	 * wq_pool_mutex protects the workqueues list, allocations of PWQs,
6238 	 * and the global freeze state.
6239 	 */
6240 	mutex_lock(&wq_pool_mutex);
6241 
6242 	if (alloc_and_link_pwqs(wq) < 0)
6243 		goto err_unlock_free_node_nr_active;
6244 
6245 	mutex_lock(&wq->mutex);
6246 	wq_adjust_max_active(wq);
6247 	mutex_unlock(&wq->mutex);
6248 
6249 	list_add_tail_rcu(&wq->list, &workqueues);
6250 
6251 	if (wq_online && init_rescuer(wq) < 0)
6252 		goto err_unlock_destroy;
6253 
6254 	mutex_unlock(&wq_pool_mutex);
6255 
6256 	if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
6257 		goto err_destroy;
6258 
6259 	return wq;
6260 
6261 err_unlock_free_node_nr_active:
6262 	mutex_unlock(&wq_pool_mutex);
6263 	/*
6264 	 * Failed alloc_and_link_pwqs() may leave pending pwq->release_work,
6265 	 * flushing the pwq_release_worker ensures that the pwq_release_workfn()
6266 	 * completes before calling kfree(wq).
6267 	 */
6268 	if (pwq_release_worker)
6269 		kthread_flush_worker(pwq_release_worker);
6270 	if (wq->flags & WQ_UNBOUND)
6271 		free_node_nr_active(wq->node_nr_active);
6272 err_free_wq:
6273 	free_workqueue_attrs(wq->attrs);
6274 	free_flush_pnodes(wq);
6275 	kfree(wq);
6276 	return NULL;
6277 err_unlock_destroy:
6278 	mutex_unlock(&wq_pool_mutex);
6279 err_destroy:
6280 	destroy_workqueue(wq);
6281 	return NULL;
6282 }
6283 
6284 __printf(1, 0)
6285 static struct workqueue_struct *alloc_workqueue_va(const char *fmt,
6286 						   unsigned int flags,
6287 						   int max_active,
6288 						   va_list args)
6289 {
6290 	struct workqueue_struct *wq;
6291 
6292 	wq = __alloc_workqueue(fmt, flags, max_active, args);
6293 	if (wq)
6294 		wq_init_lockdep(wq);
6295 
6296 	return wq;
6297 }
6298 
6299 __printf(1, 4)
6300 struct workqueue_struct *alloc_workqueue_noprof(const char *fmt,
6301 						unsigned int flags,
6302 						int max_active, ...)
6303 {
6304 	struct workqueue_struct *wq;
6305 	va_list args;
6306 
6307 	va_start(args, max_active);
6308 	wq = alloc_workqueue_va(fmt, flags, max_active, args);
6309 	va_end(args);
6310 
6311 	return wq;
6312 }
6313 EXPORT_SYMBOL_GPL(alloc_workqueue_noprof);
6314 
6315 static void devm_workqueue_release(void *res)
6316 {
6317 	destroy_workqueue(res);
6318 }
6319 
6320 __printf(2, 5) struct workqueue_struct *
6321 devm_alloc_workqueue_noprof(struct device *dev, const char *fmt,
6322 			    unsigned int flags, int max_active, ...)
6323 {
6324 	struct workqueue_struct *wq;
6325 	va_list args;
6326 	int ret;
6327 
6328 	va_start(args, max_active);
6329 	wq = alloc_workqueue_va(fmt, flags, max_active, args);
6330 	va_end(args);
6331 	if (!wq)
6332 		return NULL;
6333 
6334 	ret = devm_add_action_or_reset(dev, devm_workqueue_release, wq);
6335 	if (ret)
6336 		return NULL;
6337 
6338 	return wq;
6339 }
6340 EXPORT_SYMBOL_GPL(devm_alloc_workqueue_noprof);
6341 
6342 #ifdef CONFIG_LOCKDEP
6343 __printf(1, 5)
6344 struct workqueue_struct *
6345 alloc_workqueue_lockdep_map(const char *fmt, unsigned int flags,
6346 			    int max_active, struct lockdep_map *lockdep_map, ...)
6347 {
6348 	struct workqueue_struct *wq;
6349 	va_list args;
6350 
6351 	va_start(args, lockdep_map);
6352 	wq = __alloc_workqueue(fmt, flags, max_active, args);
6353 	va_end(args);
6354 	if (!wq)
6355 		return NULL;
6356 
6357 	wq->lockdep_map = lockdep_map;
6358 
6359 	return wq;
6360 }
6361 EXPORT_SYMBOL_GPL(alloc_workqueue_lockdep_map);
6362 #endif
6363 
6364 static bool pwq_busy(struct pool_workqueue *pwq)
6365 {
6366 	if (pwq->total_in_flight)
6367 		return true;
6368 
6369 	if ((pwq != rcu_access_pointer(pwq->wq->dfl_pwq)) && (pwq->refcnt > 1))
6370 		return true;
6371 	if (!pwq_is_empty(pwq))
6372 		return true;
6373 
6374 	return false;
6375 }
6376 
6377 /**
6378  * destroy_workqueue - safely terminate a workqueue
6379  * @wq: target workqueue
6380  *
6381  * Safely destroy a workqueue. All work currently pending will be done first.
6382  *
6383  * This function does NOT guarantee that non-pending work that has been
6384  * submitted with queue_delayed_work() and similar functions will be done
6385  * before destroying the workqueue. The fundamental problem is that, currently,
6386  * the workqueue has no way of accessing non-pending delayed_work. delayed_work
6387  * is only linked on the timer-side. All delayed_work must, therefore, be
6388  * canceled before calling this function.
6389  *
6390  * TODO: It would be better if the problem described above wouldn't exist and
6391  * destroy_workqueue() would cleanly cancel all pending and non-pending
6392  * delayed_work.
6393  */
6394 void destroy_workqueue(struct workqueue_struct *wq)
6395 {
6396 	struct pool_workqueue *pwq;
6397 	int cpu;
6398 
6399 	/*
6400 	 * Remove it from sysfs first so that sanity check failure doesn't
6401 	 * lead to sysfs name conflicts.
6402 	 */
6403 	workqueue_sysfs_unregister(wq);
6404 
6405 	/* mark the workqueue destruction is in progress */
6406 	mutex_lock(&wq->mutex);
6407 	wq->flags |= __WQ_DESTROYING;
6408 	mutex_unlock(&wq->mutex);
6409 
6410 	/* drain it before proceeding with destruction */
6411 	drain_workqueue(wq);
6412 
6413 	/* kill rescuer, if sanity checks fail, leave it w/o rescuer */
6414 	if (wq->rescuer) {
6415 		/* rescuer will empty maydays list before exiting */
6416 		kthread_stop(wq->rescuer->task);
6417 		kfree(wq->rescuer);
6418 		wq->rescuer = NULL;
6419 	}
6420 
6421 	/*
6422 	 * Sanity checks - grab all the locks so that we wait for all
6423 	 * in-flight operations which may do put_pwq().
6424 	 */
6425 	mutex_lock(&wq_pool_mutex);
6426 	mutex_lock(&wq->mutex);
6427 	for_each_pwq(pwq, wq) {
6428 		raw_spin_lock_irq(&pwq->pool->lock);
6429 		if (WARN_ON(pwq_busy(pwq))) {
6430 			pr_warn("%s: %s has the following busy pwq\n",
6431 				__func__, wq->name);
6432 			show_pwq(pwq);
6433 			raw_spin_unlock_irq(&pwq->pool->lock);
6434 			mutex_unlock(&wq->mutex);
6435 			mutex_unlock(&wq_pool_mutex);
6436 			show_one_workqueue(wq);
6437 			return;
6438 		}
6439 		raw_spin_unlock_irq(&pwq->pool->lock);
6440 	}
6441 	mutex_unlock(&wq->mutex);
6442 
6443 	/*
6444 	 * wq list is used to freeze wq, remove from list after
6445 	 * flushing is complete in case freeze races us.
6446 	 */
6447 	list_del_rcu(&wq->list);
6448 	mutex_unlock(&wq_pool_mutex);
6449 
6450 	/*
6451 	 * We're the sole accessor of @wq. Directly access cpu_pwq and dfl_pwq
6452 	 * to put the base refs. @wq will be auto-destroyed from the last
6453 	 * pwq_put. RCU read lock prevents @wq from going away from under us.
6454 	 */
6455 	rcu_read_lock();
6456 
6457 	for_each_possible_cpu(cpu) {
6458 		put_pwq_unlocked(installed_pwq(wq, cpu));
6459 		RCU_INIT_POINTER(*pwq_slot(wq, cpu), NULL);
6460 	}
6461 
6462 	put_pwq_unlocked(installed_pwq(wq, -1));
6463 	RCU_INIT_POINTER(*pwq_slot(wq, -1), NULL);
6464 
6465 	rcu_read_unlock();
6466 }
6467 EXPORT_SYMBOL_GPL(destroy_workqueue);
6468 
6469 /**
6470  * workqueue_set_max_active - adjust max_active of a workqueue
6471  * @wq: target workqueue
6472  * @max_active: new max_active value.
6473  *
6474  * Set max_active of @wq to @max_active. See the alloc_workqueue() function
6475  * comment.
6476  *
6477  * CONTEXT:
6478  * Don't call from IRQ context.
6479  */
6480 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
6481 {
6482 	/* max_active doesn't mean anything for BH workqueues */
6483 	if (WARN_ON(wq->flags & WQ_BH))
6484 		return;
6485 	/* disallow meddling with max_active for ordered workqueues */
6486 	if (WARN_ON(wq->flags & __WQ_ORDERED))
6487 		return;
6488 
6489 	max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
6490 
6491 	mutex_lock(&wq->mutex);
6492 
6493 	wq->saved_max_active = max_active;
6494 	if (wq->flags & WQ_UNBOUND)
6495 		wq->saved_min_active = min(wq->saved_min_active, max_active);
6496 
6497 	wq_adjust_max_active(wq);
6498 
6499 	mutex_unlock(&wq->mutex);
6500 }
6501 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
6502 
6503 /**
6504  * workqueue_set_min_active - adjust min_active of an unbound workqueue
6505  * @wq: target unbound workqueue
6506  * @min_active: new min_active value
6507  *
6508  * Set min_active of an unbound workqueue. Unlike other types of workqueues, an
6509  * unbound workqueue is not guaranteed to be able to process max_active
6510  * interdependent work items. Instead, an unbound workqueue is guaranteed to be
6511  * able to process min_active number of interdependent work items which is
6512  * %WQ_DFL_MIN_ACTIVE by default.
6513  *
6514  * Use this function to adjust the min_active value between 0 and the current
6515  * max_active.
6516  */
6517 void workqueue_set_min_active(struct workqueue_struct *wq, int min_active)
6518 {
6519 	/* min_active is only meaningful for non-ordered unbound workqueues */
6520 	if (WARN_ON((wq->flags & (WQ_BH | WQ_UNBOUND | __WQ_ORDERED)) !=
6521 		    WQ_UNBOUND))
6522 		return;
6523 
6524 	mutex_lock(&wq->mutex);
6525 	wq->saved_min_active = clamp(min_active, 0, wq->saved_max_active);
6526 	wq_adjust_max_active(wq);
6527 	mutex_unlock(&wq->mutex);
6528 }
6529 
6530 /**
6531  * current_work - retrieve %current task's work struct
6532  *
6533  * Determine if %current task is a workqueue worker and what it's working on.
6534  * Useful to find out the context that the %current task is running in.
6535  *
6536  * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
6537  */
6538 struct work_struct *current_work(void)
6539 {
6540 	struct worker *worker = current_wq_worker();
6541 
6542 	return worker ? worker->current_work : NULL;
6543 }
6544 EXPORT_SYMBOL(current_work);
6545 
6546 /**
6547  * current_is_workqueue_rescuer - is %current workqueue rescuer?
6548  *
6549  * Determine whether %current is a workqueue rescuer.  Can be used from
6550  * work functions to determine whether it's being run off the rescuer task.
6551  *
6552  * Return: %true if %current is a workqueue rescuer. %false otherwise.
6553  */
6554 bool current_is_workqueue_rescuer(void)
6555 {
6556 	struct worker *worker = current_wq_worker();
6557 
6558 	return worker && worker->rescue_wq;
6559 }
6560 
6561 /**
6562  * current_is_workqueue_mem_reclaim - is %current a %WQ_MEM_RECLAIM worker?
6563  *
6564  * Determine whether %current is a workqueue worker executing on a workqueue
6565  * created with %WQ_MEM_RECLAIM.  This mirrors the condition that
6566  * check_flush_dependency() warns on: flushing (or otherwise waiting on) a
6567  * !WQ_MEM_RECLAIM workqueue from such a context breaks the forward-progress
6568  * guarantee and can deadlock.  Callers that may recurse into such a flush --
6569  * e.g. NFS LOCALIO submitting into a stacked filesystem that flushes its own
6570  * !WQ_MEM_RECLAIM workqueue -- can use this to decide whether they must defer
6571  * the work to a !WQ_MEM_RECLAIM workqueue rather than run it inline.
6572  *
6573  * Return: %true if %current is a %WQ_MEM_RECLAIM worker.  %false otherwise.
6574  */
6575 bool current_is_workqueue_mem_reclaim(void)
6576 {
6577 	struct worker *worker = current_wq_worker();
6578 
6579 	return worker && worker->current_pwq &&
6580 		((worker->current_pwq->wq->flags &
6581 		  (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM);
6582 }
6583 EXPORT_SYMBOL_GPL(current_is_workqueue_mem_reclaim);
6584 
6585 /**
6586  * workqueue_congested - test whether a workqueue is congested
6587  * @cpu: CPU in question
6588  * @wq: target workqueue
6589  *
6590  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
6591  * no synchronization around this function and the test result is
6592  * unreliable and only useful as advisory hints or for debugging.
6593  *
6594  * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
6595  *
6596  * With the exception of ordered workqueues, all workqueues have per-cpu
6597  * pool_workqueues, each with its own congested state. A workqueue being
6598  * congested on one CPU doesn't mean that the workqueue is contested on any
6599  * other CPUs.
6600  *
6601  * Return:
6602  * %true if congested, %false otherwise.
6603  */
6604 bool workqueue_congested(int cpu, struct workqueue_struct *wq)
6605 {
6606 	struct pool_workqueue *pwq;
6607 	bool ret;
6608 
6609 	preempt_disable();
6610 
6611 	if (cpu == WORK_CPU_UNBOUND)
6612 		cpu = smp_processor_id();
6613 
6614 	pwq = rcu_dereference_sched(*per_cpu_ptr(wq->cpu_pwq, cpu));
6615 	ret = !list_empty(&pwq->inactive_works);
6616 
6617 	preempt_enable();
6618 
6619 	return ret;
6620 }
6621 EXPORT_SYMBOL_GPL(workqueue_congested);
6622 
6623 /**
6624  * work_busy - test whether a work is currently pending or running
6625  * @work: the work to be tested
6626  *
6627  * Test whether @work is currently pending or running.  There is no
6628  * synchronization around this function and the test result is
6629  * unreliable and only useful as advisory hints or for debugging.
6630  *
6631  * Return:
6632  * OR'd bitmask of WORK_BUSY_* bits.
6633  */
6634 unsigned int work_busy(struct work_struct *work)
6635 {
6636 	struct worker_pool *pool;
6637 	unsigned long irq_flags;
6638 	unsigned int ret = 0;
6639 
6640 	if (work_pending(work))
6641 		ret |= WORK_BUSY_PENDING;
6642 
6643 	rcu_read_lock();
6644 	pool = get_work_pool(work);
6645 	if (pool) {
6646 		raw_spin_lock_irqsave(&pool->lock, irq_flags);
6647 		if (find_worker_executing_work(pool, work))
6648 			ret |= WORK_BUSY_RUNNING;
6649 		raw_spin_unlock_irqrestore(&pool->lock, irq_flags);
6650 	}
6651 	rcu_read_unlock();
6652 
6653 	return ret;
6654 }
6655 EXPORT_SYMBOL_GPL(work_busy);
6656 
6657 /**
6658  * set_worker_desc - set description for the current work item
6659  * @fmt: printf-style format string
6660  * @...: arguments for the format string
6661  *
6662  * This function can be called by a running work function to describe what
6663  * the work item is about.  If the worker task gets dumped, this
6664  * information will be printed out together to help debugging.  The
6665  * description can be at most WORKER_DESC_LEN including the trailing '\0'.
6666  */
6667 void set_worker_desc(const char *fmt, ...)
6668 {
6669 	struct worker *worker = current_wq_worker();
6670 	va_list args;
6671 
6672 	if (worker) {
6673 		va_start(args, fmt);
6674 		vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
6675 		va_end(args);
6676 	}
6677 }
6678 EXPORT_SYMBOL_GPL(set_worker_desc);
6679 
6680 /**
6681  * print_worker_info - print out worker information and description
6682  * @log_lvl: the log level to use when printing
6683  * @task: target task
6684  *
6685  * If @task is a worker and currently executing a work item, print out the
6686  * name of the workqueue being serviced and worker description set with
6687  * set_worker_desc() by the currently executing work item.
6688  *
6689  * This function can be safely called on any task as long as the
6690  * task_struct itself is accessible.  While safe, this function isn't
6691  * synchronized and may print out mixups or garbages of limited length.
6692  */
6693 void print_worker_info(const char *log_lvl, struct task_struct *task)
6694 {
6695 	work_func_t fn = NULL;
6696 	char name[WQ_NAME_LEN] = { };
6697 	char desc[WORKER_DESC_LEN] = { };
6698 	struct pool_workqueue *pwq = NULL;
6699 	struct workqueue_struct *wq = NULL;
6700 	struct worker *worker;
6701 
6702 	if (!(task->flags & PF_WQ_WORKER))
6703 		return;
6704 
6705 	/*
6706 	 * This function is called without any synchronization and @task
6707 	 * could be in any state.  Be careful with dereferences.
6708 	 */
6709 	worker = kthread_probe_data(task);
6710 
6711 	/*
6712 	 * Carefully copy the associated workqueue's workfn, name and desc.
6713 	 * Keep the original last '\0' in case the original is garbage.
6714 	 */
6715 	copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
6716 	copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
6717 	copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
6718 	copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
6719 	copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
6720 
6721 	if (fn || name[0] || desc[0]) {
6722 		printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
6723 		if (strcmp(name, desc))
6724 			pr_cont(" (%s)", desc);
6725 		pr_cont("\n");
6726 	}
6727 }
6728 
6729 static void pr_cont_pool_info(struct worker_pool *pool)
6730 {
6731 	pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
6732 	if (pool->node != NUMA_NO_NODE)
6733 		pr_cont(" node=%d", pool->node);
6734 	pr_cont(" flags=0x%x", pool->flags);
6735 	if (pool->flags & POOL_BH)
6736 		pr_cont(" bh%s",
6737 			pool->attrs->nice == HIGHPRI_NICE_LEVEL ? "-hi" : "");
6738 	else
6739 		pr_cont(" nice=%d", pool->attrs->nice);
6740 }
6741 
6742 static void pr_cont_worker_id(struct worker *worker)
6743 {
6744 	struct worker_pool *pool = worker->pool;
6745 
6746 	if (pool->flags & POOL_BH)
6747 		pr_cont("bh%s",
6748 			pool->attrs->nice == HIGHPRI_NICE_LEVEL ? "-hi" : "");
6749 	else
6750 		pr_cont("%d%s", task_pid_nr(worker->task),
6751 			worker->rescue_wq ? "(RESCUER)" : "");
6752 }
6753 
6754 struct pr_cont_work_struct {
6755 	bool comma;
6756 	work_func_t func;
6757 	long ctr;
6758 };
6759 
6760 static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
6761 {
6762 	if (!pcwsp->ctr)
6763 		goto out_record;
6764 	if (func == pcwsp->func) {
6765 		pcwsp->ctr++;
6766 		return;
6767 	}
6768 	if (pcwsp->ctr == 1)
6769 		pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
6770 	else
6771 		pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
6772 	pcwsp->ctr = 0;
6773 out_record:
6774 	if ((long)func == -1L)
6775 		return;
6776 	pcwsp->comma = comma;
6777 	pcwsp->func = func;
6778 	pcwsp->ctr = 1;
6779 }
6780 
6781 static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
6782 {
6783 	if (work->func == wq_barrier_func) {
6784 		struct wq_barrier *barr;
6785 
6786 		barr = container_of(work, struct wq_barrier, work);
6787 
6788 		pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
6789 		pr_cont("%s BAR(%d)", comma ? "," : "",
6790 			task_pid_nr(barr->task));
6791 	} else {
6792 		if (!comma)
6793 			pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
6794 		pr_cont_work_flush(comma, work->func, pcwsp);
6795 	}
6796 }
6797 
6798 static void show_pwq(struct pool_workqueue *pwq)
6799 {
6800 	struct pr_cont_work_struct pcws = { .ctr = 0, };
6801 	struct worker_pool *pool = pwq->pool;
6802 	struct work_struct *work;
6803 	struct worker *worker;
6804 	bool has_in_flight = false, has_pending = false;
6805 	int bkt;
6806 
6807 	pr_info("  pwq %d:", pool->id);
6808 	pr_cont_pool_info(pool);
6809 
6810 	pr_cont(" active=%d refcnt=%d%s\n",
6811 		pwq->nr_active, pwq->refcnt,
6812 		!list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
6813 
6814 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
6815 		if (worker->current_pwq == pwq) {
6816 			has_in_flight = true;
6817 			break;
6818 		}
6819 	}
6820 	if (has_in_flight) {
6821 		bool comma = false;
6822 
6823 		pr_info("    in-flight:");
6824 		hash_for_each(pool->busy_hash, bkt, worker, hentry) {
6825 			if (worker->current_pwq != pwq)
6826 				continue;
6827 
6828 			pr_cont(" %s", comma ? "," : "");
6829 			pr_cont_worker_id(worker);
6830 			pr_cont(":%ps", worker->current_func);
6831 			pr_cont(" for %us",
6832 				jiffies_to_msecs(jiffies - worker->current_start) / 1000);
6833 			list_for_each_entry(work, &worker->scheduled, entry)
6834 				pr_cont_work(false, work, &pcws);
6835 			pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
6836 			comma = true;
6837 		}
6838 		pr_cont("\n");
6839 	}
6840 
6841 	list_for_each_entry(work, &pool->worklist, entry) {
6842 		if (get_work_pwq(work) == pwq) {
6843 			has_pending = true;
6844 			break;
6845 		}
6846 	}
6847 	if (has_pending) {
6848 		bool comma = false;
6849 
6850 		pr_info("    pending:");
6851 		list_for_each_entry(work, &pool->worklist, entry) {
6852 			if (get_work_pwq(work) != pwq)
6853 				continue;
6854 
6855 			pr_cont_work(comma, work, &pcws);
6856 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
6857 		}
6858 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
6859 		pr_cont("\n");
6860 	}
6861 
6862 	if (!list_empty(&pwq->inactive_works)) {
6863 		bool comma = false;
6864 
6865 		pr_info("    inactive:");
6866 		list_for_each_entry(work, &pwq->inactive_works, entry) {
6867 			pr_cont_work(comma, work, &pcws);
6868 			comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
6869 		}
6870 		pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
6871 		pr_cont("\n");
6872 	}
6873 }
6874 
6875 /**
6876  * show_one_workqueue - dump state of specified workqueue
6877  * @wq: workqueue whose state will be printed
6878  */
6879 void show_one_workqueue(struct workqueue_struct *wq)
6880 {
6881 	struct pool_workqueue *pwq;
6882 	bool idle = true;
6883 	unsigned long irq_flags;
6884 
6885 	for_each_pwq(pwq, wq) {
6886 		if (!pwq_is_empty(pwq)) {
6887 			idle = false;
6888 			break;
6889 		}
6890 	}
6891 	if (idle) /* Nothing to print for idle workqueue */
6892 		return;
6893 
6894 	pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
6895 
6896 	for_each_pwq(pwq, wq) {
6897 		raw_spin_lock_irqsave(&pwq->pool->lock, irq_flags);
6898 		if (!pwq_is_empty(pwq)) {
6899 			/*
6900 			 * Defer printing to avoid deadlocks in console
6901 			 * drivers that queue work while holding locks
6902 			 * also taken in their write paths.
6903 			 */
6904 			printk_deferred_enter();
6905 			show_pwq(pwq);
6906 			printk_deferred_exit();
6907 		}
6908 		raw_spin_unlock_irqrestore(&pwq->pool->lock, irq_flags);
6909 		/*
6910 		 * We could be printing a lot from atomic context, e.g.
6911 		 * sysrq-t -> show_all_workqueues(). Avoid triggering
6912 		 * hard lockup.
6913 		 */
6914 		touch_nmi_watchdog();
6915 	}
6916 
6917 }
6918 
6919 /**
6920  * show_one_worker_pool - dump state of specified worker pool
6921  * @pool: worker pool whose state will be printed
6922  */
6923 static void show_one_worker_pool(struct worker_pool *pool)
6924 {
6925 	struct worker *worker;
6926 	bool first = true;
6927 	unsigned long irq_flags;
6928 	unsigned long hung = 0;
6929 
6930 	raw_spin_lock_irqsave(&pool->lock, irq_flags);
6931 	if (pool->nr_workers == pool->nr_idle)
6932 		goto next_pool;
6933 
6934 	/* How long the first pending work is waiting for a worker. */
6935 	if (!list_empty(&pool->worklist))
6936 		hung = jiffies_to_msecs(jiffies - pool->last_progress_ts) / 1000;
6937 
6938 	/*
6939 	 * Defer printing to avoid deadlocks in console drivers that
6940 	 * queue work while holding locks also taken in their write
6941 	 * paths.
6942 	 */
6943 	printk_deferred_enter();
6944 	pr_info("pool %d:", pool->id);
6945 	pr_cont_pool_info(pool);
6946 	pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
6947 	if (pool->manager)
6948 		pr_cont(" manager: %d",
6949 			task_pid_nr(pool->manager->task));
6950 	list_for_each_entry(worker, &pool->idle_list, entry) {
6951 		pr_cont(" %s", first ? "idle: " : "");
6952 		pr_cont_worker_id(worker);
6953 		first = false;
6954 	}
6955 	pr_cont("\n");
6956 	printk_deferred_exit();
6957 next_pool:
6958 	raw_spin_unlock_irqrestore(&pool->lock, irq_flags);
6959 	/*
6960 	 * We could be printing a lot from atomic context, e.g.
6961 	 * sysrq-t -> show_all_workqueues(). Avoid triggering
6962 	 * hard lockup.
6963 	 */
6964 	touch_nmi_watchdog();
6965 
6966 }
6967 
6968 /**
6969  * show_all_workqueues - dump workqueue state
6970  *
6971  * Called from a sysrq handler and prints out all busy workqueues and pools.
6972  */
6973 void show_all_workqueues(void)
6974 {
6975 	struct workqueue_struct *wq;
6976 	struct worker_pool *pool;
6977 	int pi;
6978 
6979 	rcu_read_lock();
6980 
6981 	pr_info("Showing busy workqueues and worker pools:\n");
6982 
6983 	list_for_each_entry_rcu(wq, &workqueues, list)
6984 		show_one_workqueue(wq);
6985 
6986 	for_each_pool(pool, pi)
6987 		show_one_worker_pool(pool);
6988 
6989 	rcu_read_unlock();
6990 }
6991 
6992 /**
6993  * show_freezable_workqueues - dump freezable workqueue state
6994  *
6995  * Called from try_to_freeze_tasks() and prints out all freezable workqueues
6996  * still busy.
6997  */
6998 void show_freezable_workqueues(void)
6999 {
7000 	struct workqueue_struct *wq;
7001 
7002 	rcu_read_lock();
7003 
7004 	pr_info("Showing freezable workqueues that are still busy:\n");
7005 
7006 	list_for_each_entry_rcu(wq, &workqueues, list) {
7007 		if (!(wq->flags & WQ_FREEZABLE))
7008 			continue;
7009 		show_one_workqueue(wq);
7010 	}
7011 
7012 	rcu_read_unlock();
7013 }
7014 
7015 /* used to show worker information through /proc/PID/{comm,stat,status} */
7016 void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
7017 {
7018 	/* stabilize PF_WQ_WORKER and worker pool association */
7019 	mutex_lock(&wq_pool_attach_mutex);
7020 
7021 	if (task->flags & PF_WQ_WORKER) {
7022 		struct worker *worker = kthread_data(task);
7023 		struct worker_pool *pool = worker->pool;
7024 		int off;
7025 
7026 		off = format_worker_id(buf, size, worker, pool);
7027 
7028 		if (pool) {
7029 			raw_spin_lock_irq(&pool->lock);
7030 			/*
7031 			 * ->desc tracks information (wq name or
7032 			 * set_worker_desc()) for the latest execution.  If
7033 			 * current, prepend '+', otherwise '-'.
7034 			 */
7035 			if (worker->desc[0] != '\0') {
7036 				if (worker->current_work)
7037 					scnprintf(buf + off, size - off, "+%s",
7038 						  worker->desc);
7039 				else
7040 					scnprintf(buf + off, size - off, "-%s",
7041 						  worker->desc);
7042 			}
7043 			raw_spin_unlock_irq(&pool->lock);
7044 		}
7045 	} else {
7046 		strscpy(buf, task->comm, size);
7047 	}
7048 
7049 	mutex_unlock(&wq_pool_attach_mutex);
7050 }
7051 
7052 #ifdef CONFIG_SMP
7053 
7054 /*
7055  * CPU hotplug.
7056  *
7057  * There are two challenges in supporting CPU hotplug.  Firstly, there
7058  * are a lot of assumptions on strong associations among work, pwq and
7059  * pool which make migrating pending and scheduled works very
7060  * difficult to implement without impacting hot paths.  Secondly,
7061  * worker pools serve mix of short, long and very long running works making
7062  * blocked draining impractical.
7063  *
7064  * This is solved by allowing the pools to be disassociated from the CPU
7065  * running as an unbound one and allowing it to be reattached later if the
7066  * cpu comes back online.
7067  */
7068 
7069 static void unbind_workers(int cpu)
7070 {
7071 	struct worker_pool *pool;
7072 	struct worker *worker;
7073 
7074 	for_each_cpu_worker_pool(pool, cpu) {
7075 		mutex_lock(&wq_pool_attach_mutex);
7076 		raw_spin_lock_irq(&pool->lock);
7077 
7078 		/*
7079 		 * We've blocked all attach/detach operations. Make all workers
7080 		 * unbound and set DISASSOCIATED.  Before this, all workers
7081 		 * must be on the cpu.  After this, they may become diasporas.
7082 		 * And the preemption disabled section in their sched callbacks
7083 		 * are guaranteed to see WORKER_UNBOUND since the code here
7084 		 * is on the same cpu.
7085 		 */
7086 		for_each_pool_worker(worker, pool)
7087 			worker->flags |= WORKER_UNBOUND;
7088 
7089 		pool->flags |= POOL_DISASSOCIATED;
7090 
7091 		/*
7092 		 * The handling of nr_running in sched callbacks are disabled
7093 		 * now.  Zap nr_running.  After this, nr_running stays zero and
7094 		 * need_more_worker() and keep_working() are always true as
7095 		 * long as the worklist is not empty.  This pool now behaves as
7096 		 * an unbound (in terms of concurrency management) pool which
7097 		 * are served by workers tied to the pool.
7098 		 */
7099 		pool->nr_running = 0;
7100 
7101 		/*
7102 		 * With concurrency management just turned off, a busy
7103 		 * worker blocking could lead to lengthy stalls.  Kick off
7104 		 * unbound chain execution of currently pending work items.
7105 		 */
7106 		kick_pool(pool);
7107 
7108 		raw_spin_unlock_irq(&pool->lock);
7109 
7110 		for_each_pool_worker(worker, pool)
7111 			unbind_worker(worker);
7112 
7113 		mutex_unlock(&wq_pool_attach_mutex);
7114 	}
7115 }
7116 
7117 /**
7118  * rebind_workers - rebind all workers of a pool to the associated CPU
7119  * @pool: pool of interest
7120  *
7121  * @pool->cpu is coming online.  Rebind all workers to the CPU.
7122  */
7123 static void rebind_workers(struct worker_pool *pool)
7124 {
7125 	struct worker *worker;
7126 
7127 	lockdep_assert_held(&wq_pool_attach_mutex);
7128 
7129 	/*
7130 	 * Restore CPU affinity of all workers.  As all idle workers should
7131 	 * be on the run-queue of the associated CPU before any local
7132 	 * wake-ups for concurrency management happen, restore CPU affinity
7133 	 * of all workers first and then clear UNBOUND.  As we're called
7134 	 * from CPU_ONLINE, the following shouldn't fail.
7135 	 */
7136 	for_each_pool_worker(worker, pool) {
7137 		kthread_set_per_cpu(worker->task, pool->cpu);
7138 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
7139 						  pool_allowed_cpus(pool)) < 0);
7140 	}
7141 
7142 	raw_spin_lock_irq(&pool->lock);
7143 
7144 	pool->flags &= ~POOL_DISASSOCIATED;
7145 
7146 	for_each_pool_worker(worker, pool) {
7147 		unsigned int worker_flags = worker->flags;
7148 
7149 		/*
7150 		 * We want to clear UNBOUND but can't directly call
7151 		 * worker_clr_flags() or adjust nr_running.  Atomically
7152 		 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
7153 		 * @worker will clear REBOUND using worker_clr_flags() when
7154 		 * it initiates the next execution cycle thus restoring
7155 		 * concurrency management.  Note that when or whether
7156 		 * @worker clears REBOUND doesn't affect correctness.
7157 		 *
7158 		 * WRITE_ONCE() is necessary because @worker->flags may be
7159 		 * tested without holding any lock in
7160 		 * wq_worker_running().  Without it, NOT_RUNNING test may
7161 		 * fail incorrectly leading to premature concurrency
7162 		 * management operations.
7163 		 */
7164 		WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
7165 		worker_flags |= WORKER_REBOUND;
7166 		worker_flags &= ~WORKER_UNBOUND;
7167 		WRITE_ONCE(worker->flags, worker_flags);
7168 	}
7169 
7170 	raw_spin_unlock_irq(&pool->lock);
7171 }
7172 
7173 /**
7174  * restore_unbound_workers_cpumask - restore cpumask of unbound workers
7175  * @pool: unbound pool of interest
7176  * @cpu: the CPU which is coming up
7177  *
7178  * An unbound pool may end up with a cpumask which doesn't have any online
7179  * CPUs.  When a worker of such pool get scheduled, the scheduler resets
7180  * its cpus_allowed.  If @cpu is in @pool's cpumask which didn't have any
7181  * online CPU before, cpus_allowed of all its workers should be restored.
7182  */
7183 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
7184 {
7185 	static cpumask_t cpumask;
7186 	struct worker *worker;
7187 
7188 	lockdep_assert_held(&wq_pool_attach_mutex);
7189 
7190 	/* is @cpu allowed for @pool? */
7191 	if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
7192 		return;
7193 
7194 	cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
7195 
7196 	/* as we're called from CPU_ONLINE, the following shouldn't fail */
7197 	for_each_pool_worker(worker, pool)
7198 		WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
7199 }
7200 
7201 int workqueue_prepare_cpu(unsigned int cpu)
7202 {
7203 	struct worker_pool *pool;
7204 
7205 	for_each_cpu_worker_pool(pool, cpu) {
7206 		if (pool->nr_workers)
7207 			continue;
7208 		if (!create_worker(pool))
7209 			return -ENOMEM;
7210 	}
7211 	return 0;
7212 }
7213 
7214 int workqueue_online_cpu(unsigned int cpu)
7215 {
7216 	struct worker_pool *pool;
7217 	struct workqueue_struct *wq;
7218 	int pi;
7219 
7220 	mutex_lock(&wq_pool_mutex);
7221 
7222 	cpumask_set_cpu(cpu, wq_online_cpumask);
7223 
7224 	for_each_pool(pool, pi) {
7225 		/* BH pools aren't affected by hotplug */
7226 		if (pool->flags & POOL_BH)
7227 			continue;
7228 
7229 		mutex_lock(&wq_pool_attach_mutex);
7230 		if (pool->cpu == cpu)
7231 			rebind_workers(pool);
7232 		else if (pool->cpu < 0)
7233 			restore_unbound_workers_cpumask(pool, cpu);
7234 		mutex_unlock(&wq_pool_attach_mutex);
7235 	}
7236 
7237 	/*
7238 	 * Before topology initialization, the SYSTEM pod covers all possible
7239 	 * CPUs, so CPU onlining does not require updating pwq mappings.
7240 	 * wq_update_node_max_active() also returns early at this stage.
7241 	 */
7242 	if (!wq_topo_initialized)
7243 		goto out_unlock;
7244 
7245 	/* update pod affinity of unbound workqueues */
7246 	list_for_each_entry(wq, &workqueues, list) {
7247 		struct workqueue_attrs *attrs = wq->attrs;
7248 
7249 		if (wq->flags & WQ_UNBOUND) {
7250 			const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
7251 			int tcpu;
7252 
7253 			for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
7254 				unbound_wq_update_pwq(wq, tcpu);
7255 
7256 			mutex_lock(&wq->mutex);
7257 			wq_update_node_max_active(wq, -1);
7258 			mutex_unlock(&wq->mutex);
7259 		}
7260 	}
7261 
7262 out_unlock:
7263 	mutex_unlock(&wq_pool_mutex);
7264 	return 0;
7265 }
7266 
7267 int workqueue_offline_cpu(unsigned int cpu)
7268 {
7269 	struct workqueue_struct *wq;
7270 
7271 	/* unbinding per-cpu workers should happen on the local CPU */
7272 	if (WARN_ON(cpu != smp_processor_id()))
7273 		return -1;
7274 
7275 	unbind_workers(cpu);
7276 
7277 	/* update pod affinity of unbound workqueues */
7278 	mutex_lock(&wq_pool_mutex);
7279 
7280 	cpumask_clear_cpu(cpu, wq_online_cpumask);
7281 
7282 	list_for_each_entry(wq, &workqueues, list) {
7283 		struct workqueue_attrs *attrs = wq->attrs;
7284 
7285 		if (wq->flags & WQ_UNBOUND) {
7286 			const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
7287 			int tcpu;
7288 
7289 			for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
7290 				unbound_wq_update_pwq(wq, tcpu);
7291 
7292 			mutex_lock(&wq->mutex);
7293 			wq_update_node_max_active(wq, cpu);
7294 			mutex_unlock(&wq->mutex);
7295 		}
7296 	}
7297 	mutex_unlock(&wq_pool_mutex);
7298 
7299 	return 0;
7300 }
7301 
7302 struct work_for_cpu {
7303 	struct work_struct work;
7304 	long (*fn)(void *);
7305 	void *arg;
7306 	long ret;
7307 };
7308 
7309 static void work_for_cpu_fn(struct work_struct *work)
7310 {
7311 	struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
7312 
7313 	wfc->ret = wfc->fn(wfc->arg);
7314 }
7315 
7316 /**
7317  * work_on_cpu_key - run a function in thread context on a particular cpu
7318  * @cpu: the cpu to run on
7319  * @fn: the function to run
7320  * @arg: the function arg
7321  * @key: The lock class key for lock debugging purposes
7322  *
7323  * It is up to the caller to ensure that the cpu doesn't go offline.
7324  * The caller must not hold any locks which would prevent @fn from completing.
7325  *
7326  * Return: The value @fn returns.
7327  */
7328 long work_on_cpu_key(int cpu, long (*fn)(void *),
7329 		     void *arg, struct lock_class_key *key)
7330 {
7331 	struct work_for_cpu wfc = { .fn = fn, .arg = arg };
7332 
7333 	INIT_WORK_ONSTACK_KEY(&wfc.work, work_for_cpu_fn, key);
7334 	schedule_work_on(cpu, &wfc.work);
7335 	flush_work(&wfc.work);
7336 	destroy_work_on_stack(&wfc.work);
7337 	return wfc.ret;
7338 }
7339 EXPORT_SYMBOL_GPL(work_on_cpu_key);
7340 #endif /* CONFIG_SMP */
7341 
7342 #ifdef CONFIG_FREEZER
7343 
7344 /**
7345  * freeze_workqueues_begin - begin freezing workqueues
7346  *
7347  * Start freezing workqueues.  After this function returns, all freezable
7348  * workqueues will queue new works to their inactive_works list instead of
7349  * pool->worklist.
7350  *
7351  * CONTEXT:
7352  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
7353  */
7354 void freeze_workqueues_begin(void)
7355 {
7356 	struct workqueue_struct *wq;
7357 
7358 	mutex_lock(&wq_pool_mutex);
7359 
7360 	WARN_ON_ONCE(workqueue_freezing);
7361 	workqueue_freezing = true;
7362 
7363 	list_for_each_entry(wq, &workqueues, list) {
7364 		mutex_lock(&wq->mutex);
7365 		wq_adjust_max_active(wq);
7366 		mutex_unlock(&wq->mutex);
7367 	}
7368 
7369 	mutex_unlock(&wq_pool_mutex);
7370 }
7371 
7372 /**
7373  * freeze_workqueues_busy - are freezable workqueues still busy?
7374  *
7375  * Check whether freezing is complete.  This function must be called
7376  * between freeze_workqueues_begin() and thaw_workqueues().
7377  *
7378  * CONTEXT:
7379  * Grabs and releases wq_pool_mutex.
7380  *
7381  * Return:
7382  * %true if some freezable workqueues are still busy.  %false if freezing
7383  * is complete.
7384  */
7385 bool freeze_workqueues_busy(void)
7386 {
7387 	bool busy = false;
7388 	struct workqueue_struct *wq;
7389 	struct pool_workqueue *pwq;
7390 
7391 	mutex_lock(&wq_pool_mutex);
7392 
7393 	WARN_ON_ONCE(!workqueue_freezing);
7394 
7395 	list_for_each_entry(wq, &workqueues, list) {
7396 		if (!(wq->flags & WQ_FREEZABLE))
7397 			continue;
7398 		/*
7399 		 * nr_active is monotonically decreasing.  It's safe
7400 		 * to peek without lock.
7401 		 */
7402 		rcu_read_lock();
7403 		for_each_pwq(pwq, wq) {
7404 			WARN_ON_ONCE(pwq->nr_active < 0);
7405 			if (pwq->nr_active) {
7406 				busy = true;
7407 				rcu_read_unlock();
7408 				goto out_unlock;
7409 			}
7410 		}
7411 		rcu_read_unlock();
7412 	}
7413 out_unlock:
7414 	mutex_unlock(&wq_pool_mutex);
7415 	return busy;
7416 }
7417 
7418 /**
7419  * thaw_workqueues - thaw workqueues
7420  *
7421  * Thaw workqueues.  Normal queueing is restored and all collected
7422  * frozen works are transferred to their respective pool worklists.
7423  *
7424  * CONTEXT:
7425  * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
7426  */
7427 void thaw_workqueues(void)
7428 {
7429 	struct workqueue_struct *wq;
7430 
7431 	mutex_lock(&wq_pool_mutex);
7432 
7433 	if (!workqueue_freezing)
7434 		goto out_unlock;
7435 
7436 	workqueue_freezing = false;
7437 
7438 	/* restore max_active and repopulate worklist */
7439 	list_for_each_entry(wq, &workqueues, list) {
7440 		mutex_lock(&wq->mutex);
7441 		wq_adjust_max_active(wq);
7442 		mutex_unlock(&wq->mutex);
7443 	}
7444 
7445 out_unlock:
7446 	mutex_unlock(&wq_pool_mutex);
7447 }
7448 #endif /* CONFIG_FREEZER */
7449 
7450 static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
7451 {
7452 	LIST_HEAD(ctxs);
7453 	int ret = 0;
7454 	struct workqueue_struct *wq;
7455 	struct apply_wqattrs_ctx *ctx, *n;
7456 
7457 	lockdep_assert_held(&wq_pool_mutex);
7458 
7459 	list_for_each_entry(wq, &workqueues, list) {
7460 		if (!(wq->flags & WQ_UNBOUND) || (wq->flags & __WQ_DESTROYING))
7461 			continue;
7462 
7463 		ctx = apply_wqattrs_prepare(wq, wq->attrs, unbound_cpumask);
7464 		if (IS_ERR(ctx)) {
7465 			ret = PTR_ERR(ctx);
7466 			break;
7467 		}
7468 
7469 		list_add_tail(&ctx->list, &ctxs);
7470 	}
7471 
7472 	list_for_each_entry_safe(ctx, n, &ctxs, list) {
7473 		if (!ret)
7474 			apply_wqattrs_commit(ctx);
7475 		apply_wqattrs_cleanup(ctx);
7476 	}
7477 
7478 	if (!ret) {
7479 		int cpu;
7480 		struct worker_pool *pool;
7481 		struct worker *worker;
7482 
7483 		mutex_lock(&wq_pool_attach_mutex);
7484 		cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
7485 		/* rescuer needs to respect cpumask changes when it is not attached */
7486 		list_for_each_entry(wq, &workqueues, list) {
7487 			if (wq->rescuer && !wq->rescuer->pool)
7488 				unbind_worker(wq->rescuer);
7489 		}
7490 		/* DISASSOCIATED worker needs to respect wq_unbound_cpumask */
7491 		for_each_possible_cpu(cpu) {
7492 			for_each_cpu_worker_pool(pool, cpu) {
7493 				if (!(pool->flags & POOL_DISASSOCIATED))
7494 					continue;
7495 				for_each_pool_worker(worker, pool)
7496 					unbind_worker(worker);
7497 			}
7498 		}
7499 		mutex_unlock(&wq_pool_attach_mutex);
7500 	}
7501 	return ret;
7502 }
7503 
7504 /**
7505  * workqueue_unbound_housekeeping_update - Propagate housekeeping cpumask update
7506  * @hk: the new housekeeping cpumask
7507  *
7508  * Update the unbound workqueue cpumask on top of the new housekeeping cpumask such
7509  * that the effective unbound affinity is the intersection of the new housekeeping
7510  * with the requested affinity set via nohz_full=/isolcpus= or sysfs.
7511  *
7512  * Return: 0 on success and -errno on failure.
7513  */
7514 int workqueue_unbound_housekeeping_update(const struct cpumask *hk)
7515 {
7516 	cpumask_var_t cpumask;
7517 	int ret = 0;
7518 
7519 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
7520 		return -ENOMEM;
7521 
7522 	mutex_lock(&wq_pool_mutex);
7523 
7524 	/*
7525 	 * If the operation fails, it will fall back to
7526 	 * wq_requested_unbound_cpumask which is initially set to
7527 	 * HK_TYPE_DOMAIN house keeping mask and rewritten
7528 	 * by any subsequent write to workqueue/cpumask sysfs file.
7529 	 */
7530 	if (!cpumask_and(cpumask, wq_requested_unbound_cpumask, hk))
7531 		cpumask_copy(cpumask, wq_requested_unbound_cpumask);
7532 	if (!cpumask_equal(cpumask, wq_unbound_cpumask))
7533 		ret = workqueue_apply_unbound_cpumask(cpumask);
7534 
7535 	/* Save the current isolated cpumask & export it via sysfs */
7536 	if (!ret)
7537 		cpumask_andnot(wq_isolated_cpumask, cpu_possible_mask, hk);
7538 
7539 	mutex_unlock(&wq_pool_mutex);
7540 	free_cpumask_var(cpumask);
7541 	return ret;
7542 }
7543 
7544 static int parse_affn_scope(const char *val)
7545 {
7546 	return sysfs_match_string(wq_affn_names, val);
7547 }
7548 
7549 static int wq_affn_dfl_set(const char *val, const struct kernel_param *kp)
7550 {
7551 	struct workqueue_struct *wq;
7552 	int affn, cpu;
7553 
7554 	affn = parse_affn_scope(val);
7555 	if (affn < 0)
7556 		return affn;
7557 	if (affn == WQ_AFFN_DFL)
7558 		return -EINVAL;
7559 
7560 	cpus_read_lock();
7561 	mutex_lock(&wq_pool_mutex);
7562 
7563 	wq_affn_dfl = affn;
7564 
7565 	list_for_each_entry(wq, &workqueues, list) {
7566 		for_each_online_cpu(cpu)
7567 			unbound_wq_update_pwq(wq, cpu);
7568 	}
7569 
7570 	mutex_unlock(&wq_pool_mutex);
7571 	cpus_read_unlock();
7572 
7573 	return 0;
7574 }
7575 
7576 static int wq_affn_dfl_get(char *buffer, const struct kernel_param *kp)
7577 {
7578 	return scnprintf(buffer, PAGE_SIZE, "%s\n", wq_affn_names[wq_affn_dfl]);
7579 }
7580 
7581 static const struct kernel_param_ops wq_affn_dfl_ops = {
7582 	.set	= wq_affn_dfl_set,
7583 	.get	= wq_affn_dfl_get,
7584 };
7585 
7586 module_param_cb(default_affinity_scope, &wq_affn_dfl_ops, NULL, 0644);
7587 
7588 #ifdef CONFIG_SYSFS
7589 /*
7590  * Workqueues with WQ_SYSFS flag set is visible to userland via
7591  * /sys/bus/workqueue/devices/WQ_NAME.  All visible workqueues have the
7592  * following attributes.
7593  *
7594  *  per_cpu		RO bool	: whether the workqueue is per-cpu or unbound
7595  *  max_active		RW int	: maximum number of in-flight work items
7596  *
7597  * Unbound workqueues have the following extra attributes.
7598  *
7599  *  nice		RW int	: nice value of the workers
7600  *  cpumask		RW mask	: bitmask of allowed CPUs for the workers
7601  *  affinity_scope	RW str  : worker CPU affinity scope (cache, numa, none)
7602  *  affinity_strict	RW bool : worker CPU affinity is strict
7603  */
7604 struct wq_device {
7605 	struct workqueue_struct		*wq;
7606 	struct device			dev;
7607 };
7608 
7609 static struct workqueue_struct *dev_to_wq(struct device *dev)
7610 {
7611 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
7612 
7613 	return wq_dev->wq;
7614 }
7615 
7616 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
7617 			    char *buf)
7618 {
7619 	struct workqueue_struct *wq = dev_to_wq(dev);
7620 
7621 	return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
7622 }
7623 static DEVICE_ATTR_RO(per_cpu);
7624 
7625 static ssize_t max_active_show(struct device *dev,
7626 			       struct device_attribute *attr, char *buf)
7627 {
7628 	struct workqueue_struct *wq = dev_to_wq(dev);
7629 
7630 	return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
7631 }
7632 
7633 static ssize_t max_active_store(struct device *dev,
7634 				struct device_attribute *attr, const char *buf,
7635 				size_t count)
7636 {
7637 	struct workqueue_struct *wq = dev_to_wq(dev);
7638 	int val;
7639 
7640 	if (sscanf(buf, "%d", &val) != 1 || val <= 0)
7641 		return -EINVAL;
7642 
7643 	workqueue_set_max_active(wq, val);
7644 	return count;
7645 }
7646 static DEVICE_ATTR_RW(max_active);
7647 
7648 static struct attribute *wq_sysfs_attrs[] = {
7649 	&dev_attr_per_cpu.attr,
7650 	&dev_attr_max_active.attr,
7651 	NULL,
7652 };
7653 
7654 static umode_t wq_sysfs_is_visible(struct kobject *kobj, struct attribute *a, int n)
7655 {
7656 	struct device *dev = kobj_to_dev(kobj);
7657 	struct workqueue_struct *wq = dev_to_wq(dev);
7658 
7659 	/*
7660 	 * Adjusting max_active breaks ordering guarantee. Changing it has no
7661 	 * effect on BH worker. Limit max_active to RO in such case.
7662 	 */
7663 	if (wq->flags & (WQ_BH | __WQ_ORDERED))
7664 		return 0444;
7665 	return a->mode;
7666 }
7667 
7668 static const struct attribute_group wq_sysfs_group = {
7669 	.is_visible = wq_sysfs_is_visible,
7670 	.attrs = wq_sysfs_attrs,
7671 };
7672 __ATTRIBUTE_GROUPS(wq_sysfs);
7673 
7674 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
7675 			    char *buf)
7676 {
7677 	struct workqueue_struct *wq = dev_to_wq(dev);
7678 	int written;
7679 
7680 	mutex_lock(&wq->mutex);
7681 	written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->attrs->nice);
7682 	mutex_unlock(&wq->mutex);
7683 
7684 	return written;
7685 }
7686 
7687 /* prepare workqueue_attrs for sysfs store operations */
7688 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
7689 {
7690 	struct workqueue_attrs *attrs;
7691 
7692 	lockdep_assert_held(&wq_pool_mutex);
7693 
7694 	attrs = alloc_workqueue_attrs();
7695 	if (!attrs)
7696 		return NULL;
7697 
7698 	copy_workqueue_attrs(attrs, wq->attrs);
7699 	return attrs;
7700 }
7701 
7702 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
7703 			     const char *buf, size_t count)
7704 {
7705 	struct workqueue_struct *wq = dev_to_wq(dev);
7706 	struct workqueue_attrs *attrs;
7707 	int ret = -ENOMEM;
7708 
7709 	mutex_lock(&wq_pool_mutex);
7710 
7711 	attrs = wq_sysfs_prep_attrs(wq);
7712 	if (!attrs)
7713 		goto out_unlock;
7714 
7715 	if (sscanf(buf, "%d", &attrs->nice) == 1 &&
7716 	    attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
7717 		ret = apply_workqueue_attrs_locked(wq, attrs);
7718 	else
7719 		ret = -EINVAL;
7720 
7721 out_unlock:
7722 	mutex_unlock(&wq_pool_mutex);
7723 	free_workqueue_attrs(attrs);
7724 	return ret ?: count;
7725 }
7726 
7727 static ssize_t wq_cpumask_show(struct device *dev,
7728 			       struct device_attribute *attr, char *buf)
7729 {
7730 	struct workqueue_struct *wq = dev_to_wq(dev);
7731 	int written;
7732 
7733 	mutex_lock(&wq->mutex);
7734 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
7735 			    cpumask_pr_args(wq->attrs->cpumask));
7736 	mutex_unlock(&wq->mutex);
7737 	return written;
7738 }
7739 
7740 static ssize_t wq_cpumask_store(struct device *dev,
7741 				struct device_attribute *attr,
7742 				const char *buf, size_t count)
7743 {
7744 	struct workqueue_struct *wq = dev_to_wq(dev);
7745 	struct workqueue_attrs *attrs;
7746 	int ret = -ENOMEM;
7747 
7748 	mutex_lock(&wq_pool_mutex);
7749 
7750 	attrs = wq_sysfs_prep_attrs(wq);
7751 	if (!attrs)
7752 		goto out_unlock;
7753 
7754 	ret = cpumask_parse(buf, attrs->cpumask);
7755 	if (!ret)
7756 		ret = apply_workqueue_attrs_locked(wq, attrs);
7757 
7758 out_unlock:
7759 	mutex_unlock(&wq_pool_mutex);
7760 	free_workqueue_attrs(attrs);
7761 	return ret ?: count;
7762 }
7763 
7764 static ssize_t wq_affn_scope_show(struct device *dev,
7765 				  struct device_attribute *attr, char *buf)
7766 {
7767 	struct workqueue_struct *wq = dev_to_wq(dev);
7768 	int written;
7769 
7770 	mutex_lock(&wq->mutex);
7771 	if (wq->attrs->affn_scope == WQ_AFFN_DFL)
7772 		written = scnprintf(buf, PAGE_SIZE, "%s (%s)\n",
7773 				    wq_affn_names[WQ_AFFN_DFL],
7774 				    wq_affn_names[wq_affn_dfl]);
7775 	else
7776 		written = scnprintf(buf, PAGE_SIZE, "%s\n",
7777 				    wq_affn_names[wq->attrs->affn_scope]);
7778 	mutex_unlock(&wq->mutex);
7779 
7780 	return written;
7781 }
7782 
7783 static ssize_t wq_affn_scope_store(struct device *dev,
7784 				   struct device_attribute *attr,
7785 				   const char *buf, size_t count)
7786 {
7787 	struct workqueue_struct *wq = dev_to_wq(dev);
7788 	struct workqueue_attrs *attrs;
7789 	int affn, ret = -ENOMEM;
7790 
7791 	affn = parse_affn_scope(buf);
7792 	if (affn < 0)
7793 		return affn;
7794 
7795 	mutex_lock(&wq_pool_mutex);
7796 	attrs = wq_sysfs_prep_attrs(wq);
7797 	if (attrs) {
7798 		attrs->affn_scope = affn;
7799 		ret = apply_workqueue_attrs_locked(wq, attrs);
7800 	}
7801 	mutex_unlock(&wq_pool_mutex);
7802 	free_workqueue_attrs(attrs);
7803 	return ret ?: count;
7804 }
7805 
7806 static ssize_t wq_affinity_strict_show(struct device *dev,
7807 				       struct device_attribute *attr, char *buf)
7808 {
7809 	struct workqueue_struct *wq = dev_to_wq(dev);
7810 
7811 	return scnprintf(buf, PAGE_SIZE, "%d\n",
7812 			 wq->attrs->affn_strict);
7813 }
7814 
7815 static ssize_t wq_affinity_strict_store(struct device *dev,
7816 					struct device_attribute *attr,
7817 					const char *buf, size_t count)
7818 {
7819 	struct workqueue_struct *wq = dev_to_wq(dev);
7820 	struct workqueue_attrs *attrs;
7821 	int v, ret = -ENOMEM;
7822 
7823 	if (sscanf(buf, "%d", &v) != 1)
7824 		return -EINVAL;
7825 
7826 	mutex_lock(&wq_pool_mutex);
7827 	attrs = wq_sysfs_prep_attrs(wq);
7828 	if (attrs) {
7829 		attrs->affn_strict = (bool)v;
7830 		ret = apply_workqueue_attrs_locked(wq, attrs);
7831 	}
7832 	mutex_unlock(&wq_pool_mutex);
7833 	free_workqueue_attrs(attrs);
7834 	return ret ?: count;
7835 }
7836 
7837 static struct device_attribute wq_sysfs_unbound_attrs[] = {
7838 	__ATTR(nice, 0644, wq_nice_show, wq_nice_store),
7839 	__ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
7840 	__ATTR(affinity_scope, 0644, wq_affn_scope_show, wq_affn_scope_store),
7841 	__ATTR(affinity_strict, 0644, wq_affinity_strict_show, wq_affinity_strict_store),
7842 	__ATTR_NULL,
7843 };
7844 
7845 static const struct bus_type wq_subsys = {
7846 	.name				= "workqueue",
7847 	.dev_groups			= wq_sysfs_groups,
7848 };
7849 
7850 /**
7851  *  workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
7852  *  @cpumask: the cpumask to set
7853  *
7854  *  The low-level workqueues cpumask is a global cpumask that limits
7855  *  the affinity of all unbound workqueues.  This function check the @cpumask
7856  *  and apply it to all unbound workqueues and updates all pwqs of them.
7857  *
7858  *  Return:	0	- Success
7859  *		-EINVAL	- Invalid @cpumask
7860  *		-ENOMEM	- Failed to allocate memory for attrs or pwqs.
7861  */
7862 static int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
7863 {
7864 	int ret = -EINVAL;
7865 
7866 	/*
7867 	 * Not excluding isolated cpus on purpose.
7868 	 * If the user wishes to include them, we allow that.
7869 	 */
7870 	cpumask_and(cpumask, cpumask, cpu_possible_mask);
7871 	if (!cpumask_empty(cpumask)) {
7872 		ret = 0;
7873 		mutex_lock(&wq_pool_mutex);
7874 		if (!cpumask_equal(cpumask, wq_unbound_cpumask))
7875 			ret = workqueue_apply_unbound_cpumask(cpumask);
7876 		if (!ret)
7877 			cpumask_copy(wq_requested_unbound_cpumask, cpumask);
7878 		mutex_unlock(&wq_pool_mutex);
7879 	}
7880 
7881 	return ret;
7882 }
7883 
7884 static ssize_t __wq_cpumask_show(struct device *dev,
7885 		struct device_attribute *attr, char *buf, cpumask_var_t mask)
7886 {
7887 	int written;
7888 
7889 	mutex_lock(&wq_pool_mutex);
7890 	written = scnprintf(buf, PAGE_SIZE, "%*pb\n", cpumask_pr_args(mask));
7891 	mutex_unlock(&wq_pool_mutex);
7892 
7893 	return written;
7894 }
7895 
7896 static ssize_t cpumask_requested_show(struct device *dev,
7897 		struct device_attribute *attr, char *buf)
7898 {
7899 	return __wq_cpumask_show(dev, attr, buf, wq_requested_unbound_cpumask);
7900 }
7901 static DEVICE_ATTR_RO(cpumask_requested);
7902 
7903 static ssize_t cpumask_isolated_show(struct device *dev,
7904 		struct device_attribute *attr, char *buf)
7905 {
7906 	return __wq_cpumask_show(dev, attr, buf, wq_isolated_cpumask);
7907 }
7908 static DEVICE_ATTR_RO(cpumask_isolated);
7909 
7910 static ssize_t cpumask_show(struct device *dev,
7911 		struct device_attribute *attr, char *buf)
7912 {
7913 	return __wq_cpumask_show(dev, attr, buf, wq_unbound_cpumask);
7914 }
7915 
7916 static ssize_t cpumask_store(struct device *dev,
7917 		struct device_attribute *attr, const char *buf, size_t count)
7918 {
7919 	cpumask_var_t cpumask;
7920 	int ret;
7921 
7922 	if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
7923 		return -ENOMEM;
7924 
7925 	ret = cpumask_parse(buf, cpumask);
7926 	if (!ret)
7927 		ret = workqueue_set_unbound_cpumask(cpumask);
7928 
7929 	free_cpumask_var(cpumask);
7930 	return ret ? ret : count;
7931 }
7932 static DEVICE_ATTR_RW(cpumask);
7933 
7934 static struct attribute *wq_sysfs_cpumask_attrs[] = {
7935 	&dev_attr_cpumask.attr,
7936 	&dev_attr_cpumask_requested.attr,
7937 	&dev_attr_cpumask_isolated.attr,
7938 	NULL,
7939 };
7940 ATTRIBUTE_GROUPS(wq_sysfs_cpumask);
7941 
7942 static int __init wq_sysfs_init(void)
7943 {
7944 	return subsys_virtual_register(&wq_subsys, wq_sysfs_cpumask_groups);
7945 }
7946 core_initcall(wq_sysfs_init);
7947 
7948 static void wq_device_release(struct device *dev)
7949 {
7950 	struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
7951 
7952 	kfree(wq_dev);
7953 }
7954 
7955 /**
7956  * workqueue_sysfs_register - make a workqueue visible in sysfs
7957  * @wq: the workqueue to register
7958  *
7959  * Expose @wq in sysfs under /sys/bus/workqueue/devices.
7960  * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
7961  * which is the preferred method.
7962  *
7963  * Workqueue user should use this function directly iff it wants to apply
7964  * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
7965  * apply_workqueue_attrs() may race against userland updating the
7966  * attributes.
7967  *
7968  * Return: 0 on success, -errno on failure.
7969  */
7970 int workqueue_sysfs_register(struct workqueue_struct *wq)
7971 {
7972 	struct wq_device *wq_dev;
7973 	int ret;
7974 
7975 	wq->wq_dev = wq_dev = kzalloc_obj(*wq_dev);
7976 	if (!wq_dev)
7977 		return -ENOMEM;
7978 
7979 	wq_dev->wq = wq;
7980 	wq_dev->dev.bus = &wq_subsys;
7981 	wq_dev->dev.release = wq_device_release;
7982 	dev_set_name(&wq_dev->dev, "%s", wq->name);
7983 
7984 	/*
7985 	 * attrs are created separately.  Suppress uevent until
7986 	 * everything is ready.
7987 	 */
7988 	dev_set_uevent_suppress(&wq_dev->dev, true);
7989 
7990 	ret = device_register(&wq_dev->dev);
7991 	if (ret) {
7992 		put_device(&wq_dev->dev);
7993 		wq->wq_dev = NULL;
7994 		return ret;
7995 	}
7996 
7997 	if (wq->flags & WQ_UNBOUND) {
7998 		struct device_attribute *attr;
7999 
8000 		for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
8001 			ret = device_create_file(&wq_dev->dev, attr);
8002 			if (ret) {
8003 				device_unregister(&wq_dev->dev);
8004 				wq->wq_dev = NULL;
8005 				return ret;
8006 			}
8007 		}
8008 	}
8009 
8010 	dev_set_uevent_suppress(&wq_dev->dev, false);
8011 	kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
8012 	return 0;
8013 }
8014 
8015 /**
8016  * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
8017  * @wq: the workqueue to unregister
8018  *
8019  * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
8020  */
8021 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
8022 {
8023 	struct wq_device *wq_dev = wq->wq_dev;
8024 
8025 	if (!wq->wq_dev)
8026 		return;
8027 
8028 	wq->wq_dev = NULL;
8029 	device_unregister(&wq_dev->dev);
8030 }
8031 #else	/* CONFIG_SYSFS */
8032 static void workqueue_sysfs_unregister(struct workqueue_struct *wq)	{ }
8033 #endif	/* CONFIG_SYSFS */
8034 
8035 /*
8036  * Workqueue watchdog.
8037  *
8038  * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
8039  * flush dependency, a concurrency managed work item which stays RUNNING
8040  * indefinitely.  Workqueue stalls can be very difficult to debug as the
8041  * usual warning mechanisms don't trigger and internal workqueue state is
8042  * largely opaque.
8043  *
8044  * Workqueue watchdog monitors all worker pools periodically and dumps
8045  * state if some pools failed to make forward progress for a while where
8046  * forward progress is defined as the first item on ->worklist changing.
8047  *
8048  * This mechanism is controlled through the kernel parameter
8049  * "workqueue.watchdog_thresh" which can be updated at runtime through the
8050  * corresponding sysfs parameter file.
8051  */
8052 #ifdef CONFIG_WQ_WATCHDOG
8053 
8054 static unsigned long wq_watchdog_thresh = 30;
8055 static struct timer_list wq_watchdog_timer;
8056 
8057 static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
8058 static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
8059 
8060 static unsigned int wq_panic_on_stall = CONFIG_BOOTPARAM_WQ_STALL_PANIC;
8061 module_param_named(panic_on_stall, wq_panic_on_stall, uint, 0644);
8062 
8063 static unsigned int wq_panic_on_stall_time;
8064 module_param_named(panic_on_stall_time, wq_panic_on_stall_time, uint, 0644);
8065 MODULE_PARM_DESC(panic_on_stall_time, "Panic if stall exceeds this many seconds (0=disabled)");
8066 
8067 /*
8068  * Report that a pool has no worker in running state, which is a sign that the
8069  * pool may be stuck. Print pool info. Must be called with pool->lock held and
8070  * inside a printk_deferred_enter/exit region.
8071  */
8072 static void show_pool_no_running_worker(struct worker_pool *pool)
8073 {
8074 	lockdep_assert_held(&pool->lock);
8075 
8076 	printk_deferred_enter();
8077 	pr_info("pool %d: no worker in running state, cpu=%d is %s (nr_workers=%d nr_idle=%d)\n",
8078 		pool->id, pool->cpu,
8079 		idle_cpu(pool->cpu) ? "idle" : "busy",
8080 		pool->nr_workers, pool->nr_idle);
8081 	pr_info("The pool might have trouble waking an idle worker.\n");
8082 	/*
8083 	 * last_woken_worker and its task are valid here: set_worker_dying()
8084 	 * clears it under pool->lock before setting WORKER_DIE, so if
8085 	 * last_woken_worker is non-NULL the kthread has not yet exited and
8086 	 * worker->task is still alive.
8087 	 */
8088 	if (pool->last_woken_worker) {
8089 		pr_info("Backtrace of last woken worker:\n");
8090 		sched_show_task(pool->last_woken_worker->task);
8091 	} else {
8092 		pr_info("Last woken worker empty\n");
8093 	}
8094 	printk_deferred_exit();
8095 }
8096 
8097 /*
8098  * Show running workers that might prevent the processing of pending work items.
8099  * If no running worker is found, the pool may be stuck waiting for an idle
8100  * worker to be woken, so report the pool state and the last woken worker.
8101  */
8102 static void show_cpu_pool_busy_workers(struct worker_pool *pool)
8103 {
8104 	bool found_running = false;
8105 	struct worker *worker;
8106 	unsigned long irq_flags;
8107 	int cpu, bkt;
8108 
8109 	raw_spin_lock_irqsave(&pool->lock, irq_flags);
8110 
8111 	/* Snapshot cpu inside the lock to safely use it after unlock. */
8112 	cpu = pool->cpu;
8113 
8114 	hash_for_each(pool->busy_hash, bkt, worker, hentry) {
8115 		/* Skip workers that are not actively running on the CPU. */
8116 		if (!task_is_running(worker->task))
8117 			continue;
8118 
8119 		found_running = true;
8120 		/*
8121 		 * Defer printing to avoid deadlocks in console
8122 		 * drivers that queue work while holding locks
8123 		 * also taken in their write paths.
8124 		 */
8125 		printk_deferred_enter();
8126 
8127 		pr_info("pool %d:\n", pool->id);
8128 		sched_show_task(worker->task);
8129 
8130 		printk_deferred_exit();
8131 	}
8132 
8133 	/*
8134 	 * If no running worker was found, the pool is likely stuck. Print pool
8135 	 * state and the backtrace of the last woken worker, which is the prime
8136 	 * suspect for the stall.
8137 	 */
8138 	if (!found_running)
8139 		show_pool_no_running_worker(pool);
8140 
8141 	raw_spin_unlock_irqrestore(&pool->lock, irq_flags);
8142 
8143 	/*
8144 	 * Trigger a backtrace on the stalled CPU to capture what it is
8145 	 * currently executing. Skip an offline CPU, whose NMI is never acked
8146 	 * and would make the backtrace busy-wait until it times out. Done
8147 	 * after releasing the lock to avoid issues with NMI delivery.
8148 	 */
8149 	if (!found_running && cpu_online(cpu))
8150 		trigger_single_cpu_backtrace(cpu);
8151 }
8152 
8153 static void show_cpu_pools_busy_workers(void)
8154 {
8155 	struct worker_pool *pool;
8156 	int pi;
8157 
8158 	pr_info("Showing backtraces of busy workers in stalled worker pools:\n");
8159 
8160 	rcu_read_lock();
8161 
8162 	for_each_pool(pool, pi) {
8163 		if (pool->cpu_stall)
8164 			show_cpu_pool_busy_workers(pool);
8165 
8166 	}
8167 
8168 	rcu_read_unlock();
8169 }
8170 
8171 /*
8172  * It triggers a panic in two scenarios: when the total number of stalls
8173  * exceeds a threshold, and when a stall lasts longer than
8174  * wq_panic_on_stall_time
8175  */
8176 static void panic_on_wq_watchdog(unsigned int stall_time_sec)
8177 {
8178 	static unsigned int wq_stall;
8179 
8180 	if (wq_panic_on_stall) {
8181 		wq_stall++;
8182 		if (wq_stall >= wq_panic_on_stall)
8183 			panic("workqueue: %u stall(s) exceeded threshold %u\n",
8184 			      wq_stall, wq_panic_on_stall);
8185 	}
8186 
8187 	if (wq_panic_on_stall_time && stall_time_sec >= wq_panic_on_stall_time)
8188 		panic("workqueue: stall lasted %us, exceeding threshold %us\n",
8189 		      stall_time_sec, wq_panic_on_stall_time);
8190 }
8191 
8192 static void wq_watchdog_reset_touched(void)
8193 {
8194 	int cpu;
8195 
8196 	wq_watchdog_touched = jiffies;
8197 	for_each_possible_cpu(cpu)
8198 		per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
8199 }
8200 
8201 static void wq_watchdog_timer_fn(struct timer_list *unused)
8202 {
8203 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
8204 	unsigned int max_stall_time = 0;
8205 	bool lockup_detected = false;
8206 	bool cpu_pool_stall = false;
8207 	unsigned long now = jiffies;
8208 	struct worker_pool *pool;
8209 	unsigned int stall_time;
8210 	int pi;
8211 
8212 	if (!thresh)
8213 		return;
8214 
8215 	for_each_pool(pool, pi) {
8216 		unsigned long pool_ts, touched, ts;
8217 
8218 		pool->cpu_stall = false;
8219 		if (list_empty(&pool->worklist))
8220 			continue;
8221 
8222 		/*
8223 		 * If a virtual machine is stopped by the host it can look to
8224 		 * the watchdog like a stall.
8225 		 */
8226 		kvm_check_and_clear_guest_paused();
8227 
8228 		/* get the latest of pool and touched timestamps */
8229 		if (pool->cpu >= 0)
8230 			touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
8231 		else
8232 			touched = READ_ONCE(wq_watchdog_touched);
8233 		pool_ts = READ_ONCE(pool->last_progress_ts);
8234 
8235 		if (time_after(pool_ts, touched))
8236 			ts = pool_ts;
8237 		else
8238 			ts = touched;
8239 
8240 		/*
8241 		 * Did we stall?
8242 		 *
8243 		 * Do a lockless check first to do not disturb the system.
8244 		 *
8245 		 * Prevent false positives by double checking the timestamp
8246 		 * under pool->lock. The lock makes sure that the check reads
8247 		 * an updated pool->last_progress_ts when this CPU saw
8248 		 * an already updated pool->worklist above. It seems better
8249 		 * than adding another barrier into __queue_work() which
8250 		 * is a hotter path.
8251 		 */
8252 		if (time_after(now, ts + thresh)) {
8253 			scoped_guard(raw_spinlock_irqsave, &pool->lock) {
8254 				pool_ts = pool->last_progress_ts;
8255 				if (time_after(pool_ts, touched))
8256 					ts = pool_ts;
8257 				else
8258 					ts = touched;
8259 			}
8260 			if (!time_after(now, ts + thresh))
8261 				continue;
8262 
8263 			lockup_detected = true;
8264 			stall_time = jiffies_to_msecs(now - pool_ts) / 1000;
8265 			max_stall_time = max(max_stall_time, stall_time);
8266 			if (is_percpu_pool(pool) && !(pool->flags & POOL_BH)) {
8267 				pool->cpu_stall = true;
8268 				cpu_pool_stall = true;
8269 			}
8270 			pr_emerg("BUG: workqueue lockup - pool");
8271 			pr_cont_pool_info(pool);
8272 			pr_cont(" stuck for %us!\n", stall_time);
8273 		}
8274 	}
8275 
8276 	if (lockup_detected)
8277 		show_all_workqueues();
8278 
8279 	if (cpu_pool_stall)
8280 		show_cpu_pools_busy_workers();
8281 
8282 	if (lockup_detected)
8283 		panic_on_wq_watchdog(max_stall_time);
8284 
8285 	wq_watchdog_reset_touched();
8286 	mod_timer(&wq_watchdog_timer, jiffies + thresh);
8287 }
8288 
8289 notrace void wq_watchdog_touch(int cpu)
8290 {
8291 	unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
8292 	unsigned long touch_ts = READ_ONCE(wq_watchdog_touched);
8293 	unsigned long now = jiffies;
8294 
8295 	if (cpu >= 0)
8296 		per_cpu(wq_watchdog_touched_cpu, cpu) = now;
8297 	else
8298 		WARN_ONCE(1, "%s should be called with valid CPU", __func__);
8299 
8300 	/* Don't unnecessarily store to global cacheline */
8301 	if (time_after(now, touch_ts + thresh / 4))
8302 		WRITE_ONCE(wq_watchdog_touched, jiffies);
8303 }
8304 
8305 static void wq_watchdog_set_thresh(unsigned long thresh)
8306 {
8307 	wq_watchdog_thresh = 0;
8308 	timer_delete_sync(&wq_watchdog_timer);
8309 
8310 	if (thresh) {
8311 		wq_watchdog_thresh = thresh;
8312 		wq_watchdog_reset_touched();
8313 		mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
8314 	}
8315 }
8316 
8317 static int wq_watchdog_param_set_thresh(const char *val,
8318 					const struct kernel_param *kp)
8319 {
8320 	unsigned long thresh;
8321 	int ret;
8322 
8323 	ret = kstrtoul(val, 0, &thresh);
8324 	if (ret)
8325 		return ret;
8326 
8327 	if (thresh > MAX_JIFFY_OFFSET / HZ)
8328 		return -ERANGE;
8329 
8330 	if (system_percpu_wq)
8331 		wq_watchdog_set_thresh(thresh);
8332 	else
8333 		wq_watchdog_thresh = thresh;
8334 
8335 	return 0;
8336 }
8337 
8338 static const struct kernel_param_ops wq_watchdog_thresh_ops = {
8339 	.set	= wq_watchdog_param_set_thresh,
8340 	.get	= param_get_ulong,
8341 };
8342 
8343 module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
8344 		0644);
8345 
8346 static void wq_watchdog_init(void)
8347 {
8348 	timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
8349 	wq_watchdog_set_thresh(wq_watchdog_thresh);
8350 }
8351 
8352 #else	/* CONFIG_WQ_WATCHDOG */
8353 
8354 static inline void wq_watchdog_init(void) { }
8355 
8356 #endif	/* CONFIG_WQ_WATCHDOG */
8357 
8358 static void bh_pool_kick_normal(struct irq_work *irq_work)
8359 {
8360 	raise_softirq(TASKLET_SOFTIRQ);
8361 }
8362 
8363 static void bh_pool_kick_highpri(struct irq_work *irq_work)
8364 {
8365 	raise_softirq(HI_SOFTIRQ);
8366 }
8367 
8368 static void __init restrict_unbound_cpumask(const char *name, const struct cpumask *mask)
8369 {
8370 	if (!cpumask_intersects(wq_unbound_cpumask, mask)) {
8371 		pr_warn("workqueue: Restricting unbound_cpumask (%*pb) with %s (%*pb) leaves no CPU, ignoring\n",
8372 			cpumask_pr_args(wq_unbound_cpumask), name, cpumask_pr_args(mask));
8373 		return;
8374 	}
8375 
8376 	cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, mask);
8377 }
8378 
8379 static void __init init_cpu_worker_pool(struct worker_pool *pool, int cpu, int nice)
8380 {
8381 	BUG_ON(init_worker_pool(pool));
8382 	pool->cpu = cpu;
8383 	cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
8384 	cpumask_copy(pool->attrs->__pod_cpumask, cpumask_of(cpu));
8385 	pool->attrs->nice = nice;
8386 	pool->attrs->affn_strict = true;
8387 	pool->node = cpu_to_node(cpu);
8388 
8389 	/* alloc pool ID */
8390 	mutex_lock(&wq_pool_mutex);
8391 	BUG_ON(worker_pool_assign_id(pool));
8392 	mutex_unlock(&wq_pool_mutex);
8393 }
8394 
8395 /**
8396  * workqueue_init_early - early init for workqueue subsystem
8397  *
8398  * This is the first step of three-staged workqueue subsystem initialization and
8399  * invoked as soon as the bare basics - memory allocation, cpumasks and idr are
8400  * up. It sets up all the data structures and system workqueues and allows early
8401  * boot code to create workqueues and queue/cancel work items. Actual work item
8402  * execution starts only after kthreads can be created and scheduled right
8403  * before early initcalls.
8404  */
8405 void __init workqueue_init_early(void)
8406 {
8407 	struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_SYSTEM];
8408 	int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
8409 	void (*irq_work_fns[NR_STD_WORKER_POOLS])(struct irq_work *) =
8410 		{ bh_pool_kick_normal, bh_pool_kick_highpri };
8411 	int i, cpu;
8412 
8413 	BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
8414 
8415 	BUG_ON(!alloc_cpumask_var(&wq_online_cpumask, GFP_KERNEL));
8416 	BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
8417 	BUG_ON(!alloc_cpumask_var(&wq_requested_unbound_cpumask, GFP_KERNEL));
8418 	BUG_ON(!zalloc_cpumask_var(&wq_isolated_cpumask, GFP_KERNEL));
8419 
8420 	cpumask_copy(wq_online_cpumask, cpu_online_mask);
8421 	cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
8422 	restrict_unbound_cpumask("HK_TYPE_DOMAIN", housekeeping_cpumask(HK_TYPE_DOMAIN));
8423 	if (!cpumask_empty(&wq_cmdline_cpumask))
8424 		restrict_unbound_cpumask("workqueue.unbound_cpus", &wq_cmdline_cpumask);
8425 
8426 	cpumask_copy(wq_requested_unbound_cpumask, wq_unbound_cpumask);
8427 	cpumask_andnot(wq_isolated_cpumask, cpu_possible_mask,
8428 						housekeeping_cpumask(HK_TYPE_DOMAIN));
8429 	pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
8430 
8431 	unbound_wq_update_pwq_attrs_buf = alloc_workqueue_attrs();
8432 	BUG_ON(!unbound_wq_update_pwq_attrs_buf);
8433 
8434 	/*
8435 	 * If nohz_full is enabled, set power efficient workqueue as unbound.
8436 	 * This allows workqueue items to be moved to HK CPUs.
8437 	 */
8438 	if (housekeeping_enabled(HK_TYPE_TICK))
8439 		wq_power_efficient = true;
8440 
8441 	/* initialize WQ_AFFN_SYSTEM pods */
8442 	pt->pod_cpus = kzalloc_objs(pt->pod_cpus[0], 1);
8443 	pt->pod_node = kzalloc_objs(pt->pod_node[0], 1);
8444 	pt->cpu_pod = kzalloc_objs(pt->cpu_pod[0], nr_cpu_ids);
8445 	BUG_ON(!pt->pod_cpus || !pt->pod_node || !pt->cpu_pod);
8446 
8447 	BUG_ON(!zalloc_cpumask_var_node(&pt->pod_cpus[0], GFP_KERNEL, NUMA_NO_NODE));
8448 
8449 	pt->nr_pods = 1;
8450 	cpumask_copy(pt->pod_cpus[0], cpu_possible_mask);
8451 	pt->pod_node[0] = NUMA_NO_NODE;
8452 	pt->cpu_pod[0] = 0;
8453 
8454 	/* initialize BH and CPU pools */
8455 	for_each_possible_cpu(cpu) {
8456 		struct worker_pool *pool;
8457 
8458 		i = 0;
8459 		for_each_bh_worker_pool(pool, cpu) {
8460 			init_cpu_worker_pool(pool, cpu, std_nice[i]);
8461 			pool->flags |= POOL_BH;
8462 			init_irq_work(bh_pool_irq_work(pool), irq_work_fns[i]);
8463 			i++;
8464 		}
8465 
8466 		i = 0;
8467 		for_each_cpu_worker_pool(pool, cpu)
8468 			init_cpu_worker_pool(pool, cpu, std_nice[i++]);
8469 	}
8470 
8471 	system_wq = alloc_workqueue("events", WQ_PERCPU | __WQ_DEPRECATED, 0);
8472 	system_percpu_wq = alloc_workqueue("events", WQ_PERCPU, 0);
8473 	system_highpri_wq = alloc_workqueue("events_highpri",
8474 					    WQ_HIGHPRI | WQ_PERCPU, 0);
8475 	system_long_wq = alloc_workqueue("events_long", WQ_PERCPU, 0);
8476 	system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND | __WQ_DEPRECATED, WQ_MAX_ACTIVE);
8477 	system_dfl_wq = alloc_workqueue("events_unbound", WQ_UNBOUND, WQ_MAX_ACTIVE);
8478 	system_freezable_wq = alloc_workqueue("events_freezable",
8479 					      WQ_FREEZABLE | WQ_PERCPU, 0);
8480 	system_power_efficient_wq = alloc_workqueue("events_power_efficient",
8481 					      WQ_POWER_EFFICIENT | WQ_PERCPU, 0);
8482 	system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_pwr_efficient",
8483 					      WQ_FREEZABLE | WQ_POWER_EFFICIENT | WQ_PERCPU, 0);
8484 	system_bh_wq = alloc_workqueue("events_bh", WQ_BH | WQ_PERCPU, 0);
8485 	system_bh_highpri_wq = alloc_workqueue("events_bh_highpri",
8486 					       WQ_BH | WQ_HIGHPRI | WQ_PERCPU, 0);
8487 	system_dfl_long_wq = alloc_workqueue("events_dfl_long", WQ_UNBOUND, WQ_MAX_ACTIVE);
8488 	BUG_ON(!system_wq || !system_percpu_wq|| !system_highpri_wq || !system_long_wq ||
8489 	       !system_unbound_wq || !system_freezable_wq || !system_dfl_wq ||
8490 	       !system_power_efficient_wq ||
8491 	       !system_freezable_power_efficient_wq ||
8492 	       !system_bh_wq || !system_bh_highpri_wq || !system_dfl_long_wq);
8493 }
8494 
8495 static void __init wq_cpu_intensive_thresh_init(void)
8496 {
8497 	unsigned long thresh;
8498 	unsigned long bogo;
8499 
8500 	pwq_release_worker = kthread_run_worker(0, "pool_workqueue_release");
8501 	BUG_ON(IS_ERR(pwq_release_worker));
8502 
8503 	/* if the user set it to a specific value, keep it */
8504 	if (wq_cpu_intensive_thresh_us != ULONG_MAX)
8505 		return;
8506 
8507 	/*
8508 	 * The default of 10ms is derived from the fact that most modern (as of
8509 	 * 2023) processors can do a lot in 10ms and that it's just below what
8510 	 * most consider human-perceivable. However, the kernel also runs on a
8511 	 * lot slower CPUs including microcontrollers where the threshold is way
8512 	 * too low.
8513 	 *
8514 	 * Let's scale up the threshold up to 1 second if BogoMips is below 4000.
8515 	 * This is by no means accurate but it doesn't have to be. The mechanism
8516 	 * is still useful even when the threshold is fully scaled up. Also, as
8517 	 * the reports would usually be applicable to everyone, some machines
8518 	 * operating on longer thresholds won't significantly diminish their
8519 	 * usefulness.
8520 	 */
8521 	thresh = 10 * USEC_PER_MSEC;
8522 
8523 	/* see init/calibrate.c for lpj -> BogoMIPS calculation */
8524 	bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
8525 	if (bogo < 4000)
8526 		thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
8527 
8528 	pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
8529 		 loops_per_jiffy, bogo, thresh);
8530 
8531 	wq_cpu_intensive_thresh_us = thresh;
8532 }
8533 
8534 /**
8535  * workqueue_init - bring workqueue subsystem fully online
8536  *
8537  * This is the second step of three-staged workqueue subsystem initialization
8538  * and invoked as soon as kthreads can be created and scheduled. Workqueues have
8539  * been created and work items queued on them, but there are no kworkers
8540  * executing the work items yet. Populate the worker pools with the initial
8541  * workers and enable future kworker creations.
8542  */
8543 void __init workqueue_init(void)
8544 {
8545 	struct workqueue_struct *wq;
8546 	struct worker_pool *pool;
8547 	int cpu, bkt;
8548 
8549 	wq_cpu_intensive_thresh_init();
8550 
8551 	mutex_lock(&wq_pool_mutex);
8552 
8553 	/*
8554 	 * Per-cpu pools created earlier could be missing node hint. Fix them
8555 	 * up. Also, create a rescuer for workqueues that requested it.
8556 	 */
8557 	for_each_possible_cpu(cpu) {
8558 		for_each_bh_worker_pool(pool, cpu)
8559 			pool->node = cpu_to_node(cpu);
8560 		for_each_cpu_worker_pool(pool, cpu)
8561 			pool->node = cpu_to_node(cpu);
8562 	}
8563 
8564 	list_for_each_entry(wq, &workqueues, list) {
8565 		WARN(init_rescuer(wq),
8566 		     "workqueue: failed to create early rescuer for %s",
8567 		     wq->name);
8568 	}
8569 
8570 	mutex_unlock(&wq_pool_mutex);
8571 
8572 	/*
8573 	 * Create the initial workers. A BH pool has one pseudo worker that
8574 	 * represents the shared BH execution context and thus doesn't get
8575 	 * affected by hotplug events. Create the BH pseudo workers for all
8576 	 * possible CPUs here.
8577 	 */
8578 	for_each_possible_cpu(cpu)
8579 		for_each_bh_worker_pool(pool, cpu)
8580 			BUG_ON(!create_worker(pool));
8581 
8582 	for_each_online_cpu(cpu) {
8583 		for_each_cpu_worker_pool(pool, cpu) {
8584 			pool->flags &= ~POOL_DISASSOCIATED;
8585 			BUG_ON(!create_worker(pool));
8586 		}
8587 	}
8588 
8589 	hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
8590 		BUG_ON(!create_worker(pool));
8591 
8592 	wq_online = true;
8593 	wq_watchdog_init();
8594 }
8595 
8596 /*
8597  * Initialize @pt by first initializing @pt->cpu_pod[] with pod IDs according to
8598  * @cpu_shares_pod(). Each subset of CPUs that share a pod is assigned a unique
8599  * and consecutive pod ID. The rest of @pt is initialized accordingly.
8600  */
8601 static void __init init_pod_type(struct wq_pod_type *pt,
8602 				 bool (*cpus_share_pod)(int, int))
8603 {
8604 	int cur, pre, cpu, pod;
8605 
8606 	pt->nr_pods = 0;
8607 
8608 	/* init @pt->cpu_pod[] according to @cpus_share_pod() */
8609 	pt->cpu_pod = kzalloc_objs(pt->cpu_pod[0], nr_cpu_ids);
8610 	BUG_ON(!pt->cpu_pod);
8611 
8612 	for_each_possible_cpu(cur) {
8613 		for_each_possible_cpu(pre) {
8614 			if (pre >= cur) {
8615 				pt->cpu_pod[cur] = pt->nr_pods++;
8616 				break;
8617 			}
8618 			if (cpus_share_pod(cur, pre)) {
8619 				pt->cpu_pod[cur] = pt->cpu_pod[pre];
8620 				break;
8621 			}
8622 		}
8623 	}
8624 
8625 	/* init the rest to match @pt->cpu_pod[] */
8626 	pt->pod_cpus = kzalloc_objs(pt->pod_cpus[0], pt->nr_pods);
8627 	pt->pod_node = kzalloc_objs(pt->pod_node[0], pt->nr_pods);
8628 	BUG_ON(!pt->pod_cpus || !pt->pod_node);
8629 
8630 	for (pod = 0; pod < pt->nr_pods; pod++)
8631 		BUG_ON(!zalloc_cpumask_var(&pt->pod_cpus[pod], GFP_KERNEL));
8632 
8633 	for_each_possible_cpu(cpu) {
8634 		cpumask_set_cpu(cpu, pt->pod_cpus[pt->cpu_pod[cpu]]);
8635 		pt->pod_node[pt->cpu_pod[cpu]] = cpu_to_node(cpu);
8636 	}
8637 }
8638 
8639 static bool __init cpus_dont_share(int cpu0, int cpu1)
8640 {
8641 	return false;
8642 }
8643 
8644 static bool __init cpus_share_smt(int cpu0, int cpu1)
8645 {
8646 	return cpumask_test_cpu(cpu0, cpu_smt_mask(cpu1));
8647 }
8648 
8649 static bool __init cpus_share_numa(int cpu0, int cpu1)
8650 {
8651 	return cpu_to_node(cpu0) == cpu_to_node(cpu1);
8652 }
8653 
8654 /* Maps each CPU to its shard index within the LLC pod it belongs to */
8655 static int cpu_shard_id[NR_CPUS] __initdata;
8656 
8657 /**
8658  * llc_count_cores - count distinct cores (SMT groups) within an LLC pod
8659  * @pod_cpus:  the cpumask of CPUs in the LLC pod
8660  * @smt_pods:  the SMT pod type, used to identify sibling groups
8661  *
8662  * A core is represented by the lowest-numbered CPU in its SMT group. Returns
8663  * the number of distinct cores found in @pod_cpus.
8664  */
8665 static int __init llc_count_cores(const struct cpumask *pod_cpus,
8666 				  struct wq_pod_type *smt_pods)
8667 {
8668 	const struct cpumask *sibling_cpus;
8669 	int nr_cores = 0, c;
8670 
8671 	/*
8672 	 * Count distinct cores by only counting the first CPU in each
8673 	 * SMT sibling group.
8674 	 */
8675 	for_each_cpu(c, pod_cpus) {
8676 		sibling_cpus = smt_pods->pod_cpus[smt_pods->cpu_pod[c]];
8677 		if (cpumask_first(sibling_cpus) == c)
8678 			nr_cores++;
8679 	}
8680 
8681 	return nr_cores;
8682 }
8683 
8684 /*
8685  * llc_shard_size - number of cores in a given shard
8686  *
8687  * Cores are spread as evenly as possible. The first @nr_large_shards shards are
8688  * "large shards" with (cores_per_shard + 1) cores; the rest are "default
8689  * shards" with cores_per_shard cores.
8690  */
8691 static int __init llc_shard_size(int shard_id, int cores_per_shard, int nr_large_shards)
8692 {
8693 	/* The first @nr_large_shards shards are large shards */
8694 	if (shard_id < nr_large_shards)
8695 		return cores_per_shard + 1;
8696 
8697 	/* The remaining shards are default shards */
8698 	return cores_per_shard;
8699 }
8700 
8701 /*
8702  * llc_calc_shard_layout - compute the shard layout for an LLC pod
8703  * @nr_cores:  number of distinct cores in the LLC pod
8704  *
8705  * Chooses the number of shards that keeps average shard size closest to
8706  * wq_cache_shard_size. Returns a struct describing the total number of shards,
8707  * the base size of each, and how many are large shards.
8708  */
8709 static struct llc_shard_layout __init llc_calc_shard_layout(int nr_cores)
8710 {
8711 	struct llc_shard_layout layout;
8712 
8713 	/* Ensure at least one shard; pick the count closest to the target size */
8714 	layout.nr_shards = max(1, DIV_ROUND_CLOSEST(nr_cores, wq_cache_shard_size));
8715 	layout.cores_per_shard = nr_cores / layout.nr_shards;
8716 	layout.nr_large_shards = nr_cores % layout.nr_shards;
8717 
8718 	return layout;
8719 }
8720 
8721 /*
8722  * llc_shard_is_full - check whether a shard has reached its core capacity
8723  * @cores_in_shard: number of cores already assigned to this shard
8724  * @shard_id:       index of the shard being checked
8725  * @layout:         the shard layout computed by llc_calc_shard_layout()
8726  *
8727  * Returns true if @cores_in_shard equals the expected size for @shard_id.
8728  */
8729 static bool __init llc_shard_is_full(int cores_in_shard, int shard_id,
8730 				     const struct llc_shard_layout *layout)
8731 {
8732 	return cores_in_shard == llc_shard_size(shard_id, layout->cores_per_shard,
8733 						layout->nr_large_shards);
8734 }
8735 
8736 /**
8737  * llc_populate_cpu_shard_id - populate cpu_shard_id[] for each CPU in an LLC pod
8738  * @pod_cpus:  the cpumask of CPUs in the LLC pod
8739  * @smt_pods:  the SMT pod type, used to identify sibling groups
8740  * @nr_cores:  number of distinct cores in @pod_cpus (from llc_count_cores())
8741  *
8742  * Walks @pod_cpus in order. At each SMT group leader, advances to the next
8743  * shard once the current shard is full. Results are written to cpu_shard_id[].
8744  */
8745 static void __init llc_populate_cpu_shard_id(const struct cpumask *pod_cpus,
8746 					     struct wq_pod_type *smt_pods,
8747 					     int nr_cores)
8748 {
8749 	struct llc_shard_layout layout = llc_calc_shard_layout(nr_cores);
8750 	const struct cpumask *sibling_cpus;
8751 	/* Count the number of cores in the current shard_id */
8752 	int cores_in_shard = 0;
8753 	unsigned int leader;
8754 	/* This is a cursor for the shards. Go from zero to nr_shards - 1*/
8755 	int shard_id = 0;
8756 	int c;
8757 
8758 	/* Iterate at every CPU for a given LLC pod, and assign it a shard */
8759 	for_each_cpu(c, pod_cpus) {
8760 		sibling_cpus = smt_pods->pod_cpus[smt_pods->cpu_pod[c]];
8761 		if (cpumask_first(sibling_cpus) == c) {
8762 			/* This is the CPU leader for the siblings */
8763 			if (llc_shard_is_full(cores_in_shard, shard_id, &layout)) {
8764 				shard_id++;
8765 				cores_in_shard = 0;
8766 			}
8767 			cores_in_shard++;
8768 			cpu_shard_id[c] = shard_id;
8769 		} else {
8770 			/*
8771 			 * The siblings' shard MUST be the same as the leader.
8772 			 * never split threads in the same core.
8773 			 */
8774 			leader = cpumask_first(sibling_cpus);
8775 
8776 			/*
8777 			 * This check silences a Warray-bounds warning on UP
8778 			 * configs where NR_CPUS=1 makes cpu_shard_id[]
8779 			 * a single-element array, and the compiler can't
8780 			 * prove the index is always 0.
8781 			 */
8782 			if (WARN_ON_ONCE(leader >= nr_cpu_ids))
8783 				continue;
8784 			cpu_shard_id[c] = cpu_shard_id[leader];
8785 		}
8786 	}
8787 
8788 	WARN_ON_ONCE(shard_id != (layout.nr_shards - 1));
8789 }
8790 
8791 /**
8792  * precompute_cache_shard_ids - assign each CPU its shard index within its LLC
8793  *
8794  * Iterates over all LLC pods. For each pod, counts distinct cores then assigns
8795  * shard indices to all CPUs in the pod. Must be called after WQ_AFFN_CACHE and
8796  * WQ_AFFN_SMT have been initialized.
8797  */
8798 static void __init precompute_cache_shard_ids(void)
8799 {
8800 	struct wq_pod_type *llc_pods = &wq_pod_types[WQ_AFFN_CACHE];
8801 	struct wq_pod_type *smt_pods = &wq_pod_types[WQ_AFFN_SMT];
8802 	const struct cpumask *cpus_sharing_llc;
8803 	int nr_cores;
8804 	int pod;
8805 
8806 	if (!wq_cache_shard_size) {
8807 		pr_warn("workqueue: cache_shard_size must be > 0, setting to 1\n");
8808 		wq_cache_shard_size = 1;
8809 	}
8810 
8811 	for (pod = 0; pod < llc_pods->nr_pods; pod++) {
8812 		cpus_sharing_llc = llc_pods->pod_cpus[pod];
8813 
8814 		/* Number of cores in this given LLC */
8815 		nr_cores = llc_count_cores(cpus_sharing_llc, smt_pods);
8816 		llc_populate_cpu_shard_id(cpus_sharing_llc, smt_pods, nr_cores);
8817 	}
8818 }
8819 
8820 /*
8821  * cpus_share_cache_shard - test whether two CPUs belong to the same cache shard
8822  *
8823  * Two CPUs share a cache shard if they are in the same LLC and have the same
8824  * shard index. Used as the pod affinity callback for WQ_AFFN_CACHE_SHARD.
8825  */
8826 static bool __init cpus_share_cache_shard(int cpu0, int cpu1)
8827 {
8828 	if (!cpus_share_cache(cpu0, cpu1))
8829 		return false;
8830 
8831 	return cpu_shard_id[cpu0] == cpu_shard_id[cpu1];
8832 }
8833 
8834 /**
8835  * workqueue_init_topology - initialize CPU pods for unbound workqueues
8836  *
8837  * This is the third step of three-staged workqueue subsystem initialization and
8838  * invoked after SMP and topology information are fully initialized. It
8839  * initializes the unbound CPU pods accordingly.
8840  */
8841 void __init workqueue_init_topology(void)
8842 {
8843 	struct workqueue_struct *wq;
8844 	int cpu;
8845 
8846 	init_pod_type(&wq_pod_types[WQ_AFFN_CPU], cpus_dont_share);
8847 	init_pod_type(&wq_pod_types[WQ_AFFN_SMT], cpus_share_smt);
8848 	init_pod_type(&wq_pod_types[WQ_AFFN_CACHE], cpus_share_cache);
8849 	precompute_cache_shard_ids();
8850 	init_pod_type(&wq_pod_types[WQ_AFFN_CACHE_SHARD], cpus_share_cache_shard);
8851 	init_pod_type(&wq_pod_types[WQ_AFFN_NUMA], cpus_share_numa);
8852 
8853 	wq_topo_initialized = true;
8854 
8855 	mutex_lock(&wq_pool_mutex);
8856 
8857 	/*
8858 	 * Workqueues allocated earlier would have all CPUs sharing the default
8859 	 * worker pool. Explicitly call unbound_wq_update_pwq() on all workqueue
8860 	 * and CPU combinations to apply per-pod sharing.
8861 	 */
8862 	list_for_each_entry(wq, &workqueues, list) {
8863 		for_each_online_cpu(cpu)
8864 			unbound_wq_update_pwq(wq, cpu);
8865 		if (wq->flags & WQ_UNBOUND) {
8866 			mutex_lock(&wq->mutex);
8867 			wq_update_node_max_active(wq, -1);
8868 			mutex_unlock(&wq->mutex);
8869 		}
8870 	}
8871 
8872 	mutex_unlock(&wq_pool_mutex);
8873 }
8874 
8875 void __warn_flushing_systemwide_wq(void)
8876 {
8877 	pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
8878 	dump_stack();
8879 }
8880 EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
8881 
8882 static int __init workqueue_unbound_cpus_setup(char *str)
8883 {
8884 	if (cpulist_parse(str, &wq_cmdline_cpumask) < 0) {
8885 		cpumask_clear(&wq_cmdline_cpumask);
8886 		pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
8887 	}
8888 
8889 	return 1;
8890 }
8891 __setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup);
8892