1 // SPDX-License-Identifier: GPL-2.0-only
3 * kernel/workqueue.c - generic async execution with shared worker pool
5 * Copyright (C) 2002 Ingo Molnar
7 * Derived from the taskqueue/keventd code by:
8 * David Woodhouse <dwmw2@infradead.org>
10 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
11 * Theodore Ts'o <tytso@mit.edu>
13 * Made to use alloc_percpu by Christoph Lameter.
15 * Copyright (C) 2010 SUSE Linux Products GmbH
16 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
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.
25 * Please read Documentation/core-api/workqueue.rst for details.
28 #include <linux/export.h>
29 #include <linux/kernel.h>
30 #include <linux/sched.h>
31 #include <linux/init.h>
32 #include <linux/interrupt.h>
33 #include <linux/signal.h>
34 #include <linux/completion.h>
35 #include <linux/workqueue.h>
36 #include <linux/slab.h>
37 #include <linux/cpu.h>
38 #include <linux/notifier.h>
39 #include <linux/kthread.h>
40 #include <linux/hardirq.h>
41 #include <linux/mempolicy.h>
42 #include <linux/freezer.h>
43 #include <linux/debug_locks.h>
44 #include <linux/device/devres.h>
45 #include <linux/lockdep.h>
46 #include <linux/idr.h>
47 #include <linux/jhash.h>
48 #include <linux/hashtable.h>
49 #include <linux/rculist.h>
50 #include <linux/nodemask.h>
51 #include <linux/moduleparam.h>
52 #include <linux/uaccess.h>
53 #include <linux/sched/isolation.h>
54 #include <linux/sched/debug.h>
55 #include <linux/nmi.h>
56 #include <linux/kvm_para.h>
57 #include <linux/delay.h>
58 #include <linux/irq_work.h>
60 #include "workqueue_internal.h"
62 enum worker_pool_flags
{
66 * A bound pool is either associated or disassociated with its CPU.
67 * While associated (!DISASSOCIATED), all workers are bound to the
68 * CPU and none has %WORKER_UNBOUND set and concurrency management
71 * While DISASSOCIATED, the cpu may be offline and all workers have
72 * %WORKER_UNBOUND set and concurrency management disabled, and may
73 * be executing on any CPU. The pool behaves as an unbound one.
75 * Note that DISASSOCIATED should be flipped only while holding
76 * wq_pool_attach_mutex to avoid changing binding state while
77 * worker_attach_to_pool() is in progress.
79 * As there can only be one concurrent BH execution context per CPU, a
80 * BH pool is per-CPU and always DISASSOCIATED.
82 POOL_BH
= 1 << 0, /* is a BH pool */
83 POOL_MANAGER_ACTIVE
= 1 << 1, /* being managed */
84 POOL_DISASSOCIATED
= 1 << 2, /* cpu can't serve workers */
85 POOL_BH_DRAINING
= 1 << 3, /* draining after CPU offline */
90 WORKER_DIE
= 1 << 1, /* die die die */
91 WORKER_IDLE
= 1 << 2, /* is idle */
92 WORKER_PREP
= 1 << 3, /* preparing to run works */
93 WORKER_CPU_INTENSIVE
= 1 << 6, /* cpu intensive */
94 WORKER_UNBOUND
= 1 << 7, /* worker is unbound */
95 WORKER_REBOUND
= 1 << 8, /* worker was rebound */
97 WORKER_NOT_RUNNING
= WORKER_PREP
| WORKER_CPU_INTENSIVE
|
98 WORKER_UNBOUND
| WORKER_REBOUND
,
101 enum work_cancel_flags
{
102 WORK_CANCEL_DELAYED
= 1 << 0, /* canceling a delayed_work */
103 WORK_CANCEL_DISABLE
= 1 << 1, /* canceling to disable */
106 enum wq_internal_consts
{
107 NR_STD_WORKER_POOLS
= 2, /* # standard pools per cpu */
109 UNBOUND_POOL_HASH_ORDER
= 6, /* hashed by pool->attrs */
110 BUSY_WORKER_HASH_ORDER
= 6, /* 64 pointers */
112 MAX_IDLE_WORKERS_RATIO
= 4, /* 1/4 of busy can be idle */
113 IDLE_WORKER_TIMEOUT
= 300 * HZ
, /* keep idle ones for 5 mins */
115 MAYDAY_INITIAL_TIMEOUT
= HZ
/ 100 >= 2 ? HZ
/ 100 : 2,
116 /* call for help after 10ms
118 MAYDAY_INTERVAL
= HZ
/ 10, /* and then every 100ms */
119 CREATE_COOLDOWN
= HZ
, /* time to breath after fail */
121 RESCUER_BATCH
= 16, /* process items per turn */
124 * Rescue workers are used only on emergencies and shared by
125 * all cpus. Give MIN_NICE.
127 RESCUER_NICE_LEVEL
= MIN_NICE
,
128 HIGHPRI_NICE_LEVEL
= MIN_NICE
,
131 WORKER_ID_LEN
= 10 + WQ_NAME_LEN
, /* "kworker/R-" + WQ_NAME_LEN */
134 /* Layout of shards within one LLC pod */
135 struct llc_shard_layout
{
136 int nr_large_shards
; /* number of large shards (cores_per_shard + 1) */
137 int cores_per_shard
; /* base number of cores per default shard */
138 int nr_shards
; /* total number of shards */
139 /* nr_default shards = (nr_shards - nr_large_shards) */
143 * We don't want to trap softirq for too long. See MAX_SOFTIRQ_TIME and
144 * MAX_SOFTIRQ_RESTART in kernel/softirq.c. These are macros because
145 * msecs_to_jiffies() can't be an initializer.
147 #define BH_WORKER_JIFFIES msecs_to_jiffies(2)
148 #define BH_WORKER_RESTARTS 10
151 * Structure fields follow one of the following exclusion rules.
153 * I: Modifiable by initialization/destruction paths and read-only for
156 * P: Preemption protected. Disabling preemption is enough and should
157 * only be modified and accessed from the local cpu.
159 * L: pool->lock protected. Access with pool->lock held.
161 * LN: pool->lock and wq_node_nr_active->lock protected for writes. Either for
164 * K: Only modified by worker while holding pool->lock. Can be safely read by
165 * self, while holding pool->lock or from IRQ context if %current is the
168 * S: Only modified by worker self.
170 * A: wq_pool_attach_mutex protected.
172 * PL: wq_pool_mutex protected.
174 * PR: wq_pool_mutex protected for writes. RCU protected for reads.
176 * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
178 * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
181 * WQ: wq->mutex protected.
183 * WR: wq->mutex protected for writes. RCU protected for reads.
185 * WO: wq->mutex protected for writes. Updated with WRITE_ONCE() and can be read
186 * with READ_ONCE() without locking.
188 * MD: wq_mayday_lock protected.
190 * WD: Used internally by the watchdog.
193 /* struct worker is defined in workqueue_internal.h */
196 raw_spinlock_t lock
; /* the pool lock */
197 int cpu
; /* I: the associated cpu */
198 int node
; /* I: the associated node ID */
199 int id
; /* I: pool ID */
200 unsigned int flags
; /* L: flags */
202 unsigned long last_progress_ts
; /* L: last forward progress timestamp */
203 bool cpu_stall
; /* WD: stalled cpu bound pool */
206 * The counter is incremented in a process context on the associated CPU
207 * w/ preemption disabled, and decremented or reset in the same context
208 * but w/ pool->lock held. The readers grab pool->lock and are
209 * guaranteed to see if the counter reached zero.
213 struct list_head worklist
; /* L: list of pending works */
215 int nr_workers
; /* L: total number of workers */
216 int nr_idle
; /* L: currently idle workers */
218 struct list_head idle_list
; /* L: list of idle workers */
219 struct timer_list idle_timer
; /* L: worker idle timeout */
220 struct work_struct idle_cull_work
; /* L: worker idle cleanup */
222 struct timer_list mayday_timer
; /* L: SOS timer for workers */
224 /* a workers is either on busy_hash or idle_list, or the manager */
225 DECLARE_HASHTABLE(busy_hash
, BUSY_WORKER_HASH_ORDER
);
226 /* L: hash of busy workers */
228 struct worker
*manager
; /* L: purely informational */
229 struct list_head workers
; /* A: attached workers */
231 struct ida worker_ida
; /* worker IDs for task name */
233 struct workqueue_attrs
*attrs
; /* I: worker attributes */
234 struct hlist_node hash_node
; /* PL: unbound_pool_hash node */
235 int refcnt
; /* PL: refcnt for unbound pools */
236 #ifdef CONFIG_PREEMPT_RT
237 spinlock_t cb_lock
; /* BH worker cancel lock */
240 * Destruction of pool is RCU protected to allow dereferences
241 * from get_work_pool().
247 * Per-pool_workqueue statistics. These can be monitored using
248 * tools/workqueue/wq_monitor.py.
250 enum pool_workqueue_stats
{
251 PWQ_STAT_STARTED
, /* work items started execution */
252 PWQ_STAT_COMPLETED
, /* work items completed execution */
253 PWQ_STAT_CPU_TIME
, /* total CPU time consumed */
254 PWQ_STAT_CPU_INTENSIVE
, /* wq_cpu_intensive_thresh_us violations */
255 PWQ_STAT_CM_WAKEUP
, /* concurrency-management worker wakeups */
256 PWQ_STAT_REPATRIATED
, /* unbound workers brought back into scope */
257 PWQ_STAT_MAYDAY
, /* maydays to rescuer */
258 PWQ_STAT_RESCUED
, /* linked work items executed by rescuer */
264 * The per-pool workqueue. While queued, bits below WORK_PWQ_SHIFT
265 * of work_struct->data are used for flags and the remaining high bits
266 * point to the pwq; thus, pwqs need to be aligned at two's power of the
267 * number of flag bits.
269 struct pool_workqueue
{
270 struct worker_pool
*pool
; /* I: the associated pool */
271 struct workqueue_struct
*wq
; /* I: the owning workqueue */
272 int work_color
; /* L: current color */
273 int flush_color
; /* L: flushing color */
274 int refcnt
; /* L: reference count */
275 int nr_in_flight
[WORK_NR_COLORS
];
276 /* L: nr of in_flight works */
277 bool plugged
; /* L: execution suspended */
280 * nr_active management and WORK_STRUCT_INACTIVE:
282 * When pwq->nr_active >= max_active, new work item is queued to
283 * pwq->inactive_works instead of pool->worklist and marked with
284 * WORK_STRUCT_INACTIVE.
286 * All work items marked with WORK_STRUCT_INACTIVE do not participate in
287 * nr_active and all work items in pwq->inactive_works are marked with
288 * WORK_STRUCT_INACTIVE. But not all WORK_STRUCT_INACTIVE work items are
289 * in pwq->inactive_works. Some of them are ready to run in
290 * pool->worklist or worker->scheduled. Those work itmes are only struct
291 * wq_barrier which is used for flush_work() and should not participate
292 * in nr_active. For non-barrier work item, it is marked with
293 * WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
295 int nr_active
; /* L: nr of active works */
296 struct list_head inactive_works
; /* L: inactive works */
297 struct list_head pending_node
; /* LN: node on wq_node_nr_active->pending_pwqs */
298 struct list_head pwqs_node
; /* WR: node on wq->pwqs */
299 struct list_head mayday_node
; /* MD: node on wq->maydays */
300 struct work_struct mayday_cursor
; /* L: cursor on pool->worklist */
302 u64 stats
[PWQ_NR_STATS
];
305 * Release of unbound pwq is punted to a kthread_worker. See put_pwq()
306 * and pwq_release_workfn() for details. pool_workqueue itself is also
307 * RCU protected so that the first pwq can be determined without
308 * grabbing wq->mutex.
310 struct kthread_work release_work
;
312 } __aligned(1 << WORK_STRUCT_PWQ_SHIFT
);
315 * Structure used to wait for workqueue flush.
318 struct list_head list
; /* WQ: list of flushers */
319 int flush_color
; /* WQ: flush color waiting for */
320 struct completion done
; /* flush completion */
326 * Unlike in a per-cpu workqueue where max_active limits its concurrency level
327 * on each CPU, in an unbound workqueue, max_active applies to the whole system.
328 * As sharing a single nr_active across multiple sockets can be very expensive,
329 * the counting and enforcement is per NUMA node.
331 * The following struct is used to enforce per-node max_active. When a pwq wants
332 * to start executing a work item, it should increment ->nr using
333 * tryinc_node_nr_active(). If acquisition fails due to ->nr already being over
334 * ->max, the pwq is queued on ->pending_pwqs. As in-flight work items finish
335 * and decrement ->nr, node_activate_pending_pwq() activates the pending pwqs in
338 struct wq_node_nr_active
{
339 int max
; /* per-node max_active */
340 atomic_t nr
; /* per-node nr_active */
341 raw_spinlock_t lock
; /* nests inside pool locks */
342 struct list_head pending_pwqs
; /* LN: pwqs with inactive works */
346 * The externally visible workqueue. It relays the issued work items to
347 * the appropriate worker_pool through its pool_workqueues.
349 struct workqueue_struct
{
350 struct list_head pwqs
; /* WR: all pwqs of this wq */
351 struct list_head list
; /* PR: list of all workqueues */
353 struct mutex mutex
; /* protects this wq */
354 int work_color
; /* WQ: current work color */
355 int flush_color
; /* WQ: current flush color */
356 atomic_t nr_pwqs_to_flush
; /* flush in progress */
357 struct wq_flusher
*first_flusher
; /* WQ: first flusher */
358 struct list_head flusher_queue
; /* WQ: flush waiters */
359 struct list_head flusher_overflow
; /* WQ: flush overflow list */
361 struct list_head maydays
; /* MD: pwqs requesting rescue */
362 struct worker
*rescuer
; /* MD: rescue worker */
364 int nr_drainers
; /* WQ: drain in progress */
366 /* See alloc_workqueue() function comment for info on min/max_active */
367 int max_active
; /* WO: max active works */
368 int min_active
; /* WO: min active works */
369 int saved_max_active
; /* WQ: saved max_active */
370 int saved_min_active
; /* WQ: saved min_active */
372 struct workqueue_attrs
*unbound_attrs
; /* PW: only for unbound wqs */
373 struct pool_workqueue __rcu
*dfl_pwq
; /* PW: only for unbound wqs */
376 struct wq_device
*wq_dev
; /* I: for sysfs interface */
378 #ifdef CONFIG_LOCKDEP
380 struct lock_class_key key
;
381 struct lockdep_map __lockdep_map
;
382 struct lockdep_map
*lockdep_map
;
384 char name
[WQ_NAME_LEN
]; /* I: workqueue name */
387 * Destruction of workqueue_struct is RCU protected to allow walking
388 * the workqueues list without grabbing wq_pool_mutex.
389 * This is used to dump all workqueues from sysrq.
393 /* hot fields used during command issue, aligned to cacheline */
394 unsigned int flags ____cacheline_aligned
; /* WQ: WQ_* flags */
395 struct pool_workqueue __rcu
* __percpu
*cpu_pwq
; /* I: per-cpu pwqs */
396 struct wq_node_nr_active
*node_nr_active
[]; /* I: per-node nr_active */
400 * Each pod type describes how CPUs should be grouped for unbound workqueues.
401 * See the comment above workqueue_attrs->affn_scope.
404 int nr_pods
; /* number of pods */
405 cpumask_var_t
*pod_cpus
; /* pod -> cpus */
406 int *pod_node
; /* pod -> node */
407 int *cpu_pod
; /* cpu -> pod */
410 struct work_offq_data
{
416 static const char * const wq_affn_names
[WQ_AFFN_NR_TYPES
] = {
417 [WQ_AFFN_DFL
] = "default",
418 [WQ_AFFN_CPU
] = "cpu",
419 [WQ_AFFN_SMT
] = "smt",
420 [WQ_AFFN_CACHE
] = "cache",
421 [WQ_AFFN_CACHE_SHARD
] = "cache_shard",
422 [WQ_AFFN_NUMA
] = "numa",
423 [WQ_AFFN_SYSTEM
] = "system",
427 * Per-cpu work items which run for longer than the following threshold are
428 * automatically considered CPU intensive and excluded from concurrency
429 * management to prevent them from noticeably delaying other per-cpu work items.
430 * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
431 * The actual value is initialized in wq_cpu_intensive_thresh_init().
433 static unsigned long wq_cpu_intensive_thresh_us
= ULONG_MAX
;
434 module_param_named(cpu_intensive_thresh_us
, wq_cpu_intensive_thresh_us
, ulong
, 0644);
435 #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
436 static unsigned int wq_cpu_intensive_warning_thresh
= 4;
437 module_param_named(cpu_intensive_warning_thresh
, wq_cpu_intensive_warning_thresh
, uint
, 0644);
440 /* see the comment above the definition of WQ_POWER_EFFICIENT */
441 static bool wq_power_efficient
= IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT
);
442 module_param_named(power_efficient
, wq_power_efficient
, bool, 0444);
444 static unsigned int wq_cache_shard_size
= 8;
445 module_param_named(cache_shard_size
, wq_cache_shard_size
, uint
, 0444);
447 static bool wq_online
; /* can kworkers be created yet? */
448 static bool wq_topo_initialized __read_mostly
= false;
450 static struct kmem_cache
*pwq_cache
;
452 static struct wq_pod_type wq_pod_types
[WQ_AFFN_NR_TYPES
];
453 static enum wq_affn_scope wq_affn_dfl
= WQ_AFFN_CACHE_SHARD
;
455 /* buf for wq_update_unbound_pod_attrs(), protected by CPU hotplug exclusion */
456 static struct workqueue_attrs
*unbound_wq_update_pwq_attrs_buf
;
458 static DEFINE_MUTEX(wq_pool_mutex
); /* protects pools and workqueues list */
459 static DEFINE_MUTEX(wq_pool_attach_mutex
); /* protects worker attach/detach */
460 static DEFINE_RAW_SPINLOCK(wq_mayday_lock
); /* protects wq->maydays list */
461 /* wait for manager to go away */
462 static struct rcuwait manager_wait
= __RCUWAIT_INITIALIZER(manager_wait
);
464 static LIST_HEAD(workqueues
); /* PR: list of all workqueues */
465 static bool workqueue_freezing
; /* PL: have wqs started freezing? */
467 /* PL: mirror the cpu_online_mask excluding the CPU in the midst of hotplugging */
468 static cpumask_var_t wq_online_cpumask
;
470 /* PL&A: allowable cpus for unbound wqs and work items */
471 static cpumask_var_t wq_unbound_cpumask
;
473 /* PL: user requested unbound cpumask via sysfs */
474 static cpumask_var_t wq_requested_unbound_cpumask
;
476 /* PL: isolated cpumask to be excluded from unbound cpumask */
477 static cpumask_var_t wq_isolated_cpumask
;
479 /* for further constrain wq_unbound_cpumask by cmdline parameter*/
480 static struct cpumask wq_cmdline_cpumask __initdata
;
482 /* CPU where unbound work was last round robin scheduled from this CPU */
483 static DEFINE_PER_CPU(int, wq_rr_cpu_last
);
486 * Local execution of unbound work items is no longer guaranteed. The
487 * following always forces round-robin CPU selection on unbound work items
488 * to uncover usages which depend on it.
490 #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
491 static bool wq_debug_force_rr_cpu
= true;
493 static bool wq_debug_force_rr_cpu
= false;
495 module_param_named(debug_force_rr_cpu
, wq_debug_force_rr_cpu
, bool, 0644);
497 /* to raise softirq for the BH worker pools on other CPUs */
498 static DEFINE_PER_CPU_SHARED_ALIGNED(struct irq_work
[NR_STD_WORKER_POOLS
], bh_pool_irq_works
);
500 /* the BH worker pools */
501 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool
[NR_STD_WORKER_POOLS
], bh_worker_pools
);
503 /* the per-cpu worker pools */
504 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool
[NR_STD_WORKER_POOLS
], cpu_worker_pools
);
506 static DEFINE_IDR(worker_pool_idr
); /* PR: idr of all pools */
508 /* PL: hash of all unbound pools keyed by pool->attrs */
509 static DEFINE_HASHTABLE(unbound_pool_hash
, UNBOUND_POOL_HASH_ORDER
);
511 /* I: attributes used when instantiating standard unbound pools on demand */
512 static struct workqueue_attrs
*unbound_std_wq_attrs
[NR_STD_WORKER_POOLS
];
514 /* I: attributes used when instantiating ordered pools on demand */
515 static struct workqueue_attrs
*ordered_wq_attrs
[NR_STD_WORKER_POOLS
];
518 * I: kthread_worker to release pwq's. pwq release needs to be bounced to a
519 * process context while holding a pool lock. Bounce to a dedicated kthread
520 * worker to avoid A-A deadlocks.
522 static struct kthread_worker
*pwq_release_worker __ro_after_init
;
524 struct workqueue_struct
*system_wq __ro_after_init
;
525 EXPORT_SYMBOL(system_wq
);
526 struct workqueue_struct
*system_percpu_wq __ro_after_init
;
527 EXPORT_SYMBOL(system_percpu_wq
);
528 struct workqueue_struct
*system_highpri_wq __ro_after_init
;
529 EXPORT_SYMBOL_GPL(system_highpri_wq
);
530 struct workqueue_struct
*system_long_wq __ro_after_init
;
531 EXPORT_SYMBOL_GPL(system_long_wq
);
532 struct workqueue_struct
*system_unbound_wq __ro_after_init
;
533 EXPORT_SYMBOL_GPL(system_unbound_wq
);
534 struct workqueue_struct
*system_dfl_wq __ro_after_init
;
535 EXPORT_SYMBOL_GPL(system_dfl_wq
);
536 struct workqueue_struct
*system_freezable_wq __ro_after_init
;
537 EXPORT_SYMBOL_GPL(system_freezable_wq
);
538 struct workqueue_struct
*system_power_efficient_wq __ro_after_init
;
539 EXPORT_SYMBOL_GPL(system_power_efficient_wq
);
540 struct workqueue_struct
*system_freezable_power_efficient_wq __ro_after_init
;
541 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq
);
542 struct workqueue_struct
*system_bh_wq
;
543 EXPORT_SYMBOL_GPL(system_bh_wq
);
544 struct workqueue_struct
*system_bh_highpri_wq
;
545 EXPORT_SYMBOL_GPL(system_bh_highpri_wq
);
546 struct workqueue_struct
*system_dfl_long_wq __ro_after_init
;
547 EXPORT_SYMBOL_GPL(system_dfl_long_wq
);
549 static int worker_thread(void *__worker
);
550 static void workqueue_sysfs_unregister(struct workqueue_struct
*wq
);
551 static void show_pwq(struct pool_workqueue
*pwq
);
552 static void show_one_worker_pool(struct worker_pool
*pool
);
554 #define CREATE_TRACE_POINTS
555 #include <trace/events/workqueue.h>
557 #define assert_rcu_or_pool_mutex() \
558 RCU_LOCKDEP_WARN(!rcu_read_lock_any_held() && \
559 !lockdep_is_held(&wq_pool_mutex), \
560 "RCU or wq_pool_mutex should be held")
562 #define for_each_bh_worker_pool(pool, cpu) \
563 for ((pool) = &per_cpu(bh_worker_pools, cpu)[0]; \
564 (pool) < &per_cpu(bh_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
567 #define for_each_cpu_worker_pool(pool, cpu) \
568 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
569 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
573 * for_each_pool - iterate through all worker_pools in the system
574 * @pool: iteration cursor
575 * @pi: integer used for iteration
577 * This must be called either with wq_pool_mutex held or RCU read
578 * locked. If the pool needs to be used beyond the locking in effect, the
579 * caller is responsible for guaranteeing that the pool stays online.
581 * The if/else clause exists only for the lockdep assertion and can be
584 #define for_each_pool(pool, pi) \
585 idr_for_each_entry(&worker_pool_idr, pool, pi) \
586 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
590 * for_each_pool_worker - iterate through all workers of a worker_pool
591 * @worker: iteration cursor
592 * @pool: worker_pool to iterate workers of
594 * This must be called with wq_pool_attach_mutex.
596 * The if/else clause exists only for the lockdep assertion and can be
599 #define for_each_pool_worker(worker, pool) \
600 list_for_each_entry((worker), &(pool)->workers, node) \
601 if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
605 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
606 * @pwq: iteration cursor
607 * @wq: the target workqueue
609 * This must be called either with wq->mutex held or RCU read locked.
610 * If the pwq needs to be used beyond the locking in effect, the caller is
611 * responsible for guaranteeing that the pwq stays online.
613 * The if/else clause exists only for the lockdep assertion and can be
616 #define for_each_pwq(pwq, wq) \
617 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node, \
618 lockdep_is_held(&(wq->mutex)))
620 #ifdef CONFIG_DEBUG_OBJECTS_WORK
622 static const struct debug_obj_descr work_debug_descr
;
624 static void *work_debug_hint(void *addr
)
626 return ((struct work_struct
*) addr
)->func
;
629 static bool work_is_static_object(void *addr
)
631 struct work_struct
*work
= addr
;
633 return test_bit(WORK_STRUCT_STATIC_BIT
, work_data_bits(work
));
637 * fixup_init is called when:
638 * - an active object is initialized
640 static bool work_fixup_init(void *addr
, enum debug_obj_state state
)
642 struct work_struct
*work
= addr
;
645 case ODEBUG_STATE_ACTIVE
:
646 cancel_work_sync(work
);
647 debug_object_init(work
, &work_debug_descr
);
655 * fixup_free is called when:
656 * - an active object is freed
658 static bool work_fixup_free(void *addr
, enum debug_obj_state state
)
660 struct work_struct
*work
= addr
;
663 case ODEBUG_STATE_ACTIVE
:
664 cancel_work_sync(work
);
665 debug_object_free(work
, &work_debug_descr
);
672 static const struct debug_obj_descr work_debug_descr
= {
673 .name
= "work_struct",
674 .debug_hint
= work_debug_hint
,
675 .is_static_object
= work_is_static_object
,
676 .fixup_init
= work_fixup_init
,
677 .fixup_free
= work_fixup_free
,
680 static inline void debug_work_activate(struct work_struct
*work
)
682 debug_object_activate(work
, &work_debug_descr
);
685 static inline void debug_work_deactivate(struct work_struct
*work
)
687 debug_object_deactivate(work
, &work_debug_descr
);
690 void __init_work(struct work_struct
*work
, int onstack
)
693 debug_object_init_on_stack(work
, &work_debug_descr
);
695 debug_object_init(work
, &work_debug_descr
);
697 EXPORT_SYMBOL_GPL(__init_work
);
699 void destroy_work_on_stack(struct work_struct
*work
)
701 debug_object_free(work
, &work_debug_descr
);
703 EXPORT_SYMBOL_GPL(destroy_work_on_stack
);
705 void destroy_delayed_work_on_stack(struct delayed_work
*work
)
707 timer_destroy_on_stack(&work
->timer
);
708 debug_object_free(&work
->work
, &work_debug_descr
);
710 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack
);
713 static inline void debug_work_activate(struct work_struct
*work
) { }
714 static inline void debug_work_deactivate(struct work_struct
*work
) { }
718 * worker_pool_assign_id - allocate ID and assign it to @pool
719 * @pool: the pool pointer of interest
721 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
722 * successfully, -errno on failure.
724 static int worker_pool_assign_id(struct worker_pool
*pool
)
728 lockdep_assert_held(&wq_pool_mutex
);
730 ret
= idr_alloc(&worker_pool_idr
, pool
, 0, WORK_OFFQ_POOL_NONE
,
739 static struct pool_workqueue __rcu
**
740 unbound_pwq_slot(struct workqueue_struct
*wq
, int cpu
)
743 return per_cpu_ptr(wq
->cpu_pwq
, cpu
);
748 /* @cpu < 0 for dfl_pwq */
749 static struct pool_workqueue
*unbound_pwq(struct workqueue_struct
*wq
, int cpu
)
751 return rcu_dereference_check(*unbound_pwq_slot(wq
, cpu
),
752 lockdep_is_held(&wq_pool_mutex
) ||
753 lockdep_is_held(&wq
->mutex
));
757 * unbound_effective_cpumask - effective cpumask of an unbound workqueue
758 * @wq: workqueue of interest
760 * @wq->unbound_attrs->cpumask contains the cpumask requested by the user which
761 * is masked with wq_unbound_cpumask to determine the effective cpumask. The
762 * default pwq is always mapped to the pool with the current effective cpumask.
764 static struct cpumask
*unbound_effective_cpumask(struct workqueue_struct
*wq
)
766 return unbound_pwq(wq
, -1)->pool
->attrs
->__pod_cpumask
;
769 static unsigned int work_color_to_flags(int color
)
771 return color
<< WORK_STRUCT_COLOR_SHIFT
;
774 static int get_work_color(unsigned long work_data
)
776 return (work_data
>> WORK_STRUCT_COLOR_SHIFT
) &
777 ((1 << WORK_STRUCT_COLOR_BITS
) - 1);
780 static int work_next_color(int color
)
782 return (color
+ 1) % WORK_NR_COLORS
;
785 static unsigned long pool_offq_flags(struct worker_pool
*pool
)
787 return (pool
->flags
& POOL_BH
) ? WORK_OFFQ_BH
: 0;
791 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
792 * contain the pointer to the queued pwq. Once execution starts, the flag
793 * is cleared and the high bits contain OFFQ flags and pool ID.
795 * set_work_pwq(), set_work_pool_and_clear_pending() and mark_work_canceling()
796 * can be used to set the pwq, pool or clear work->data. These functions should
797 * only be called while the work is owned - ie. while the PENDING bit is set.
799 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
800 * corresponding to a work. Pool is available once the work has been
801 * queued anywhere after initialization until it is sync canceled. pwq is
802 * available only while the work item is queued.
804 static inline void set_work_data(struct work_struct
*work
, unsigned long data
)
806 WARN_ON_ONCE(!work_pending(work
));
807 atomic_long_set(&work
->data
, data
| work_static(work
));
810 static void set_work_pwq(struct work_struct
*work
, struct pool_workqueue
*pwq
,
813 set_work_data(work
, (unsigned long)pwq
| WORK_STRUCT_PENDING
|
814 WORK_STRUCT_PWQ
| flags
);
817 static void set_work_pool_and_keep_pending(struct work_struct
*work
,
818 int pool_id
, unsigned long flags
)
820 set_work_data(work
, ((unsigned long)pool_id
<< WORK_OFFQ_POOL_SHIFT
) |
821 WORK_STRUCT_PENDING
| flags
);
824 static void set_work_pool_and_clear_pending(struct work_struct
*work
,
825 int pool_id
, unsigned long flags
)
828 * The following wmb is paired with the implied mb in
829 * test_and_set_bit(PENDING) and ensures all updates to @work made
830 * here are visible to and precede any updates by the next PENDING
834 set_work_data(work
, ((unsigned long)pool_id
<< WORK_OFFQ_POOL_SHIFT
) |
837 * The following mb guarantees that previous clear of a PENDING bit
838 * will not be reordered with any speculative LOADS or STORES from
839 * work->current_func, which is executed afterwards. This possible
840 * reordering can lead to a missed execution on attempt to queue
841 * the same @work. E.g. consider this case:
844 * ---------------------------- --------------------------------
846 * 1 STORE event_indicated
847 * 2 queue_work_on() {
848 * 3 test_and_set_bit(PENDING)
849 * 4 } set_..._and_clear_pending() {
850 * 5 set_work_data() # clear bit
852 * 7 work->current_func() {
853 * 8 LOAD event_indicated
856 * Without an explicit full barrier speculative LOAD on line 8 can
857 * be executed before CPU#0 does STORE on line 1. If that happens,
858 * CPU#0 observes the PENDING bit is still set and new execution of
859 * a @work is not queued in a hope, that CPU#1 will eventually
860 * finish the queued @work. Meanwhile CPU#1 does not see
861 * event_indicated is set, because speculative LOAD was executed
862 * before actual STORE.
867 static inline struct pool_workqueue
*work_struct_pwq(unsigned long data
)
869 return (struct pool_workqueue
*)(data
& WORK_STRUCT_PWQ_MASK
);
872 static struct pool_workqueue
*get_work_pwq(struct work_struct
*work
)
874 unsigned long data
= atomic_long_read(&work
->data
);
876 if (data
& WORK_STRUCT_PWQ
)
877 return work_struct_pwq(data
);
883 * get_work_pool - return the worker_pool a given work was associated with
884 * @work: the work item of interest
886 * Pools are created and destroyed under wq_pool_mutex, and allows read
887 * access under RCU read lock. As such, this function should be
888 * called under wq_pool_mutex or inside of a rcu_read_lock() region.
890 * All fields of the returned pool are accessible as long as the above
891 * mentioned locking is in effect. If the returned pool needs to be used
892 * beyond the critical section, the caller is responsible for ensuring the
893 * returned pool is and stays online.
895 * Return: The worker_pool @work was last associated with. %NULL if none.
897 static struct worker_pool
*get_work_pool(struct work_struct
*work
)
899 unsigned long data
= atomic_long_read(&work
->data
);
902 assert_rcu_or_pool_mutex();
904 if (data
& WORK_STRUCT_PWQ
)
905 return work_struct_pwq(data
)->pool
;
907 pool_id
= data
>> WORK_OFFQ_POOL_SHIFT
;
908 if (pool_id
== WORK_OFFQ_POOL_NONE
)
911 return idr_find(&worker_pool_idr
, pool_id
);
914 static unsigned long shift_and_mask(unsigned long v
, u32 shift
, u32 bits
)
916 return (v
>> shift
) & ((1U << bits
) - 1);
919 static void work_offqd_unpack(struct work_offq_data
*offqd
, unsigned long data
)
921 WARN_ON_ONCE(data
& WORK_STRUCT_PWQ
);
923 offqd
->pool_id
= shift_and_mask(data
, WORK_OFFQ_POOL_SHIFT
,
924 WORK_OFFQ_POOL_BITS
);
925 offqd
->disable
= shift_and_mask(data
, WORK_OFFQ_DISABLE_SHIFT
,
926 WORK_OFFQ_DISABLE_BITS
);
927 offqd
->flags
= data
& WORK_OFFQ_FLAG_MASK
;
930 static unsigned long work_offqd_pack_flags(struct work_offq_data
*offqd
)
932 return ((unsigned long)offqd
->disable
<< WORK_OFFQ_DISABLE_SHIFT
) |
933 ((unsigned long)offqd
->flags
);
937 * Policy functions. These define the policies on how the global worker
938 * pools are managed. Unless noted otherwise, these functions assume that
939 * they're being called with pool->lock held.
943 * Need to wake up a worker? Called from anything but currently
946 * Note that, because unbound workers never contribute to nr_running, this
947 * function will always return %true for unbound pools as long as the
948 * worklist isn't empty.
950 static bool need_more_worker(struct worker_pool
*pool
)
952 return !list_empty(&pool
->worklist
) && !pool
->nr_running
;
955 /* Can I start working? Called from busy but !running workers. */
956 static bool may_start_working(struct worker_pool
*pool
)
958 return pool
->nr_idle
;
961 /* Do I need to keep working? Called from currently running workers. */
962 static bool keep_working(struct worker_pool
*pool
)
964 return !list_empty(&pool
->worklist
) && (pool
->nr_running
<= 1);
967 /* Do we need a new worker? Called from manager. */
968 static bool need_to_create_worker(struct worker_pool
*pool
)
970 return need_more_worker(pool
) && !may_start_working(pool
);
973 /* Do we have too many workers and should some go away? */
974 static bool too_many_workers(struct worker_pool
*pool
)
976 bool managing
= pool
->flags
& POOL_MANAGER_ACTIVE
;
977 int nr_idle
= pool
->nr_idle
+ managing
; /* manager is considered idle */
978 int nr_busy
= pool
->nr_workers
- nr_idle
;
980 return nr_idle
> 2 && (nr_idle
- 2) * MAX_IDLE_WORKERS_RATIO
>= nr_busy
;
984 * worker_set_flags - set worker flags and adjust nr_running accordingly
986 * @flags: flags to set
988 * Set @flags in @worker->flags and adjust nr_running accordingly.
990 static inline void worker_set_flags(struct worker
*worker
, unsigned int flags
)
992 struct worker_pool
*pool
= worker
->pool
;
994 lockdep_assert_held(&pool
->lock
);
996 /* If transitioning into NOT_RUNNING, adjust nr_running. */
997 if ((flags
& WORKER_NOT_RUNNING
) &&
998 !(worker
->flags
& WORKER_NOT_RUNNING
)) {
1002 worker
->flags
|= flags
;
1006 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
1008 * @flags: flags to clear
1010 * Clear @flags in @worker->flags and adjust nr_running accordingly.
1012 static inline void worker_clr_flags(struct worker
*worker
, unsigned int flags
)
1014 struct worker_pool
*pool
= worker
->pool
;
1015 unsigned int oflags
= worker
->flags
;
1017 lockdep_assert_held(&pool
->lock
);
1019 worker
->flags
&= ~flags
;
1022 * If transitioning out of NOT_RUNNING, increment nr_running. Note
1023 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
1024 * of multiple flags, not a single flag.
1026 if ((flags
& WORKER_NOT_RUNNING
) && (oflags
& WORKER_NOT_RUNNING
))
1027 if (!(worker
->flags
& WORKER_NOT_RUNNING
))
1031 /* Return the first idle worker. Called with pool->lock held. */
1032 static struct worker
*first_idle_worker(struct worker_pool
*pool
)
1034 if (unlikely(list_empty(&pool
->idle_list
)))
1037 return list_first_entry(&pool
->idle_list
, struct worker
, entry
);
1041 * worker_enter_idle - enter idle state
1042 * @worker: worker which is entering idle state
1044 * @worker is entering idle state. Update stats and idle timer if
1048 * raw_spin_lock_irq(pool->lock).
1050 static void worker_enter_idle(struct worker
*worker
)
1052 struct worker_pool
*pool
= worker
->pool
;
1054 if (WARN_ON_ONCE(worker
->flags
& WORKER_IDLE
) ||
1055 WARN_ON_ONCE(!list_empty(&worker
->entry
) &&
1056 (worker
->hentry
.next
|| worker
->hentry
.pprev
)))
1059 /* can't use worker_set_flags(), also called from create_worker() */
1060 worker
->flags
|= WORKER_IDLE
;
1062 worker
->last_active
= jiffies
;
1064 /* idle_list is LIFO */
1065 list_add(&worker
->entry
, &pool
->idle_list
);
1067 if (too_many_workers(pool
) && !timer_pending(&pool
->idle_timer
))
1068 mod_timer(&pool
->idle_timer
, jiffies
+ IDLE_WORKER_TIMEOUT
);
1070 /* Sanity check nr_running. */
1071 WARN_ON_ONCE(pool
->nr_workers
== pool
->nr_idle
&& pool
->nr_running
);
1075 * worker_leave_idle - leave idle state
1076 * @worker: worker which is leaving idle state
1078 * @worker is leaving idle state. Update stats.
1081 * raw_spin_lock_irq(pool->lock).
1083 static void worker_leave_idle(struct worker
*worker
)
1085 struct worker_pool
*pool
= worker
->pool
;
1087 if (WARN_ON_ONCE(!(worker
->flags
& WORKER_IDLE
)))
1089 worker_clr_flags(worker
, WORKER_IDLE
);
1091 list_del_init(&worker
->entry
);
1095 * find_worker_executing_work - find worker which is executing a work
1096 * @pool: pool of interest
1097 * @work: work to find worker for
1099 * Find a worker which is executing @work on @pool by searching
1100 * @pool->busy_hash which is keyed by the address of @work. For a worker
1101 * to match, its current execution should match the address of @work and
1102 * its work function. This is to avoid unwanted dependency between
1103 * unrelated work executions through a work item being recycled while still
1106 * This is a bit tricky. A work item may be freed once its execution
1107 * starts and nothing prevents the freed area from being recycled for
1108 * another work item. If the same work item address ends up being reused
1109 * before the original execution finishes, workqueue will identify the
1110 * recycled work item as currently executing and make it wait until the
1111 * current execution finishes, introducing an unwanted dependency.
1113 * This function checks the work item address and work function to avoid
1114 * false positives. Note that this isn't complete as one may construct a
1115 * work function which can introduce dependency onto itself through a
1116 * recycled work item. Well, if somebody wants to shoot oneself in the
1117 * foot that badly, there's only so much we can do, and if such deadlock
1118 * actually occurs, it should be easy to locate the culprit work function.
1121 * raw_spin_lock_irq(pool->lock).
1124 * Pointer to worker which is executing @work if found, %NULL
1127 static struct worker
*find_worker_executing_work(struct worker_pool
*pool
,
1128 struct work_struct
*work
)
1130 struct worker
*worker
;
1132 hash_for_each_possible(pool
->busy_hash
, worker
, hentry
,
1133 (unsigned long)work
)
1134 if (worker
->current_work
== work
&&
1135 worker
->current_func
== work
->func
)
1141 static void mayday_cursor_func(struct work_struct
*work
)
1143 /* should not be processed, only for marking position */
1148 * move_linked_works - move linked works to a list
1149 * @work: start of series of works to be scheduled
1150 * @head: target list to append @work to
1151 * @nextp: out parameter for nested worklist walking
1153 * Schedule linked works starting from @work to @head. Work series to be
1154 * scheduled starts at @work and includes any consecutive work with
1155 * WORK_STRUCT_LINKED set in its predecessor. See assign_work() for details on
1159 * raw_spin_lock_irq(pool->lock).
1161 static void move_linked_works(struct work_struct
*work
, struct list_head
*head
,
1162 struct work_struct
**nextp
)
1164 struct work_struct
*n
;
1167 * Linked worklist will always end before the end of the list,
1168 * use NULL for list head.
1170 list_for_each_entry_safe_from(work
, n
, NULL
, entry
) {
1171 list_move_tail(&work
->entry
, head
);
1172 if (!(*work_data_bits(work
) & WORK_STRUCT_LINKED
))
1177 * If we're already inside safe list traversal and have moved
1178 * multiple works to the scheduled queue, the next position
1179 * needs to be updated.
1186 * assign_work - assign a work item and its linked work items to a worker
1187 * @work: work to assign
1188 * @worker: worker to assign to
1189 * @nextp: out parameter for nested worklist walking
1191 * Assign @work and its linked work items to @worker. If @work is already being
1192 * executed by another worker in the same pool, it'll be punted there.
1194 * If @nextp is not NULL, it's updated to point to the next work of the last
1195 * scheduled work. This allows assign_work() to be nested inside
1196 * list_for_each_entry_safe().
1198 * Returns %true if @work was successfully assigned to @worker. %false if @work
1199 * was punted to another worker already executing it.
1201 static bool assign_work(struct work_struct
*work
, struct worker
*worker
,
1202 struct work_struct
**nextp
)
1204 struct worker_pool
*pool
= worker
->pool
;
1205 struct worker
*collision
;
1207 lockdep_assert_held(&pool
->lock
);
1209 /* The cursor work should not be processed */
1210 if (unlikely(work
->func
== mayday_cursor_func
)) {
1211 /* only worker_thread() can possibly take this branch */
1212 WARN_ON_ONCE(worker
->rescue_wq
);
1214 *nextp
= list_next_entry(work
, entry
);
1215 list_del_init(&work
->entry
);
1220 * A single work shouldn't be executed concurrently by multiple workers.
1221 * __queue_work() ensures that @work doesn't jump to a different pool
1222 * while still running in the previous pool. Here, we should ensure that
1223 * @work is not executed concurrently by multiple workers from the same
1224 * pool. Check whether anyone is already processing the work. If so,
1225 * defer the work to the currently executing one.
1227 collision
= find_worker_executing_work(pool
, work
);
1228 if (unlikely(collision
)) {
1229 move_linked_works(work
, &collision
->scheduled
, nextp
);
1233 move_linked_works(work
, &worker
->scheduled
, nextp
);
1237 static struct irq_work
*bh_pool_irq_work(struct worker_pool
*pool
)
1239 int high
= pool
->attrs
->nice
== HIGHPRI_NICE_LEVEL
? 1 : 0;
1241 return &per_cpu(bh_pool_irq_works
, pool
->cpu
)[high
];
1244 static void kick_bh_pool(struct worker_pool
*pool
)
1247 /* see drain_dead_softirq_workfn() for BH_DRAINING */
1248 if (unlikely(pool
->cpu
!= smp_processor_id() &&
1249 !(pool
->flags
& POOL_BH_DRAINING
))) {
1250 irq_work_queue_on(bh_pool_irq_work(pool
), pool
->cpu
);
1254 if (pool
->attrs
->nice
== HIGHPRI_NICE_LEVEL
)
1255 raise_softirq_irqoff(HI_SOFTIRQ
);
1257 raise_softirq_irqoff(TASKLET_SOFTIRQ
);
1261 * kick_pool - wake up an idle worker if necessary
1262 * @pool: pool to kick
1264 * @pool may have pending work items. Wake up worker if necessary. Returns
1265 * whether a worker was woken up.
1267 static bool kick_pool(struct worker_pool
*pool
)
1269 struct worker
*worker
= first_idle_worker(pool
);
1270 struct task_struct
*p
;
1272 lockdep_assert_held(&pool
->lock
);
1274 if (!need_more_worker(pool
) || !worker
)
1277 if (pool
->flags
& POOL_BH
) {
1286 * Idle @worker is about to execute @work and waking up provides an
1287 * opportunity to migrate @worker at a lower cost by setting the task's
1288 * wake_cpu field. Let's see if we want to move @worker to improve
1289 * execution locality.
1291 * We're waking the worker that went idle the latest and there's some
1292 * chance that @worker is marked idle but hasn't gone off CPU yet. If
1293 * so, setting the wake_cpu won't do anything. As this is a best-effort
1294 * optimization and the race window is narrow, let's leave as-is for
1295 * now. If this becomes pronounced, we can skip over workers which are
1296 * still on cpu when picking an idle worker.
1298 * If @pool has non-strict affinity, @worker might have ended up outside
1299 * its affinity scope. Repatriate.
1301 if (!pool
->attrs
->affn_strict
&&
1302 !cpumask_test_cpu(p
->wake_cpu
, pool
->attrs
->__pod_cpumask
)) {
1303 struct work_struct
*work
= list_first_entry(&pool
->worklist
,
1304 struct work_struct
, entry
);
1305 int wake_cpu
= cpumask_any_and_distribute(pool
->attrs
->__pod_cpumask
,
1307 if (wake_cpu
< nr_cpu_ids
) {
1308 p
->wake_cpu
= wake_cpu
;
1309 get_work_pwq(work
)->stats
[PWQ_STAT_REPATRIATED
]++;
1317 #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
1320 * Concurrency-managed per-cpu work items that hog CPU for longer than
1321 * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
1322 * which prevents them from stalling other concurrency-managed work items. If a
1323 * work function keeps triggering this mechanism, it's likely that the work item
1324 * should be using an unbound workqueue instead.
1326 * wq_cpu_intensive_report() tracks work functions which trigger such conditions
1327 * and report them so that they can be examined and converted to use unbound
1328 * workqueues as appropriate. To avoid flooding the console, each violating work
1329 * function is tracked and reported with exponential backoff.
1331 #define WCI_MAX_ENTS 128
1336 struct hlist_node hash_node
;
1339 static struct wci_ent wci_ents
[WCI_MAX_ENTS
];
1340 static int wci_nr_ents
;
1341 static DEFINE_RAW_SPINLOCK(wci_lock
);
1342 static DEFINE_HASHTABLE(wci_hash
, ilog2(WCI_MAX_ENTS
));
1344 static struct wci_ent
*wci_find_ent(work_func_t func
)
1346 struct wci_ent
*ent
;
1348 hash_for_each_possible_rcu(wci_hash
, ent
, hash_node
,
1349 (unsigned long)func
) {
1350 if (ent
->func
== func
)
1356 static void wq_cpu_intensive_report(work_func_t func
)
1358 struct wci_ent
*ent
;
1361 ent
= wci_find_ent(func
);
1366 * Start reporting from the warning_thresh and back off
1369 cnt
= atomic64_inc_return_relaxed(&ent
->cnt
);
1370 if (wq_cpu_intensive_warning_thresh
&&
1371 cnt
>= wq_cpu_intensive_warning_thresh
&&
1372 is_power_of_2(cnt
+ 1 - wq_cpu_intensive_warning_thresh
))
1373 printk_deferred(KERN_WARNING
"workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
1374 ent
->func
, wq_cpu_intensive_thresh_us
,
1375 atomic64_read(&ent
->cnt
));
1380 * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
1381 * is exhausted, something went really wrong and we probably made enough
1384 if (wci_nr_ents
>= WCI_MAX_ENTS
)
1387 raw_spin_lock(&wci_lock
);
1389 if (wci_nr_ents
>= WCI_MAX_ENTS
) {
1390 raw_spin_unlock(&wci_lock
);
1394 if (wci_find_ent(func
)) {
1395 raw_spin_unlock(&wci_lock
);
1399 ent
= &wci_ents
[wci_nr_ents
++];
1401 atomic64_set(&ent
->cnt
, 0);
1402 hash_add_rcu(wci_hash
, &ent
->hash_node
, (unsigned long)func
);
1404 raw_spin_unlock(&wci_lock
);
1409 #else /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1410 static void wq_cpu_intensive_report(work_func_t func
) {}
1411 #endif /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
1414 * wq_worker_running - a worker is running again
1415 * @task: task waking up
1417 * This function is called when a worker returns from schedule()
1419 void wq_worker_running(struct task_struct
*task
)
1421 struct worker
*worker
= kthread_data(task
);
1423 if (!READ_ONCE(worker
->sleeping
))
1427 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
1428 * and the nr_running increment below, we may ruin the nr_running reset
1429 * and leave with an unexpected pool->nr_running == 1 on the newly unbound
1430 * pool. Protect against such race.
1433 if (!(worker
->flags
& WORKER_NOT_RUNNING
))
1434 worker
->pool
->nr_running
++;
1438 * CPU intensive auto-detection cares about how long a work item hogged
1439 * CPU without sleeping. Reset the starting timestamp on wakeup.
1441 worker
->current_at
= worker
->task
->se
.sum_exec_runtime
;
1443 WRITE_ONCE(worker
->sleeping
, 0);
1447 * wq_worker_sleeping - a worker is going to sleep
1448 * @task: task going to sleep
1450 * This function is called from schedule() when a busy worker is
1453 void wq_worker_sleeping(struct task_struct
*task
)
1455 struct worker
*worker
= kthread_data(task
);
1456 struct worker_pool
*pool
;
1459 * Rescuers, which may not have all the fields set up like normal
1460 * workers, also reach here, let's not access anything before
1461 * checking NOT_RUNNING.
1463 if (worker
->flags
& WORKER_NOT_RUNNING
)
1466 pool
= worker
->pool
;
1468 /* Return if preempted before wq_worker_running() was reached */
1469 if (READ_ONCE(worker
->sleeping
))
1472 WRITE_ONCE(worker
->sleeping
, 1);
1473 raw_spin_lock_irq(&pool
->lock
);
1476 * Recheck in case unbind_workers() preempted us. We don't
1477 * want to decrement nr_running after the worker is unbound
1478 * and nr_running has been reset.
1480 if (worker
->flags
& WORKER_NOT_RUNNING
) {
1481 raw_spin_unlock_irq(&pool
->lock
);
1486 if (kick_pool(pool
))
1487 worker
->current_pwq
->stats
[PWQ_STAT_CM_WAKEUP
]++;
1489 raw_spin_unlock_irq(&pool
->lock
);
1493 * wq_worker_tick - a scheduler tick occurred while a kworker is running
1494 * @task: task currently running
1496 * Called from sched_tick(). We're in the IRQ context and the current
1497 * worker's fields which follow the 'K' locking rule can be accessed safely.
1499 void wq_worker_tick(struct task_struct
*task
)
1501 struct worker
*worker
= kthread_data(task
);
1502 struct pool_workqueue
*pwq
= worker
->current_pwq
;
1503 struct worker_pool
*pool
= worker
->pool
;
1508 pwq
->stats
[PWQ_STAT_CPU_TIME
] += TICK_USEC
;
1510 if (!wq_cpu_intensive_thresh_us
)
1514 * If the current worker is concurrency managed and hogged the CPU for
1515 * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1516 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1518 * Set @worker->sleeping means that @worker is in the process of
1519 * switching out voluntarily and won't be contributing to
1520 * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1521 * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1522 * double decrements. The task is releasing the CPU anyway. Let's skip.
1523 * We probably want to make this prettier in the future.
1525 if ((worker
->flags
& WORKER_NOT_RUNNING
) || READ_ONCE(worker
->sleeping
) ||
1526 worker
->task
->se
.sum_exec_runtime
- worker
->current_at
<
1527 wq_cpu_intensive_thresh_us
* NSEC_PER_USEC
)
1530 raw_spin_lock(&pool
->lock
);
1532 worker_set_flags(worker
, WORKER_CPU_INTENSIVE
);
1533 wq_cpu_intensive_report(worker
->current_func
);
1534 pwq
->stats
[PWQ_STAT_CPU_INTENSIVE
]++;
1536 if (kick_pool(pool
))
1537 pwq
->stats
[PWQ_STAT_CM_WAKEUP
]++;
1539 raw_spin_unlock(&pool
->lock
);
1543 * wq_worker_last_func - retrieve worker's last work function
1544 * @task: Task to retrieve last work function of.
1546 * Determine the last function a worker executed. This is called from
1547 * the scheduler to get a worker's last known identity.
1550 * raw_spin_lock_irq(rq->lock)
1552 * This function is called during schedule() when a kworker is going
1553 * to sleep. It's used by psi to identify aggregation workers during
1554 * dequeuing, to allow periodic aggregation to shut-off when that
1555 * worker is the last task in the system or cgroup to go to sleep.
1557 * As this function doesn't involve any workqueue-related locking, it
1558 * only returns stable values when called from inside the scheduler's
1559 * queuing and dequeuing paths, when @task, which must be a kworker,
1560 * is guaranteed to not be processing any works.
1563 * The last work function %current executed as a worker, NULL if it
1564 * hasn't executed any work yet.
1566 work_func_t
wq_worker_last_func(struct task_struct
*task
)
1568 struct worker
*worker
= kthread_data(task
);
1570 return worker
->last_func
;
1574 * wq_node_nr_active - Determine wq_node_nr_active to use
1575 * @wq: workqueue of interest
1576 * @node: NUMA node, can be %NUMA_NO_NODE
1578 * Determine wq_node_nr_active to use for @wq on @node. Returns:
1580 * - %NULL for per-cpu workqueues as they don't need to use shared nr_active.
1582 * - node_nr_active[nr_node_ids] if @node is %NUMA_NO_NODE.
1584 * - Otherwise, node_nr_active[@node].
1586 static struct wq_node_nr_active
*wq_node_nr_active(struct workqueue_struct
*wq
,
1589 if (!(wq
->flags
& WQ_UNBOUND
))
1592 if (node
== NUMA_NO_NODE
)
1595 return wq
->node_nr_active
[node
];
1599 * wq_update_node_max_active - Update per-node max_actives to use
1600 * @wq: workqueue to update
1601 * @off_cpu: CPU that's going down, -1 if a CPU is not going down
1603 * Update @wq->node_nr_active[]->max. @wq must be unbound. max_active is
1604 * distributed among nodes according to the proportions of numbers of online
1605 * cpus. The result is always between @wq->min_active and max_active.
1607 static void wq_update_node_max_active(struct workqueue_struct
*wq
, int off_cpu
)
1609 struct cpumask
*effective
= unbound_effective_cpumask(wq
);
1610 int min_active
= READ_ONCE(wq
->min_active
);
1611 int max_active
= READ_ONCE(wq
->max_active
);
1612 int total_cpus
, node
;
1614 lockdep_assert_held(&wq
->mutex
);
1616 if (!wq_topo_initialized
)
1619 if (off_cpu
>= 0 && !cpumask_test_cpu(off_cpu
, effective
))
1622 total_cpus
= cpumask_weight_and(effective
, cpu_online_mask
);
1626 /* If all CPUs of the wq get offline, use the default values */
1627 if (unlikely(!total_cpus
)) {
1629 wq_node_nr_active(wq
, node
)->max
= min_active
;
1631 wq_node_nr_active(wq
, NUMA_NO_NODE
)->max
= max_active
;
1635 for_each_node(node
) {
1638 node_cpus
= cpumask_weight_and(effective
, cpumask_of_node(node
));
1639 if (off_cpu
>= 0 && cpu_to_node(off_cpu
) == node
)
1642 wq_node_nr_active(wq
, node
)->max
=
1643 clamp(DIV_ROUND_UP(max_active
* node_cpus
, total_cpus
),
1644 min_active
, max_active
);
1647 wq_node_nr_active(wq
, NUMA_NO_NODE
)->max
= max_active
;
1651 * get_pwq - get an extra reference on the specified pool_workqueue
1652 * @pwq: pool_workqueue to get
1654 * Obtain an extra reference on @pwq. The caller should guarantee that
1655 * @pwq has positive refcnt and be holding the matching pool->lock.
1657 static void get_pwq(struct pool_workqueue
*pwq
)
1659 lockdep_assert_held(&pwq
->pool
->lock
);
1660 WARN_ON_ONCE(pwq
->refcnt
<= 0);
1665 * put_pwq - put a pool_workqueue reference
1666 * @pwq: pool_workqueue to put
1668 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1669 * destruction. The caller should be holding the matching pool->lock.
1671 static void put_pwq(struct pool_workqueue
*pwq
)
1673 lockdep_assert_held(&pwq
->pool
->lock
);
1674 if (likely(--pwq
->refcnt
))
1677 * @pwq can't be released under pool->lock, bounce to a dedicated
1678 * kthread_worker to avoid A-A deadlocks.
1680 kthread_queue_work(pwq_release_worker
, &pwq
->release_work
);
1684 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1685 * @pwq: pool_workqueue to put (can be %NULL)
1687 * put_pwq() with locking. This function also allows %NULL @pwq.
1689 static void put_pwq_unlocked(struct pool_workqueue
*pwq
)
1693 * As both pwqs and pools are RCU protected, the
1694 * following lock operations are safe.
1696 raw_spin_lock_irq(&pwq
->pool
->lock
);
1698 raw_spin_unlock_irq(&pwq
->pool
->lock
);
1702 static bool pwq_is_empty(struct pool_workqueue
*pwq
)
1704 return !pwq
->nr_active
&& list_empty(&pwq
->inactive_works
);
1707 static void __pwq_activate_work(struct pool_workqueue
*pwq
,
1708 struct work_struct
*work
)
1710 unsigned long *wdb
= work_data_bits(work
);
1712 WARN_ON_ONCE(!(*wdb
& WORK_STRUCT_INACTIVE
));
1713 trace_workqueue_activate_work(work
);
1714 if (list_empty(&pwq
->pool
->worklist
))
1715 pwq
->pool
->last_progress_ts
= jiffies
;
1716 move_linked_works(work
, &pwq
->pool
->worklist
, NULL
);
1717 __clear_bit(WORK_STRUCT_INACTIVE_BIT
, wdb
);
1720 static bool tryinc_node_nr_active(struct wq_node_nr_active
*nna
)
1722 int max
= READ_ONCE(nna
->max
);
1723 int old
= atomic_read(&nna
->nr
);
1728 } while (!atomic_try_cmpxchg_relaxed(&nna
->nr
, &old
, old
+ 1));
1734 * pwq_tryinc_nr_active - Try to increment nr_active for a pwq
1735 * @pwq: pool_workqueue of interest
1736 * @fill: max_active may have increased, try to increase concurrency level
1738 * Try to increment nr_active for @pwq. Returns %true if an nr_active count is
1739 * successfully obtained. %false otherwise.
1741 static bool pwq_tryinc_nr_active(struct pool_workqueue
*pwq
, bool fill
)
1743 struct workqueue_struct
*wq
= pwq
->wq
;
1744 struct worker_pool
*pool
= pwq
->pool
;
1745 struct wq_node_nr_active
*nna
= wq_node_nr_active(wq
, pool
->node
);
1746 bool obtained
= false;
1748 lockdep_assert_held(&pool
->lock
);
1751 /* BH or per-cpu workqueue, pwq->nr_active is sufficient */
1752 obtained
= pwq
->nr_active
< READ_ONCE(wq
->max_active
);
1756 if (unlikely(pwq
->plugged
))
1760 * Unbound workqueue uses per-node shared nr_active $nna. If @pwq is
1761 * already waiting on $nna, pwq_dec_nr_active() will maintain the
1762 * concurrency level. Don't jump the line.
1764 * We need to ignore the pending test after max_active has increased as
1765 * pwq_dec_nr_active() can only maintain the concurrency level but not
1766 * increase it. This is indicated by @fill.
1768 if (!list_empty(&pwq
->pending_node
) && likely(!fill
))
1771 obtained
= tryinc_node_nr_active(nna
);
1776 * Lockless acquisition failed. Lock, add ourself to $nna->pending_pwqs
1777 * and try again. The smp_mb() is paired with the implied memory barrier
1778 * of atomic_dec_return() in pwq_dec_nr_active() to ensure that either
1779 * we see the decremented $nna->nr or they see non-empty
1780 * $nna->pending_pwqs.
1782 raw_spin_lock(&nna
->lock
);
1784 if (list_empty(&pwq
->pending_node
))
1785 list_add_tail(&pwq
->pending_node
, &nna
->pending_pwqs
);
1786 else if (likely(!fill
))
1791 obtained
= tryinc_node_nr_active(nna
);
1794 * If @fill, @pwq might have already been pending. Being spuriously
1795 * pending in cold paths doesn't affect anything. Let's leave it be.
1797 if (obtained
&& likely(!fill
))
1798 list_del_init(&pwq
->pending_node
);
1801 raw_spin_unlock(&nna
->lock
);
1809 * pwq_activate_first_inactive - Activate the first inactive work item on a pwq
1810 * @pwq: pool_workqueue of interest
1811 * @fill: max_active may have increased, try to increase concurrency level
1813 * Activate the first inactive work item of @pwq if available and allowed by
1816 * Returns %true if an inactive work item has been activated. %false if no
1817 * inactive work item is found or max_active limit is reached.
1819 static bool pwq_activate_first_inactive(struct pool_workqueue
*pwq
, bool fill
)
1821 struct work_struct
*work
=
1822 list_first_entry_or_null(&pwq
->inactive_works
,
1823 struct work_struct
, entry
);
1825 if (work
&& pwq_tryinc_nr_active(pwq
, fill
)) {
1826 __pwq_activate_work(pwq
, work
);
1834 * unplug_oldest_pwq - unplug the oldest pool_workqueue
1835 * @wq: workqueue_struct where its oldest pwq is to be unplugged
1837 * This function should only be called for ordered workqueues where only the
1838 * oldest pwq is unplugged, the others are plugged to suspend execution to
1839 * ensure proper work item ordering::
1841 * dfl_pwq --------------+ [P] - plugged
1844 * pwqs -> A -> B [P] -> C [P] (newest)
1850 * When the oldest pwq is drained and removed, this function should be called
1851 * to unplug the next oldest one to start its work item execution. Note that
1852 * pwq's are linked into wq->pwqs with the oldest first, so the first one in
1853 * the list is the oldest.
1855 static void unplug_oldest_pwq(struct workqueue_struct
*wq
)
1857 struct pool_workqueue
*pwq
;
1859 lockdep_assert_held(&wq
->mutex
);
1861 /* Caller should make sure that pwqs isn't empty before calling */
1862 pwq
= list_first_entry_or_null(&wq
->pwqs
, struct pool_workqueue
,
1864 raw_spin_lock_irq(&pwq
->pool
->lock
);
1866 pwq
->plugged
= false;
1867 if (pwq_activate_first_inactive(pwq
, true)) {
1869 * While plugged, queueing skips activation which
1870 * includes bumping the nr_active count and adding the
1871 * pwq to nna->pending_pwqs if the count can't be
1872 * obtained. We need to restore both for the pwq being
1873 * unplugged. The first call activates the first
1874 * inactive work item and the second, if there are more
1875 * inactive, puts the pwq on pending_pwqs.
1877 pwq_activate_first_inactive(pwq
, false);
1879 kick_pool(pwq
->pool
);
1882 raw_spin_unlock_irq(&pwq
->pool
->lock
);
1886 * node_activate_pending_pwq - Activate a pending pwq on a wq_node_nr_active
1887 * @nna: wq_node_nr_active to activate a pending pwq for
1888 * @caller_pool: worker_pool the caller is locking
1890 * Activate a pwq in @nna->pending_pwqs. Called with @caller_pool locked.
1891 * @caller_pool may be unlocked and relocked to lock other worker_pools.
1893 static void node_activate_pending_pwq(struct wq_node_nr_active
*nna
,
1894 struct worker_pool
*caller_pool
)
1896 struct worker_pool
*locked_pool
= caller_pool
;
1897 struct pool_workqueue
*pwq
;
1898 struct work_struct
*work
;
1900 lockdep_assert_held(&caller_pool
->lock
);
1902 raw_spin_lock(&nna
->lock
);
1904 pwq
= list_first_entry_or_null(&nna
->pending_pwqs
,
1905 struct pool_workqueue
, pending_node
);
1910 * If @pwq is for a different pool than @locked_pool, we need to lock
1911 * @pwq->pool->lock. Let's trylock first. If unsuccessful, do the unlock
1912 * / lock dance. For that, we also need to release @nna->lock as it's
1913 * nested inside pool locks.
1915 if (pwq
->pool
!= locked_pool
) {
1916 raw_spin_unlock(&locked_pool
->lock
);
1917 locked_pool
= pwq
->pool
;
1918 if (!raw_spin_trylock(&locked_pool
->lock
)) {
1919 raw_spin_unlock(&nna
->lock
);
1920 raw_spin_lock(&locked_pool
->lock
);
1921 raw_spin_lock(&nna
->lock
);
1927 * $pwq may not have any inactive work items due to e.g. cancellations.
1928 * Drop it from pending_pwqs and see if there's another one.
1930 work
= list_first_entry_or_null(&pwq
->inactive_works
,
1931 struct work_struct
, entry
);
1933 list_del_init(&pwq
->pending_node
);
1938 * Acquire an nr_active count and activate the inactive work item. If
1939 * $pwq still has inactive work items, rotate it to the end of the
1940 * pending_pwqs so that we round-robin through them. This means that
1941 * inactive work items are not activated in queueing order which is fine
1942 * given that there has never been any ordering across different pwqs.
1944 if (likely(tryinc_node_nr_active(nna
))) {
1946 __pwq_activate_work(pwq
, work
);
1948 if (list_empty(&pwq
->inactive_works
))
1949 list_del_init(&pwq
->pending_node
);
1951 list_move_tail(&pwq
->pending_node
, &nna
->pending_pwqs
);
1953 /* if activating a foreign pool, make sure it's running */
1954 if (pwq
->pool
!= caller_pool
)
1955 kick_pool(pwq
->pool
);
1959 raw_spin_unlock(&nna
->lock
);
1960 if (locked_pool
!= caller_pool
) {
1961 raw_spin_unlock(&locked_pool
->lock
);
1962 raw_spin_lock(&caller_pool
->lock
);
1967 * pwq_dec_nr_active - Retire an active count
1968 * @pwq: pool_workqueue of interest
1970 * Decrement @pwq's nr_active and try to activate the first inactive work item.
1971 * For unbound workqueues, this function may temporarily drop @pwq->pool->lock.
1973 static void pwq_dec_nr_active(struct pool_workqueue
*pwq
)
1975 struct worker_pool
*pool
= pwq
->pool
;
1976 struct wq_node_nr_active
*nna
= wq_node_nr_active(pwq
->wq
, pool
->node
);
1978 lockdep_assert_held(&pool
->lock
);
1981 * @pwq->nr_active should be decremented for both percpu and unbound
1987 * For a percpu workqueue, it's simple. Just need to kick the first
1988 * inactive work item on @pwq itself.
1991 pwq_activate_first_inactive(pwq
, false);
1996 * If @pwq is for an unbound workqueue, it's more complicated because
1997 * multiple pwqs and pools may be sharing the nr_active count. When a
1998 * pwq needs to wait for an nr_active count, it puts itself on
1999 * $nna->pending_pwqs. The following atomic_dec_return()'s implied
2000 * memory barrier is paired with smp_mb() in pwq_tryinc_nr_active() to
2001 * guarantee that either we see non-empty pending_pwqs or they see
2002 * decremented $nna->nr.
2004 * $nna->max may change as CPUs come online/offline and @pwq->wq's
2005 * max_active gets updated. However, it is guaranteed to be equal to or
2006 * larger than @pwq->wq->min_active which is above zero unless freezing.
2007 * This maintains the forward progress guarantee.
2009 if (atomic_dec_return(&nna
->nr
) >= READ_ONCE(nna
->max
))
2012 if (!list_empty(&nna
->pending_pwqs
))
2013 node_activate_pending_pwq(nna
, pool
);
2017 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
2018 * @pwq: pwq of interest
2019 * @work_data: work_data of work which left the queue
2021 * A work either has completed or is removed from pending queue,
2022 * decrement nr_in_flight of its pwq and handle workqueue flushing.
2025 * For unbound workqueues, this function may temporarily drop @pwq->pool->lock
2026 * and thus should be called after all other state updates for the in-flight
2027 * work item is complete.
2030 * raw_spin_lock_irq(pool->lock).
2032 static void pwq_dec_nr_in_flight(struct pool_workqueue
*pwq
, unsigned long work_data
)
2034 int color
= get_work_color(work_data
);
2036 if (!(work_data
& WORK_STRUCT_INACTIVE
))
2037 pwq_dec_nr_active(pwq
);
2039 pwq
->nr_in_flight
[color
]--;
2041 /* is flush in progress and are we at the flushing tip? */
2042 if (likely(pwq
->flush_color
!= color
))
2045 /* are there still in-flight works? */
2046 if (pwq
->nr_in_flight
[color
])
2049 /* this pwq is done, clear flush_color */
2050 pwq
->flush_color
= -1;
2053 * If this was the last pwq, wake up the first flusher. It
2054 * will handle the rest.
2056 if (atomic_dec_and_test(&pwq
->wq
->nr_pwqs_to_flush
))
2057 complete(&pwq
->wq
->first_flusher
->done
);
2063 * try_to_grab_pending - steal work item from worklist and disable irq
2064 * @work: work item to steal
2065 * @cflags: %WORK_CANCEL_ flags
2066 * @irq_flags: place to store irq state
2068 * Try to grab PENDING bit of @work. This function can handle @work in any
2069 * stable state - idle, on timer or on worklist.
2073 * ======== ================================================================
2074 * 1 if @work was pending and we successfully stole PENDING
2075 * 0 if @work was idle and we claimed PENDING
2076 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
2077 * ======== ================================================================
2080 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
2081 * interrupted while holding PENDING and @work off queue, irq must be
2082 * disabled on entry. This, combined with delayed_work->timer being
2083 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
2085 * On successful return, >= 0, irq is disabled and the caller is
2086 * responsible for releasing it using local_irq_restore(*@irq_flags).
2088 * This function is safe to call from any context including IRQ handler.
2090 static int try_to_grab_pending(struct work_struct
*work
, u32 cflags
,
2091 unsigned long *irq_flags
)
2093 struct worker_pool
*pool
;
2094 struct pool_workqueue
*pwq
;
2096 local_irq_save(*irq_flags
);
2098 /* try to steal the timer if it exists */
2099 if (cflags
& WORK_CANCEL_DELAYED
) {
2100 struct delayed_work
*dwork
= to_delayed_work(work
);
2103 * dwork->timer is irqsafe. If timer_delete() fails, it's
2104 * guaranteed that the timer is not queued anywhere and not
2105 * running on the local CPU.
2107 if (likely(timer_delete(&dwork
->timer
)))
2111 /* try to claim PENDING the normal way */
2112 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
)))
2117 * The queueing is in progress, or it is already queued. Try to
2118 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
2120 pool
= get_work_pool(work
);
2124 raw_spin_lock(&pool
->lock
);
2126 * work->data is guaranteed to point to pwq only while the work
2127 * item is queued on pwq->wq, and both updating work->data to point
2128 * to pwq on queueing and to pool on dequeueing are done under
2129 * pwq->pool->lock. This in turn guarantees that, if work->data
2130 * points to pwq which is associated with a locked pool, the work
2131 * item is currently queued on that pool.
2133 pwq
= get_work_pwq(work
);
2134 if (pwq
&& pwq
->pool
== pool
) {
2135 unsigned long work_data
= *work_data_bits(work
);
2137 debug_work_deactivate(work
);
2140 * A cancelable inactive work item must be in the
2141 * pwq->inactive_works since a queued barrier can't be
2142 * canceled (see the comments in insert_wq_barrier()).
2144 * An inactive work item cannot be deleted directly because
2145 * it might have linked barrier work items which, if left
2146 * on the inactive_works list, will confuse pwq->nr_active
2147 * management later on and cause stall. Move the linked
2148 * barrier work items to the worklist when deleting the grabbed
2149 * item. Also keep WORK_STRUCT_INACTIVE in work_data, so that
2150 * it doesn't participate in nr_active management in later
2151 * pwq_dec_nr_in_flight().
2153 if (work_data
& WORK_STRUCT_INACTIVE
)
2154 move_linked_works(work
, &pwq
->pool
->worklist
, NULL
);
2156 list_del_init(&work
->entry
);
2159 * work->data points to pwq iff queued. Let's point to pool. As
2160 * this destroys work->data needed by the next step, stash it.
2162 set_work_pool_and_keep_pending(work
, pool
->id
,
2163 pool_offq_flags(pool
));
2165 /* must be the last step, see the function comment */
2166 pwq_dec_nr_in_flight(pwq
, work_data
);
2168 raw_spin_unlock(&pool
->lock
);
2172 raw_spin_unlock(&pool
->lock
);
2175 local_irq_restore(*irq_flags
);
2180 * work_grab_pending - steal work item from worklist and disable irq
2181 * @work: work item to steal
2182 * @cflags: %WORK_CANCEL_ flags
2183 * @irq_flags: place to store IRQ state
2185 * Grab PENDING bit of @work. @work can be in any stable state - idle, on timer
2188 * Can be called from any context. IRQ is disabled on return with IRQ state
2189 * stored in *@irq_flags. The caller is responsible for re-enabling it using
2190 * local_irq_restore().
2192 * Returns %true if @work was pending. %false if idle.
2194 static bool work_grab_pending(struct work_struct
*work
, u32 cflags
,
2195 unsigned long *irq_flags
)
2200 ret
= try_to_grab_pending(work
, cflags
, irq_flags
);
2208 * insert_work - insert a work into a pool
2209 * @pwq: pwq @work belongs to
2210 * @work: work to insert
2211 * @head: insertion point
2212 * @extra_flags: extra WORK_STRUCT_* flags to set
2214 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
2215 * work_struct flags.
2218 * raw_spin_lock_irq(pool->lock).
2220 static void insert_work(struct pool_workqueue
*pwq
, struct work_struct
*work
,
2221 struct list_head
*head
, unsigned int extra_flags
)
2223 debug_work_activate(work
);
2225 /* record the work call stack in order to print it in KASAN reports */
2226 kasan_record_aux_stack(work
);
2228 /* we own @work, set data and link */
2229 set_work_pwq(work
, pwq
, extra_flags
);
2230 list_add_tail(&work
->entry
, head
);
2235 * Test whether @work is being queued from another work executing on the
2238 static bool is_chained_work(struct workqueue_struct
*wq
)
2240 struct worker
*worker
;
2242 worker
= current_wq_worker();
2244 * Return %true iff I'm a worker executing a work item on @wq. If
2245 * I'm @worker, it's safe to dereference it without locking.
2247 return worker
&& worker
->current_pwq
->wq
== wq
;
2251 * When queueing an unbound work item to a wq, prefer local CPU if allowed
2252 * by wq_unbound_cpumask. Otherwise, round robin among the allowed ones to
2253 * avoid perturbing sensitive tasks.
2255 static int wq_select_unbound_cpu(int cpu
)
2259 if (likely(!wq_debug_force_rr_cpu
)) {
2260 if (cpumask_test_cpu(cpu
, wq_unbound_cpumask
))
2263 pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
2266 new_cpu
= __this_cpu_read(wq_rr_cpu_last
);
2267 new_cpu
= cpumask_next_and_wrap(new_cpu
, wq_unbound_cpumask
, cpu_online_mask
);
2268 if (unlikely(new_cpu
>= nr_cpu_ids
))
2270 __this_cpu_write(wq_rr_cpu_last
, new_cpu
);
2275 static void __queue_work(int cpu
, struct workqueue_struct
*wq
,
2276 struct work_struct
*work
)
2278 struct pool_workqueue
*pwq
;
2279 struct worker_pool
*last_pool
, *pool
;
2280 unsigned int work_flags
;
2281 unsigned int req_cpu
= cpu
;
2284 * NOTE: Check whether the used workqueue is deprecated and warn
2286 if (unlikely(wq
->flags
& __WQ_DEPRECATED
))
2287 pr_warn_once("workqueue: work func %ps enqueued on deprecated workqueue. "
2288 "Use system_{percpu|dfl}_wq instead.\n",
2292 * While a work item is PENDING && off queue, a task trying to
2293 * steal the PENDING will busy-loop waiting for it to either get
2294 * queued or lose PENDING. Grabbing PENDING and queueing should
2295 * happen with IRQ disabled.
2297 lockdep_assert_irqs_disabled();
2300 * For a draining wq, only works from the same workqueue are
2301 * allowed. The __WQ_DESTROYING helps to spot the issue that
2302 * queues a new work item to a wq after destroy_workqueue(wq).
2304 if (unlikely(wq
->flags
& (__WQ_DESTROYING
| __WQ_DRAINING
) &&
2305 WARN_ONCE(!is_chained_work(wq
), "workqueue: cannot queue %ps on wq %s\n",
2306 work
->func
, wq
->name
))) {
2307 struct work_offq_data offqd
;
2310 * State on entry: PENDING is set, work is off-queue (no
2311 * insert_work() has run).
2313 * Returning without clearing PENDING would leave the work
2314 * in a weird state (PENDING=1, PWQ=0, entry empty)
2316 work_offqd_unpack(&offqd
, *work_data_bits(work
));
2317 set_work_pool_and_clear_pending(work
, offqd
.pool_id
,
2318 work_offqd_pack_flags(&offqd
));
2323 /* pwq which will be used unless @work is executing elsewhere */
2324 if (req_cpu
== WORK_CPU_UNBOUND
) {
2325 if (wq
->flags
& WQ_UNBOUND
)
2326 cpu
= wq_select_unbound_cpu(raw_smp_processor_id());
2328 cpu
= raw_smp_processor_id();
2331 pwq
= rcu_dereference(*per_cpu_ptr(wq
->cpu_pwq
, cpu
));
2335 * If @work was previously on a different pool, it might still be
2336 * running there, in which case the work needs to be queued on that
2337 * pool to guarantee non-reentrancy.
2339 * For ordered workqueue, work items must be queued on the newest pwq
2340 * for accurate order management. Guaranteed order also guarantees
2341 * non-reentrancy. See the comments above unplug_oldest_pwq().
2343 last_pool
= get_work_pool(work
);
2344 if (last_pool
&& last_pool
!= pool
&& !(wq
->flags
& __WQ_ORDERED
)) {
2345 struct worker
*worker
;
2347 raw_spin_lock(&last_pool
->lock
);
2349 worker
= find_worker_executing_work(last_pool
, work
);
2351 if (worker
&& worker
->current_pwq
->wq
== wq
) {
2352 pwq
= worker
->current_pwq
;
2354 WARN_ON_ONCE(pool
!= last_pool
);
2356 /* meh... not running there, queue here */
2357 raw_spin_unlock(&last_pool
->lock
);
2358 raw_spin_lock(&pool
->lock
);
2361 raw_spin_lock(&pool
->lock
);
2365 * pwq is determined and locked. For unbound pools, we could have raced
2366 * with pwq release and it could already be dead. If its refcnt is zero,
2367 * repeat pwq selection. Note that unbound pwqs never die without
2368 * another pwq replacing it in cpu_pwq or while work items are executing
2369 * on it, so the retrying is guaranteed to make forward-progress.
2371 if (unlikely(!pwq
->refcnt
)) {
2372 if (wq
->flags
& WQ_UNBOUND
) {
2373 raw_spin_unlock(&pool
->lock
);
2378 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
2382 /* pwq determined, queue */
2383 trace_workqueue_queue_work(req_cpu
, pwq
, work
);
2385 if (WARN_ON(!list_empty(&work
->entry
)))
2388 pwq
->nr_in_flight
[pwq
->work_color
]++;
2389 work_flags
= work_color_to_flags(pwq
->work_color
);
2392 * Limit the number of concurrently active work items to max_active.
2393 * @work must also queue behind existing inactive work items to maintain
2394 * ordering when max_active changes. See wq_adjust_max_active().
2396 if (list_empty(&pwq
->inactive_works
) && pwq_tryinc_nr_active(pwq
, false)) {
2397 if (list_empty(&pool
->worklist
))
2398 pool
->last_progress_ts
= jiffies
;
2400 trace_workqueue_activate_work(work
);
2401 insert_work(pwq
, work
, &pool
->worklist
, work_flags
);
2404 work_flags
|= WORK_STRUCT_INACTIVE
;
2405 insert_work(pwq
, work
, &pwq
->inactive_works
, work_flags
);
2409 raw_spin_unlock(&pool
->lock
);
2413 static bool clear_pending_if_disabled(struct work_struct
*work
)
2415 unsigned long data
= *work_data_bits(work
);
2416 struct work_offq_data offqd
;
2418 if (likely((data
& WORK_STRUCT_PWQ
) ||
2419 !(data
& WORK_OFFQ_DISABLE_MASK
)))
2422 work_offqd_unpack(&offqd
, data
);
2423 set_work_pool_and_clear_pending(work
, offqd
.pool_id
,
2424 work_offqd_pack_flags(&offqd
));
2429 * queue_work_on - queue work on specific cpu
2430 * @cpu: CPU number to execute work on
2431 * @wq: workqueue to use
2432 * @work: work to queue
2434 * We queue the work to a specific CPU, the caller must ensure it
2435 * can't go away. Callers that fail to ensure that the specified
2436 * CPU cannot go away will execute on a randomly chosen CPU.
2437 * But note well that callers specifying a CPU that never has been
2438 * online will get a splat.
2440 * Return: %false if @work was already on a queue, %true otherwise.
2442 bool queue_work_on(int cpu
, struct workqueue_struct
*wq
,
2443 struct work_struct
*work
)
2446 unsigned long irq_flags
;
2448 local_irq_save(irq_flags
);
2450 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
)) &&
2451 !clear_pending_if_disabled(work
)) {
2452 __queue_work(cpu
, wq
, work
);
2456 local_irq_restore(irq_flags
);
2459 EXPORT_SYMBOL(queue_work_on
);
2462 * select_numa_node_cpu - Select a CPU based on NUMA node
2463 * @node: NUMA node ID that we want to select a CPU from
2465 * This function will attempt to find a "random" cpu available on a given
2466 * node. If there are no CPUs available on the given node it will return
2467 * WORK_CPU_UNBOUND indicating that we should just schedule to any
2468 * available CPU if we need to schedule this work.
2470 static int select_numa_node_cpu(int node
)
2474 /* Delay binding to CPU if node is not valid or online */
2475 if (node
< 0 || node
>= MAX_NUMNODES
|| !node_online(node
))
2476 return WORK_CPU_UNBOUND
;
2478 /* Use local node/cpu if we are already there */
2479 cpu
= raw_smp_processor_id();
2480 if (node
== cpu_to_node(cpu
))
2483 /* Use "random" otherwise know as "first" online CPU of node */
2484 cpu
= cpumask_any_and(cpumask_of_node(node
), cpu_online_mask
);
2486 /* If CPU is valid return that, otherwise just defer */
2487 return cpu
< nr_cpu_ids
? cpu
: WORK_CPU_UNBOUND
;
2491 * queue_work_node - queue work on a "random" cpu for a given NUMA node
2492 * @node: NUMA node that we are targeting the work for
2493 * @wq: workqueue to use
2494 * @work: work to queue
2496 * We queue the work to a "random" CPU within a given NUMA node. The basic
2497 * idea here is to provide a way to somehow associate work with a given
2500 * This function will only make a best effort attempt at getting this onto
2501 * the right NUMA node. If no node is requested or the requested node is
2502 * offline then we just fall back to standard queue_work behavior.
2504 * Currently the "random" CPU ends up being the first available CPU in the
2505 * intersection of cpu_online_mask and the cpumask of the node, unless we
2506 * are running on the node. In that case we just use the current CPU.
2508 * Return: %false if @work was already on a queue, %true otherwise.
2510 bool queue_work_node(int node
, struct workqueue_struct
*wq
,
2511 struct work_struct
*work
)
2513 unsigned long irq_flags
;
2517 * This current implementation is specific to unbound workqueues.
2518 * Specifically we only return the first available CPU for a given
2519 * node instead of cycling through individual CPUs within the node.
2521 * If this is used with a per-cpu workqueue then the logic in
2522 * workqueue_select_cpu_near would need to be updated to allow for
2523 * some round robin type logic.
2525 WARN_ON_ONCE(!(wq
->flags
& WQ_UNBOUND
));
2527 local_irq_save(irq_flags
);
2529 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
)) &&
2530 !clear_pending_if_disabled(work
)) {
2531 int cpu
= select_numa_node_cpu(node
);
2533 __queue_work(cpu
, wq
, work
);
2537 local_irq_restore(irq_flags
);
2540 EXPORT_SYMBOL_GPL(queue_work_node
);
2542 void delayed_work_timer_fn(struct timer_list
*t
)
2544 struct delayed_work
*dwork
= timer_container_of(dwork
, t
, timer
);
2546 /* should have been called from irqsafe timer with irq already off */
2547 __queue_work(dwork
->cpu
, dwork
->wq
, &dwork
->work
);
2549 EXPORT_SYMBOL(delayed_work_timer_fn
);
2551 static void __queue_delayed_work(int cpu
, struct workqueue_struct
*wq
,
2552 struct delayed_work
*dwork
, unsigned long delay
)
2554 struct timer_list
*timer
= &dwork
->timer
;
2555 struct work_struct
*work
= &dwork
->work
;
2557 WARN_ON_ONCE(timer
->function
!= delayed_work_timer_fn
);
2558 WARN_ON_ONCE(timer_pending(timer
));
2559 WARN_ON_ONCE(!list_empty(&work
->entry
));
2562 * If @delay is 0, queue @dwork->work immediately. This is for
2563 * both optimization and correctness. The earliest @timer can
2564 * expire is on the closest next tick and delayed_work users depend
2565 * on that there's no such delay when @delay is 0.
2568 __queue_work(cpu
, wq
, &dwork
->work
);
2572 WARN_ON_ONCE(cpu
!= WORK_CPU_UNBOUND
&& !cpu_online(cpu
));
2575 timer
->expires
= jiffies
+ delay
;
2577 if (housekeeping_enabled(HK_TYPE_TIMER
)) {
2578 /* If the current cpu is a housekeeping cpu, use it. */
2579 cpu
= smp_processor_id();
2580 if (!housekeeping_test_cpu(cpu
, HK_TYPE_TIMER
))
2581 cpu
= housekeeping_any_cpu(HK_TYPE_TIMER
);
2582 add_timer_on(timer
, cpu
);
2584 if (likely(cpu
== WORK_CPU_UNBOUND
))
2585 add_timer_global(timer
);
2587 add_timer_on(timer
, cpu
);
2592 * queue_delayed_work_on - queue work on specific CPU after delay
2593 * @cpu: CPU number to execute work on
2594 * @wq: workqueue to use
2595 * @dwork: work to queue
2596 * @delay: number of jiffies to wait before queueing
2598 * We queue the delayed_work to a specific CPU, for non-zero delays the
2599 * caller must ensure it is online and can't go away. Callers that fail
2600 * to ensure this, may get @dwork->timer queued to an offlined CPU and
2601 * this will prevent queueing of @dwork->work unless the offlined CPU
2602 * becomes online again.
2604 * Return: %false if @work was already on a queue, %true otherwise. If
2605 * @delay is zero and @dwork is idle, it will be scheduled for immediate
2608 bool queue_delayed_work_on(int cpu
, struct workqueue_struct
*wq
,
2609 struct delayed_work
*dwork
, unsigned long delay
)
2611 struct work_struct
*work
= &dwork
->work
;
2613 unsigned long irq_flags
;
2615 /* read the comment in __queue_work() */
2616 local_irq_save(irq_flags
);
2618 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
)) &&
2619 !clear_pending_if_disabled(work
)) {
2620 __queue_delayed_work(cpu
, wq
, dwork
, delay
);
2624 local_irq_restore(irq_flags
);
2627 EXPORT_SYMBOL(queue_delayed_work_on
);
2630 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
2631 * @cpu: CPU number to execute work on
2632 * @wq: workqueue to use
2633 * @dwork: work to queue
2634 * @delay: number of jiffies to wait before queueing
2636 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
2637 * modify @dwork's timer so that it expires after @delay. If @delay is
2638 * zero, @work is guaranteed to be scheduled immediately regardless of its
2641 * Return: %false if @dwork was idle and queued, %true if @dwork was
2642 * pending and its timer was modified.
2644 * This function is safe to call from any context including IRQ handler.
2645 * See try_to_grab_pending() for details.
2647 bool mod_delayed_work_on(int cpu
, struct workqueue_struct
*wq
,
2648 struct delayed_work
*dwork
, unsigned long delay
)
2650 unsigned long irq_flags
;
2653 ret
= work_grab_pending(&dwork
->work
, WORK_CANCEL_DELAYED
, &irq_flags
);
2655 if (!clear_pending_if_disabled(&dwork
->work
))
2656 __queue_delayed_work(cpu
, wq
, dwork
, delay
);
2658 local_irq_restore(irq_flags
);
2661 EXPORT_SYMBOL_GPL(mod_delayed_work_on
);
2663 static void rcu_work_rcufn(struct rcu_head
*rcu
)
2665 struct rcu_work
*rwork
= container_of(rcu
, struct rcu_work
, rcu
);
2667 /* read the comment in __queue_work() */
2668 local_irq_disable();
2669 __queue_work(WORK_CPU_UNBOUND
, rwork
->wq
, &rwork
->work
);
2674 * queue_rcu_work - queue work after a RCU grace period
2675 * @wq: workqueue to use
2676 * @rwork: work to queue
2678 * Return: %false if @rwork was already pending, %true otherwise. Note
2679 * that a full RCU grace period is guaranteed only after a %true return.
2680 * While @rwork is guaranteed to be executed after a %false return, the
2681 * execution may happen before a full RCU grace period has passed.
2683 bool queue_rcu_work(struct workqueue_struct
*wq
, struct rcu_work
*rwork
)
2685 struct work_struct
*work
= &rwork
->work
;
2688 * rcu_work can't be canceled or disabled. Warn if the user reached
2689 * inside @rwork and disabled the inner work.
2691 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
)) &&
2692 !WARN_ON_ONCE(clear_pending_if_disabled(work
))) {
2694 call_rcu_hurry(&rwork
->rcu
, rcu_work_rcufn
);
2700 EXPORT_SYMBOL(queue_rcu_work
);
2702 static struct worker
*alloc_worker(int node
)
2704 struct worker
*worker
;
2706 worker
= kzalloc_node(sizeof(*worker
), GFP_KERNEL
, node
);
2708 INIT_LIST_HEAD(&worker
->entry
);
2709 INIT_LIST_HEAD(&worker
->scheduled
);
2710 INIT_LIST_HEAD(&worker
->node
);
2711 /* on creation a worker is in !idle && prep state */
2712 worker
->flags
= WORKER_PREP
;
2717 static cpumask_t
*pool_allowed_cpus(struct worker_pool
*pool
)
2719 if (pool
->cpu
< 0 && pool
->attrs
->affn_strict
)
2720 return pool
->attrs
->__pod_cpumask
;
2722 return pool
->attrs
->cpumask
;
2726 * worker_attach_to_pool() - attach a worker to a pool
2727 * @worker: worker to be attached
2728 * @pool: the target pool
2730 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
2731 * cpu-binding of @worker are kept coordinated with the pool across
2734 static void worker_attach_to_pool(struct worker
*worker
,
2735 struct worker_pool
*pool
)
2737 mutex_lock(&wq_pool_attach_mutex
);
2740 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains stable
2741 * across this function. See the comments above the flag definition for
2742 * details. BH workers are, while per-CPU, always DISASSOCIATED.
2744 if (pool
->flags
& POOL_DISASSOCIATED
) {
2745 worker
->flags
|= WORKER_UNBOUND
;
2747 WARN_ON_ONCE(pool
->flags
& POOL_BH
);
2748 kthread_set_per_cpu(worker
->task
, pool
->cpu
);
2751 if (worker
->rescue_wq
)
2752 set_cpus_allowed_ptr(worker
->task
, pool_allowed_cpus(pool
));
2754 list_add_tail(&worker
->node
, &pool
->workers
);
2755 worker
->pool
= pool
;
2757 mutex_unlock(&wq_pool_attach_mutex
);
2760 static void unbind_worker(struct worker
*worker
)
2762 lockdep_assert_held(&wq_pool_attach_mutex
);
2764 kthread_set_per_cpu(worker
->task
, -1);
2765 if (cpumask_intersects(wq_unbound_cpumask
, cpu_active_mask
))
2766 WARN_ON_ONCE(set_cpus_allowed_ptr(worker
->task
, wq_unbound_cpumask
) < 0);
2768 WARN_ON_ONCE(set_cpus_allowed_ptr(worker
->task
, cpu_possible_mask
) < 0);
2772 static void detach_worker(struct worker
*worker
)
2774 lockdep_assert_held(&wq_pool_attach_mutex
);
2776 unbind_worker(worker
);
2777 list_del(&worker
->node
);
2781 * worker_detach_from_pool() - detach a worker from its pool
2782 * @worker: worker which is attached to its pool
2784 * Undo the attaching which had been done in worker_attach_to_pool(). The
2785 * caller worker shouldn't access to the pool after detached except it has
2786 * other reference to the pool.
2788 static void worker_detach_from_pool(struct worker
*worker
)
2790 struct worker_pool
*pool
= worker
->pool
;
2792 /* there is one permanent BH worker per CPU which should never detach */
2793 WARN_ON_ONCE(pool
->flags
& POOL_BH
);
2795 mutex_lock(&wq_pool_attach_mutex
);
2796 detach_worker(worker
);
2797 worker
->pool
= NULL
;
2798 mutex_unlock(&wq_pool_attach_mutex
);
2800 /* clear leftover flags without pool->lock after it is detached */
2801 worker
->flags
&= ~(WORKER_UNBOUND
| WORKER_REBOUND
);
2804 static int format_worker_id(char *buf
, size_t size
, struct worker
*worker
,
2805 struct worker_pool
*pool
)
2807 if (worker
->rescue_wq
)
2808 return scnprintf(buf
, size
, "kworker/R-%s",
2809 worker
->rescue_wq
->name
);
2813 return scnprintf(buf
, size
, "kworker/%d:%d%s",
2814 pool
->cpu
, worker
->id
,
2815 pool
->attrs
->nice
< 0 ? "H" : "");
2817 return scnprintf(buf
, size
, "kworker/u%d:%d",
2818 pool
->id
, worker
->id
);
2820 return scnprintf(buf
, size
, "kworker/dying");
2825 * create_worker - create a new workqueue worker
2826 * @pool: pool the new worker will belong to
2828 * Create and start a new worker which is attached to @pool.
2831 * Might sleep. Does GFP_KERNEL allocations.
2834 * Pointer to the newly created worker.
2836 static struct worker
*create_worker(struct worker_pool
*pool
)
2838 struct worker
*worker
;
2841 /* ID is needed to determine kthread name */
2842 id
= ida_alloc(&pool
->worker_ida
, GFP_KERNEL
);
2844 pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
2849 worker
= alloc_worker(pool
->node
);
2851 pr_err_once("workqueue: Failed to allocate a worker\n");
2857 if (!(pool
->flags
& POOL_BH
)) {
2858 char id_buf
[WORKER_ID_LEN
];
2860 format_worker_id(id_buf
, sizeof(id_buf
), worker
, pool
);
2861 worker
->task
= kthread_create_on_node(worker_thread
, worker
,
2862 pool
->node
, "%s", id_buf
);
2863 if (IS_ERR(worker
->task
)) {
2864 if (PTR_ERR(worker
->task
) == -EINTR
) {
2865 pr_err("workqueue: Interrupted when creating a worker thread \"%s\"\n",
2868 pr_err_once("workqueue: Failed to create a worker thread: %pe",
2874 set_user_nice(worker
->task
, pool
->attrs
->nice
);
2875 kthread_bind_mask(worker
->task
, pool_allowed_cpus(pool
));
2878 /* successful, attach the worker to the pool */
2879 worker_attach_to_pool(worker
, pool
);
2881 /* start the newly created worker */
2882 raw_spin_lock_irq(&pool
->lock
);
2884 worker
->pool
->nr_workers
++;
2885 worker_enter_idle(worker
);
2888 * @worker is waiting on a completion in kthread() and will trigger hung
2889 * check if not woken up soon. As kick_pool() is noop if @pool is empty,
2890 * wake it up explicitly.
2893 wake_up_process(worker
->task
);
2895 raw_spin_unlock_irq(&pool
->lock
);
2900 ida_free(&pool
->worker_ida
, id
);
2905 static void detach_dying_workers(struct list_head
*cull_list
)
2907 struct worker
*worker
;
2909 list_for_each_entry(worker
, cull_list
, entry
)
2910 detach_worker(worker
);
2913 static void reap_dying_workers(struct list_head
*cull_list
)
2915 struct worker
*worker
, *tmp
;
2917 list_for_each_entry_safe(worker
, tmp
, cull_list
, entry
) {
2918 list_del_init(&worker
->entry
);
2919 kthread_stop_put(worker
->task
);
2925 * set_worker_dying - Tag a worker for destruction
2926 * @worker: worker to be destroyed
2927 * @list: transfer worker away from its pool->idle_list and into list
2929 * Tag @worker for destruction and adjust @pool stats accordingly. The worker
2933 * raw_spin_lock_irq(pool->lock).
2935 static void set_worker_dying(struct worker
*worker
, struct list_head
*list
)
2937 struct worker_pool
*pool
= worker
->pool
;
2939 lockdep_assert_held(&pool
->lock
);
2940 lockdep_assert_held(&wq_pool_attach_mutex
);
2942 /* sanity check frenzy */
2943 if (WARN_ON(worker
->current_work
) ||
2944 WARN_ON(!list_empty(&worker
->scheduled
)) ||
2945 WARN_ON(!(worker
->flags
& WORKER_IDLE
)))
2951 worker
->flags
|= WORKER_DIE
;
2953 list_move(&worker
->entry
, list
);
2955 /* get an extra task struct reference for later kthread_stop_put() */
2956 get_task_struct(worker
->task
);
2960 * idle_worker_timeout - check if some idle workers can now be deleted.
2961 * @t: The pool's idle_timer that just expired
2963 * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
2964 * worker_leave_idle(), as a worker flicking between idle and active while its
2965 * pool is at the too_many_workers() tipping point would cause too much timer
2966 * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
2967 * it expire and re-evaluate things from there.
2969 static void idle_worker_timeout(struct timer_list
*t
)
2971 struct worker_pool
*pool
= timer_container_of(pool
, t
, idle_timer
);
2972 bool do_cull
= false;
2974 if (work_pending(&pool
->idle_cull_work
))
2977 raw_spin_lock_irq(&pool
->lock
);
2979 if (too_many_workers(pool
)) {
2980 struct worker
*worker
;
2981 unsigned long expires
;
2983 /* idle_list is kept in LIFO order, check the last one */
2984 worker
= list_last_entry(&pool
->idle_list
, struct worker
, entry
);
2985 expires
= worker
->last_active
+ IDLE_WORKER_TIMEOUT
;
2986 do_cull
= !time_before(jiffies
, expires
);
2989 mod_timer(&pool
->idle_timer
, expires
);
2991 raw_spin_unlock_irq(&pool
->lock
);
2994 queue_work(system_dfl_wq
, &pool
->idle_cull_work
);
2998 * idle_cull_fn - cull workers that have been idle for too long.
2999 * @work: the pool's work for handling these idle workers
3001 * This goes through a pool's idle workers and gets rid of those that have been
3002 * idle for at least IDLE_WORKER_TIMEOUT seconds.
3004 * We don't want to disturb isolated CPUs because of a pcpu kworker being
3005 * culled, so this also resets worker affinity. This requires a sleepable
3006 * context, hence the split between timer callback and work item.
3008 static void idle_cull_fn(struct work_struct
*work
)
3010 struct worker_pool
*pool
= container_of(work
, struct worker_pool
, idle_cull_work
);
3011 LIST_HEAD(cull_list
);
3014 * Grabbing wq_pool_attach_mutex here ensures an already-running worker
3015 * cannot proceed beyong set_pf_worker() in its self-destruct path.
3016 * This is required as a previously-preempted worker could run after
3017 * set_worker_dying() has happened but before detach_dying_workers() did.
3019 mutex_lock(&wq_pool_attach_mutex
);
3020 raw_spin_lock_irq(&pool
->lock
);
3022 while (too_many_workers(pool
)) {
3023 struct worker
*worker
;
3024 unsigned long expires
;
3026 worker
= list_last_entry(&pool
->idle_list
, struct worker
, entry
);
3027 expires
= worker
->last_active
+ IDLE_WORKER_TIMEOUT
;
3029 if (time_before(jiffies
, expires
)) {
3030 mod_timer(&pool
->idle_timer
, expires
);
3034 set_worker_dying(worker
, &cull_list
);
3037 raw_spin_unlock_irq(&pool
->lock
);
3038 detach_dying_workers(&cull_list
);
3039 mutex_unlock(&wq_pool_attach_mutex
);
3041 reap_dying_workers(&cull_list
);
3044 static void send_mayday(struct pool_workqueue
*pwq
)
3046 struct workqueue_struct
*wq
= pwq
->wq
;
3048 lockdep_assert_held(&wq_mayday_lock
);
3053 /* mayday mayday mayday */
3054 if (list_empty(&pwq
->mayday_node
)) {
3056 * If @pwq is for an unbound wq, its base ref may be put at
3057 * any time due to an attribute change. Pin @pwq until the
3058 * rescuer is done with it.
3061 list_add_tail(&pwq
->mayday_node
, &wq
->maydays
);
3062 wake_up_process(wq
->rescuer
->task
);
3063 pwq
->stats
[PWQ_STAT_MAYDAY
]++;
3067 static void pool_mayday_timeout(struct timer_list
*t
)
3069 struct worker_pool
*pool
= timer_container_of(pool
, t
, mayday_timer
);
3070 struct work_struct
*work
;
3072 raw_spin_lock_irq(&pool
->lock
);
3073 raw_spin_lock(&wq_mayday_lock
); /* for wq->maydays */
3075 if (need_to_create_worker(pool
)) {
3077 * We've been trying to create a new worker but
3078 * haven't been successful. We might be hitting an
3079 * allocation deadlock. Send distress signals to
3082 list_for_each_entry(work
, &pool
->worklist
, entry
)
3083 send_mayday(get_work_pwq(work
));
3086 raw_spin_unlock(&wq_mayday_lock
);
3087 raw_spin_unlock_irq(&pool
->lock
);
3089 mod_timer(&pool
->mayday_timer
, jiffies
+ MAYDAY_INTERVAL
);
3093 * maybe_create_worker - create a new worker if necessary
3094 * @pool: pool to create a new worker for
3096 * Create a new worker for @pool if necessary. @pool is guaranteed to
3097 * have at least one idle worker on return from this function. If
3098 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
3099 * sent to all rescuers with works scheduled on @pool to resolve
3100 * possible allocation deadlock.
3102 * On return, need_to_create_worker() is guaranteed to be %false and
3103 * may_start_working() %true.
3106 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3107 * multiple times. Does GFP_KERNEL allocations. Called only from
3110 static void maybe_create_worker(struct worker_pool
*pool
)
3111 __releases(&pool
->lock
)
3112 __acquires(&pool
->lock
)
3115 raw_spin_unlock_irq(&pool
->lock
);
3117 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
3118 mod_timer(&pool
->mayday_timer
, jiffies
+ MAYDAY_INITIAL_TIMEOUT
);
3121 if (create_worker(pool
) || !need_to_create_worker(pool
))
3124 schedule_timeout_interruptible(CREATE_COOLDOWN
);
3126 if (!need_to_create_worker(pool
))
3130 timer_delete_sync(&pool
->mayday_timer
);
3131 raw_spin_lock_irq(&pool
->lock
);
3133 * This is necessary even after a new worker was just successfully
3134 * created as @pool->lock was dropped and the new worker might have
3135 * already become busy.
3137 if (need_to_create_worker(pool
))
3141 #ifdef CONFIG_PREEMPT_RT
3142 static void worker_lock_callback(struct worker_pool
*pool
)
3144 spin_lock(&pool
->cb_lock
);
3147 static void worker_unlock_callback(struct worker_pool
*pool
)
3149 spin_unlock(&pool
->cb_lock
);
3152 static void workqueue_callback_cancel_wait_running(struct worker_pool
*pool
)
3154 spin_lock(&pool
->cb_lock
);
3155 spin_unlock(&pool
->cb_lock
);
3160 static void worker_lock_callback(struct worker_pool
*pool
) { }
3161 static void worker_unlock_callback(struct worker_pool
*pool
) { }
3162 static void workqueue_callback_cancel_wait_running(struct worker_pool
*pool
) { }
3167 * manage_workers - manage worker pool
3170 * Assume the manager role and manage the worker pool @worker belongs
3171 * to. At any given time, there can be only zero or one manager per
3172 * pool. The exclusion is handled automatically by this function.
3174 * The caller can safely start processing works on false return. On
3175 * true return, it's guaranteed that need_to_create_worker() is false
3176 * and may_start_working() is true.
3179 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3180 * multiple times. Does GFP_KERNEL allocations.
3183 * %false if the pool doesn't need management and the caller can safely
3184 * start processing works, %true if management function was performed and
3185 * the conditions that the caller verified before calling the function may
3186 * no longer be true.
3188 static bool manage_workers(struct worker
*worker
)
3190 struct worker_pool
*pool
= worker
->pool
;
3192 if (pool
->flags
& POOL_MANAGER_ACTIVE
)
3195 pool
->flags
|= POOL_MANAGER_ACTIVE
;
3196 pool
->manager
= worker
;
3198 maybe_create_worker(pool
);
3200 pool
->manager
= NULL
;
3201 pool
->flags
&= ~POOL_MANAGER_ACTIVE
;
3202 rcuwait_wake_up(&manager_wait
);
3207 * process_one_work - process single work
3209 * @work: work to process
3211 * Process @work. This function contains all the logics necessary to
3212 * process a single work including synchronization against and
3213 * interaction with other workers on the same cpu, queueing and
3214 * flushing. As long as context requirement is met, any worker can
3215 * call this function to process a work.
3218 * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
3220 static void process_one_work(struct worker
*worker
, struct work_struct
*work
)
3221 __releases(&pool
->lock
)
3222 __acquires(&pool
->lock
)
3224 struct pool_workqueue
*pwq
= get_work_pwq(work
);
3225 struct worker_pool
*pool
= worker
->pool
;
3226 unsigned long work_data
;
3227 int lockdep_start_depth
, rcu_start_depth
;
3228 bool bh_draining
= pool
->flags
& POOL_BH_DRAINING
;
3229 #ifdef CONFIG_LOCKDEP
3231 * It is permissible to free the struct work_struct from
3232 * inside the function that is called from it, this we need to
3233 * take into account for lockdep too. To avoid bogus "held
3234 * lock freed" warnings as well as problems when looking into
3235 * work->lockdep_map, make a copy and use that here.
3237 struct lockdep_map lockdep_map
;
3239 lockdep_copy_map(&lockdep_map
, &work
->lockdep_map
);
3241 /* ensure we're on the correct CPU */
3242 WARN_ON_ONCE(!(pool
->flags
& POOL_DISASSOCIATED
) &&
3243 raw_smp_processor_id() != pool
->cpu
);
3245 /* claim and dequeue */
3246 debug_work_deactivate(work
);
3247 hash_add(pool
->busy_hash
, &worker
->hentry
, (unsigned long)work
);
3248 worker
->current_work
= work
;
3249 worker
->current_func
= work
->func
;
3250 worker
->current_pwq
= pwq
;
3252 worker
->current_at
= worker
->task
->se
.sum_exec_runtime
;
3253 worker
->current_start
= jiffies
;
3254 work_data
= *work_data_bits(work
);
3255 worker
->current_color
= get_work_color(work_data
);
3258 * Record wq name for cmdline and debug reporting, may get
3259 * overridden through set_worker_desc().
3261 strscpy(worker
->desc
, pwq
->wq
->name
, WORKER_DESC_LEN
);
3263 list_del_init(&work
->entry
);
3266 * CPU intensive works don't participate in concurrency management.
3267 * They're the scheduler's responsibility. This takes @worker out
3268 * of concurrency management and the next code block will chain
3269 * execution of the pending work items.
3271 if (unlikely(pwq
->wq
->flags
& WQ_CPU_INTENSIVE
))
3272 worker_set_flags(worker
, WORKER_CPU_INTENSIVE
);
3275 * Kick @pool if necessary. It's always noop for per-cpu worker pools
3276 * since nr_running would always be >= 1 at this point. This is used to
3277 * chain execution of the pending work items for WORKER_NOT_RUNNING
3278 * workers such as the UNBOUND and CPU_INTENSIVE ones.
3283 * Record the last pool and clear PENDING which should be the last
3284 * update to @work. Also, do this inside @pool->lock so that
3285 * PENDING and queued state changes happen together while IRQ is
3288 set_work_pool_and_clear_pending(work
, pool
->id
, pool_offq_flags(pool
));
3290 pwq
->stats
[PWQ_STAT_STARTED
]++;
3291 raw_spin_unlock_irq(&pool
->lock
);
3293 rcu_start_depth
= rcu_preempt_depth();
3294 lockdep_start_depth
= lockdep_depth(current
);
3295 /* see drain_dead_softirq_workfn() */
3297 lock_map_acquire(pwq
->wq
->lockdep_map
);
3298 lock_map_acquire(&lockdep_map
);
3300 * Strictly speaking we should mark the invariant state without holding
3301 * any locks, that is, before these two lock_map_acquire()'s.
3303 * However, that would result in:
3310 * Which would create W1->C->W1 dependencies, even though there is no
3311 * actual deadlock possible. There are two solutions, using a
3312 * read-recursive acquire on the work(queue) 'locks', but this will then
3313 * hit the lockdep limitation on recursive locks, or simply discard
3316 * AFAICT there is no possible deadlock scenario between the
3317 * flush_work() and complete() primitives (except for single-threaded
3318 * workqueues), so hiding them isn't a problem.
3320 lockdep_invariant_state(true);
3321 trace_workqueue_execute_start(work
);
3322 worker
->current_func(work
);
3324 * While we must be careful to not use "work" after this, the trace
3325 * point will only record its address.
3327 trace_workqueue_execute_end(work
, worker
->current_func
);
3329 lock_map_release(&lockdep_map
);
3331 lock_map_release(pwq
->wq
->lockdep_map
);
3333 if (unlikely((worker
->task
&& in_atomic()) ||
3334 lockdep_depth(current
) != lockdep_start_depth
||
3335 rcu_preempt_depth() != rcu_start_depth
)) {
3336 pr_err("BUG: workqueue leaked atomic, lock or RCU: %s[%d]\n"
3337 " preempt=0x%08x lock=%d->%d RCU=%d->%d workfn=%ps\n",
3338 current
->comm
, task_pid_nr(current
), preempt_count(),
3339 lockdep_start_depth
, lockdep_depth(current
),
3340 rcu_start_depth
, rcu_preempt_depth(),
3341 worker
->current_func
);
3342 debug_show_held_locks(current
);
3347 * The following prevents a kworker from hogging CPU on !PREEMPTION
3348 * kernels, where a requeueing work item waiting for something to
3349 * happen could deadlock with stop_machine as such work item could
3350 * indefinitely requeue itself while all other CPUs are trapped in
3351 * stop_machine. At the same time, report a quiescent RCU state so
3352 * the same condition doesn't freeze RCU.
3357 raw_spin_lock_irq(&pool
->lock
);
3359 pwq
->stats
[PWQ_STAT_COMPLETED
]++;
3362 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
3363 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
3364 * wq_cpu_intensive_thresh_us. Clear it.
3366 worker_clr_flags(worker
, WORKER_CPU_INTENSIVE
);
3368 /* tag the worker for identification in schedule() */
3369 worker
->last_func
= worker
->current_func
;
3371 /* we're done with it, release */
3372 hash_del(&worker
->hentry
);
3373 worker
->current_work
= NULL
;
3374 worker
->current_func
= NULL
;
3375 worker
->current_pwq
= NULL
;
3376 worker
->current_color
= INT_MAX
;
3378 /* must be the last step, see the function comment */
3379 pwq_dec_nr_in_flight(pwq
, work_data
);
3383 * process_scheduled_works - process scheduled works
3386 * Process all scheduled works. Please note that the scheduled list
3387 * may change while processing a work, so this function repeatedly
3388 * fetches a work from the top and executes it.
3391 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
3394 static void process_scheduled_works(struct worker
*worker
)
3396 struct work_struct
*work
;
3399 while ((work
= list_first_entry_or_null(&worker
->scheduled
,
3400 struct work_struct
, entry
))) {
3402 worker
->pool
->last_progress_ts
= jiffies
;
3405 process_one_work(worker
, work
);
3409 static void set_pf_worker(bool val
)
3411 mutex_lock(&wq_pool_attach_mutex
);
3413 current
->flags
|= PF_WQ_WORKER
;
3415 current
->flags
&= ~PF_WQ_WORKER
;
3416 mutex_unlock(&wq_pool_attach_mutex
);
3420 * worker_thread - the worker thread function
3423 * The worker thread function. All workers belong to a worker_pool -
3424 * either a per-cpu one or dynamic unbound one. These workers process all
3425 * work items regardless of their specific target workqueue. The only
3426 * exception is work items which belong to workqueues with a rescuer which
3427 * will be explained in rescuer_thread().
3431 static int worker_thread(void *__worker
)
3433 struct worker
*worker
= __worker
;
3434 struct worker_pool
*pool
= worker
->pool
;
3436 /* tell the scheduler that this is a workqueue worker */
3437 set_pf_worker(true);
3439 raw_spin_lock_irq(&pool
->lock
);
3441 /* am I supposed to die? */
3442 if (unlikely(worker
->flags
& WORKER_DIE
)) {
3443 raw_spin_unlock_irq(&pool
->lock
);
3444 set_pf_worker(false);
3446 * The worker is dead and PF_WQ_WORKER is cleared, worker->pool
3447 * shouldn't be accessed, reset it to NULL in case otherwise.
3449 worker
->pool
= NULL
;
3450 ida_free(&pool
->worker_ida
, worker
->id
);
3454 worker_leave_idle(worker
);
3456 /* no more worker necessary? */
3457 if (!need_more_worker(pool
))
3460 /* do we need to manage? */
3461 if (unlikely(!may_start_working(pool
)) && manage_workers(worker
))
3465 * ->scheduled list can only be filled while a worker is
3466 * preparing to process a work or actually processing it.
3467 * Make sure nobody diddled with it while I was sleeping.
3469 WARN_ON_ONCE(!list_empty(&worker
->scheduled
));
3472 * Finish PREP stage. We're guaranteed to have at least one idle
3473 * worker or that someone else has already assumed the manager
3474 * role. This is where @worker starts participating in concurrency
3475 * management if applicable and concurrency management is restored
3476 * after being rebound. See rebind_workers() for details.
3478 worker_clr_flags(worker
, WORKER_PREP
| WORKER_REBOUND
);
3481 struct work_struct
*work
=
3482 list_first_entry(&pool
->worklist
,
3483 struct work_struct
, entry
);
3485 if (assign_work(work
, worker
, NULL
))
3486 process_scheduled_works(worker
);
3487 } while (keep_working(pool
));
3489 worker_set_flags(worker
, WORKER_PREP
);
3492 * pool->lock is held and there's no work to process and no need to
3493 * manage, sleep. Workers are woken up only while holding
3494 * pool->lock or from local cpu, so setting the current state
3495 * before releasing pool->lock is enough to prevent losing any
3498 worker_enter_idle(worker
);
3499 __set_current_state(TASK_IDLE
);
3500 raw_spin_unlock_irq(&pool
->lock
);
3505 static bool assign_rescuer_work(struct pool_workqueue
*pwq
, struct worker
*rescuer
)
3507 struct worker_pool
*pool
= pwq
->pool
;
3508 struct work_struct
*cursor
= &pwq
->mayday_cursor
;
3509 struct work_struct
*work
, *n
;
3511 /* have work items to rescue? */
3512 if (!pwq
->nr_active
)
3516 if (!need_to_create_worker(pool
)) {
3518 * The pool has idle workers and doesn't need the rescuer, so it
3519 * could simply return false here.
3521 * However, the memory pressure might not be fully relieved.
3522 * In PERCPU pool with concurrency enabled, having idle workers
3523 * does not necessarily mean memory pressure is gone; it may
3524 * simply mean regular workers have woken up, completed their
3525 * work, and gone idle again due to concurrency limits.
3527 * In this case, those working workers may later sleep again,
3528 * the pool may run out of idle workers, and it will have to
3529 * allocate new ones and wait for the timer to send mayday,
3530 * causing unnecessary delay - especially if memory pressure
3531 * was never resolved throughout.
3533 * Do more work if memory pressure is still on to reduce
3534 * relapse, using (pool->flags & POOL_MANAGER_ACTIVE), though
3535 * not precisely, unless there are other PWQs needing help.
3537 if (!(pool
->flags
& POOL_MANAGER_ACTIVE
) ||
3538 !list_empty(&pwq
->wq
->maydays
))
3542 /* search from the start or cursor if available */
3543 if (list_empty(&cursor
->entry
))
3544 work
= list_first_entry(&pool
->worklist
, struct work_struct
, entry
);
3546 work
= list_next_entry(cursor
, entry
);
3548 /* find the next work item to rescue */
3549 list_for_each_entry_safe_from(work
, n
, &pool
->worklist
, entry
) {
3550 if (get_work_pwq(work
) == pwq
&& assign_work(work
, rescuer
, &n
)) {
3551 pwq
->stats
[PWQ_STAT_RESCUED
]++;
3552 /* put the cursor for next search */
3553 list_move_tail(&cursor
->entry
, &n
->entry
);
3562 * rescuer_thread - the rescuer thread function
3565 * Workqueue rescuer thread function. There's one rescuer for each
3566 * workqueue which has WQ_MEM_RECLAIM set.
3568 * Regular work processing on a pool may block trying to create a new
3569 * worker which uses GFP_KERNEL allocation which has slight chance of
3570 * developing into deadlock if some works currently on the same queue
3571 * need to be processed to satisfy the GFP_KERNEL allocation. This is
3572 * the problem rescuer solves.
3574 * When such condition is possible, the pool summons rescuers of all
3575 * workqueues which have works queued on the pool and let them process
3576 * those works so that forward progress can be guaranteed.
3578 * This should happen rarely.
3582 static int rescuer_thread(void *__rescuer
)
3584 struct worker
*rescuer
= __rescuer
;
3585 struct workqueue_struct
*wq
= rescuer
->rescue_wq
;
3588 set_user_nice(current
, RESCUER_NICE_LEVEL
);
3591 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
3592 * doesn't participate in concurrency management.
3594 set_pf_worker(true);
3596 set_current_state(TASK_IDLE
);
3599 * By the time the rescuer is requested to stop, the workqueue
3600 * shouldn't have any work pending, but @wq->maydays may still have
3601 * pwq(s) queued. This can happen by non-rescuer workers consuming
3602 * all the work items before the rescuer got to them. Go through
3603 * @wq->maydays processing before acting on should_stop so that the
3604 * list is always empty on exit.
3606 should_stop
= kthread_should_stop();
3608 /* see whether any pwq is asking for help */
3609 raw_spin_lock_irq(&wq_mayday_lock
);
3611 while (!list_empty(&wq
->maydays
)) {
3612 struct pool_workqueue
*pwq
= list_first_entry(&wq
->maydays
,
3613 struct pool_workqueue
, mayday_node
);
3614 struct worker_pool
*pool
= pwq
->pool
;
3615 unsigned int count
= 0;
3617 __set_current_state(TASK_RUNNING
);
3618 list_del_init(&pwq
->mayday_node
);
3620 raw_spin_unlock_irq(&wq_mayday_lock
);
3622 worker_attach_to_pool(rescuer
, pool
);
3624 raw_spin_lock_irq(&pool
->lock
);
3626 WARN_ON_ONCE(!list_empty(&rescuer
->scheduled
));
3628 while (assign_rescuer_work(pwq
, rescuer
)) {
3629 process_scheduled_works(rescuer
);
3632 * If the per-turn work item limit is reached and other
3633 * PWQs are in mayday, requeue mayday for this PWQ and
3634 * let the rescuer handle the other PWQs first.
3636 if (++count
> RESCUER_BATCH
&& !list_empty(&pwq
->wq
->maydays
) &&
3637 pwq
->nr_active
&& need_to_create_worker(pool
)) {
3638 raw_spin_lock(&wq_mayday_lock
);
3640 raw_spin_unlock(&wq_mayday_lock
);
3645 /* The cursor can not be left behind without the rescuer watching it. */
3646 if (!list_empty(&pwq
->mayday_cursor
.entry
) && list_empty(&pwq
->mayday_node
))
3647 list_del_init(&pwq
->mayday_cursor
.entry
);
3650 * Leave this pool. Notify regular workers; otherwise, we end up
3651 * with 0 concurrency and stalling the execution.
3655 raw_spin_unlock_irq(&pool
->lock
);
3657 worker_detach_from_pool(rescuer
);
3660 * Put the reference grabbed by send_mayday(). @pool might
3661 * go away any time after it.
3663 put_pwq_unlocked(pwq
);
3665 raw_spin_lock_irq(&wq_mayday_lock
);
3668 raw_spin_unlock_irq(&wq_mayday_lock
);
3671 __set_current_state(TASK_RUNNING
);
3672 set_pf_worker(false);
3676 /* rescuers should never participate in concurrency management */
3677 WARN_ON_ONCE(!(rescuer
->flags
& WORKER_NOT_RUNNING
));
3682 static void bh_worker(struct worker
*worker
)
3684 struct worker_pool
*pool
= worker
->pool
;
3685 int nr_restarts
= BH_WORKER_RESTARTS
;
3686 unsigned long end
= jiffies
+ BH_WORKER_JIFFIES
;
3688 worker_lock_callback(pool
);
3689 raw_spin_lock_irq(&pool
->lock
);
3690 worker_leave_idle(worker
);
3693 * This function follows the structure of worker_thread(). See there for
3694 * explanations on each step.
3696 if (!need_more_worker(pool
))
3699 WARN_ON_ONCE(!list_empty(&worker
->scheduled
));
3700 worker_clr_flags(worker
, WORKER_PREP
| WORKER_REBOUND
);
3703 struct work_struct
*work
=
3704 list_first_entry(&pool
->worklist
,
3705 struct work_struct
, entry
);
3707 if (assign_work(work
, worker
, NULL
))
3708 process_scheduled_works(worker
);
3709 } while (keep_working(pool
) &&
3710 --nr_restarts
&& time_before(jiffies
, end
));
3712 worker_set_flags(worker
, WORKER_PREP
);
3714 worker_enter_idle(worker
);
3716 raw_spin_unlock_irq(&pool
->lock
);
3717 worker_unlock_callback(pool
);
3721 * TODO: Convert all tasklet users to workqueue and use softirq directly.
3723 * This is currently called from tasklet[_hi]action() and thus is also called
3724 * whenever there are tasklets to run. Let's do an early exit if there's nothing
3725 * queued. Once conversion from tasklet is complete, the need_more_worker() test
3728 * After full conversion, we'll add worker->softirq_action, directly use the
3729 * softirq action and obtain the worker pointer from the softirq_action pointer.
3731 void workqueue_softirq_action(bool highpri
)
3733 struct worker_pool
*pool
=
3734 &per_cpu(bh_worker_pools
, smp_processor_id())[highpri
];
3735 if (need_more_worker(pool
))
3736 bh_worker(list_first_entry(&pool
->workers
, struct worker
, node
));
3739 struct wq_drain_dead_softirq_work
{
3740 struct work_struct work
;
3741 struct worker_pool
*pool
;
3742 struct completion done
;
3745 static void drain_dead_softirq_workfn(struct work_struct
*work
)
3747 struct wq_drain_dead_softirq_work
*dead_work
=
3748 container_of(work
, struct wq_drain_dead_softirq_work
, work
);
3749 struct worker_pool
*pool
= dead_work
->pool
;
3753 * @pool's CPU is dead and we want to execute its still pending work
3754 * items from this BH work item which is running on a different CPU. As
3755 * its CPU is dead, @pool can't be kicked and, as work execution path
3756 * will be nested, a lockdep annotation needs to be suppressed. Mark
3757 * @pool with %POOL_BH_DRAINING for the special treatments.
3759 raw_spin_lock_irq(&pool
->lock
);
3760 pool
->flags
|= POOL_BH_DRAINING
;
3761 raw_spin_unlock_irq(&pool
->lock
);
3763 bh_worker(list_first_entry(&pool
->workers
, struct worker
, node
));
3765 raw_spin_lock_irq(&pool
->lock
);
3766 pool
->flags
&= ~POOL_BH_DRAINING
;
3767 repeat
= need_more_worker(pool
);
3768 raw_spin_unlock_irq(&pool
->lock
);
3771 * bh_worker() might hit consecutive execution limit and bail. If there
3772 * still are pending work items, reschedule self and return so that we
3773 * don't hog this CPU's BH.
3776 if (pool
->attrs
->nice
== HIGHPRI_NICE_LEVEL
)
3777 queue_work(system_bh_highpri_wq
, work
);
3779 queue_work(system_bh_wq
, work
);
3781 complete(&dead_work
->done
);
3786 * @cpu is dead. Drain the remaining BH work items on the current CPU. It's
3787 * possible to allocate dead_work per CPU and avoid flushing. However, then we
3788 * have to worry about draining overlapping with CPU coming back online or
3789 * nesting (one CPU's dead_work queued on another CPU which is also dead and so
3790 * on). Let's keep it simple and drain them synchronously. These are BH work
3791 * items which shouldn't be requeued on the same pool. Shouldn't take long.
3793 void workqueue_softirq_dead(unsigned int cpu
)
3797 for (i
= 0; i
< NR_STD_WORKER_POOLS
; i
++) {
3798 struct worker_pool
*pool
= &per_cpu(bh_worker_pools
, cpu
)[i
];
3799 struct wq_drain_dead_softirq_work dead_work
;
3801 if (!need_more_worker(pool
))
3804 INIT_WORK_ONSTACK(&dead_work
.work
, drain_dead_softirq_workfn
);
3805 dead_work
.pool
= pool
;
3806 init_completion(&dead_work
.done
);
3808 if (pool
->attrs
->nice
== HIGHPRI_NICE_LEVEL
)
3809 queue_work(system_bh_highpri_wq
, &dead_work
.work
);
3811 queue_work(system_bh_wq
, &dead_work
.work
);
3813 wait_for_completion(&dead_work
.done
);
3814 destroy_work_on_stack(&dead_work
.work
);
3819 * check_flush_dependency - check for flush dependency sanity
3820 * @target_wq: workqueue being flushed
3821 * @target_work: work item being flushed (NULL for workqueue flushes)
3822 * @from_cancel: are we called from the work cancel path
3824 * %current is trying to flush the whole @target_wq or @target_work on it.
3825 * If this is not the cancel path (which implies work being flushed is either
3826 * already running, or will not be at all), check if @target_wq doesn't have
3827 * %WQ_MEM_RECLAIM and verify that %current is not reclaiming memory or running
3828 * on a workqueue which doesn't have %WQ_MEM_RECLAIM as that can break forward-
3829 * progress guarantee leading to a deadlock.
3831 static void check_flush_dependency(struct workqueue_struct
*target_wq
,
3832 struct work_struct
*target_work
,
3835 work_func_t target_func
;
3836 struct worker
*worker
;
3838 if (from_cancel
|| target_wq
->flags
& WQ_MEM_RECLAIM
)
3841 worker
= current_wq_worker();
3842 target_func
= target_work
? target_work
->func
: NULL
;
3844 WARN_ONCE(current
->flags
& PF_MEMALLOC
,
3845 "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
3846 current
->pid
, current
->comm
, target_wq
->name
, target_func
);
3847 WARN_ONCE(worker
&& ((worker
->current_pwq
->wq
->flags
&
3848 (WQ_MEM_RECLAIM
| __WQ_LEGACY
)) == WQ_MEM_RECLAIM
),
3849 "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
3850 worker
->current_pwq
->wq
->name
, worker
->current_func
,
3851 target_wq
->name
, target_func
);
3855 struct work_struct work
;
3856 struct completion done
;
3857 struct task_struct
*task
; /* purely informational */
3860 static void wq_barrier_func(struct work_struct
*work
)
3862 struct wq_barrier
*barr
= container_of(work
, struct wq_barrier
, work
);
3863 complete(&barr
->done
);
3867 * insert_wq_barrier - insert a barrier work
3868 * @pwq: pwq to insert barrier into
3869 * @barr: wq_barrier to insert
3870 * @target: target work to attach @barr to
3871 * @worker: worker currently executing @target, NULL if @target is not executing
3873 * @barr is linked to @target such that @barr is completed only after
3874 * @target finishes execution. Please note that the ordering
3875 * guarantee is observed only with respect to @target and on the local
3878 * Currently, a queued barrier can't be canceled. This is because
3879 * try_to_grab_pending() can't determine whether the work to be
3880 * grabbed is at the head of the queue and thus can't clear LINKED
3881 * flag of the previous work while there must be a valid next work
3882 * after a work with LINKED flag set.
3884 * Note that when @worker is non-NULL, @target may be modified
3885 * underneath us, so we can't reliably determine pwq from @target.
3888 * raw_spin_lock_irq(pool->lock).
3890 static void insert_wq_barrier(struct pool_workqueue
*pwq
,
3891 struct wq_barrier
*barr
,
3892 struct work_struct
*target
, struct worker
*worker
)
3894 static __maybe_unused
struct lock_class_key bh_key
, thr_key
;
3895 unsigned int work_flags
= 0;
3896 unsigned int work_color
;
3897 struct list_head
*head
;
3900 * debugobject calls are safe here even with pool->lock locked
3901 * as we know for sure that this will not trigger any of the
3902 * checks and call back into the fixup functions where we
3905 * BH and threaded workqueues need separate lockdep keys to avoid
3906 * spuriously triggering "inconsistent {SOFTIRQ-ON-W} -> {IN-SOFTIRQ-W}
3909 INIT_WORK_ONSTACK_KEY(&barr
->work
, wq_barrier_func
,
3910 (pwq
->wq
->flags
& WQ_BH
) ? &bh_key
: &thr_key
);
3911 __set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(&barr
->work
));
3913 init_completion_map(&barr
->done
, &target
->lockdep_map
);
3915 barr
->task
= current
;
3917 /* The barrier work item does not participate in nr_active. */
3918 work_flags
|= WORK_STRUCT_INACTIVE
;
3921 * If @target is currently being executed, schedule the
3922 * barrier to the worker; otherwise, put it after @target.
3925 head
= worker
->scheduled
.next
;
3926 work_color
= worker
->current_color
;
3928 unsigned long *bits
= work_data_bits(target
);
3930 head
= target
->entry
.next
;
3931 /* there can already be other linked works, inherit and set */
3932 work_flags
|= *bits
& WORK_STRUCT_LINKED
;
3933 work_color
= get_work_color(*bits
);
3934 __set_bit(WORK_STRUCT_LINKED_BIT
, bits
);
3937 pwq
->nr_in_flight
[work_color
]++;
3938 work_flags
|= work_color_to_flags(work_color
);
3940 insert_work(pwq
, &barr
->work
, head
, work_flags
);
3944 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
3945 * @wq: workqueue being flushed
3946 * @flush_color: new flush color, < 0 for no-op
3947 * @work_color: new work color, < 0 for no-op
3949 * Prepare pwqs for workqueue flushing.
3951 * If @flush_color is non-negative, flush_color on all pwqs should be
3952 * -1. If no pwq has in-flight commands at the specified color, all
3953 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
3954 * has in flight commands, its pwq->flush_color is set to
3955 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
3956 * wakeup logic is armed and %true is returned.
3958 * The caller should have initialized @wq->first_flusher prior to
3959 * calling this function with non-negative @flush_color. If
3960 * @flush_color is negative, no flush color update is done and %false
3963 * If @work_color is non-negative, all pwqs should have the same
3964 * work_color which is previous to @work_color and all will be
3965 * advanced to @work_color.
3968 * mutex_lock(wq->mutex).
3971 * %true if @flush_color >= 0 and there's something to flush. %false
3974 static bool flush_workqueue_prep_pwqs(struct workqueue_struct
*wq
,
3975 int flush_color
, int work_color
)
3978 struct pool_workqueue
*pwq
;
3979 struct worker_pool
*current_pool
= NULL
;
3981 if (flush_color
>= 0) {
3982 WARN_ON_ONCE(atomic_read(&wq
->nr_pwqs_to_flush
));
3983 atomic_set(&wq
->nr_pwqs_to_flush
, 1);
3987 * For unbound workqueue, pwqs will map to only a few pools.
3988 * Most of the time, pwqs within the same pool will be linked
3989 * sequentially to wq->pwqs by cpu index. So in the majority
3990 * of pwq iters, the pool is the same, only doing lock/unlock
3991 * if the pool has changed. This can largely reduce expensive
3994 for_each_pwq(pwq
, wq
) {
3995 if (current_pool
!= pwq
->pool
) {
3996 if (likely(current_pool
))
3997 raw_spin_unlock_irq(¤t_pool
->lock
);
3998 current_pool
= pwq
->pool
;
3999 raw_spin_lock_irq(¤t_pool
->lock
);
4002 if (flush_color
>= 0) {
4003 WARN_ON_ONCE(pwq
->flush_color
!= -1);
4005 if (pwq
->nr_in_flight
[flush_color
]) {
4006 pwq
->flush_color
= flush_color
;
4007 atomic_inc(&wq
->nr_pwqs_to_flush
);
4012 if (work_color
>= 0) {
4013 WARN_ON_ONCE(work_color
!= work_next_color(pwq
->work_color
));
4014 pwq
->work_color
= work_color
;
4020 raw_spin_unlock_irq(¤t_pool
->lock
);
4022 if (flush_color
>= 0 && atomic_dec_and_test(&wq
->nr_pwqs_to_flush
))
4023 complete(&wq
->first_flusher
->done
);
4028 static void touch_wq_lockdep_map(struct workqueue_struct
*wq
)
4030 #ifdef CONFIG_LOCKDEP
4031 if (unlikely(!wq
->lockdep_map
))
4034 if (wq
->flags
& WQ_BH
)
4037 lock_map_acquire(wq
->lockdep_map
);
4038 lock_map_release(wq
->lockdep_map
);
4040 if (wq
->flags
& WQ_BH
)
4045 static void touch_work_lockdep_map(struct work_struct
*work
,
4046 struct workqueue_struct
*wq
)
4048 #ifdef CONFIG_LOCKDEP
4049 if (wq
->flags
& WQ_BH
)
4052 lock_map_acquire(&work
->lockdep_map
);
4053 lock_map_release(&work
->lockdep_map
);
4055 if (wq
->flags
& WQ_BH
)
4061 * __flush_workqueue - ensure that any scheduled work has run to completion.
4062 * @wq: workqueue to flush
4064 * This function sleeps until all work items which were queued on entry
4065 * have finished execution, but it is not livelocked by new incoming ones.
4067 void __flush_workqueue(struct workqueue_struct
*wq
)
4069 struct wq_flusher this_flusher
= {
4070 .list
= LIST_HEAD_INIT(this_flusher
.list
),
4072 .done
= COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher
.done
, (*wq
->lockdep_map
)),
4076 if (WARN_ON(!wq_online
))
4079 touch_wq_lockdep_map(wq
);
4081 mutex_lock(&wq
->mutex
);
4084 * Start-to-wait phase
4086 next_color
= work_next_color(wq
->work_color
);
4088 if (next_color
!= wq
->flush_color
) {
4090 * Color space is not full. The current work_color
4091 * becomes our flush_color and work_color is advanced
4094 WARN_ON_ONCE(!list_empty(&wq
->flusher_overflow
));
4095 this_flusher
.flush_color
= wq
->work_color
;
4096 wq
->work_color
= next_color
;
4098 if (!wq
->first_flusher
) {
4099 /* no flush in progress, become the first flusher */
4100 WARN_ON_ONCE(wq
->flush_color
!= this_flusher
.flush_color
);
4102 wq
->first_flusher
= &this_flusher
;
4104 if (!flush_workqueue_prep_pwqs(wq
, wq
->flush_color
,
4106 /* nothing to flush, done */
4107 wq
->flush_color
= next_color
;
4108 wq
->first_flusher
= NULL
;
4113 WARN_ON_ONCE(wq
->flush_color
== this_flusher
.flush_color
);
4114 list_add_tail(&this_flusher
.list
, &wq
->flusher_queue
);
4115 flush_workqueue_prep_pwqs(wq
, -1, wq
->work_color
);
4119 * Oops, color space is full, wait on overflow queue.
4120 * The next flush completion will assign us
4121 * flush_color and transfer to flusher_queue.
4123 list_add_tail(&this_flusher
.list
, &wq
->flusher_overflow
);
4126 check_flush_dependency(wq
, NULL
, false);
4128 mutex_unlock(&wq
->mutex
);
4130 wait_for_completion(&this_flusher
.done
);
4133 * Wake-up-and-cascade phase
4135 * First flushers are responsible for cascading flushes and
4136 * handling overflow. Non-first flushers can simply return.
4138 if (READ_ONCE(wq
->first_flusher
) != &this_flusher
)
4141 mutex_lock(&wq
->mutex
);
4143 /* we might have raced, check again with mutex held */
4144 if (wq
->first_flusher
!= &this_flusher
)
4147 WRITE_ONCE(wq
->first_flusher
, NULL
);
4149 WARN_ON_ONCE(!list_empty(&this_flusher
.list
));
4150 WARN_ON_ONCE(wq
->flush_color
!= this_flusher
.flush_color
);
4153 struct wq_flusher
*next
, *tmp
;
4155 /* complete all the flushers sharing the current flush color */
4156 list_for_each_entry_safe(next
, tmp
, &wq
->flusher_queue
, list
) {
4157 if (next
->flush_color
!= wq
->flush_color
)
4159 list_del_init(&next
->list
);
4160 complete(&next
->done
);
4163 WARN_ON_ONCE(!list_empty(&wq
->flusher_overflow
) &&
4164 wq
->flush_color
!= work_next_color(wq
->work_color
));
4166 /* this flush_color is finished, advance by one */
4167 wq
->flush_color
= work_next_color(wq
->flush_color
);
4169 /* one color has been freed, handle overflow queue */
4170 if (!list_empty(&wq
->flusher_overflow
)) {
4172 * Assign the same color to all overflowed
4173 * flushers, advance work_color and append to
4174 * flusher_queue. This is the start-to-wait
4175 * phase for these overflowed flushers.
4177 list_for_each_entry(tmp
, &wq
->flusher_overflow
, list
)
4178 tmp
->flush_color
= wq
->work_color
;
4180 wq
->work_color
= work_next_color(wq
->work_color
);
4182 list_splice_tail_init(&wq
->flusher_overflow
,
4183 &wq
->flusher_queue
);
4184 flush_workqueue_prep_pwqs(wq
, -1, wq
->work_color
);
4187 if (list_empty(&wq
->flusher_queue
)) {
4188 WARN_ON_ONCE(wq
->flush_color
!= wq
->work_color
);
4193 * Need to flush more colors. Make the next flusher
4194 * the new first flusher and arm pwqs.
4196 WARN_ON_ONCE(wq
->flush_color
== wq
->work_color
);
4197 WARN_ON_ONCE(wq
->flush_color
!= next
->flush_color
);
4199 list_del_init(&next
->list
);
4200 wq
->first_flusher
= next
;
4202 if (flush_workqueue_prep_pwqs(wq
, wq
->flush_color
, -1))
4206 * Meh... this color is already done, clear first
4207 * flusher and repeat cascading.
4209 wq
->first_flusher
= NULL
;
4213 mutex_unlock(&wq
->mutex
);
4215 EXPORT_SYMBOL(__flush_workqueue
);
4218 * drain_workqueue - drain a workqueue
4219 * @wq: workqueue to drain
4221 * Wait until the workqueue becomes empty. While draining is in progress,
4222 * only chain queueing is allowed. IOW, only currently pending or running
4223 * work items on @wq can queue further work items on it. @wq is flushed
4224 * repeatedly until it becomes empty. The number of flushing is determined
4225 * by the depth of chaining and should be relatively short. Whine if it
4228 void drain_workqueue(struct workqueue_struct
*wq
)
4230 unsigned int flush_cnt
= 0;
4231 struct pool_workqueue
*pwq
;
4234 * __queue_work() needs to test whether there are drainers, is much
4235 * hotter than drain_workqueue() and already looks at @wq->flags.
4236 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
4238 mutex_lock(&wq
->mutex
);
4239 if (!wq
->nr_drainers
++)
4240 wq
->flags
|= __WQ_DRAINING
;
4241 mutex_unlock(&wq
->mutex
);
4243 __flush_workqueue(wq
);
4245 mutex_lock(&wq
->mutex
);
4247 for_each_pwq(pwq
, wq
) {
4250 raw_spin_lock_irq(&pwq
->pool
->lock
);
4251 drained
= pwq_is_empty(pwq
);
4252 raw_spin_unlock_irq(&pwq
->pool
->lock
);
4257 if (++flush_cnt
== 10 ||
4258 (flush_cnt
% 100 == 0 && flush_cnt
<= 1000))
4259 pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
4260 wq
->name
, __func__
, flush_cnt
);
4262 mutex_unlock(&wq
->mutex
);
4266 if (!--wq
->nr_drainers
)
4267 wq
->flags
&= ~__WQ_DRAINING
;
4268 mutex_unlock(&wq
->mutex
);
4270 EXPORT_SYMBOL_GPL(drain_workqueue
);
4272 static bool start_flush_work(struct work_struct
*work
, struct wq_barrier
*barr
,
4275 struct worker
*worker
= NULL
;
4276 struct worker_pool
*pool
;
4277 struct pool_workqueue
*pwq
;
4278 struct workqueue_struct
*wq
;
4281 pool
= get_work_pool(work
);
4287 raw_spin_lock_irq(&pool
->lock
);
4288 /* see the comment in try_to_grab_pending() with the same code */
4289 pwq
= get_work_pwq(work
);
4291 if (unlikely(pwq
->pool
!= pool
))
4294 worker
= find_worker_executing_work(pool
, work
);
4297 pwq
= worker
->current_pwq
;
4301 check_flush_dependency(wq
, work
, from_cancel
);
4303 insert_wq_barrier(pwq
, barr
, work
, worker
);
4304 raw_spin_unlock_irq(&pool
->lock
);
4306 touch_work_lockdep_map(work
, wq
);
4309 * Force a lock recursion deadlock when using flush_work() inside a
4310 * single-threaded or rescuer equipped workqueue.
4312 * For single threaded workqueues the deadlock happens when the work
4313 * is after the work issuing the flush_work(). For rescuer equipped
4314 * workqueues the deadlock happens when the rescuer stalls, blocking
4317 if (!from_cancel
&& (wq
->saved_max_active
== 1 || wq
->rescuer
))
4318 touch_wq_lockdep_map(wq
);
4323 raw_spin_unlock_irq(&pool
->lock
);
4328 static bool __flush_work(struct work_struct
*work
, bool from_cancel
)
4330 struct wq_barrier barr
;
4332 if (WARN_ON(!wq_online
))
4335 if (WARN_ON(!work
->func
))
4338 if (!start_flush_work(work
, &barr
, from_cancel
))
4342 * start_flush_work() returned %true. If @from_cancel is set, we know
4343 * that @work must have been executing during start_flush_work() and
4344 * can't currently be queued. Its data must contain OFFQ bits. If @work
4345 * was queued on a BH workqueue, we also know that it was running in the
4346 * BH context and thus can be busy-waited.
4349 unsigned long data
= *work_data_bits(work
);
4351 if (!WARN_ON_ONCE(data
& WORK_STRUCT_PWQ
) &&
4352 (data
& WORK_OFFQ_BH
)) {
4354 * On RT, prevent a live lock when %current preempted
4355 * soft interrupt processing by blocking on lock which
4356 * is owned by the thread invoking the callback.
4358 while (!try_wait_for_completion(&barr
.done
)) {
4359 if (IS_ENABLED(CONFIG_PREEMPT_RT
)) {
4360 struct worker_pool
*pool
;
4363 pool
= get_work_pool(work
);
4365 workqueue_callback_cancel_wait_running(pool
);
4374 wait_for_completion(&barr
.done
);
4377 destroy_work_on_stack(&barr
.work
);
4382 * flush_work - wait for a work to finish executing the last queueing instance
4383 * @work: the work to flush
4385 * Wait until @work has finished execution. @work is guaranteed to be idle
4386 * on return if it hasn't been requeued since flush started.
4389 * %true if flush_work() waited for the work to finish execution,
4390 * %false if it was already idle.
4392 bool flush_work(struct work_struct
*work
)
4395 return __flush_work(work
, false);
4397 EXPORT_SYMBOL_GPL(flush_work
);
4400 * flush_delayed_work - wait for a dwork to finish executing the last queueing
4401 * @dwork: the delayed work to flush
4403 * Delayed timer is cancelled and the pending work is queued for
4404 * immediate execution. Like flush_work(), this function only
4405 * considers the last queueing instance of @dwork.
4408 * %true if flush_work() waited for the work to finish execution,
4409 * %false if it was already idle.
4411 bool flush_delayed_work(struct delayed_work
*dwork
)
4413 local_irq_disable();
4414 if (timer_delete_sync(&dwork
->timer
))
4415 __queue_work(dwork
->cpu
, dwork
->wq
, &dwork
->work
);
4417 return flush_work(&dwork
->work
);
4419 EXPORT_SYMBOL(flush_delayed_work
);
4422 * flush_rcu_work - wait for a rwork to finish executing the last queueing
4423 * @rwork: the rcu work to flush
4426 * %true if flush_rcu_work() waited for the work to finish execution,
4427 * %false if it was already idle.
4429 bool flush_rcu_work(struct rcu_work
*rwork
)
4431 if (test_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(&rwork
->work
))) {
4433 flush_work(&rwork
->work
);
4436 return flush_work(&rwork
->work
);
4439 EXPORT_SYMBOL(flush_rcu_work
);
4441 static void work_offqd_disable(struct work_offq_data
*offqd
)
4443 const unsigned long max
= (1lu << WORK_OFFQ_DISABLE_BITS
) - 1;
4445 if (likely(offqd
->disable
< max
))
4448 WARN_ONCE(true, "workqueue: work disable count overflowed\n");
4451 static void work_offqd_enable(struct work_offq_data
*offqd
)
4453 if (likely(offqd
->disable
> 0))
4456 WARN_ONCE(true, "workqueue: work disable count underflowed\n");
4459 static bool __cancel_work(struct work_struct
*work
, u32 cflags
)
4461 struct work_offq_data offqd
;
4462 unsigned long irq_flags
;
4465 ret
= work_grab_pending(work
, cflags
, &irq_flags
);
4467 work_offqd_unpack(&offqd
, *work_data_bits(work
));
4469 if (cflags
& WORK_CANCEL_DISABLE
)
4470 work_offqd_disable(&offqd
);
4472 set_work_pool_and_clear_pending(work
, offqd
.pool_id
,
4473 work_offqd_pack_flags(&offqd
));
4474 local_irq_restore(irq_flags
);
4478 static bool __cancel_work_sync(struct work_struct
*work
, u32 cflags
)
4482 ret
= __cancel_work(work
, cflags
| WORK_CANCEL_DISABLE
);
4484 if (*work_data_bits(work
) & WORK_OFFQ_BH
)
4485 WARN_ON_ONCE(in_hardirq());
4490 * Skip __flush_work() during early boot when we know that @work isn't
4491 * executing. This allows canceling during early boot.
4494 __flush_work(work
, true);
4496 if (!(cflags
& WORK_CANCEL_DISABLE
))
4503 * See cancel_delayed_work()
4505 bool cancel_work(struct work_struct
*work
)
4507 return __cancel_work(work
, 0);
4509 EXPORT_SYMBOL(cancel_work
);
4512 * cancel_work_sync - cancel a work and wait for it to finish
4513 * @work: the work to cancel
4515 * Cancel @work and wait for its execution to finish. This function can be used
4516 * even if the work re-queues itself or migrates to another workqueue. On return
4517 * from this function, @work is guaranteed to be not pending or executing on any
4518 * CPU as long as there aren't racing enqueues.
4520 * cancel_work_sync(&delayed_work->work) must not be used for delayed_work's.
4521 * Use cancel_delayed_work_sync() instead.
4523 * Must be called from a sleepable context if @work was last queued on a non-BH
4524 * workqueue. Can also be called from non-hardirq atomic contexts including BH
4525 * if @work was last queued on a BH workqueue.
4527 * Returns %true if @work was pending, %false otherwise.
4529 bool cancel_work_sync(struct work_struct
*work
)
4531 return __cancel_work_sync(work
, 0);
4533 EXPORT_SYMBOL_GPL(cancel_work_sync
);
4536 * cancel_delayed_work - cancel a delayed work
4537 * @dwork: delayed_work to cancel
4539 * Kill off a pending delayed_work.
4541 * Return: %true if @dwork was pending and canceled; %false if it wasn't
4545 * The work callback function may still be running on return, unless
4546 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
4547 * use cancel_delayed_work_sync() to wait on it.
4549 * This function is safe to call from any context including IRQ handler.
4551 bool cancel_delayed_work(struct delayed_work
*dwork
)
4553 return __cancel_work(&dwork
->work
, WORK_CANCEL_DELAYED
);
4555 EXPORT_SYMBOL(cancel_delayed_work
);
4558 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
4559 * @dwork: the delayed work cancel
4561 * This is cancel_work_sync() for delayed works.
4564 * %true if @dwork was pending, %false otherwise.
4566 bool cancel_delayed_work_sync(struct delayed_work
*dwork
)
4568 return __cancel_work_sync(&dwork
->work
, WORK_CANCEL_DELAYED
);
4570 EXPORT_SYMBOL(cancel_delayed_work_sync
);
4573 * disable_work - Disable and cancel a work item
4574 * @work: work item to disable
4576 * Disable @work by incrementing its disable count and cancel it if currently
4577 * pending. As long as the disable count is non-zero, any attempt to queue @work
4578 * will fail and return %false. The maximum supported disable depth is 2 to the
4579 * power of %WORK_OFFQ_DISABLE_BITS, currently 65536.
4581 * Can be called from any context. Returns %true if @work was pending, %false
4584 bool disable_work(struct work_struct
*work
)
4586 return __cancel_work(work
, WORK_CANCEL_DISABLE
);
4588 EXPORT_SYMBOL_GPL(disable_work
);
4591 * disable_work_sync - Disable, cancel and drain a work item
4592 * @work: work item to disable
4594 * Similar to disable_work() but also wait for @work to finish if currently
4597 * Must be called from a sleepable context if @work was last queued on a non-BH
4598 * workqueue. Can also be called from non-hardirq atomic contexts including BH
4599 * if @work was last queued on a BH workqueue.
4601 * Returns %true if @work was pending, %false otherwise.
4603 bool disable_work_sync(struct work_struct
*work
)
4605 return __cancel_work_sync(work
, WORK_CANCEL_DISABLE
);
4607 EXPORT_SYMBOL_GPL(disable_work_sync
);
4610 * enable_work - Enable a work item
4611 * @work: work item to enable
4613 * Undo disable_work[_sync]() by decrementing @work's disable count. @work can
4614 * only be queued if its disable count is 0.
4616 * Can be called from any context. Returns %true if the disable count reached 0.
4617 * Otherwise, %false.
4619 bool enable_work(struct work_struct
*work
)
4621 struct work_offq_data offqd
;
4622 unsigned long irq_flags
;
4624 work_grab_pending(work
, 0, &irq_flags
);
4626 work_offqd_unpack(&offqd
, *work_data_bits(work
));
4627 work_offqd_enable(&offqd
);
4628 set_work_pool_and_clear_pending(work
, offqd
.pool_id
,
4629 work_offqd_pack_flags(&offqd
));
4630 local_irq_restore(irq_flags
);
4632 return !offqd
.disable
;
4634 EXPORT_SYMBOL_GPL(enable_work
);
4637 * disable_delayed_work - Disable and cancel a delayed work item
4638 * @dwork: delayed work item to disable
4640 * disable_work() for delayed work items.
4642 bool disable_delayed_work(struct delayed_work
*dwork
)
4644 return __cancel_work(&dwork
->work
,
4645 WORK_CANCEL_DELAYED
| WORK_CANCEL_DISABLE
);
4647 EXPORT_SYMBOL_GPL(disable_delayed_work
);
4650 * disable_delayed_work_sync - Disable, cancel and drain a delayed work item
4651 * @dwork: delayed work item to disable
4653 * disable_work_sync() for delayed work items.
4655 bool disable_delayed_work_sync(struct delayed_work
*dwork
)
4657 return __cancel_work_sync(&dwork
->work
,
4658 WORK_CANCEL_DELAYED
| WORK_CANCEL_DISABLE
);
4660 EXPORT_SYMBOL_GPL(disable_delayed_work_sync
);
4663 * enable_delayed_work - Enable a delayed work item
4664 * @dwork: delayed work item to enable
4666 * enable_work() for delayed work items.
4668 bool enable_delayed_work(struct delayed_work
*dwork
)
4670 return enable_work(&dwork
->work
);
4672 EXPORT_SYMBOL_GPL(enable_delayed_work
);
4675 * schedule_on_each_cpu - execute a function synchronously on each online CPU
4676 * @func: the function to call
4678 * schedule_on_each_cpu() executes @func on each online CPU using the
4679 * system workqueue and blocks until all CPUs have completed.
4680 * schedule_on_each_cpu() is very slow.
4683 * 0 on success, -errno on failure.
4685 int schedule_on_each_cpu(work_func_t func
)
4688 struct work_struct __percpu
*works
;
4690 works
= alloc_percpu(struct work_struct
);
4696 for_each_online_cpu(cpu
) {
4697 struct work_struct
*work
= per_cpu_ptr(works
, cpu
);
4699 INIT_WORK(work
, func
);
4700 schedule_work_on(cpu
, work
);
4703 for_each_online_cpu(cpu
)
4704 flush_work(per_cpu_ptr(works
, cpu
));
4712 * execute_in_process_context - reliably execute the routine with user context
4713 * @fn: the function to execute
4714 * @ew: guaranteed storage for the execute work structure (must
4715 * be available when the work executes)
4717 * Executes the function immediately if process context is available,
4718 * otherwise schedules the function for delayed execution.
4720 * Return: 0 - function was executed
4721 * 1 - function was scheduled for execution
4723 int execute_in_process_context(work_func_t fn
, struct execute_work
*ew
)
4725 if (!in_interrupt()) {
4730 INIT_WORK(&ew
->work
, fn
);
4731 schedule_work(&ew
->work
);
4735 EXPORT_SYMBOL_GPL(execute_in_process_context
);
4738 * free_workqueue_attrs - free a workqueue_attrs
4739 * @attrs: workqueue_attrs to free
4741 * Undo alloc_workqueue_attrs().
4743 void free_workqueue_attrs(struct workqueue_attrs
*attrs
)
4746 free_cpumask_var(attrs
->cpumask
);
4747 free_cpumask_var(attrs
->__pod_cpumask
);
4753 * alloc_workqueue_attrs - allocate a workqueue_attrs
4755 * Allocate a new workqueue_attrs, initialize with default settings and
4758 * Return: The allocated new workqueue_attr on success. %NULL on failure.
4760 struct workqueue_attrs
*alloc_workqueue_attrs_noprof(void)
4762 struct workqueue_attrs
*attrs
;
4764 attrs
= kzalloc_obj(*attrs
);
4767 if (!alloc_cpumask_var(&attrs
->cpumask
, GFP_KERNEL
))
4769 if (!alloc_cpumask_var(&attrs
->__pod_cpumask
, GFP_KERNEL
))
4772 cpumask_copy(attrs
->cpumask
, cpu_possible_mask
);
4773 attrs
->affn_scope
= WQ_AFFN_DFL
;
4776 free_workqueue_attrs(attrs
);
4780 static void copy_workqueue_attrs(struct workqueue_attrs
*to
,
4781 const struct workqueue_attrs
*from
)
4783 to
->nice
= from
->nice
;
4784 cpumask_copy(to
->cpumask
, from
->cpumask
);
4785 cpumask_copy(to
->__pod_cpumask
, from
->__pod_cpumask
);
4786 to
->affn_strict
= from
->affn_strict
;
4789 * Unlike hash and equality test, copying shouldn't ignore wq-only
4790 * fields as copying is used for both pool and wq attrs. Instead,
4791 * get_unbound_pool() explicitly clears the fields.
4793 to
->affn_scope
= from
->affn_scope
;
4794 to
->ordered
= from
->ordered
;
4798 * Some attrs fields are workqueue-only. Clear them for worker_pool's. See the
4799 * comments in 'struct workqueue_attrs' definition.
4801 static void wqattrs_clear_for_pool(struct workqueue_attrs
*attrs
)
4803 attrs
->affn_scope
= WQ_AFFN_NR_TYPES
;
4804 attrs
->ordered
= false;
4805 if (attrs
->affn_strict
)
4806 cpumask_copy(attrs
->cpumask
, cpu_possible_mask
);
4809 /* hash value of the content of @attr */
4810 static u32
wqattrs_hash(const struct workqueue_attrs
*attrs
)
4814 hash
= jhash_1word(attrs
->nice
, hash
);
4815 hash
= jhash_1word(attrs
->affn_strict
, hash
);
4816 hash
= jhash(cpumask_bits(attrs
->__pod_cpumask
),
4817 BITS_TO_LONGS(nr_cpumask_bits
) * sizeof(long), hash
);
4818 if (!attrs
->affn_strict
)
4819 hash
= jhash(cpumask_bits(attrs
->cpumask
),
4820 BITS_TO_LONGS(nr_cpumask_bits
) * sizeof(long), hash
);
4824 /* content equality test */
4825 static bool wqattrs_equal(const struct workqueue_attrs
*a
,
4826 const struct workqueue_attrs
*b
)
4828 if (a
->nice
!= b
->nice
)
4830 if (a
->affn_strict
!= b
->affn_strict
)
4832 if (!cpumask_equal(a
->__pod_cpumask
, b
->__pod_cpumask
))
4834 if (!a
->affn_strict
&& !cpumask_equal(a
->cpumask
, b
->cpumask
))
4839 /* Update @attrs with actually available CPUs */
4840 static void wqattrs_actualize_cpumask(struct workqueue_attrs
*attrs
,
4841 const cpumask_t
*unbound_cpumask
)
4844 * Calculate the effective CPU mask of @attrs given @unbound_cpumask. If
4845 * @attrs->cpumask doesn't overlap with @unbound_cpumask, we fallback to
4848 cpumask_and(attrs
->cpumask
, attrs
->cpumask
, unbound_cpumask
);
4849 if (unlikely(cpumask_empty(attrs
->cpumask
)))
4850 cpumask_copy(attrs
->cpumask
, unbound_cpumask
);
4853 /* find wq_pod_type to use for @attrs */
4854 static const struct wq_pod_type
*
4855 wqattrs_pod_type(const struct workqueue_attrs
*attrs
)
4857 enum wq_affn_scope scope
;
4858 struct wq_pod_type
*pt
;
4860 /* to synchronize access to wq_affn_dfl */
4861 lockdep_assert_held(&wq_pool_mutex
);
4863 if (attrs
->affn_scope
== WQ_AFFN_DFL
)
4864 scope
= wq_affn_dfl
;
4866 scope
= attrs
->affn_scope
;
4868 pt
= &wq_pod_types
[scope
];
4870 if (!WARN_ON_ONCE(attrs
->affn_scope
== WQ_AFFN_NR_TYPES
) &&
4871 likely(pt
->nr_pods
))
4875 * Before workqueue_init_topology(), only SYSTEM is available which is
4876 * initialized in workqueue_init_early().
4878 pt
= &wq_pod_types
[WQ_AFFN_SYSTEM
];
4879 BUG_ON(!pt
->nr_pods
);
4884 * init_worker_pool - initialize a newly zalloc'd worker_pool
4885 * @pool: worker_pool to initialize
4887 * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
4889 * Return: 0 on success, -errno on failure. Even on failure, all fields
4890 * inside @pool proper are initialized and put_unbound_pool() can be called
4891 * on @pool safely to release it.
4893 static int init_worker_pool(struct worker_pool
*pool
)
4895 raw_spin_lock_init(&pool
->lock
);
4898 pool
->node
= NUMA_NO_NODE
;
4899 pool
->flags
|= POOL_DISASSOCIATED
;
4900 pool
->last_progress_ts
= jiffies
;
4901 INIT_LIST_HEAD(&pool
->worklist
);
4902 INIT_LIST_HEAD(&pool
->idle_list
);
4903 hash_init(pool
->busy_hash
);
4905 timer_setup(&pool
->idle_timer
, idle_worker_timeout
, TIMER_DEFERRABLE
);
4906 INIT_WORK(&pool
->idle_cull_work
, idle_cull_fn
);
4908 timer_setup(&pool
->mayday_timer
, pool_mayday_timeout
, 0);
4910 INIT_LIST_HEAD(&pool
->workers
);
4912 ida_init(&pool
->worker_ida
);
4913 INIT_HLIST_NODE(&pool
->hash_node
);
4915 #ifdef CONFIG_PREEMPT_RT
4916 spin_lock_init(&pool
->cb_lock
);
4919 /* shouldn't fail above this point */
4920 pool
->attrs
= alloc_workqueue_attrs();
4924 wqattrs_clear_for_pool(pool
->attrs
);
4929 #ifdef CONFIG_LOCKDEP
4930 static void wq_init_lockdep(struct workqueue_struct
*wq
)
4934 lockdep_register_key(&wq
->key
);
4935 lock_name
= kasprintf(GFP_KERNEL
, "%s%s", "(wq_completion)", wq
->name
);
4937 lock_name
= wq
->name
;
4939 wq
->lock_name
= lock_name
;
4940 wq
->lockdep_map
= &wq
->__lockdep_map
;
4941 lockdep_init_map(wq
->lockdep_map
, lock_name
, &wq
->key
, 0);
4944 static void wq_unregister_lockdep(struct workqueue_struct
*wq
)
4946 if (wq
->lockdep_map
!= &wq
->__lockdep_map
)
4949 lockdep_unregister_key(&wq
->key
);
4952 static void wq_free_lockdep(struct workqueue_struct
*wq
)
4954 if (wq
->lockdep_map
!= &wq
->__lockdep_map
)
4957 if (wq
->lock_name
!= wq
->name
)
4958 kfree(wq
->lock_name
);
4961 static void wq_init_lockdep(struct workqueue_struct
*wq
)
4965 static void wq_unregister_lockdep(struct workqueue_struct
*wq
)
4969 static void wq_free_lockdep(struct workqueue_struct
*wq
)
4974 static void free_node_nr_active(struct wq_node_nr_active
**nna_ar
)
4978 for_each_node(node
) {
4979 kfree(nna_ar
[node
]);
4980 nna_ar
[node
] = NULL
;
4983 kfree(nna_ar
[nr_node_ids
]);
4984 nna_ar
[nr_node_ids
] = NULL
;
4987 static void init_node_nr_active(struct wq_node_nr_active
*nna
)
4989 nna
->max
= WQ_DFL_MIN_ACTIVE
;
4990 atomic_set(&nna
->nr
, 0);
4991 raw_spin_lock_init(&nna
->lock
);
4992 INIT_LIST_HEAD(&nna
->pending_pwqs
);
4996 * Each node's nr_active counter will be accessed mostly from its own node and
4997 * should be allocated in the node.
4999 static int alloc_node_nr_active(struct wq_node_nr_active
**nna_ar
)
5001 struct wq_node_nr_active
*nna
;
5004 for_each_node(node
) {
5005 nna
= kzalloc_node(sizeof(*nna
), GFP_KERNEL
, node
);
5008 init_node_nr_active(nna
);
5012 /* [nr_node_ids] is used as the fallback */
5013 nna
= kzalloc_node(sizeof(*nna
), GFP_KERNEL
, NUMA_NO_NODE
);
5016 init_node_nr_active(nna
);
5017 nna_ar
[nr_node_ids
] = nna
;
5022 free_node_nr_active(nna_ar
);
5026 static void rcu_free_wq(struct rcu_head
*rcu
)
5028 struct workqueue_struct
*wq
=
5029 container_of(rcu
, struct workqueue_struct
, rcu
);
5031 if (wq
->flags
& WQ_UNBOUND
)
5032 free_node_nr_active(wq
->node_nr_active
);
5034 wq_free_lockdep(wq
);
5035 free_percpu(wq
->cpu_pwq
);
5036 free_workqueue_attrs(wq
->unbound_attrs
);
5040 static void rcu_free_pool(struct rcu_head
*rcu
)
5042 struct worker_pool
*pool
= container_of(rcu
, struct worker_pool
, rcu
);
5044 ida_destroy(&pool
->worker_ida
);
5045 free_workqueue_attrs(pool
->attrs
);
5050 * put_unbound_pool - put a worker_pool
5051 * @pool: worker_pool to put
5053 * Put @pool. If its refcnt reaches zero, it gets destroyed in RCU
5054 * safe manner. get_unbound_pool() calls this function on its failure path
5055 * and this function should be able to release pools which went through,
5056 * successfully or not, init_worker_pool().
5058 * Should be called with wq_pool_mutex held.
5060 static void put_unbound_pool(struct worker_pool
*pool
)
5062 struct worker
*worker
;
5063 LIST_HEAD(cull_list
);
5065 lockdep_assert_held(&wq_pool_mutex
);
5071 if (WARN_ON(!(pool
->cpu
< 0)) ||
5072 WARN_ON(!list_empty(&pool
->worklist
)))
5075 /* release id and unhash */
5077 idr_remove(&worker_pool_idr
, pool
->id
);
5078 hash_del(&pool
->hash_node
);
5081 * Become the manager and destroy all workers. This prevents
5082 * @pool's workers from blocking on attach_mutex. We're the last
5083 * manager and @pool gets freed with the flag set.
5085 * Having a concurrent manager is quite unlikely to happen as we can
5086 * only get here with
5087 * pwq->refcnt == pool->refcnt == 0
5088 * which implies no work queued to the pool, which implies no worker can
5089 * become the manager. However a worker could have taken the role of
5090 * manager before the refcnts dropped to 0, since maybe_create_worker()
5094 rcuwait_wait_event(&manager_wait
,
5095 !(pool
->flags
& POOL_MANAGER_ACTIVE
),
5096 TASK_UNINTERRUPTIBLE
);
5098 mutex_lock(&wq_pool_attach_mutex
);
5099 raw_spin_lock_irq(&pool
->lock
);
5100 if (!(pool
->flags
& POOL_MANAGER_ACTIVE
)) {
5101 pool
->flags
|= POOL_MANAGER_ACTIVE
;
5104 raw_spin_unlock_irq(&pool
->lock
);
5105 mutex_unlock(&wq_pool_attach_mutex
);
5108 while ((worker
= first_idle_worker(pool
)))
5109 set_worker_dying(worker
, &cull_list
);
5110 WARN_ON(pool
->nr_workers
|| pool
->nr_idle
);
5111 raw_spin_unlock_irq(&pool
->lock
);
5113 detach_dying_workers(&cull_list
);
5115 mutex_unlock(&wq_pool_attach_mutex
);
5117 reap_dying_workers(&cull_list
);
5119 /* shut down the timers */
5120 timer_delete_sync(&pool
->idle_timer
);
5121 cancel_work_sync(&pool
->idle_cull_work
);
5122 timer_delete_sync(&pool
->mayday_timer
);
5124 /* RCU protected to allow dereferences from get_work_pool() */
5125 call_rcu(&pool
->rcu
, rcu_free_pool
);
5129 * get_unbound_pool - get a worker_pool with the specified attributes
5130 * @attrs: the attributes of the worker_pool to get
5132 * Obtain a worker_pool which has the same attributes as @attrs, bump the
5133 * reference count and return it. If there already is a matching
5134 * worker_pool, it will be used; otherwise, this function attempts to
5137 * Should be called with wq_pool_mutex held.
5139 * Return: On success, a worker_pool with the same attributes as @attrs.
5140 * On failure, %NULL.
5142 static struct worker_pool
*get_unbound_pool(const struct workqueue_attrs
*attrs
)
5144 struct wq_pod_type
*pt
= &wq_pod_types
[WQ_AFFN_NUMA
];
5145 u32 hash
= wqattrs_hash(attrs
);
5146 struct worker_pool
*pool
;
5147 int pod
, node
= NUMA_NO_NODE
;
5149 lockdep_assert_held(&wq_pool_mutex
);
5151 /* do we already have a matching pool? */
5152 hash_for_each_possible(unbound_pool_hash
, pool
, hash_node
, hash
) {
5153 if (wqattrs_equal(pool
->attrs
, attrs
)) {
5159 /* If __pod_cpumask is contained inside a NUMA pod, that's our node */
5160 for (pod
= 0; pod
< pt
->nr_pods
; pod
++) {
5161 if (cpumask_subset(attrs
->__pod_cpumask
, pt
->pod_cpus
[pod
])) {
5162 node
= pt
->pod_node
[pod
];
5167 /* nope, create a new one */
5168 pool
= kzalloc_node(sizeof(*pool
), GFP_KERNEL
, node
);
5169 if (!pool
|| init_worker_pool(pool
) < 0)
5173 copy_workqueue_attrs(pool
->attrs
, attrs
);
5174 wqattrs_clear_for_pool(pool
->attrs
);
5176 if (worker_pool_assign_id(pool
) < 0)
5179 /* create and start the initial worker */
5180 if (wq_online
&& !create_worker(pool
))
5184 hash_add(unbound_pool_hash
, &pool
->hash_node
, hash
);
5189 put_unbound_pool(pool
);
5194 * Scheduled on pwq_release_worker by put_pwq() when an unbound pwq hits zero
5195 * refcnt and needs to be destroyed.
5197 static void pwq_release_workfn(struct kthread_work
*work
)
5199 struct pool_workqueue
*pwq
= container_of(work
, struct pool_workqueue
,
5201 struct workqueue_struct
*wq
= pwq
->wq
;
5202 struct worker_pool
*pool
= pwq
->pool
;
5203 bool is_last
= false;
5206 * When @pwq is not linked, it doesn't hold any reference to the
5207 * @wq, and @wq is invalid to access.
5209 if (!list_empty(&pwq
->pwqs_node
)) {
5210 mutex_lock(&wq
->mutex
);
5211 list_del_rcu(&pwq
->pwqs_node
);
5212 is_last
= list_empty(&wq
->pwqs
);
5215 * For ordered workqueue with a plugged dfl_pwq, restart it now.
5217 if (!is_last
&& (wq
->flags
& __WQ_ORDERED
))
5218 unplug_oldest_pwq(wq
);
5220 mutex_unlock(&wq
->mutex
);
5223 if (wq
->flags
& WQ_UNBOUND
) {
5224 mutex_lock(&wq_pool_mutex
);
5225 put_unbound_pool(pool
);
5226 mutex_unlock(&wq_pool_mutex
);
5229 if (!list_empty(&pwq
->pending_node
)) {
5230 struct wq_node_nr_active
*nna
=
5231 wq_node_nr_active(pwq
->wq
, pwq
->pool
->node
);
5233 raw_spin_lock_irq(&nna
->lock
);
5234 list_del_init(&pwq
->pending_node
);
5235 raw_spin_unlock_irq(&nna
->lock
);
5238 kfree_rcu(pwq
, rcu
);
5241 * If we're the last pwq going away, @wq is already dead and no one
5242 * is gonna access it anymore. Schedule RCU free.
5245 wq_unregister_lockdep(wq
);
5246 call_rcu(&wq
->rcu
, rcu_free_wq
);
5250 /* initialize newly allocated @pwq which is associated with @wq and @pool */
5251 static void init_pwq(struct pool_workqueue
*pwq
, struct workqueue_struct
*wq
,
5252 struct worker_pool
*pool
)
5254 BUG_ON((unsigned long)pwq
& ~WORK_STRUCT_PWQ_MASK
);
5256 memset(pwq
, 0, sizeof(*pwq
));
5260 pwq
->flush_color
= -1;
5262 INIT_LIST_HEAD(&pwq
->inactive_works
);
5263 INIT_LIST_HEAD(&pwq
->pending_node
);
5264 INIT_LIST_HEAD(&pwq
->pwqs_node
);
5265 INIT_LIST_HEAD(&pwq
->mayday_node
);
5266 kthread_init_work(&pwq
->release_work
, pwq_release_workfn
);
5269 * Set the dummy cursor work with valid function and get_work_pwq().
5271 * The cursor work should only be in the pwq->pool->worklist, and
5272 * should not be treated as a processable work item.
5274 * WORK_STRUCT_PENDING and WORK_STRUCT_INACTIVE just make it less
5275 * surprise for kernel debugging tools and reviewers.
5277 INIT_WORK(&pwq
->mayday_cursor
, mayday_cursor_func
);
5278 atomic_long_set(&pwq
->mayday_cursor
.data
, (unsigned long)pwq
|
5279 WORK_STRUCT_PENDING
| WORK_STRUCT_PWQ
| WORK_STRUCT_INACTIVE
);
5282 /* sync @pwq with the current state of its associated wq and link it */
5283 static void link_pwq(struct pool_workqueue
*pwq
)
5285 struct workqueue_struct
*wq
= pwq
->wq
;
5287 lockdep_assert_held(&wq
->mutex
);
5289 /* may be called multiple times, ignore if already linked */
5290 if (!list_empty(&pwq
->pwqs_node
))
5293 /* set the matching work_color */
5294 pwq
->work_color
= wq
->work_color
;
5297 list_add_tail_rcu(&pwq
->pwqs_node
, &wq
->pwqs
);
5300 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
5301 static struct pool_workqueue
*alloc_unbound_pwq(struct workqueue_struct
*wq
,
5302 const struct workqueue_attrs
*attrs
)
5304 struct worker_pool
*pool
;
5305 struct pool_workqueue
*pwq
;
5307 lockdep_assert_held(&wq_pool_mutex
);
5309 pool
= get_unbound_pool(attrs
);
5313 pwq
= kmem_cache_alloc_node(pwq_cache
, GFP_KERNEL
, pool
->node
);
5315 put_unbound_pool(pool
);
5319 init_pwq(pwq
, wq
, pool
);
5324 * wq_calc_pod_cpumask - calculate a wq_attrs' cpumask for a pod
5325 * @attrs: the wq_attrs of the default pwq of the target workqueue
5326 * @cpu: the target CPU
5328 * Calculate the cpumask a workqueue with @attrs should use on @pod.
5329 * The result is stored in @attrs->__pod_cpumask.
5331 * If pod affinity is not enabled, @attrs->cpumask is always used. If enabled
5332 * and @pod has online CPUs requested by @attrs, the returned cpumask is the
5333 * intersection of the possible CPUs of @pod and @attrs->cpumask.
5335 * The caller is responsible for ensuring that the cpumask of @pod stays stable.
5337 static void wq_calc_pod_cpumask(struct workqueue_attrs
*attrs
, int cpu
)
5339 const struct wq_pod_type
*pt
= wqattrs_pod_type(attrs
);
5340 int pod
= pt
->cpu_pod
[cpu
];
5342 /* calculate possible CPUs in @pod that @attrs wants */
5343 cpumask_and(attrs
->__pod_cpumask
, pt
->pod_cpus
[pod
], attrs
->cpumask
);
5344 /* does @pod have any online CPUs @attrs wants? */
5345 if (!cpumask_intersects(attrs
->__pod_cpumask
, wq_online_cpumask
)) {
5346 cpumask_copy(attrs
->__pod_cpumask
, attrs
->cpumask
);
5351 /* install @pwq into @wq and return the old pwq, @cpu < 0 for dfl_pwq */
5352 static struct pool_workqueue
*install_unbound_pwq(struct workqueue_struct
*wq
,
5353 int cpu
, struct pool_workqueue
*pwq
)
5355 struct pool_workqueue __rcu
**slot
= unbound_pwq_slot(wq
, cpu
);
5356 struct pool_workqueue
*old_pwq
;
5358 lockdep_assert_held(&wq_pool_mutex
);
5359 lockdep_assert_held(&wq
->mutex
);
5361 /* link_pwq() can handle duplicate calls */
5364 old_pwq
= rcu_access_pointer(*slot
);
5365 rcu_assign_pointer(*slot
, pwq
);
5369 /* context to store the prepared attrs & pwqs before applying */
5370 struct apply_wqattrs_ctx
{
5371 struct workqueue_struct
*wq
; /* target workqueue */
5372 struct workqueue_attrs
*attrs
; /* attrs to apply */
5373 struct list_head list
; /* queued for batching commit */
5374 struct pool_workqueue
*dfl_pwq
;
5375 struct pool_workqueue
*pwq_tbl
[];
5378 /* free the resources after success or abort */
5379 static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx
*ctx
)
5384 for_each_possible_cpu(cpu
)
5385 put_pwq_unlocked(ctx
->pwq_tbl
[cpu
]);
5386 put_pwq_unlocked(ctx
->dfl_pwq
);
5388 free_workqueue_attrs(ctx
->attrs
);
5394 /* allocate the attrs and pwqs for later installation */
5395 static struct apply_wqattrs_ctx
*
5396 apply_wqattrs_prepare(struct workqueue_struct
*wq
,
5397 const struct workqueue_attrs
*attrs
,
5398 const cpumask_var_t unbound_cpumask
)
5400 struct apply_wqattrs_ctx
*ctx
;
5401 struct workqueue_attrs
*new_attrs
;
5404 lockdep_assert_held(&wq_pool_mutex
);
5406 if (WARN_ON(attrs
->affn_scope
< 0 ||
5407 attrs
->affn_scope
>= WQ_AFFN_NR_TYPES
))
5408 return ERR_PTR(-EINVAL
);
5410 ctx
= kzalloc_flex(*ctx
, pwq_tbl
, nr_cpu_ids
);
5412 new_attrs
= alloc_workqueue_attrs();
5413 if (!ctx
|| !new_attrs
)
5417 * If something goes wrong during CPU up/down, we'll fall back to
5418 * the default pwq covering whole @attrs->cpumask. Always create
5419 * it even if we don't use it immediately.
5421 copy_workqueue_attrs(new_attrs
, attrs
);
5422 wqattrs_actualize_cpumask(new_attrs
, unbound_cpumask
);
5423 cpumask_copy(new_attrs
->__pod_cpumask
, new_attrs
->cpumask
);
5424 ctx
->dfl_pwq
= alloc_unbound_pwq(wq
, new_attrs
);
5428 for_each_possible_cpu(cpu
) {
5429 if (new_attrs
->ordered
) {
5430 ctx
->dfl_pwq
->refcnt
++;
5431 ctx
->pwq_tbl
[cpu
] = ctx
->dfl_pwq
;
5433 wq_calc_pod_cpumask(new_attrs
, cpu
);
5434 ctx
->pwq_tbl
[cpu
] = alloc_unbound_pwq(wq
, new_attrs
);
5435 if (!ctx
->pwq_tbl
[cpu
])
5440 /* save the user configured attrs and sanitize it. */
5441 copy_workqueue_attrs(new_attrs
, attrs
);
5442 cpumask_and(new_attrs
->cpumask
, new_attrs
->cpumask
, cpu_possible_mask
);
5443 cpumask_copy(new_attrs
->__pod_cpumask
, new_attrs
->cpumask
);
5444 ctx
->attrs
= new_attrs
;
5447 * For initialized ordered workqueues, there should only be one pwq
5448 * (dfl_pwq). Set the plugged flag of ctx->dfl_pwq to suspend execution
5449 * of newly queued work items until execution of older work items in
5450 * the old pwq's have completed.
5452 if ((wq
->flags
& __WQ_ORDERED
) && !list_empty(&wq
->pwqs
))
5453 ctx
->dfl_pwq
->plugged
= true;
5459 free_workqueue_attrs(new_attrs
);
5460 apply_wqattrs_cleanup(ctx
);
5461 return ERR_PTR(-ENOMEM
);
5464 /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
5465 static void apply_wqattrs_commit(struct apply_wqattrs_ctx
*ctx
)
5469 /* all pwqs have been created successfully, let's install'em */
5470 mutex_lock(&ctx
->wq
->mutex
);
5472 copy_workqueue_attrs(ctx
->wq
->unbound_attrs
, ctx
->attrs
);
5474 /* save the previous pwqs and install the new ones */
5475 for_each_possible_cpu(cpu
)
5476 ctx
->pwq_tbl
[cpu
] = install_unbound_pwq(ctx
->wq
, cpu
,
5478 ctx
->dfl_pwq
= install_unbound_pwq(ctx
->wq
, -1, ctx
->dfl_pwq
);
5480 /* update node_nr_active->max */
5481 wq_update_node_max_active(ctx
->wq
, -1);
5483 mutex_unlock(&ctx
->wq
->mutex
);
5486 static int apply_workqueue_attrs_locked(struct workqueue_struct
*wq
,
5487 const struct workqueue_attrs
*attrs
)
5489 struct apply_wqattrs_ctx
*ctx
;
5491 /* only unbound workqueues can change attributes */
5492 if (WARN_ON(!(wq
->flags
& WQ_UNBOUND
)))
5495 ctx
= apply_wqattrs_prepare(wq
, attrs
, wq_unbound_cpumask
);
5497 return PTR_ERR(ctx
);
5499 /* the ctx has been prepared successfully, let's commit it */
5500 apply_wqattrs_commit(ctx
);
5501 apply_wqattrs_cleanup(ctx
);
5507 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
5508 * @wq: the target workqueue
5509 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
5511 * Apply @attrs to an unbound workqueue @wq. Unless disabled, this function maps
5512 * a separate pwq to each CPU pod with possibles CPUs in @attrs->cpumask so that
5513 * work items are affine to the pod it was issued on. Older pwqs are released as
5514 * in-flight work items finish. Note that a work item which repeatedly requeues
5515 * itself back-to-back will stay on its current pwq.
5517 * Performs GFP_KERNEL allocations.
5519 * Return: 0 on success and -errno on failure.
5521 int apply_workqueue_attrs(struct workqueue_struct
*wq
,
5522 const struct workqueue_attrs
*attrs
)
5526 mutex_lock(&wq_pool_mutex
);
5527 ret
= apply_workqueue_attrs_locked(wq
, attrs
);
5528 mutex_unlock(&wq_pool_mutex
);
5534 * unbound_wq_update_pwq - update a pwq slot for CPU hot[un]plug
5535 * @wq: the target workqueue
5536 * @cpu: the CPU to update the pwq slot for
5538 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
5539 * %CPU_DOWN_FAILED. @cpu is in the same pod of the CPU being hot[un]plugged.
5542 * If pod affinity can't be adjusted due to memory allocation failure, it falls
5543 * back to @wq->dfl_pwq which may not be optimal but is always correct.
5545 * Note that when the last allowed CPU of a pod goes offline for a workqueue
5546 * with a cpumask spanning multiple pods, the workers which were already
5547 * executing the work items for the workqueue will lose their CPU affinity and
5548 * may execute on any CPU. This is similar to how per-cpu workqueues behave on
5549 * CPU_DOWN. If a workqueue user wants strict affinity, it's the user's
5550 * responsibility to flush the work item from CPU_DOWN_PREPARE.
5552 static void unbound_wq_update_pwq(struct workqueue_struct
*wq
, int cpu
)
5554 struct pool_workqueue
*old_pwq
= NULL
, *pwq
;
5555 struct workqueue_attrs
*target_attrs
;
5557 lockdep_assert_held(&wq_pool_mutex
);
5559 if (!(wq
->flags
& WQ_UNBOUND
) || wq
->unbound_attrs
->ordered
)
5563 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
5564 * Let's use a preallocated one. The following buf is protected by
5565 * CPU hotplug exclusion.
5567 target_attrs
= unbound_wq_update_pwq_attrs_buf
;
5569 copy_workqueue_attrs(target_attrs
, wq
->unbound_attrs
);
5570 wqattrs_actualize_cpumask(target_attrs
, wq_unbound_cpumask
);
5572 /* nothing to do if the target cpumask matches the current pwq */
5573 wq_calc_pod_cpumask(target_attrs
, cpu
);
5574 if (wqattrs_equal(target_attrs
, unbound_pwq(wq
, cpu
)->pool
->attrs
))
5577 /* create a new pwq */
5578 pwq
= alloc_unbound_pwq(wq
, target_attrs
);
5580 pr_warn("workqueue: allocation failed while updating CPU pod affinity of \"%s\"\n",
5585 /* Install the new pwq. */
5586 mutex_lock(&wq
->mutex
);
5587 old_pwq
= install_unbound_pwq(wq
, cpu
, pwq
);
5591 mutex_lock(&wq
->mutex
);
5592 pwq
= unbound_pwq(wq
, -1);
5593 raw_spin_lock_irq(&pwq
->pool
->lock
);
5595 raw_spin_unlock_irq(&pwq
->pool
->lock
);
5596 old_pwq
= install_unbound_pwq(wq
, cpu
, pwq
);
5598 mutex_unlock(&wq
->mutex
);
5599 put_pwq_unlocked(old_pwq
);
5602 static int alloc_and_link_pwqs(struct workqueue_struct
*wq
)
5604 bool highpri
= wq
->flags
& WQ_HIGHPRI
;
5607 lockdep_assert_held(&wq_pool_mutex
);
5609 wq
->cpu_pwq
= alloc_percpu(struct pool_workqueue
*);
5613 if (!(wq
->flags
& WQ_UNBOUND
)) {
5614 struct worker_pool __percpu
*pools
;
5616 if (wq
->flags
& WQ_BH
)
5617 pools
= bh_worker_pools
;
5619 pools
= cpu_worker_pools
;
5621 for_each_possible_cpu(cpu
) {
5622 struct pool_workqueue
**pwq_p
;
5623 struct worker_pool
*pool
;
5625 pool
= &(per_cpu_ptr(pools
, cpu
)[highpri
]);
5626 pwq_p
= per_cpu_ptr(wq
->cpu_pwq
, cpu
);
5628 *pwq_p
= kmem_cache_alloc_node(pwq_cache
, GFP_KERNEL
,
5633 init_pwq(*pwq_p
, wq
, pool
);
5635 mutex_lock(&wq
->mutex
);
5637 mutex_unlock(&wq
->mutex
);
5642 if (wq
->flags
& __WQ_ORDERED
) {
5643 struct pool_workqueue
*dfl_pwq
;
5645 ret
= apply_workqueue_attrs_locked(wq
, ordered_wq_attrs
[highpri
]);
5646 /* there should only be single pwq for ordering guarantee */
5647 dfl_pwq
= rcu_access_pointer(wq
->dfl_pwq
);
5648 WARN(!ret
&& (wq
->pwqs
.next
!= &dfl_pwq
->pwqs_node
||
5649 wq
->pwqs
.prev
!= &dfl_pwq
->pwqs_node
),
5650 "ordering guarantee broken for workqueue %s\n", wq
->name
);
5652 ret
= apply_workqueue_attrs_locked(wq
, unbound_std_wq_attrs
[highpri
]);
5661 for_each_possible_cpu(cpu
) {
5662 struct pool_workqueue
*pwq
= *per_cpu_ptr(wq
->cpu_pwq
, cpu
);
5666 * Unlink pwq from wq->pwqs since link_pwq()
5667 * may have already added it. wq->mutex is not
5668 * needed as the wq has not been published yet.
5670 if (!list_empty(&pwq
->pwqs_node
))
5671 list_del_rcu(&pwq
->pwqs_node
);
5672 kmem_cache_free(pwq_cache
, pwq
);
5675 free_percpu(wq
->cpu_pwq
);
5681 static int wq_clamp_max_active(int max_active
, unsigned int flags
,
5684 if (max_active
< 1 || max_active
> WQ_MAX_ACTIVE
)
5685 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
5686 max_active
, name
, 1, WQ_MAX_ACTIVE
);
5688 return clamp_val(max_active
, 1, WQ_MAX_ACTIVE
);
5692 * Workqueues which may be used during memory reclaim should have a rescuer
5693 * to guarantee forward progress.
5695 static int init_rescuer(struct workqueue_struct
*wq
)
5697 struct worker
*rescuer
;
5698 char id_buf
[WORKER_ID_LEN
];
5701 lockdep_assert_held(&wq_pool_mutex
);
5703 if (!(wq
->flags
& WQ_MEM_RECLAIM
))
5706 rescuer
= alloc_worker(NUMA_NO_NODE
);
5708 pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
5713 rescuer
->rescue_wq
= wq
;
5714 format_worker_id(id_buf
, sizeof(id_buf
), rescuer
, NULL
);
5716 rescuer
->task
= kthread_create(rescuer_thread
, rescuer
, "%s", id_buf
);
5717 if (IS_ERR(rescuer
->task
)) {
5718 ret
= PTR_ERR(rescuer
->task
);
5719 pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
5720 wq
->name
, ERR_PTR(ret
));
5725 wq
->rescuer
= rescuer
;
5727 /* initial cpumask is consistent with the detached rescuer and unbind_worker() */
5728 if (cpumask_intersects(wq_unbound_cpumask
, cpu_active_mask
))
5729 kthread_bind_mask(rescuer
->task
, wq_unbound_cpumask
);
5731 kthread_bind_mask(rescuer
->task
, cpu_possible_mask
);
5733 wake_up_process(rescuer
->task
);
5739 * wq_adjust_max_active - update a wq's max_active to the current setting
5740 * @wq: target workqueue
5742 * If @wq isn't freezing, set @wq->max_active to the saved_max_active and
5743 * activate inactive work items accordingly. If @wq is freezing, clear
5744 * @wq->max_active to zero.
5746 static void wq_adjust_max_active(struct workqueue_struct
*wq
)
5749 int new_max
, new_min
;
5751 lockdep_assert_held(&wq
->mutex
);
5753 if ((wq
->flags
& WQ_FREEZABLE
) && workqueue_freezing
) {
5757 new_max
= wq
->saved_max_active
;
5758 new_min
= wq
->saved_min_active
;
5761 if (wq
->max_active
== new_max
&& wq
->min_active
== new_min
)
5765 * Update @wq->max/min_active and then kick inactive work items if more
5766 * active work items are allowed. This doesn't break work item ordering
5767 * because new work items are always queued behind existing inactive
5768 * work items if there are any.
5770 WRITE_ONCE(wq
->max_active
, new_max
);
5771 WRITE_ONCE(wq
->min_active
, new_min
);
5773 if (wq
->flags
& WQ_UNBOUND
)
5774 wq_update_node_max_active(wq
, -1);
5780 * Round-robin through pwq's activating the first inactive work item
5781 * until max_active is filled.
5784 struct pool_workqueue
*pwq
;
5787 for_each_pwq(pwq
, wq
) {
5788 unsigned long irq_flags
;
5790 /* can be called during early boot w/ irq disabled */
5791 raw_spin_lock_irqsave(&pwq
->pool
->lock
, irq_flags
);
5792 if (pwq_activate_first_inactive(pwq
, true)) {
5794 kick_pool(pwq
->pool
);
5796 raw_spin_unlock_irqrestore(&pwq
->pool
->lock
, irq_flags
);
5798 } while (activated
);
5802 static struct workqueue_struct
*__alloc_workqueue(const char *fmt
,
5804 int max_active
, va_list args
)
5806 struct workqueue_struct
*wq
;
5810 if (flags
& WQ_BH
) {
5811 if (WARN_ON_ONCE(flags
& ~__WQ_BH_ALLOWS
))
5813 if (WARN_ON_ONCE(max_active
))
5817 /* see the comment above the definition of WQ_POWER_EFFICIENT */
5818 if ((flags
& WQ_POWER_EFFICIENT
) && wq_power_efficient
)
5819 flags
= (flags
& ~WQ_PERCPU
) | WQ_UNBOUND
;
5821 /* allocate wq and format name */
5822 if (flags
& WQ_UNBOUND
)
5823 wq_size
= struct_size(wq
, node_nr_active
, nr_node_ids
+ 1);
5825 wq_size
= sizeof(*wq
);
5827 wq
= kzalloc_noprof(wq_size
, GFP_KERNEL
);
5831 if (flags
& WQ_UNBOUND
) {
5832 wq
->unbound_attrs
= alloc_workqueue_attrs_noprof();
5833 if (!wq
->unbound_attrs
)
5837 name_len
= vsnprintf(wq
->name
, sizeof(wq
->name
), fmt
, args
);
5839 if (name_len
>= WQ_NAME_LEN
)
5840 pr_warn_once("workqueue: name exceeds WQ_NAME_LEN. Truncating to: %s\n",
5844 * One among WQ_PERCPU and WQ_UNBOUND must be set, but not both.
5845 * - If neither is set, default to WQ_PERCPU
5846 * - If both are set, default to WQ_UNBOUND
5848 * This code can be removed after workqueue are unbound by default
5850 if (unlikely(!(flags
& (WQ_UNBOUND
| WQ_PERCPU
)))) {
5851 WARN_ONCE(1, "workqueue: %s is using neither WQ_PERCPU or WQ_UNBOUND. "
5852 "Setting WQ_PERCPU.\n", wq
->name
);
5854 } else if (unlikely((flags
& WQ_PERCPU
) && (flags
& WQ_UNBOUND
))) {
5855 WARN_ONCE(1, "workqueue: %s uses both WQ_PERCPU and WQ_UNBOUND. "
5856 "Dropped WQ_PERCPU, keeping WQ_UNBOUND.\n", wq
->name
);
5857 flags
&= ~WQ_PERCPU
;
5860 if (flags
& WQ_BH
) {
5862 * BH workqueues always share a single execution context per CPU
5863 * and don't impose any max_active limit.
5865 max_active
= INT_MAX
;
5867 max_active
= max_active
?: WQ_DFL_ACTIVE
;
5868 max_active
= wq_clamp_max_active(max_active
, flags
, wq
->name
);
5873 wq
->max_active
= max_active
;
5874 wq
->min_active
= min(max_active
, WQ_DFL_MIN_ACTIVE
);
5875 wq
->saved_max_active
= wq
->max_active
;
5876 wq
->saved_min_active
= wq
->min_active
;
5877 mutex_init(&wq
->mutex
);
5878 atomic_set(&wq
->nr_pwqs_to_flush
, 0);
5879 INIT_LIST_HEAD(&wq
->pwqs
);
5880 INIT_LIST_HEAD(&wq
->flusher_queue
);
5881 INIT_LIST_HEAD(&wq
->flusher_overflow
);
5882 INIT_LIST_HEAD(&wq
->maydays
);
5884 INIT_LIST_HEAD(&wq
->list
);
5886 if (flags
& WQ_UNBOUND
) {
5887 if (alloc_node_nr_active(wq
->node_nr_active
) < 0)
5892 * wq_pool_mutex protects the workqueues list, allocations of PWQs,
5893 * and the global freeze state.
5895 mutex_lock(&wq_pool_mutex
);
5897 if (alloc_and_link_pwqs(wq
) < 0)
5898 goto err_unlock_free_node_nr_active
;
5900 mutex_lock(&wq
->mutex
);
5901 wq_adjust_max_active(wq
);
5902 mutex_unlock(&wq
->mutex
);
5904 list_add_tail_rcu(&wq
->list
, &workqueues
);
5906 if (wq_online
&& init_rescuer(wq
) < 0)
5907 goto err_unlock_destroy
;
5909 mutex_unlock(&wq_pool_mutex
);
5911 if ((wq
->flags
& WQ_SYSFS
) && workqueue_sysfs_register(wq
))
5916 err_unlock_free_node_nr_active
:
5917 mutex_unlock(&wq_pool_mutex
);
5919 * Failed alloc_and_link_pwqs() may leave pending pwq->release_work,
5920 * flushing the pwq_release_worker ensures that the pwq_release_workfn()
5921 * completes before calling kfree(wq).
5923 if (wq
->flags
& WQ_UNBOUND
) {
5924 kthread_flush_worker(pwq_release_worker
);
5925 free_node_nr_active(wq
->node_nr_active
);
5928 free_workqueue_attrs(wq
->unbound_attrs
);
5932 mutex_unlock(&wq_pool_mutex
);
5934 destroy_workqueue(wq
);
5939 static struct workqueue_struct
*alloc_workqueue_va(const char *fmt
,
5944 struct workqueue_struct
*wq
;
5946 wq
= __alloc_workqueue(fmt
, flags
, max_active
, args
);
5948 wq_init_lockdep(wq
);
5954 struct workqueue_struct
*alloc_workqueue_noprof(const char *fmt
,
5956 int max_active
, ...)
5958 struct workqueue_struct
*wq
;
5961 va_start(args
, max_active
);
5962 wq
= alloc_workqueue_va(fmt
, flags
, max_active
, args
);
5967 EXPORT_SYMBOL_GPL(alloc_workqueue_noprof
);
5969 static void devm_workqueue_release(void *res
)
5971 destroy_workqueue(res
);
5974 __printf(2, 5) struct workqueue_struct
*
5975 devm_alloc_workqueue_noprof(struct device
*dev
, const char *fmt
,
5976 unsigned int flags
, int max_active
, ...)
5978 struct workqueue_struct
*wq
;
5982 va_start(args
, max_active
);
5983 wq
= alloc_workqueue_va(fmt
, flags
, max_active
, args
);
5988 ret
= devm_add_action_or_reset(dev
, devm_workqueue_release
, wq
);
5994 EXPORT_SYMBOL_GPL(devm_alloc_workqueue_noprof
);
5996 #ifdef CONFIG_LOCKDEP
5998 struct workqueue_struct
*
5999 alloc_workqueue_lockdep_map(const char *fmt
, unsigned int flags
,
6000 int max_active
, struct lockdep_map
*lockdep_map
, ...)
6002 struct workqueue_struct
*wq
;
6005 va_start(args
, lockdep_map
);
6006 wq
= __alloc_workqueue(fmt
, flags
, max_active
, args
);
6011 wq
->lockdep_map
= lockdep_map
;
6015 EXPORT_SYMBOL_GPL(alloc_workqueue_lockdep_map
);
6018 static bool pwq_busy(struct pool_workqueue
*pwq
)
6022 for (i
= 0; i
< WORK_NR_COLORS
; i
++)
6023 if (pwq
->nr_in_flight
[i
])
6026 if ((pwq
!= rcu_access_pointer(pwq
->wq
->dfl_pwq
)) && (pwq
->refcnt
> 1))
6028 if (!pwq_is_empty(pwq
))
6035 * destroy_workqueue - safely terminate a workqueue
6036 * @wq: target workqueue
6038 * Safely destroy a workqueue. All work currently pending will be done first.
6040 * This function does NOT guarantee that non-pending work that has been
6041 * submitted with queue_delayed_work() and similar functions will be done
6042 * before destroying the workqueue. The fundamental problem is that, currently,
6043 * the workqueue has no way of accessing non-pending delayed_work. delayed_work
6044 * is only linked on the timer-side. All delayed_work must, therefore, be
6045 * canceled before calling this function.
6047 * TODO: It would be better if the problem described above wouldn't exist and
6048 * destroy_workqueue() would cleanly cancel all pending and non-pending
6051 void destroy_workqueue(struct workqueue_struct
*wq
)
6053 struct pool_workqueue
*pwq
;
6057 * Remove it from sysfs first so that sanity check failure doesn't
6058 * lead to sysfs name conflicts.
6060 workqueue_sysfs_unregister(wq
);
6062 /* mark the workqueue destruction is in progress */
6063 mutex_lock(&wq
->mutex
);
6064 wq
->flags
|= __WQ_DESTROYING
;
6065 mutex_unlock(&wq
->mutex
);
6067 /* drain it before proceeding with destruction */
6068 drain_workqueue(wq
);
6070 /* kill rescuer, if sanity checks fail, leave it w/o rescuer */
6072 /* rescuer will empty maydays list before exiting */
6073 kthread_stop(wq
->rescuer
->task
);
6079 * Sanity checks - grab all the locks so that we wait for all
6080 * in-flight operations which may do put_pwq().
6082 mutex_lock(&wq_pool_mutex
);
6083 mutex_lock(&wq
->mutex
);
6084 for_each_pwq(pwq
, wq
) {
6085 raw_spin_lock_irq(&pwq
->pool
->lock
);
6086 if (WARN_ON(pwq_busy(pwq
))) {
6087 pr_warn("%s: %s has the following busy pwq\n",
6088 __func__
, wq
->name
);
6090 raw_spin_unlock_irq(&pwq
->pool
->lock
);
6091 mutex_unlock(&wq
->mutex
);
6092 mutex_unlock(&wq_pool_mutex
);
6093 show_one_workqueue(wq
);
6096 raw_spin_unlock_irq(&pwq
->pool
->lock
);
6098 mutex_unlock(&wq
->mutex
);
6101 * wq list is used to freeze wq, remove from list after
6102 * flushing is complete in case freeze races us.
6104 list_del_rcu(&wq
->list
);
6105 mutex_unlock(&wq_pool_mutex
);
6108 * We're the sole accessor of @wq. Directly access cpu_pwq and dfl_pwq
6109 * to put the base refs. @wq will be auto-destroyed from the last
6110 * pwq_put. RCU read lock prevents @wq from going away from under us.
6114 for_each_possible_cpu(cpu
) {
6115 put_pwq_unlocked(unbound_pwq(wq
, cpu
));
6116 RCU_INIT_POINTER(*unbound_pwq_slot(wq
, cpu
), NULL
);
6119 put_pwq_unlocked(unbound_pwq(wq
, -1));
6120 RCU_INIT_POINTER(*unbound_pwq_slot(wq
, -1), NULL
);
6124 EXPORT_SYMBOL_GPL(destroy_workqueue
);
6127 * workqueue_set_max_active - adjust max_active of a workqueue
6128 * @wq: target workqueue
6129 * @max_active: new max_active value.
6131 * Set max_active of @wq to @max_active. See the alloc_workqueue() function
6135 * Don't call from IRQ context.
6137 void workqueue_set_max_active(struct workqueue_struct
*wq
, int max_active
)
6139 /* max_active doesn't mean anything for BH workqueues */
6140 if (WARN_ON(wq
->flags
& WQ_BH
))
6142 /* disallow meddling with max_active for ordered workqueues */
6143 if (WARN_ON(wq
->flags
& __WQ_ORDERED
))
6146 max_active
= wq_clamp_max_active(max_active
, wq
->flags
, wq
->name
);
6148 mutex_lock(&wq
->mutex
);
6150 wq
->saved_max_active
= max_active
;
6151 if (wq
->flags
& WQ_UNBOUND
)
6152 wq
->saved_min_active
= min(wq
->saved_min_active
, max_active
);
6154 wq_adjust_max_active(wq
);
6156 mutex_unlock(&wq
->mutex
);
6158 EXPORT_SYMBOL_GPL(workqueue_set_max_active
);
6161 * workqueue_set_min_active - adjust min_active of an unbound workqueue
6162 * @wq: target unbound workqueue
6163 * @min_active: new min_active value
6165 * Set min_active of an unbound workqueue. Unlike other types of workqueues, an
6166 * unbound workqueue is not guaranteed to be able to process max_active
6167 * interdependent work items. Instead, an unbound workqueue is guaranteed to be
6168 * able to process min_active number of interdependent work items which is
6169 * %WQ_DFL_MIN_ACTIVE by default.
6171 * Use this function to adjust the min_active value between 0 and the current
6174 void workqueue_set_min_active(struct workqueue_struct
*wq
, int min_active
)
6176 /* min_active is only meaningful for non-ordered unbound workqueues */
6177 if (WARN_ON((wq
->flags
& (WQ_BH
| WQ_UNBOUND
| __WQ_ORDERED
)) !=
6181 mutex_lock(&wq
->mutex
);
6182 wq
->saved_min_active
= clamp(min_active
, 0, wq
->saved_max_active
);
6183 wq_adjust_max_active(wq
);
6184 mutex_unlock(&wq
->mutex
);
6188 * current_work - retrieve %current task's work struct
6190 * Determine if %current task is a workqueue worker and what it's working on.
6191 * Useful to find out the context that the %current task is running in.
6193 * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
6195 struct work_struct
*current_work(void)
6197 struct worker
*worker
= current_wq_worker();
6199 return worker
? worker
->current_work
: NULL
;
6201 EXPORT_SYMBOL(current_work
);
6204 * current_is_workqueue_rescuer - is %current workqueue rescuer?
6206 * Determine whether %current is a workqueue rescuer. Can be used from
6207 * work functions to determine whether it's being run off the rescuer task.
6209 * Return: %true if %current is a workqueue rescuer. %false otherwise.
6211 bool current_is_workqueue_rescuer(void)
6213 struct worker
*worker
= current_wq_worker();
6215 return worker
&& worker
->rescue_wq
;
6219 * workqueue_congested - test whether a workqueue is congested
6220 * @cpu: CPU in question
6221 * @wq: target workqueue
6223 * Test whether @wq's cpu workqueue for @cpu is congested. There is
6224 * no synchronization around this function and the test result is
6225 * unreliable and only useful as advisory hints or for debugging.
6227 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
6229 * With the exception of ordered workqueues, all workqueues have per-cpu
6230 * pool_workqueues, each with its own congested state. A workqueue being
6231 * congested on one CPU doesn't mean that the workqueue is contested on any
6235 * %true if congested, %false otherwise.
6237 bool workqueue_congested(int cpu
, struct workqueue_struct
*wq
)
6239 struct pool_workqueue
*pwq
;
6244 if (cpu
== WORK_CPU_UNBOUND
)
6245 cpu
= smp_processor_id();
6247 pwq
= *per_cpu_ptr(wq
->cpu_pwq
, cpu
);
6248 ret
= !list_empty(&pwq
->inactive_works
);
6254 EXPORT_SYMBOL_GPL(workqueue_congested
);
6257 * work_busy - test whether a work is currently pending or running
6258 * @work: the work to be tested
6260 * Test whether @work is currently pending or running. There is no
6261 * synchronization around this function and the test result is
6262 * unreliable and only useful as advisory hints or for debugging.
6265 * OR'd bitmask of WORK_BUSY_* bits.
6267 unsigned int work_busy(struct work_struct
*work
)
6269 struct worker_pool
*pool
;
6270 unsigned long irq_flags
;
6271 unsigned int ret
= 0;
6273 if (work_pending(work
))
6274 ret
|= WORK_BUSY_PENDING
;
6277 pool
= get_work_pool(work
);
6279 raw_spin_lock_irqsave(&pool
->lock
, irq_flags
);
6280 if (find_worker_executing_work(pool
, work
))
6281 ret
|= WORK_BUSY_RUNNING
;
6282 raw_spin_unlock_irqrestore(&pool
->lock
, irq_flags
);
6288 EXPORT_SYMBOL_GPL(work_busy
);
6291 * set_worker_desc - set description for the current work item
6292 * @fmt: printf-style format string
6293 * @...: arguments for the format string
6295 * This function can be called by a running work function to describe what
6296 * the work item is about. If the worker task gets dumped, this
6297 * information will be printed out together to help debugging. The
6298 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
6300 void set_worker_desc(const char *fmt
, ...)
6302 struct worker
*worker
= current_wq_worker();
6306 va_start(args
, fmt
);
6307 vsnprintf(worker
->desc
, sizeof(worker
->desc
), fmt
, args
);
6311 EXPORT_SYMBOL_GPL(set_worker_desc
);
6314 * print_worker_info - print out worker information and description
6315 * @log_lvl: the log level to use when printing
6316 * @task: target task
6318 * If @task is a worker and currently executing a work item, print out the
6319 * name of the workqueue being serviced and worker description set with
6320 * set_worker_desc() by the currently executing work item.
6322 * This function can be safely called on any task as long as the
6323 * task_struct itself is accessible. While safe, this function isn't
6324 * synchronized and may print out mixups or garbages of limited length.
6326 void print_worker_info(const char *log_lvl
, struct task_struct
*task
)
6328 work_func_t fn
= NULL
;
6329 char name
[WQ_NAME_LEN
] = { };
6330 char desc
[WORKER_DESC_LEN
] = { };
6331 struct pool_workqueue
*pwq
= NULL
;
6332 struct workqueue_struct
*wq
= NULL
;
6333 struct worker
*worker
;
6335 if (!(task
->flags
& PF_WQ_WORKER
))
6339 * This function is called without any synchronization and @task
6340 * could be in any state. Be careful with dereferences.
6342 worker
= kthread_probe_data(task
);
6345 * Carefully copy the associated workqueue's workfn, name and desc.
6346 * Keep the original last '\0' in case the original is garbage.
6348 copy_from_kernel_nofault(&fn
, &worker
->current_func
, sizeof(fn
));
6349 copy_from_kernel_nofault(&pwq
, &worker
->current_pwq
, sizeof(pwq
));
6350 copy_from_kernel_nofault(&wq
, &pwq
->wq
, sizeof(wq
));
6351 copy_from_kernel_nofault(name
, wq
->name
, sizeof(name
) - 1);
6352 copy_from_kernel_nofault(desc
, worker
->desc
, sizeof(desc
) - 1);
6354 if (fn
|| name
[0] || desc
[0]) {
6355 printk("%sWorkqueue: %s %ps", log_lvl
, name
, fn
);
6356 if (strcmp(name
, desc
))
6357 pr_cont(" (%s)", desc
);
6362 static void pr_cont_pool_info(struct worker_pool
*pool
)
6364 pr_cont(" cpus=%*pbl", nr_cpumask_bits
, pool
->attrs
->cpumask
);
6365 if (pool
->node
!= NUMA_NO_NODE
)
6366 pr_cont(" node=%d", pool
->node
);
6367 pr_cont(" flags=0x%x", pool
->flags
);
6368 if (pool
->flags
& POOL_BH
)
6370 pool
->attrs
->nice
== HIGHPRI_NICE_LEVEL
? "-hi" : "");
6372 pr_cont(" nice=%d", pool
->attrs
->nice
);
6375 static void pr_cont_worker_id(struct worker
*worker
)
6377 struct worker_pool
*pool
= worker
->pool
;
6379 if (pool
->flags
& POOL_BH
)
6381 pool
->attrs
->nice
== HIGHPRI_NICE_LEVEL
? "-hi" : "");
6383 pr_cont("%d%s", task_pid_nr(worker
->task
),
6384 worker
->rescue_wq
? "(RESCUER)" : "");
6387 struct pr_cont_work_struct
{
6393 static void pr_cont_work_flush(bool comma
, work_func_t func
, struct pr_cont_work_struct
*pcwsp
)
6397 if (func
== pcwsp
->func
) {
6401 if (pcwsp
->ctr
== 1)
6402 pr_cont("%s %ps", pcwsp
->comma
? "," : "", pcwsp
->func
);
6404 pr_cont("%s %ld*%ps", pcwsp
->comma
? "," : "", pcwsp
->ctr
, pcwsp
->func
);
6407 if ((long)func
== -1L)
6409 pcwsp
->comma
= comma
;
6414 static void pr_cont_work(bool comma
, struct work_struct
*work
, struct pr_cont_work_struct
*pcwsp
)
6416 if (work
->func
== wq_barrier_func
) {
6417 struct wq_barrier
*barr
;
6419 barr
= container_of(work
, struct wq_barrier
, work
);
6421 pr_cont_work_flush(comma
, (work_func_t
)-1, pcwsp
);
6422 pr_cont("%s BAR(%d)", comma
? "," : "",
6423 task_pid_nr(barr
->task
));
6426 pr_cont_work_flush(comma
, (work_func_t
)-1, pcwsp
);
6427 pr_cont_work_flush(comma
, work
->func
, pcwsp
);
6431 static void show_pwq(struct pool_workqueue
*pwq
)
6433 struct pr_cont_work_struct pcws
= { .ctr
= 0, };
6434 struct worker_pool
*pool
= pwq
->pool
;
6435 struct work_struct
*work
;
6436 struct worker
*worker
;
6437 bool has_in_flight
= false, has_pending
= false;
6440 pr_info(" pwq %d:", pool
->id
);
6441 pr_cont_pool_info(pool
);
6443 pr_cont(" active=%d refcnt=%d%s\n",
6444 pwq
->nr_active
, pwq
->refcnt
,
6445 !list_empty(&pwq
->mayday_node
) ? " MAYDAY" : "");
6447 hash_for_each(pool
->busy_hash
, bkt
, worker
, hentry
) {
6448 if (worker
->current_pwq
== pwq
) {
6449 has_in_flight
= true;
6453 if (has_in_flight
) {
6456 pr_info(" in-flight:");
6457 hash_for_each(pool
->busy_hash
, bkt
, worker
, hentry
) {
6458 if (worker
->current_pwq
!= pwq
)
6461 pr_cont(" %s", comma
? "," : "");
6462 pr_cont_worker_id(worker
);
6463 pr_cont(":%ps", worker
->current_func
);
6465 jiffies_to_msecs(jiffies
- worker
->current_start
) / 1000);
6466 list_for_each_entry(work
, &worker
->scheduled
, entry
)
6467 pr_cont_work(false, work
, &pcws
);
6468 pr_cont_work_flush(comma
, (work_func_t
)-1L, &pcws
);
6474 list_for_each_entry(work
, &pool
->worklist
, entry
) {
6475 if (get_work_pwq(work
) == pwq
) {
6483 pr_info(" pending:");
6484 list_for_each_entry(work
, &pool
->worklist
, entry
) {
6485 if (get_work_pwq(work
) != pwq
)
6488 pr_cont_work(comma
, work
, &pcws
);
6489 comma
= !(*work_data_bits(work
) & WORK_STRUCT_LINKED
);
6491 pr_cont_work_flush(comma
, (work_func_t
)-1L, &pcws
);
6495 if (!list_empty(&pwq
->inactive_works
)) {
6498 pr_info(" inactive:");
6499 list_for_each_entry(work
, &pwq
->inactive_works
, entry
) {
6500 pr_cont_work(comma
, work
, &pcws
);
6501 comma
= !(*work_data_bits(work
) & WORK_STRUCT_LINKED
);
6503 pr_cont_work_flush(comma
, (work_func_t
)-1L, &pcws
);
6509 * show_one_workqueue - dump state of specified workqueue
6510 * @wq: workqueue whose state will be printed
6512 void show_one_workqueue(struct workqueue_struct
*wq
)
6514 struct pool_workqueue
*pwq
;
6516 unsigned long irq_flags
;
6518 for_each_pwq(pwq
, wq
) {
6519 if (!pwq_is_empty(pwq
)) {
6524 if (idle
) /* Nothing to print for idle workqueue */
6527 pr_info("workqueue %s: flags=0x%x\n", wq
->name
, wq
->flags
);
6529 for_each_pwq(pwq
, wq
) {
6530 raw_spin_lock_irqsave(&pwq
->pool
->lock
, irq_flags
);
6531 if (!pwq_is_empty(pwq
)) {
6533 * Defer printing to avoid deadlocks in console
6534 * drivers that queue work while holding locks
6535 * also taken in their write paths.
6537 printk_deferred_enter();
6539 printk_deferred_exit();
6541 raw_spin_unlock_irqrestore(&pwq
->pool
->lock
, irq_flags
);
6543 * We could be printing a lot from atomic context, e.g.
6544 * sysrq-t -> show_all_workqueues(). Avoid triggering
6547 touch_nmi_watchdog();
6553 * show_one_worker_pool - dump state of specified worker pool
6554 * @pool: worker pool whose state will be printed
6556 static void show_one_worker_pool(struct worker_pool
*pool
)
6558 struct worker
*worker
;
6560 unsigned long irq_flags
;
6561 unsigned long hung
= 0;
6563 raw_spin_lock_irqsave(&pool
->lock
, irq_flags
);
6564 if (pool
->nr_workers
== pool
->nr_idle
)
6567 /* How long the first pending work is waiting for a worker. */
6568 if (!list_empty(&pool
->worklist
))
6569 hung
= jiffies_to_msecs(jiffies
- pool
->last_progress_ts
) / 1000;
6572 * Defer printing to avoid deadlocks in console drivers that
6573 * queue work while holding locks also taken in their write
6576 printk_deferred_enter();
6577 pr_info("pool %d:", pool
->id
);
6578 pr_cont_pool_info(pool
);
6579 pr_cont(" hung=%lus workers=%d", hung
, pool
->nr_workers
);
6581 pr_cont(" manager: %d",
6582 task_pid_nr(pool
->manager
->task
));
6583 list_for_each_entry(worker
, &pool
->idle_list
, entry
) {
6584 pr_cont(" %s", first
? "idle: " : "");
6585 pr_cont_worker_id(worker
);
6589 printk_deferred_exit();
6591 raw_spin_unlock_irqrestore(&pool
->lock
, irq_flags
);
6593 * We could be printing a lot from atomic context, e.g.
6594 * sysrq-t -> show_all_workqueues(). Avoid triggering
6597 touch_nmi_watchdog();
6602 * show_all_workqueues - dump workqueue state
6604 * Called from a sysrq handler and prints out all busy workqueues and pools.
6606 void show_all_workqueues(void)
6608 struct workqueue_struct
*wq
;
6609 struct worker_pool
*pool
;
6614 pr_info("Showing busy workqueues and worker pools:\n");
6616 list_for_each_entry_rcu(wq
, &workqueues
, list
)
6617 show_one_workqueue(wq
);
6619 for_each_pool(pool
, pi
)
6620 show_one_worker_pool(pool
);
6626 * show_freezable_workqueues - dump freezable workqueue state
6628 * Called from try_to_freeze_tasks() and prints out all freezable workqueues
6631 void show_freezable_workqueues(void)
6633 struct workqueue_struct
*wq
;
6637 pr_info("Showing freezable workqueues that are still busy:\n");
6639 list_for_each_entry_rcu(wq
, &workqueues
, list
) {
6640 if (!(wq
->flags
& WQ_FREEZABLE
))
6642 show_one_workqueue(wq
);
6648 /* used to show worker information through /proc/PID/{comm,stat,status} */
6649 void wq_worker_comm(char *buf
, size_t size
, struct task_struct
*task
)
6651 /* stabilize PF_WQ_WORKER and worker pool association */
6652 mutex_lock(&wq_pool_attach_mutex
);
6654 if (task
->flags
& PF_WQ_WORKER
) {
6655 struct worker
*worker
= kthread_data(task
);
6656 struct worker_pool
*pool
= worker
->pool
;
6659 off
= format_worker_id(buf
, size
, worker
, pool
);
6662 raw_spin_lock_irq(&pool
->lock
);
6664 * ->desc tracks information (wq name or
6665 * set_worker_desc()) for the latest execution. If
6666 * current, prepend '+', otherwise '-'.
6668 if (worker
->desc
[0] != '\0') {
6669 if (worker
->current_work
)
6670 scnprintf(buf
+ off
, size
- off
, "+%s",
6673 scnprintf(buf
+ off
, size
- off
, "-%s",
6676 raw_spin_unlock_irq(&pool
->lock
);
6679 strscpy(buf
, task
->comm
, size
);
6682 mutex_unlock(&wq_pool_attach_mutex
);
6690 * There are two challenges in supporting CPU hotplug. Firstly, there
6691 * are a lot of assumptions on strong associations among work, pwq and
6692 * pool which make migrating pending and scheduled works very
6693 * difficult to implement without impacting hot paths. Secondly,
6694 * worker pools serve mix of short, long and very long running works making
6695 * blocked draining impractical.
6697 * This is solved by allowing the pools to be disassociated from the CPU
6698 * running as an unbound one and allowing it to be reattached later if the
6699 * cpu comes back online.
6702 static void unbind_workers(int cpu
)
6704 struct worker_pool
*pool
;
6705 struct worker
*worker
;
6707 for_each_cpu_worker_pool(pool
, cpu
) {
6708 mutex_lock(&wq_pool_attach_mutex
);
6709 raw_spin_lock_irq(&pool
->lock
);
6712 * We've blocked all attach/detach operations. Make all workers
6713 * unbound and set DISASSOCIATED. Before this, all workers
6714 * must be on the cpu. After this, they may become diasporas.
6715 * And the preemption disabled section in their sched callbacks
6716 * are guaranteed to see WORKER_UNBOUND since the code here
6717 * is on the same cpu.
6719 for_each_pool_worker(worker
, pool
)
6720 worker
->flags
|= WORKER_UNBOUND
;
6722 pool
->flags
|= POOL_DISASSOCIATED
;
6725 * The handling of nr_running in sched callbacks are disabled
6726 * now. Zap nr_running. After this, nr_running stays zero and
6727 * need_more_worker() and keep_working() are always true as
6728 * long as the worklist is not empty. This pool now behaves as
6729 * an unbound (in terms of concurrency management) pool which
6730 * are served by workers tied to the pool.
6732 pool
->nr_running
= 0;
6735 * With concurrency management just turned off, a busy
6736 * worker blocking could lead to lengthy stalls. Kick off
6737 * unbound chain execution of currently pending work items.
6741 raw_spin_unlock_irq(&pool
->lock
);
6743 for_each_pool_worker(worker
, pool
)
6744 unbind_worker(worker
);
6746 mutex_unlock(&wq_pool_attach_mutex
);
6751 * rebind_workers - rebind all workers of a pool to the associated CPU
6752 * @pool: pool of interest
6754 * @pool->cpu is coming online. Rebind all workers to the CPU.
6756 static void rebind_workers(struct worker_pool
*pool
)
6758 struct worker
*worker
;
6760 lockdep_assert_held(&wq_pool_attach_mutex
);
6763 * Restore CPU affinity of all workers. As all idle workers should
6764 * be on the run-queue of the associated CPU before any local
6765 * wake-ups for concurrency management happen, restore CPU affinity
6766 * of all workers first and then clear UNBOUND. As we're called
6767 * from CPU_ONLINE, the following shouldn't fail.
6769 for_each_pool_worker(worker
, pool
) {
6770 kthread_set_per_cpu(worker
->task
, pool
->cpu
);
6771 WARN_ON_ONCE(set_cpus_allowed_ptr(worker
->task
,
6772 pool_allowed_cpus(pool
)) < 0);
6775 raw_spin_lock_irq(&pool
->lock
);
6777 pool
->flags
&= ~POOL_DISASSOCIATED
;
6779 for_each_pool_worker(worker
, pool
) {
6780 unsigned int worker_flags
= worker
->flags
;
6783 * We want to clear UNBOUND but can't directly call
6784 * worker_clr_flags() or adjust nr_running. Atomically
6785 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
6786 * @worker will clear REBOUND using worker_clr_flags() when
6787 * it initiates the next execution cycle thus restoring
6788 * concurrency management. Note that when or whether
6789 * @worker clears REBOUND doesn't affect correctness.
6791 * WRITE_ONCE() is necessary because @worker->flags may be
6792 * tested without holding any lock in
6793 * wq_worker_running(). Without it, NOT_RUNNING test may
6794 * fail incorrectly leading to premature concurrency
6795 * management operations.
6797 WARN_ON_ONCE(!(worker_flags
& WORKER_UNBOUND
));
6798 worker_flags
|= WORKER_REBOUND
;
6799 worker_flags
&= ~WORKER_UNBOUND
;
6800 WRITE_ONCE(worker
->flags
, worker_flags
);
6803 raw_spin_unlock_irq(&pool
->lock
);
6807 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
6808 * @pool: unbound pool of interest
6809 * @cpu: the CPU which is coming up
6811 * An unbound pool may end up with a cpumask which doesn't have any online
6812 * CPUs. When a worker of such pool get scheduled, the scheduler resets
6813 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
6814 * online CPU before, cpus_allowed of all its workers should be restored.
6816 static void restore_unbound_workers_cpumask(struct worker_pool
*pool
, int cpu
)
6818 static cpumask_t cpumask
;
6819 struct worker
*worker
;
6821 lockdep_assert_held(&wq_pool_attach_mutex
);
6823 /* is @cpu allowed for @pool? */
6824 if (!cpumask_test_cpu(cpu
, pool
->attrs
->cpumask
))
6827 cpumask_and(&cpumask
, pool
->attrs
->cpumask
, cpu_online_mask
);
6829 /* as we're called from CPU_ONLINE, the following shouldn't fail */
6830 for_each_pool_worker(worker
, pool
)
6831 WARN_ON_ONCE(set_cpus_allowed_ptr(worker
->task
, &cpumask
) < 0);
6834 int workqueue_prepare_cpu(unsigned int cpu
)
6836 struct worker_pool
*pool
;
6838 for_each_cpu_worker_pool(pool
, cpu
) {
6839 if (pool
->nr_workers
)
6841 if (!create_worker(pool
))
6847 int workqueue_online_cpu(unsigned int cpu
)
6849 struct worker_pool
*pool
;
6850 struct workqueue_struct
*wq
;
6853 mutex_lock(&wq_pool_mutex
);
6855 cpumask_set_cpu(cpu
, wq_online_cpumask
);
6857 for_each_pool(pool
, pi
) {
6858 /* BH pools aren't affected by hotplug */
6859 if (pool
->flags
& POOL_BH
)
6862 mutex_lock(&wq_pool_attach_mutex
);
6863 if (pool
->cpu
== cpu
)
6864 rebind_workers(pool
);
6865 else if (pool
->cpu
< 0)
6866 restore_unbound_workers_cpumask(pool
, cpu
);
6867 mutex_unlock(&wq_pool_attach_mutex
);
6870 /* update pod affinity of unbound workqueues */
6871 list_for_each_entry(wq
, &workqueues
, list
) {
6872 struct workqueue_attrs
*attrs
= wq
->unbound_attrs
;
6875 const struct wq_pod_type
*pt
= wqattrs_pod_type(attrs
);
6878 for_each_cpu(tcpu
, pt
->pod_cpus
[pt
->cpu_pod
[cpu
]])
6879 unbound_wq_update_pwq(wq
, tcpu
);
6881 mutex_lock(&wq
->mutex
);
6882 wq_update_node_max_active(wq
, -1);
6883 mutex_unlock(&wq
->mutex
);
6887 mutex_unlock(&wq_pool_mutex
);
6891 int workqueue_offline_cpu(unsigned int cpu
)
6893 struct workqueue_struct
*wq
;
6895 /* unbinding per-cpu workers should happen on the local CPU */
6896 if (WARN_ON(cpu
!= smp_processor_id()))
6899 unbind_workers(cpu
);
6901 /* update pod affinity of unbound workqueues */
6902 mutex_lock(&wq_pool_mutex
);
6904 cpumask_clear_cpu(cpu
, wq_online_cpumask
);
6906 list_for_each_entry(wq
, &workqueues
, list
) {
6907 struct workqueue_attrs
*attrs
= wq
->unbound_attrs
;
6910 const struct wq_pod_type
*pt
= wqattrs_pod_type(attrs
);
6913 for_each_cpu(tcpu
, pt
->pod_cpus
[pt
->cpu_pod
[cpu
]])
6914 unbound_wq_update_pwq(wq
, tcpu
);
6916 mutex_lock(&wq
->mutex
);
6917 wq_update_node_max_active(wq
, cpu
);
6918 mutex_unlock(&wq
->mutex
);
6921 mutex_unlock(&wq_pool_mutex
);
6926 struct work_for_cpu
{
6927 struct work_struct work
;
6933 static void work_for_cpu_fn(struct work_struct
*work
)
6935 struct work_for_cpu
*wfc
= container_of(work
, struct work_for_cpu
, work
);
6937 wfc
->ret
= wfc
->fn(wfc
->arg
);
6941 * work_on_cpu_key - run a function in thread context on a particular cpu
6942 * @cpu: the cpu to run on
6943 * @fn: the function to run
6944 * @arg: the function arg
6945 * @key: The lock class key for lock debugging purposes
6947 * It is up to the caller to ensure that the cpu doesn't go offline.
6948 * The caller must not hold any locks which would prevent @fn from completing.
6950 * Return: The value @fn returns.
6952 long work_on_cpu_key(int cpu
, long (*fn
)(void *),
6953 void *arg
, struct lock_class_key
*key
)
6955 struct work_for_cpu wfc
= { .fn
= fn
, .arg
= arg
};
6957 INIT_WORK_ONSTACK_KEY(&wfc
.work
, work_for_cpu_fn
, key
);
6958 schedule_work_on(cpu
, &wfc
.work
);
6959 flush_work(&wfc
.work
);
6960 destroy_work_on_stack(&wfc
.work
);
6963 EXPORT_SYMBOL_GPL(work_on_cpu_key
);
6964 #endif /* CONFIG_SMP */
6966 #ifdef CONFIG_FREEZER
6969 * freeze_workqueues_begin - begin freezing workqueues
6971 * Start freezing workqueues. After this function returns, all freezable
6972 * workqueues will queue new works to their inactive_works list instead of
6976 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
6978 void freeze_workqueues_begin(void)
6980 struct workqueue_struct
*wq
;
6982 mutex_lock(&wq_pool_mutex
);
6984 WARN_ON_ONCE(workqueue_freezing
);
6985 workqueue_freezing
= true;
6987 list_for_each_entry(wq
, &workqueues
, list
) {
6988 mutex_lock(&wq
->mutex
);
6989 wq_adjust_max_active(wq
);
6990 mutex_unlock(&wq
->mutex
);
6993 mutex_unlock(&wq_pool_mutex
);
6997 * freeze_workqueues_busy - are freezable workqueues still busy?
6999 * Check whether freezing is complete. This function must be called
7000 * between freeze_workqueues_begin() and thaw_workqueues().
7003 * Grabs and releases wq_pool_mutex.
7006 * %true if some freezable workqueues are still busy. %false if freezing
7009 bool freeze_workqueues_busy(void)
7012 struct workqueue_struct
*wq
;
7013 struct pool_workqueue
*pwq
;
7015 mutex_lock(&wq_pool_mutex
);
7017 WARN_ON_ONCE(!workqueue_freezing
);
7019 list_for_each_entry(wq
, &workqueues
, list
) {
7020 if (!(wq
->flags
& WQ_FREEZABLE
))
7023 * nr_active is monotonically decreasing. It's safe
7024 * to peek without lock.
7027 for_each_pwq(pwq
, wq
) {
7028 WARN_ON_ONCE(pwq
->nr_active
< 0);
7029 if (pwq
->nr_active
) {
7038 mutex_unlock(&wq_pool_mutex
);
7043 * thaw_workqueues - thaw workqueues
7045 * Thaw workqueues. Normal queueing is restored and all collected
7046 * frozen works are transferred to their respective pool worklists.
7049 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
7051 void thaw_workqueues(void)
7053 struct workqueue_struct
*wq
;
7055 mutex_lock(&wq_pool_mutex
);
7057 if (!workqueue_freezing
)
7060 workqueue_freezing
= false;
7062 /* restore max_active and repopulate worklist */
7063 list_for_each_entry(wq
, &workqueues
, list
) {
7064 mutex_lock(&wq
->mutex
);
7065 wq_adjust_max_active(wq
);
7066 mutex_unlock(&wq
->mutex
);
7070 mutex_unlock(&wq_pool_mutex
);
7072 #endif /* CONFIG_FREEZER */
7074 static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask
)
7078 struct workqueue_struct
*wq
;
7079 struct apply_wqattrs_ctx
*ctx
, *n
;
7081 lockdep_assert_held(&wq_pool_mutex
);
7083 list_for_each_entry(wq
, &workqueues
, list
) {
7084 if (!(wq
->flags
& WQ_UNBOUND
) || (wq
->flags
& __WQ_DESTROYING
))
7087 ctx
= apply_wqattrs_prepare(wq
, wq
->unbound_attrs
, unbound_cpumask
);
7093 list_add_tail(&ctx
->list
, &ctxs
);
7096 list_for_each_entry_safe(ctx
, n
, &ctxs
, list
) {
7098 apply_wqattrs_commit(ctx
);
7099 apply_wqattrs_cleanup(ctx
);
7104 struct worker_pool
*pool
;
7105 struct worker
*worker
;
7107 mutex_lock(&wq_pool_attach_mutex
);
7108 cpumask_copy(wq_unbound_cpumask
, unbound_cpumask
);
7109 /* rescuer needs to respect cpumask changes when it is not attached */
7110 list_for_each_entry(wq
, &workqueues
, list
) {
7111 if (wq
->rescuer
&& !wq
->rescuer
->pool
)
7112 unbind_worker(wq
->rescuer
);
7114 /* DISASSOCIATED worker needs to respect wq_unbound_cpumask */
7115 for_each_possible_cpu(cpu
) {
7116 for_each_cpu_worker_pool(pool
, cpu
) {
7117 if (!(pool
->flags
& POOL_DISASSOCIATED
))
7119 for_each_pool_worker(worker
, pool
)
7120 unbind_worker(worker
);
7123 mutex_unlock(&wq_pool_attach_mutex
);
7129 * workqueue_unbound_housekeeping_update - Propagate housekeeping cpumask update
7130 * @hk: the new housekeeping cpumask
7132 * Update the unbound workqueue cpumask on top of the new housekeeping cpumask such
7133 * that the effective unbound affinity is the intersection of the new housekeeping
7134 * with the requested affinity set via nohz_full=/isolcpus= or sysfs.
7136 * Return: 0 on success and -errno on failure.
7138 int workqueue_unbound_housekeeping_update(const struct cpumask
*hk
)
7140 cpumask_var_t cpumask
;
7143 if (!zalloc_cpumask_var(&cpumask
, GFP_KERNEL
))
7146 mutex_lock(&wq_pool_mutex
);
7149 * If the operation fails, it will fall back to
7150 * wq_requested_unbound_cpumask which is initially set to
7151 * HK_TYPE_DOMAIN house keeping mask and rewritten
7152 * by any subsequent write to workqueue/cpumask sysfs file.
7154 if (!cpumask_and(cpumask
, wq_requested_unbound_cpumask
, hk
))
7155 cpumask_copy(cpumask
, wq_requested_unbound_cpumask
);
7156 if (!cpumask_equal(cpumask
, wq_unbound_cpumask
))
7157 ret
= workqueue_apply_unbound_cpumask(cpumask
);
7159 /* Save the current isolated cpumask & export it via sysfs */
7161 cpumask_andnot(wq_isolated_cpumask
, cpu_possible_mask
, hk
);
7163 mutex_unlock(&wq_pool_mutex
);
7164 free_cpumask_var(cpumask
);
7168 static int parse_affn_scope(const char *val
)
7170 return sysfs_match_string(wq_affn_names
, val
);
7173 static int wq_affn_dfl_set(const char *val
, const struct kernel_param
*kp
)
7175 struct workqueue_struct
*wq
;
7178 affn
= parse_affn_scope(val
);
7181 if (affn
== WQ_AFFN_DFL
)
7185 mutex_lock(&wq_pool_mutex
);
7189 list_for_each_entry(wq
, &workqueues
, list
) {
7190 for_each_online_cpu(cpu
)
7191 unbound_wq_update_pwq(wq
, cpu
);
7194 mutex_unlock(&wq_pool_mutex
);
7200 static int wq_affn_dfl_get(char *buffer
, const struct kernel_param
*kp
)
7202 return scnprintf(buffer
, PAGE_SIZE
, "%s\n", wq_affn_names
[wq_affn_dfl
]);
7205 static const struct kernel_param_ops wq_affn_dfl_ops
= {
7206 .set
= wq_affn_dfl_set
,
7207 .get
= wq_affn_dfl_get
,
7210 module_param_cb(default_affinity_scope
, &wq_affn_dfl_ops
, NULL
, 0644);
7214 * Workqueues with WQ_SYSFS flag set is visible to userland via
7215 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
7216 * following attributes.
7218 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
7219 * max_active RW int : maximum number of in-flight work items
7221 * Unbound workqueues have the following extra attributes.
7223 * nice RW int : nice value of the workers
7224 * cpumask RW mask : bitmask of allowed CPUs for the workers
7225 * affinity_scope RW str : worker CPU affinity scope (cache, numa, none)
7226 * affinity_strict RW bool : worker CPU affinity is strict
7229 struct workqueue_struct
*wq
;
7233 static struct workqueue_struct
*dev_to_wq(struct device
*dev
)
7235 struct wq_device
*wq_dev
= container_of(dev
, struct wq_device
, dev
);
7240 static ssize_t
per_cpu_show(struct device
*dev
, struct device_attribute
*attr
,
7243 struct workqueue_struct
*wq
= dev_to_wq(dev
);
7245 return scnprintf(buf
, PAGE_SIZE
, "%d\n", (bool)!(wq
->flags
& WQ_UNBOUND
));
7247 static DEVICE_ATTR_RO(per_cpu
);
7249 static ssize_t
max_active_show(struct device
*dev
,
7250 struct device_attribute
*attr
, char *buf
)
7252 struct workqueue_struct
*wq
= dev_to_wq(dev
);
7254 return scnprintf(buf
, PAGE_SIZE
, "%d\n", wq
->saved_max_active
);
7257 static ssize_t
max_active_store(struct device
*dev
,
7258 struct device_attribute
*attr
, const char *buf
,
7261 struct workqueue_struct
*wq
= dev_to_wq(dev
);
7264 if (sscanf(buf
, "%d", &val
) != 1 || val
<= 0)
7267 workqueue_set_max_active(wq
, val
);
7270 static DEVICE_ATTR_RW(max_active
);
7272 static struct attribute
*wq_sysfs_attrs
[] = {
7273 &dev_attr_per_cpu
.attr
,
7274 &dev_attr_max_active
.attr
,
7278 static umode_t
wq_sysfs_is_visible(struct kobject
*kobj
, struct attribute
*a
, int n
)
7280 struct device
*dev
= kobj_to_dev(kobj
);
7281 struct workqueue_struct
*wq
= dev_to_wq(dev
);
7284 * Adjusting max_active breaks ordering guarantee. Changing it has no
7285 * effect on BH worker. Limit max_active to RO in such case.
7287 if (wq
->flags
& (WQ_BH
| __WQ_ORDERED
))
7292 static const struct attribute_group wq_sysfs_group
= {
7293 .is_visible
= wq_sysfs_is_visible
,
7294 .attrs
= wq_sysfs_attrs
,
7296 __ATTRIBUTE_GROUPS(wq_sysfs
);
7298 static ssize_t
wq_nice_show(struct device
*dev
, struct device_attribute
*attr
,
7301 struct workqueue_struct
*wq
= dev_to_wq(dev
);
7304 mutex_lock(&wq
->mutex
);
7305 written
= scnprintf(buf
, PAGE_SIZE
, "%d\n", wq
->unbound_attrs
->nice
);
7306 mutex_unlock(&wq
->mutex
);
7311 /* prepare workqueue_attrs for sysfs store operations */
7312 static struct workqueue_attrs
*wq_sysfs_prep_attrs(struct workqueue_struct
*wq
)
7314 struct workqueue_attrs
*attrs
;
7316 lockdep_assert_held(&wq_pool_mutex
);
7318 attrs
= alloc_workqueue_attrs();
7322 copy_workqueue_attrs(attrs
, wq
->unbound_attrs
);
7326 static ssize_t
wq_nice_store(struct device
*dev
, struct device_attribute
*attr
,
7327 const char *buf
, size_t count
)
7329 struct workqueue_struct
*wq
= dev_to_wq(dev
);
7330 struct workqueue_attrs
*attrs
;
7333 mutex_lock(&wq_pool_mutex
);
7335 attrs
= wq_sysfs_prep_attrs(wq
);
7339 if (sscanf(buf
, "%d", &attrs
->nice
) == 1 &&
7340 attrs
->nice
>= MIN_NICE
&& attrs
->nice
<= MAX_NICE
)
7341 ret
= apply_workqueue_attrs_locked(wq
, attrs
);
7346 mutex_unlock(&wq_pool_mutex
);
7347 free_workqueue_attrs(attrs
);
7348 return ret
?: count
;
7351 static ssize_t
wq_cpumask_show(struct device
*dev
,
7352 struct device_attribute
*attr
, char *buf
)
7354 struct workqueue_struct
*wq
= dev_to_wq(dev
);
7357 mutex_lock(&wq
->mutex
);
7358 written
= scnprintf(buf
, PAGE_SIZE
, "%*pb\n",
7359 cpumask_pr_args(wq
->unbound_attrs
->cpumask
));
7360 mutex_unlock(&wq
->mutex
);
7364 static ssize_t
wq_cpumask_store(struct device
*dev
,
7365 struct device_attribute
*attr
,
7366 const char *buf
, size_t count
)
7368 struct workqueue_struct
*wq
= dev_to_wq(dev
);
7369 struct workqueue_attrs
*attrs
;
7372 mutex_lock(&wq_pool_mutex
);
7374 attrs
= wq_sysfs_prep_attrs(wq
);
7378 ret
= cpumask_parse(buf
, attrs
->cpumask
);
7380 ret
= apply_workqueue_attrs_locked(wq
, attrs
);
7383 mutex_unlock(&wq_pool_mutex
);
7384 free_workqueue_attrs(attrs
);
7385 return ret
?: count
;
7388 static ssize_t
wq_affn_scope_show(struct device
*dev
,
7389 struct device_attribute
*attr
, char *buf
)
7391 struct workqueue_struct
*wq
= dev_to_wq(dev
);
7394 mutex_lock(&wq
->mutex
);
7395 if (wq
->unbound_attrs
->affn_scope
== WQ_AFFN_DFL
)
7396 written
= scnprintf(buf
, PAGE_SIZE
, "%s (%s)\n",
7397 wq_affn_names
[WQ_AFFN_DFL
],
7398 wq_affn_names
[wq_affn_dfl
]);
7400 written
= scnprintf(buf
, PAGE_SIZE
, "%s\n",
7401 wq_affn_names
[wq
->unbound_attrs
->affn_scope
]);
7402 mutex_unlock(&wq
->mutex
);
7407 static ssize_t
wq_affn_scope_store(struct device
*dev
,
7408 struct device_attribute
*attr
,
7409 const char *buf
, size_t count
)
7411 struct workqueue_struct
*wq
= dev_to_wq(dev
);
7412 struct workqueue_attrs
*attrs
;
7413 int affn
, ret
= -ENOMEM
;
7415 affn
= parse_affn_scope(buf
);
7419 mutex_lock(&wq_pool_mutex
);
7420 attrs
= wq_sysfs_prep_attrs(wq
);
7422 attrs
->affn_scope
= affn
;
7423 ret
= apply_workqueue_attrs_locked(wq
, attrs
);
7425 mutex_unlock(&wq_pool_mutex
);
7426 free_workqueue_attrs(attrs
);
7427 return ret
?: count
;
7430 static ssize_t
wq_affinity_strict_show(struct device
*dev
,
7431 struct device_attribute
*attr
, char *buf
)
7433 struct workqueue_struct
*wq
= dev_to_wq(dev
);
7435 return scnprintf(buf
, PAGE_SIZE
, "%d\n",
7436 wq
->unbound_attrs
->affn_strict
);
7439 static ssize_t
wq_affinity_strict_store(struct device
*dev
,
7440 struct device_attribute
*attr
,
7441 const char *buf
, size_t count
)
7443 struct workqueue_struct
*wq
= dev_to_wq(dev
);
7444 struct workqueue_attrs
*attrs
;
7445 int v
, ret
= -ENOMEM
;
7447 if (sscanf(buf
, "%d", &v
) != 1)
7450 mutex_lock(&wq_pool_mutex
);
7451 attrs
= wq_sysfs_prep_attrs(wq
);
7453 attrs
->affn_strict
= (bool)v
;
7454 ret
= apply_workqueue_attrs_locked(wq
, attrs
);
7456 mutex_unlock(&wq_pool_mutex
);
7457 free_workqueue_attrs(attrs
);
7458 return ret
?: count
;
7461 static struct device_attribute wq_sysfs_unbound_attrs
[] = {
7462 __ATTR(nice
, 0644, wq_nice_show
, wq_nice_store
),
7463 __ATTR(cpumask
, 0644, wq_cpumask_show
, wq_cpumask_store
),
7464 __ATTR(affinity_scope
, 0644, wq_affn_scope_show
, wq_affn_scope_store
),
7465 __ATTR(affinity_strict
, 0644, wq_affinity_strict_show
, wq_affinity_strict_store
),
7469 static const struct bus_type wq_subsys
= {
7470 .name
= "workqueue",
7471 .dev_groups
= wq_sysfs_groups
,
7475 * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
7476 * @cpumask: the cpumask to set
7478 * The low-level workqueues cpumask is a global cpumask that limits
7479 * the affinity of all unbound workqueues. This function check the @cpumask
7480 * and apply it to all unbound workqueues and updates all pwqs of them.
7482 * Return: 0 - Success
7483 * -EINVAL - Invalid @cpumask
7484 * -ENOMEM - Failed to allocate memory for attrs or pwqs.
7486 static int workqueue_set_unbound_cpumask(cpumask_var_t cpumask
)
7491 * Not excluding isolated cpus on purpose.
7492 * If the user wishes to include them, we allow that.
7494 cpumask_and(cpumask
, cpumask
, cpu_possible_mask
);
7495 if (!cpumask_empty(cpumask
)) {
7497 mutex_lock(&wq_pool_mutex
);
7498 if (!cpumask_equal(cpumask
, wq_unbound_cpumask
))
7499 ret
= workqueue_apply_unbound_cpumask(cpumask
);
7501 cpumask_copy(wq_requested_unbound_cpumask
, cpumask
);
7502 mutex_unlock(&wq_pool_mutex
);
7508 static ssize_t
__wq_cpumask_show(struct device
*dev
,
7509 struct device_attribute
*attr
, char *buf
, cpumask_var_t mask
)
7513 mutex_lock(&wq_pool_mutex
);
7514 written
= scnprintf(buf
, PAGE_SIZE
, "%*pb\n", cpumask_pr_args(mask
));
7515 mutex_unlock(&wq_pool_mutex
);
7520 static ssize_t
cpumask_requested_show(struct device
*dev
,
7521 struct device_attribute
*attr
, char *buf
)
7523 return __wq_cpumask_show(dev
, attr
, buf
, wq_requested_unbound_cpumask
);
7525 static DEVICE_ATTR_RO(cpumask_requested
);
7527 static ssize_t
cpumask_isolated_show(struct device
*dev
,
7528 struct device_attribute
*attr
, char *buf
)
7530 return __wq_cpumask_show(dev
, attr
, buf
, wq_isolated_cpumask
);
7532 static DEVICE_ATTR_RO(cpumask_isolated
);
7534 static ssize_t
cpumask_show(struct device
*dev
,
7535 struct device_attribute
*attr
, char *buf
)
7537 return __wq_cpumask_show(dev
, attr
, buf
, wq_unbound_cpumask
);
7540 static ssize_t
cpumask_store(struct device
*dev
,
7541 struct device_attribute
*attr
, const char *buf
, size_t count
)
7543 cpumask_var_t cpumask
;
7546 if (!zalloc_cpumask_var(&cpumask
, GFP_KERNEL
))
7549 ret
= cpumask_parse(buf
, cpumask
);
7551 ret
= workqueue_set_unbound_cpumask(cpumask
);
7553 free_cpumask_var(cpumask
);
7554 return ret
? ret
: count
;
7556 static DEVICE_ATTR_RW(cpumask
);
7558 static struct attribute
*wq_sysfs_cpumask_attrs
[] = {
7559 &dev_attr_cpumask
.attr
,
7560 &dev_attr_cpumask_requested
.attr
,
7561 &dev_attr_cpumask_isolated
.attr
,
7564 ATTRIBUTE_GROUPS(wq_sysfs_cpumask
);
7566 static int __init
wq_sysfs_init(void)
7568 return subsys_virtual_register(&wq_subsys
, wq_sysfs_cpumask_groups
);
7570 core_initcall(wq_sysfs_init
);
7572 static void wq_device_release(struct device
*dev
)
7574 struct wq_device
*wq_dev
= container_of(dev
, struct wq_device
, dev
);
7580 * workqueue_sysfs_register - make a workqueue visible in sysfs
7581 * @wq: the workqueue to register
7583 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
7584 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
7585 * which is the preferred method.
7587 * Workqueue user should use this function directly iff it wants to apply
7588 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
7589 * apply_workqueue_attrs() may race against userland updating the
7592 * Return: 0 on success, -errno on failure.
7594 int workqueue_sysfs_register(struct workqueue_struct
*wq
)
7596 struct wq_device
*wq_dev
;
7599 wq
->wq_dev
= wq_dev
= kzalloc_obj(*wq_dev
);
7604 wq_dev
->dev
.bus
= &wq_subsys
;
7605 wq_dev
->dev
.release
= wq_device_release
;
7606 dev_set_name(&wq_dev
->dev
, "%s", wq
->name
);
7609 * unbound_attrs are created separately. Suppress uevent until
7610 * everything is ready.
7612 dev_set_uevent_suppress(&wq_dev
->dev
, true);
7614 ret
= device_register(&wq_dev
->dev
);
7616 put_device(&wq_dev
->dev
);
7621 if (wq
->flags
& WQ_UNBOUND
) {
7622 struct device_attribute
*attr
;
7624 for (attr
= wq_sysfs_unbound_attrs
; attr
->attr
.name
; attr
++) {
7625 ret
= device_create_file(&wq_dev
->dev
, attr
);
7627 device_unregister(&wq_dev
->dev
);
7634 dev_set_uevent_suppress(&wq_dev
->dev
, false);
7635 kobject_uevent(&wq_dev
->dev
.kobj
, KOBJ_ADD
);
7640 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
7641 * @wq: the workqueue to unregister
7643 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
7645 static void workqueue_sysfs_unregister(struct workqueue_struct
*wq
)
7647 struct wq_device
*wq_dev
= wq
->wq_dev
;
7653 device_unregister(&wq_dev
->dev
);
7655 #else /* CONFIG_SYSFS */
7656 static void workqueue_sysfs_unregister(struct workqueue_struct
*wq
) { }
7657 #endif /* CONFIG_SYSFS */
7660 * Workqueue watchdog.
7662 * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
7663 * flush dependency, a concurrency managed work item which stays RUNNING
7664 * indefinitely. Workqueue stalls can be very difficult to debug as the
7665 * usual warning mechanisms don't trigger and internal workqueue state is
7668 * Workqueue watchdog monitors all worker pools periodically and dumps
7669 * state if some pools failed to make forward progress for a while where
7670 * forward progress is defined as the first item on ->worklist changing.
7672 * This mechanism is controlled through the kernel parameter
7673 * "workqueue.watchdog_thresh" which can be updated at runtime through the
7674 * corresponding sysfs parameter file.
7676 #ifdef CONFIG_WQ_WATCHDOG
7678 static unsigned long wq_watchdog_thresh
= 30;
7679 static struct timer_list wq_watchdog_timer
;
7681 static unsigned long wq_watchdog_touched
= INITIAL_JIFFIES
;
7682 static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu
) = INITIAL_JIFFIES
;
7684 static unsigned int wq_panic_on_stall
= CONFIG_BOOTPARAM_WQ_STALL_PANIC
;
7685 module_param_named(panic_on_stall
, wq_panic_on_stall
, uint
, 0644);
7687 static unsigned int wq_panic_on_stall_time
;
7688 module_param_named(panic_on_stall_time
, wq_panic_on_stall_time
, uint
, 0644);
7689 MODULE_PARM_DESC(panic_on_stall_time
, "Panic if stall exceeds this many seconds (0=disabled)");
7692 * Show workers that might prevent the processing of pending work items.
7693 * A busy worker that is not running on the CPU (e.g. sleeping in
7694 * wait_event_idle() with PF_WQ_WORKER cleared) can stall the pool just as
7695 * effectively as a CPU-bound one, so dump every in-flight worker.
7697 static void show_cpu_pool_busy_workers(struct worker_pool
*pool
)
7699 struct worker
*worker
;
7700 unsigned long irq_flags
;
7703 raw_spin_lock_irqsave(&pool
->lock
, irq_flags
);
7705 hash_for_each(pool
->busy_hash
, bkt
, worker
, hentry
) {
7707 * Defer printing to avoid deadlocks in console
7708 * drivers that queue work while holding locks
7709 * also taken in their write paths.
7711 printk_deferred_enter();
7713 pr_info("pool %d:\n", pool
->id
);
7714 sched_show_task(worker
->task
);
7716 printk_deferred_exit();
7719 raw_spin_unlock_irqrestore(&pool
->lock
, irq_flags
);
7722 static void show_cpu_pools_busy_workers(void)
7724 struct worker_pool
*pool
;
7727 pr_info("Showing backtraces of busy workers in stalled worker pools:\n");
7731 for_each_pool(pool
, pi
) {
7732 if (pool
->cpu_stall
)
7733 show_cpu_pool_busy_workers(pool
);
7741 * It triggers a panic in two scenarios: when the total number of stalls
7742 * exceeds a threshold, and when a stall lasts longer than
7743 * wq_panic_on_stall_time
7745 static void panic_on_wq_watchdog(unsigned int stall_time_sec
)
7747 static unsigned int wq_stall
;
7749 if (wq_panic_on_stall
) {
7751 if (wq_stall
>= wq_panic_on_stall
)
7752 panic("workqueue: %u stall(s) exceeded threshold %u\n",
7753 wq_stall
, wq_panic_on_stall
);
7756 if (wq_panic_on_stall_time
&& stall_time_sec
>= wq_panic_on_stall_time
)
7757 panic("workqueue: stall lasted %us, exceeding threshold %us\n",
7758 stall_time_sec
, wq_panic_on_stall_time
);
7761 static void wq_watchdog_reset_touched(void)
7765 wq_watchdog_touched
= jiffies
;
7766 for_each_possible_cpu(cpu
)
7767 per_cpu(wq_watchdog_touched_cpu
, cpu
) = jiffies
;
7770 static void wq_watchdog_timer_fn(struct timer_list
*unused
)
7772 unsigned long thresh
= READ_ONCE(wq_watchdog_thresh
) * HZ
;
7773 unsigned int max_stall_time
= 0;
7774 bool lockup_detected
= false;
7775 bool cpu_pool_stall
= false;
7776 unsigned long now
= jiffies
;
7777 struct worker_pool
*pool
;
7778 unsigned int stall_time
;
7784 for_each_pool(pool
, pi
) {
7785 unsigned long pool_ts
, touched
, ts
;
7787 pool
->cpu_stall
= false;
7788 if (list_empty(&pool
->worklist
))
7792 * If a virtual machine is stopped by the host it can look to
7793 * the watchdog like a stall.
7795 kvm_check_and_clear_guest_paused();
7797 /* get the latest of pool and touched timestamps */
7799 touched
= READ_ONCE(per_cpu(wq_watchdog_touched_cpu
, pool
->cpu
));
7801 touched
= READ_ONCE(wq_watchdog_touched
);
7802 pool_ts
= READ_ONCE(pool
->last_progress_ts
);
7804 if (time_after(pool_ts
, touched
))
7812 * Do a lockless check first to do not disturb the system.
7814 * Prevent false positives by double checking the timestamp
7815 * under pool->lock. The lock makes sure that the check reads
7816 * an updated pool->last_progress_ts when this CPU saw
7817 * an already updated pool->worklist above. It seems better
7818 * than adding another barrier into __queue_work() which
7821 if (time_after(now
, ts
+ thresh
)) {
7822 scoped_guard(raw_spinlock_irqsave
, &pool
->lock
) {
7823 pool_ts
= pool
->last_progress_ts
;
7824 if (time_after(pool_ts
, touched
))
7829 if (!time_after(now
, ts
+ thresh
))
7832 lockup_detected
= true;
7833 stall_time
= jiffies_to_msecs(now
- pool_ts
) / 1000;
7834 max_stall_time
= max(max_stall_time
, stall_time
);
7835 if (pool
->cpu
>= 0 && !(pool
->flags
& POOL_BH
)) {
7836 pool
->cpu_stall
= true;
7837 cpu_pool_stall
= true;
7839 pr_emerg("BUG: workqueue lockup - pool");
7840 pr_cont_pool_info(pool
);
7841 pr_cont(" stuck for %us!\n", stall_time
);
7845 if (lockup_detected
)
7846 show_all_workqueues();
7849 show_cpu_pools_busy_workers();
7851 if (lockup_detected
)
7852 panic_on_wq_watchdog(max_stall_time
);
7854 wq_watchdog_reset_touched();
7855 mod_timer(&wq_watchdog_timer
, jiffies
+ thresh
);
7858 notrace
void wq_watchdog_touch(int cpu
)
7860 unsigned long thresh
= READ_ONCE(wq_watchdog_thresh
) * HZ
;
7861 unsigned long touch_ts
= READ_ONCE(wq_watchdog_touched
);
7862 unsigned long now
= jiffies
;
7865 per_cpu(wq_watchdog_touched_cpu
, cpu
) = now
;
7867 WARN_ONCE(1, "%s should be called with valid CPU", __func__
);
7869 /* Don't unnecessarily store to global cacheline */
7870 if (time_after(now
, touch_ts
+ thresh
/ 4))
7871 WRITE_ONCE(wq_watchdog_touched
, jiffies
);
7874 static void wq_watchdog_set_thresh(unsigned long thresh
)
7876 wq_watchdog_thresh
= 0;
7877 timer_delete_sync(&wq_watchdog_timer
);
7880 wq_watchdog_thresh
= thresh
;
7881 wq_watchdog_reset_touched();
7882 mod_timer(&wq_watchdog_timer
, jiffies
+ thresh
* HZ
);
7886 static int wq_watchdog_param_set_thresh(const char *val
,
7887 const struct kernel_param
*kp
)
7889 unsigned long thresh
;
7892 ret
= kstrtoul(val
, 0, &thresh
);
7896 if (system_percpu_wq
)
7897 wq_watchdog_set_thresh(thresh
);
7899 wq_watchdog_thresh
= thresh
;
7904 static const struct kernel_param_ops wq_watchdog_thresh_ops
= {
7905 .set
= wq_watchdog_param_set_thresh
,
7906 .get
= param_get_ulong
,
7909 module_param_cb(watchdog_thresh
, &wq_watchdog_thresh_ops
, &wq_watchdog_thresh
,
7912 static void wq_watchdog_init(void)
7914 timer_setup(&wq_watchdog_timer
, wq_watchdog_timer_fn
, TIMER_DEFERRABLE
);
7915 wq_watchdog_set_thresh(wq_watchdog_thresh
);
7918 #else /* CONFIG_WQ_WATCHDOG */
7920 static inline void wq_watchdog_init(void) { }
7922 #endif /* CONFIG_WQ_WATCHDOG */
7924 static void bh_pool_kick_normal(struct irq_work
*irq_work
)
7926 raise_softirq_irqoff(TASKLET_SOFTIRQ
);
7929 static void bh_pool_kick_highpri(struct irq_work
*irq_work
)
7931 raise_softirq_irqoff(HI_SOFTIRQ
);
7934 static void __init
restrict_unbound_cpumask(const char *name
, const struct cpumask
*mask
)
7936 if (!cpumask_intersects(wq_unbound_cpumask
, mask
)) {
7937 pr_warn("workqueue: Restricting unbound_cpumask (%*pb) with %s (%*pb) leaves no CPU, ignoring\n",
7938 cpumask_pr_args(wq_unbound_cpumask
), name
, cpumask_pr_args(mask
));
7942 cpumask_and(wq_unbound_cpumask
, wq_unbound_cpumask
, mask
);
7945 static void __init
init_cpu_worker_pool(struct worker_pool
*pool
, int cpu
, int nice
)
7947 BUG_ON(init_worker_pool(pool
));
7949 cpumask_copy(pool
->attrs
->cpumask
, cpumask_of(cpu
));
7950 cpumask_copy(pool
->attrs
->__pod_cpumask
, cpumask_of(cpu
));
7951 pool
->attrs
->nice
= nice
;
7952 pool
->attrs
->affn_strict
= true;
7953 pool
->node
= cpu_to_node(cpu
);
7956 mutex_lock(&wq_pool_mutex
);
7957 BUG_ON(worker_pool_assign_id(pool
));
7958 mutex_unlock(&wq_pool_mutex
);
7962 * workqueue_init_early - early init for workqueue subsystem
7964 * This is the first step of three-staged workqueue subsystem initialization and
7965 * invoked as soon as the bare basics - memory allocation, cpumasks and idr are
7966 * up. It sets up all the data structures and system workqueues and allows early
7967 * boot code to create workqueues and queue/cancel work items. Actual work item
7968 * execution starts only after kthreads can be created and scheduled right
7969 * before early initcalls.
7971 void __init
workqueue_init_early(void)
7973 struct wq_pod_type
*pt
= &wq_pod_types
[WQ_AFFN_SYSTEM
];
7974 int std_nice
[NR_STD_WORKER_POOLS
] = { 0, HIGHPRI_NICE_LEVEL
};
7975 void (*irq_work_fns
[NR_STD_WORKER_POOLS
])(struct irq_work
*) =
7976 { bh_pool_kick_normal
, bh_pool_kick_highpri
};
7979 BUILD_BUG_ON(__alignof__(struct pool_workqueue
) < __alignof__(long long));
7981 BUG_ON(!alloc_cpumask_var(&wq_online_cpumask
, GFP_KERNEL
));
7982 BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask
, GFP_KERNEL
));
7983 BUG_ON(!alloc_cpumask_var(&wq_requested_unbound_cpumask
, GFP_KERNEL
));
7984 BUG_ON(!zalloc_cpumask_var(&wq_isolated_cpumask
, GFP_KERNEL
));
7986 cpumask_copy(wq_online_cpumask
, cpu_online_mask
);
7987 cpumask_copy(wq_unbound_cpumask
, cpu_possible_mask
);
7988 restrict_unbound_cpumask("HK_TYPE_DOMAIN", housekeeping_cpumask(HK_TYPE_DOMAIN
));
7989 if (!cpumask_empty(&wq_cmdline_cpumask
))
7990 restrict_unbound_cpumask("workqueue.unbound_cpus", &wq_cmdline_cpumask
);
7992 cpumask_copy(wq_requested_unbound_cpumask
, wq_unbound_cpumask
);
7993 cpumask_andnot(wq_isolated_cpumask
, cpu_possible_mask
,
7994 housekeeping_cpumask(HK_TYPE_DOMAIN
));
7995 pwq_cache
= KMEM_CACHE(pool_workqueue
, SLAB_PANIC
);
7997 unbound_wq_update_pwq_attrs_buf
= alloc_workqueue_attrs();
7998 BUG_ON(!unbound_wq_update_pwq_attrs_buf
);
8001 * If nohz_full is enabled, set power efficient workqueue as unbound.
8002 * This allows workqueue items to be moved to HK CPUs.
8004 if (housekeeping_enabled(HK_TYPE_TICK
))
8005 wq_power_efficient
= true;
8007 /* initialize WQ_AFFN_SYSTEM pods */
8008 pt
->pod_cpus
= kzalloc_objs(pt
->pod_cpus
[0], 1);
8009 pt
->pod_node
= kzalloc_objs(pt
->pod_node
[0], 1);
8010 pt
->cpu_pod
= kzalloc_objs(pt
->cpu_pod
[0], nr_cpu_ids
);
8011 BUG_ON(!pt
->pod_cpus
|| !pt
->pod_node
|| !pt
->cpu_pod
);
8013 BUG_ON(!zalloc_cpumask_var_node(&pt
->pod_cpus
[0], GFP_KERNEL
, NUMA_NO_NODE
));
8016 cpumask_copy(pt
->pod_cpus
[0], cpu_possible_mask
);
8017 pt
->pod_node
[0] = NUMA_NO_NODE
;
8020 /* initialize BH and CPU pools */
8021 for_each_possible_cpu(cpu
) {
8022 struct worker_pool
*pool
;
8025 for_each_bh_worker_pool(pool
, cpu
) {
8026 init_cpu_worker_pool(pool
, cpu
, std_nice
[i
]);
8027 pool
->flags
|= POOL_BH
;
8028 init_irq_work(bh_pool_irq_work(pool
), irq_work_fns
[i
]);
8033 for_each_cpu_worker_pool(pool
, cpu
)
8034 init_cpu_worker_pool(pool
, cpu
, std_nice
[i
++]);
8037 /* create default unbound and ordered wq attrs */
8038 for (i
= 0; i
< NR_STD_WORKER_POOLS
; i
++) {
8039 struct workqueue_attrs
*attrs
;
8041 BUG_ON(!(attrs
= alloc_workqueue_attrs()));
8042 attrs
->nice
= std_nice
[i
];
8043 unbound_std_wq_attrs
[i
] = attrs
;
8046 * An ordered wq should have only one pwq as ordering is
8047 * guaranteed by max_active which is enforced by pwqs.
8049 BUG_ON(!(attrs
= alloc_workqueue_attrs()));
8050 attrs
->nice
= std_nice
[i
];
8051 attrs
->ordered
= true;
8052 ordered_wq_attrs
[i
] = attrs
;
8055 system_wq
= alloc_workqueue("events", WQ_PERCPU
| __WQ_DEPRECATED
, 0);
8056 system_percpu_wq
= alloc_workqueue("events", WQ_PERCPU
, 0);
8057 system_highpri_wq
= alloc_workqueue("events_highpri",
8058 WQ_HIGHPRI
| WQ_PERCPU
, 0);
8059 system_long_wq
= alloc_workqueue("events_long", WQ_PERCPU
, 0);
8060 system_unbound_wq
= alloc_workqueue("events_unbound", WQ_UNBOUND
| __WQ_DEPRECATED
, WQ_MAX_ACTIVE
);
8061 system_dfl_wq
= alloc_workqueue("events_unbound", WQ_UNBOUND
, WQ_MAX_ACTIVE
);
8062 system_freezable_wq
= alloc_workqueue("events_freezable",
8063 WQ_FREEZABLE
| WQ_PERCPU
, 0);
8064 system_power_efficient_wq
= alloc_workqueue("events_power_efficient",
8065 WQ_POWER_EFFICIENT
| WQ_PERCPU
, 0);
8066 system_freezable_power_efficient_wq
= alloc_workqueue("events_freezable_pwr_efficient",
8067 WQ_FREEZABLE
| WQ_POWER_EFFICIENT
| WQ_PERCPU
, 0);
8068 system_bh_wq
= alloc_workqueue("events_bh", WQ_BH
| WQ_PERCPU
, 0);
8069 system_bh_highpri_wq
= alloc_workqueue("events_bh_highpri",
8070 WQ_BH
| WQ_HIGHPRI
| WQ_PERCPU
, 0);
8071 system_dfl_long_wq
= alloc_workqueue("events_dfl_long", WQ_UNBOUND
, WQ_MAX_ACTIVE
);
8072 BUG_ON(!system_wq
|| !system_percpu_wq
|| !system_highpri_wq
|| !system_long_wq
||
8073 !system_unbound_wq
|| !system_freezable_wq
|| !system_dfl_wq
||
8074 !system_power_efficient_wq
||
8075 !system_freezable_power_efficient_wq
||
8076 !system_bh_wq
|| !system_bh_highpri_wq
|| !system_dfl_long_wq
);
8079 static void __init
wq_cpu_intensive_thresh_init(void)
8081 unsigned long thresh
;
8084 pwq_release_worker
= kthread_run_worker(0, "pool_workqueue_release");
8085 BUG_ON(IS_ERR(pwq_release_worker
));
8087 /* if the user set it to a specific value, keep it */
8088 if (wq_cpu_intensive_thresh_us
!= ULONG_MAX
)
8092 * The default of 10ms is derived from the fact that most modern (as of
8093 * 2023) processors can do a lot in 10ms and that it's just below what
8094 * most consider human-perceivable. However, the kernel also runs on a
8095 * lot slower CPUs including microcontrollers where the threshold is way
8098 * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
8099 * This is by no means accurate but it doesn't have to be. The mechanism
8100 * is still useful even when the threshold is fully scaled up. Also, as
8101 * the reports would usually be applicable to everyone, some machines
8102 * operating on longer thresholds won't significantly diminish their
8105 thresh
= 10 * USEC_PER_MSEC
;
8107 /* see init/calibrate.c for lpj -> BogoMIPS calculation */
8108 bogo
= max_t(unsigned long, loops_per_jiffy
/ 500000 * HZ
, 1);
8110 thresh
= min_t(unsigned long, thresh
* 4000 / bogo
, USEC_PER_SEC
);
8112 pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
8113 loops_per_jiffy
, bogo
, thresh
);
8115 wq_cpu_intensive_thresh_us
= thresh
;
8119 * workqueue_init - bring workqueue subsystem fully online
8121 * This is the second step of three-staged workqueue subsystem initialization
8122 * and invoked as soon as kthreads can be created and scheduled. Workqueues have
8123 * been created and work items queued on them, but there are no kworkers
8124 * executing the work items yet. Populate the worker pools with the initial
8125 * workers and enable future kworker creations.
8127 void __init
workqueue_init(void)
8129 struct workqueue_struct
*wq
;
8130 struct worker_pool
*pool
;
8133 wq_cpu_intensive_thresh_init();
8135 mutex_lock(&wq_pool_mutex
);
8138 * Per-cpu pools created earlier could be missing node hint. Fix them
8139 * up. Also, create a rescuer for workqueues that requested it.
8141 for_each_possible_cpu(cpu
) {
8142 for_each_bh_worker_pool(pool
, cpu
)
8143 pool
->node
= cpu_to_node(cpu
);
8144 for_each_cpu_worker_pool(pool
, cpu
)
8145 pool
->node
= cpu_to_node(cpu
);
8148 list_for_each_entry(wq
, &workqueues
, list
) {
8149 WARN(init_rescuer(wq
),
8150 "workqueue: failed to create early rescuer for %s",
8154 mutex_unlock(&wq_pool_mutex
);
8157 * Create the initial workers. A BH pool has one pseudo worker that
8158 * represents the shared BH execution context and thus doesn't get
8159 * affected by hotplug events. Create the BH pseudo workers for all
8160 * possible CPUs here.
8162 for_each_possible_cpu(cpu
)
8163 for_each_bh_worker_pool(pool
, cpu
)
8164 BUG_ON(!create_worker(pool
));
8166 for_each_online_cpu(cpu
) {
8167 for_each_cpu_worker_pool(pool
, cpu
) {
8168 pool
->flags
&= ~POOL_DISASSOCIATED
;
8169 BUG_ON(!create_worker(pool
));
8173 hash_for_each(unbound_pool_hash
, bkt
, pool
, hash_node
)
8174 BUG_ON(!create_worker(pool
));
8181 * Initialize @pt by first initializing @pt->cpu_pod[] with pod IDs according to
8182 * @cpu_shares_pod(). Each subset of CPUs that share a pod is assigned a unique
8183 * and consecutive pod ID. The rest of @pt is initialized accordingly.
8185 static void __init
init_pod_type(struct wq_pod_type
*pt
,
8186 bool (*cpus_share_pod
)(int, int))
8188 int cur
, pre
, cpu
, pod
;
8192 /* init @pt->cpu_pod[] according to @cpus_share_pod() */
8193 pt
->cpu_pod
= kzalloc_objs(pt
->cpu_pod
[0], nr_cpu_ids
);
8194 BUG_ON(!pt
->cpu_pod
);
8196 for_each_possible_cpu(cur
) {
8197 for_each_possible_cpu(pre
) {
8199 pt
->cpu_pod
[cur
] = pt
->nr_pods
++;
8202 if (cpus_share_pod(cur
, pre
)) {
8203 pt
->cpu_pod
[cur
] = pt
->cpu_pod
[pre
];
8209 /* init the rest to match @pt->cpu_pod[] */
8210 pt
->pod_cpus
= kzalloc_objs(pt
->pod_cpus
[0], pt
->nr_pods
);
8211 pt
->pod_node
= kzalloc_objs(pt
->pod_node
[0], pt
->nr_pods
);
8212 BUG_ON(!pt
->pod_cpus
|| !pt
->pod_node
);
8214 for (pod
= 0; pod
< pt
->nr_pods
; pod
++)
8215 BUG_ON(!zalloc_cpumask_var(&pt
->pod_cpus
[pod
], GFP_KERNEL
));
8217 for_each_possible_cpu(cpu
) {
8218 cpumask_set_cpu(cpu
, pt
->pod_cpus
[pt
->cpu_pod
[cpu
]]);
8219 pt
->pod_node
[pt
->cpu_pod
[cpu
]] = cpu_to_node(cpu
);
8223 static bool __init
cpus_dont_share(int cpu0
, int cpu1
)
8228 static bool __init
cpus_share_smt(int cpu0
, int cpu1
)
8230 return cpumask_test_cpu(cpu0
, cpu_smt_mask(cpu1
));
8233 static bool __init
cpus_share_numa(int cpu0
, int cpu1
)
8235 return cpu_to_node(cpu0
) == cpu_to_node(cpu1
);
8238 /* Maps each CPU to its shard index within the LLC pod it belongs to */
8239 static int cpu_shard_id
[NR_CPUS
] __initdata
;
8242 * llc_count_cores - count distinct cores (SMT groups) within an LLC pod
8243 * @pod_cpus: the cpumask of CPUs in the LLC pod
8244 * @smt_pods: the SMT pod type, used to identify sibling groups
8246 * A core is represented by the lowest-numbered CPU in its SMT group. Returns
8247 * the number of distinct cores found in @pod_cpus.
8249 static int __init
llc_count_cores(const struct cpumask
*pod_cpus
,
8250 struct wq_pod_type
*smt_pods
)
8252 const struct cpumask
*sibling_cpus
;
8253 int nr_cores
= 0, c
;
8256 * Count distinct cores by only counting the first CPU in each
8257 * SMT sibling group.
8259 for_each_cpu(c
, pod_cpus
) {
8260 sibling_cpus
= smt_pods
->pod_cpus
[smt_pods
->cpu_pod
[c
]];
8261 if (cpumask_first(sibling_cpus
) == c
)
8269 * llc_shard_size - number of cores in a given shard
8271 * Cores are spread as evenly as possible. The first @nr_large_shards shards are
8272 * "large shards" with (cores_per_shard + 1) cores; the rest are "default
8273 * shards" with cores_per_shard cores.
8275 static int __init
llc_shard_size(int shard_id
, int cores_per_shard
, int nr_large_shards
)
8277 /* The first @nr_large_shards shards are large shards */
8278 if (shard_id
< nr_large_shards
)
8279 return cores_per_shard
+ 1;
8281 /* The remaining shards are default shards */
8282 return cores_per_shard
;
8286 * llc_calc_shard_layout - compute the shard layout for an LLC pod
8287 * @nr_cores: number of distinct cores in the LLC pod
8289 * Chooses the number of shards that keeps average shard size closest to
8290 * wq_cache_shard_size. Returns a struct describing the total number of shards,
8291 * the base size of each, and how many are large shards.
8293 static struct llc_shard_layout __init
llc_calc_shard_layout(int nr_cores
)
8295 struct llc_shard_layout layout
;
8297 /* Ensure at least one shard; pick the count closest to the target size */
8298 layout
.nr_shards
= max(1, DIV_ROUND_CLOSEST(nr_cores
, wq_cache_shard_size
));
8299 layout
.cores_per_shard
= nr_cores
/ layout
.nr_shards
;
8300 layout
.nr_large_shards
= nr_cores
% layout
.nr_shards
;
8306 * llc_shard_is_full - check whether a shard has reached its core capacity
8307 * @cores_in_shard: number of cores already assigned to this shard
8308 * @shard_id: index of the shard being checked
8309 * @layout: the shard layout computed by llc_calc_shard_layout()
8311 * Returns true if @cores_in_shard equals the expected size for @shard_id.
8313 static bool __init
llc_shard_is_full(int cores_in_shard
, int shard_id
,
8314 const struct llc_shard_layout
*layout
)
8316 return cores_in_shard
== llc_shard_size(shard_id
, layout
->cores_per_shard
,
8317 layout
->nr_large_shards
);
8321 * llc_populate_cpu_shard_id - populate cpu_shard_id[] for each CPU in an LLC pod
8322 * @pod_cpus: the cpumask of CPUs in the LLC pod
8323 * @smt_pods: the SMT pod type, used to identify sibling groups
8324 * @nr_cores: number of distinct cores in @pod_cpus (from llc_count_cores())
8326 * Walks @pod_cpus in order. At each SMT group leader, advances to the next
8327 * shard once the current shard is full. Results are written to cpu_shard_id[].
8329 static void __init
llc_populate_cpu_shard_id(const struct cpumask
*pod_cpus
,
8330 struct wq_pod_type
*smt_pods
,
8333 struct llc_shard_layout layout
= llc_calc_shard_layout(nr_cores
);
8334 const struct cpumask
*sibling_cpus
;
8335 /* Count the number of cores in the current shard_id */
8336 int cores_in_shard
= 0;
8337 unsigned int leader
;
8338 /* This is a cursor for the shards. Go from zero to nr_shards - 1*/
8342 /* Iterate at every CPU for a given LLC pod, and assign it a shard */
8343 for_each_cpu(c
, pod_cpus
) {
8344 sibling_cpus
= smt_pods
->pod_cpus
[smt_pods
->cpu_pod
[c
]];
8345 if (cpumask_first(sibling_cpus
) == c
) {
8346 /* This is the CPU leader for the siblings */
8347 if (llc_shard_is_full(cores_in_shard
, shard_id
, &layout
)) {
8352 cpu_shard_id
[c
] = shard_id
;
8355 * The siblings' shard MUST be the same as the leader.
8356 * never split threads in the same core.
8358 leader
= cpumask_first(sibling_cpus
);
8361 * This check silences a Warray-bounds warning on UP
8362 * configs where NR_CPUS=1 makes cpu_shard_id[]
8363 * a single-element array, and the compiler can't
8364 * prove the index is always 0.
8366 if (WARN_ON_ONCE(leader
>= nr_cpu_ids
))
8368 cpu_shard_id
[c
] = cpu_shard_id
[leader
];
8372 WARN_ON_ONCE(shard_id
!= (layout
.nr_shards
- 1));
8376 * precompute_cache_shard_ids - assign each CPU its shard index within its LLC
8378 * Iterates over all LLC pods. For each pod, counts distinct cores then assigns
8379 * shard indices to all CPUs in the pod. Must be called after WQ_AFFN_CACHE and
8380 * WQ_AFFN_SMT have been initialized.
8382 static void __init
precompute_cache_shard_ids(void)
8384 struct wq_pod_type
*llc_pods
= &wq_pod_types
[WQ_AFFN_CACHE
];
8385 struct wq_pod_type
*smt_pods
= &wq_pod_types
[WQ_AFFN_SMT
];
8386 const struct cpumask
*cpus_sharing_llc
;
8390 if (!wq_cache_shard_size
) {
8391 pr_warn("workqueue: cache_shard_size must be > 0, setting to 1\n");
8392 wq_cache_shard_size
= 1;
8395 for (pod
= 0; pod
< llc_pods
->nr_pods
; pod
++) {
8396 cpus_sharing_llc
= llc_pods
->pod_cpus
[pod
];
8398 /* Number of cores in this given LLC */
8399 nr_cores
= llc_count_cores(cpus_sharing_llc
, smt_pods
);
8400 llc_populate_cpu_shard_id(cpus_sharing_llc
, smt_pods
, nr_cores
);
8405 * cpus_share_cache_shard - test whether two CPUs belong to the same cache shard
8407 * Two CPUs share a cache shard if they are in the same LLC and have the same
8408 * shard index. Used as the pod affinity callback for WQ_AFFN_CACHE_SHARD.
8410 static bool __init
cpus_share_cache_shard(int cpu0
, int cpu1
)
8412 if (!cpus_share_cache(cpu0
, cpu1
))
8415 return cpu_shard_id
[cpu0
] == cpu_shard_id
[cpu1
];
8419 * workqueue_init_topology - initialize CPU pods for unbound workqueues
8421 * This is the third step of three-staged workqueue subsystem initialization and
8422 * invoked after SMP and topology information are fully initialized. It
8423 * initializes the unbound CPU pods accordingly.
8425 void __init
workqueue_init_topology(void)
8427 struct workqueue_struct
*wq
;
8430 init_pod_type(&wq_pod_types
[WQ_AFFN_CPU
], cpus_dont_share
);
8431 init_pod_type(&wq_pod_types
[WQ_AFFN_SMT
], cpus_share_smt
);
8432 init_pod_type(&wq_pod_types
[WQ_AFFN_CACHE
], cpus_share_cache
);
8433 precompute_cache_shard_ids();
8434 init_pod_type(&wq_pod_types
[WQ_AFFN_CACHE_SHARD
], cpus_share_cache_shard
);
8435 init_pod_type(&wq_pod_types
[WQ_AFFN_NUMA
], cpus_share_numa
);
8437 wq_topo_initialized
= true;
8439 mutex_lock(&wq_pool_mutex
);
8442 * Workqueues allocated earlier would have all CPUs sharing the default
8443 * worker pool. Explicitly call unbound_wq_update_pwq() on all workqueue
8444 * and CPU combinations to apply per-pod sharing.
8446 list_for_each_entry(wq
, &workqueues
, list
) {
8447 for_each_online_cpu(cpu
)
8448 unbound_wq_update_pwq(wq
, cpu
);
8449 if (wq
->flags
& WQ_UNBOUND
) {
8450 mutex_lock(&wq
->mutex
);
8451 wq_update_node_max_active(wq
, -1);
8452 mutex_unlock(&wq
->mutex
);
8456 mutex_unlock(&wq_pool_mutex
);
8459 void __warn_flushing_systemwide_wq(void)
8461 pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
8464 EXPORT_SYMBOL(__warn_flushing_systemwide_wq
);
8466 static int __init
workqueue_unbound_cpus_setup(char *str
)
8468 if (cpulist_parse(str
, &wq_cmdline_cpumask
) < 0) {
8469 cpumask_clear(&wq_cmdline_cpumask
);
8470 pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
8475 __setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup
);