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