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