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