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