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