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