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