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

source code of linux/kernel/workqueue.c