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