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