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