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