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