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