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