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