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