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