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