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 <[email protected]> 9 * Andrew Morton 10 * Kai Petzke <[email protected]> 11 * Theodore Ts'o <[email protected]> 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 <[email protected]> 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/signal.h> 33 #include <linux/completion.h> 34 #include <linux/workqueue.h> 35 #include <linux/slab.h> 36 #include <linux/cpu.h> 37 #include <linux/notifier.h> 38 #include <linux/kthread.h> 39 #include <linux/hardirq.h> 40 #include <linux/mempolicy.h> 41 #include <linux/freezer.h> 42 #include <linux/debug_locks.h> 43 #include <linux/lockdep.h> 44 #include <linux/idr.h> 45 #include <linux/jhash.h> 46 #include <linux/hashtable.h> 47 #include <linux/rculist.h> 48 #include <linux/nodemask.h> 49 #include <linux/moduleparam.h> 50 #include <linux/uaccess.h> 51 #include <linux/sched/isolation.h> 52 #include <linux/sched/debug.h> 53 #include <linux/nmi.h> 54 #include <linux/kvm_para.h> 55 56 #include "workqueue_internal.h" 57 58 enum { 59 /* 60 * worker_pool flags 61 * 62 * A bound pool is either associated or disassociated with its CPU. 63 * While associated (!DISASSOCIATED), all workers are bound to the 64 * CPU and none has %WORKER_UNBOUND set and concurrency management 65 * is in effect. 66 * 67 * While DISASSOCIATED, the cpu may be offline and all workers have 68 * %WORKER_UNBOUND set and concurrency management disabled, and may 69 * be executing on any CPU. The pool behaves as an unbound one. 70 * 71 * Note that DISASSOCIATED should be flipped only while holding 72 * wq_pool_attach_mutex to avoid changing binding state while 73 * worker_attach_to_pool() is in progress. 74 */ 75 POOL_MANAGER_ACTIVE = 1 << 0, /* being managed */ 76 POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */ 77 78 /* worker flags */ 79 WORKER_DIE = 1 << 1, /* die die die */ 80 WORKER_IDLE = 1 << 2, /* is idle */ 81 WORKER_PREP = 1 << 3, /* preparing to run works */ 82 WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */ 83 WORKER_UNBOUND = 1 << 7, /* worker is unbound */ 84 WORKER_REBOUND = 1 << 8, /* worker was rebound */ 85 86 WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE | 87 WORKER_UNBOUND | WORKER_REBOUND, 88 89 NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */ 90 91 UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */ 92 BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */ 93 94 MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */ 95 IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */ 96 97 MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2, 98 /* call for help after 10ms 99 (min two ticks) */ 100 MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */ 101 CREATE_COOLDOWN = HZ, /* time to breath after fail */ 102 103 /* 104 * Rescue workers are used only on emergencies and shared by 105 * all cpus. Give MIN_NICE. 106 */ 107 RESCUER_NICE_LEVEL = MIN_NICE, 108 HIGHPRI_NICE_LEVEL = MIN_NICE, 109 110 WQ_NAME_LEN = 24, 111 }; 112 113 /* 114 * Structure fields follow one of the following exclusion rules. 115 * 116 * I: Modifiable by initialization/destruction paths and read-only for 117 * everyone else. 118 * 119 * P: Preemption protected. Disabling preemption is enough and should 120 * only be modified and accessed from the local cpu. 121 * 122 * L: pool->lock protected. Access with pool->lock held. 123 * 124 * X: During normal operation, modification requires pool->lock and should 125 * be done only from local cpu. Either disabling preemption on local 126 * cpu or grabbing pool->lock is enough for read access. If 127 * POOL_DISASSOCIATED is set, it's identical to L. 128 * 129 * K: Only modified by worker while holding pool->lock. Can be safely read by 130 * self, while holding pool->lock or from IRQ context if %current is the 131 * kworker. 132 * 133 * S: Only modified by worker self. 134 * 135 * A: wq_pool_attach_mutex protected. 136 * 137 * PL: wq_pool_mutex protected. 138 * 139 * PR: wq_pool_mutex protected for writes. RCU protected for reads. 140 * 141 * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads. 142 * 143 * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or 144 * RCU for reads. 145 * 146 * WQ: wq->mutex protected. 147 * 148 * WR: wq->mutex protected for writes. RCU protected for reads. 149 * 150 * MD: wq_mayday_lock protected. 151 * 152 * WD: Used internally by the watchdog. 153 */ 154 155 /* struct worker is defined in workqueue_internal.h */ 156 157 struct worker_pool { 158 raw_spinlock_t lock; /* the pool lock */ 159 int cpu; /* I: the associated cpu */ 160 int node; /* I: the associated node ID */ 161 int id; /* I: pool ID */ 162 unsigned int flags; /* X: flags */ 163 164 unsigned long watchdog_ts; /* L: watchdog timestamp */ 165 bool cpu_stall; /* WD: stalled cpu bound pool */ 166 167 /* 168 * The counter is incremented in a process context on the associated CPU 169 * w/ preemption disabled, and decremented or reset in the same context 170 * but w/ pool->lock held. The readers grab pool->lock and are 171 * guaranteed to see if the counter reached zero. 172 */ 173 int nr_running; 174 175 struct list_head worklist; /* L: list of pending works */ 176 177 int nr_workers; /* L: total number of workers */ 178 int nr_idle; /* L: currently idle workers */ 179 180 struct list_head idle_list; /* L: list of idle workers */ 181 struct timer_list idle_timer; /* L: worker idle timeout */ 182 struct work_struct idle_cull_work; /* L: worker idle cleanup */ 183 184 struct timer_list mayday_timer; /* L: SOS timer for workers */ 185 186 /* a workers is either on busy_hash or idle_list, or the manager */ 187 DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER); 188 /* L: hash of busy workers */ 189 190 struct worker *manager; /* L: purely informational */ 191 struct list_head workers; /* A: attached workers */ 192 struct list_head dying_workers; /* A: workers about to die */ 193 struct completion *detach_completion; /* all workers detached */ 194 195 struct ida worker_ida; /* worker IDs for task name */ 196 197 struct workqueue_attrs *attrs; /* I: worker attributes */ 198 struct hlist_node hash_node; /* PL: unbound_pool_hash node */ 199 int refcnt; /* PL: refcnt for unbound pools */ 200 201 /* 202 * Destruction of pool is RCU protected to allow dereferences 203 * from get_work_pool(). 204 */ 205 struct rcu_head rcu; 206 }; 207 208 /* 209 * Per-pool_workqueue statistics. These can be monitored using 210 * tools/workqueue/wq_monitor.py. 211 */ 212 enum pool_workqueue_stats { 213 PWQ_STAT_STARTED, /* work items started execution */ 214 PWQ_STAT_COMPLETED, /* work items completed execution */ 215 PWQ_STAT_CPU_INTENSIVE, /* wq_cpu_intensive_thresh_us violations */ 216 PWQ_STAT_CM_WAKEUP, /* concurrency-management worker wakeups */ 217 PWQ_STAT_MAYDAY, /* maydays to rescuer */ 218 PWQ_STAT_RESCUED, /* linked work items executed by rescuer */ 219 220 PWQ_NR_STATS, 221 }; 222 223 /* 224 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS 225 * of work_struct->data are used for flags and the remaining high bits 226 * point to the pwq; thus, pwqs need to be aligned at two's power of the 227 * number of flag bits. 228 */ 229 struct pool_workqueue { 230 struct worker_pool *pool; /* I: the associated pool */ 231 struct workqueue_struct *wq; /* I: the owning workqueue */ 232 int work_color; /* L: current color */ 233 int flush_color; /* L: flushing color */ 234 int refcnt; /* L: reference count */ 235 int nr_in_flight[WORK_NR_COLORS]; 236 /* L: nr of in_flight works */ 237 238 /* 239 * nr_active management and WORK_STRUCT_INACTIVE: 240 * 241 * When pwq->nr_active >= max_active, new work item is queued to 242 * pwq->inactive_works instead of pool->worklist and marked with 243 * WORK_STRUCT_INACTIVE. 244 * 245 * All work items marked with WORK_STRUCT_INACTIVE do not participate 246 * in pwq->nr_active and all work items in pwq->inactive_works are 247 * marked with WORK_STRUCT_INACTIVE. But not all WORK_STRUCT_INACTIVE 248 * work items are in pwq->inactive_works. Some of them are ready to 249 * run in pool->worklist or worker->scheduled. Those work itmes are 250 * only struct wq_barrier which is used for flush_work() and should 251 * not participate in pwq->nr_active. For non-barrier work item, it 252 * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works. 253 */ 254 int nr_active; /* L: nr of active works */ 255 int max_active; /* L: max active works */ 256 struct list_head inactive_works; /* L: inactive works */ 257 struct list_head pwqs_node; /* WR: node on wq->pwqs */ 258 struct list_head mayday_node; /* MD: node on wq->maydays */ 259 260 u64 stats[PWQ_NR_STATS]; 261 262 /* 263 * Release of unbound pwq is punted to system_wq. See put_pwq() 264 * and pwq_unbound_release_workfn() for details. pool_workqueue 265 * itself is also RCU protected so that the first pwq can be 266 * determined without grabbing wq->mutex. 267 */ 268 struct work_struct unbound_release_work; 269 struct rcu_head rcu; 270 } __aligned(1 << WORK_STRUCT_FLAG_BITS); 271 272 /* 273 * Structure used to wait for workqueue flush. 274 */ 275 struct wq_flusher { 276 struct list_head list; /* WQ: list of flushers */ 277 int flush_color; /* WQ: flush color waiting for */ 278 struct completion done; /* flush completion */ 279 }; 280 281 struct wq_device; 282 283 /* 284 * The externally visible workqueue. It relays the issued work items to 285 * the appropriate worker_pool through its pool_workqueues. 286 */ 287 struct workqueue_struct { 288 struct list_head pwqs; /* WR: all pwqs of this wq */ 289 struct list_head list; /* PR: list of all workqueues */ 290 291 struct mutex mutex; /* protects this wq */ 292 int work_color; /* WQ: current work color */ 293 int flush_color; /* WQ: current flush color */ 294 atomic_t nr_pwqs_to_flush; /* flush in progress */ 295 struct wq_flusher *first_flusher; /* WQ: first flusher */ 296 struct list_head flusher_queue; /* WQ: flush waiters */ 297 struct list_head flusher_overflow; /* WQ: flush overflow list */ 298 299 struct list_head maydays; /* MD: pwqs requesting rescue */ 300 struct worker *rescuer; /* MD: rescue worker */ 301 302 int nr_drainers; /* WQ: drain in progress */ 303 int saved_max_active; /* WQ: saved pwq max_active */ 304 305 struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */ 306 struct pool_workqueue *dfl_pwq; /* PW: only for unbound wqs */ 307 308 #ifdef CONFIG_SYSFS 309 struct wq_device *wq_dev; /* I: for sysfs interface */ 310 #endif 311 #ifdef CONFIG_LOCKDEP 312 char *lock_name; 313 struct lock_class_key key; 314 struct lockdep_map lockdep_map; 315 #endif 316 char name[WQ_NAME_LEN]; /* I: workqueue name */ 317 318 /* 319 * Destruction of workqueue_struct is RCU protected to allow walking 320 * the workqueues list without grabbing wq_pool_mutex. 321 * This is used to dump all workqueues from sysrq. 322 */ 323 struct rcu_head rcu; 324 325 /* hot fields used during command issue, aligned to cacheline */ 326 unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */ 327 struct pool_workqueue __percpu *cpu_pwqs; /* I: per-cpu pwqs */ 328 struct pool_workqueue __rcu *numa_pwq_tbl[]; /* PWR: unbound pwqs indexed by node */ 329 }; 330 331 static struct kmem_cache *pwq_cache; 332 333 static cpumask_var_t *wq_numa_possible_cpumask; 334 /* possible CPUs of each node */ 335 336 /* 337 * Per-cpu work items which run for longer than the following threshold are 338 * automatically considered CPU intensive and excluded from concurrency 339 * management to prevent them from noticeably delaying other per-cpu work items. 340 */ 341 static unsigned long wq_cpu_intensive_thresh_us = 10000; 342 module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644); 343 344 static bool wq_disable_numa; 345 module_param_named(disable_numa, wq_disable_numa, bool, 0444); 346 347 /* see the comment above the definition of WQ_POWER_EFFICIENT */ 348 static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT); 349 module_param_named(power_efficient, wq_power_efficient, bool, 0444); 350 351 static bool wq_online; /* can kworkers be created yet? */ 352 353 static bool wq_numa_enabled; /* unbound NUMA affinity enabled */ 354 355 /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */ 356 static struct workqueue_attrs *wq_update_unbound_numa_attrs_buf; 357 358 static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */ 359 static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */ 360 static DEFINE_RAW_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */ 361 /* wait for manager to go away */ 362 static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait); 363 364 static LIST_HEAD(workqueues); /* PR: list of all workqueues */ 365 static bool workqueue_freezing; /* PL: have wqs started freezing? */ 366 367 /* PL&A: allowable cpus for unbound wqs and work items */ 368 static cpumask_var_t wq_unbound_cpumask; 369 370 /* CPU where unbound work was last round robin scheduled from this CPU */ 371 static DEFINE_PER_CPU(int, wq_rr_cpu_last); 372 373 /* 374 * Local execution of unbound work items is no longer guaranteed. The 375 * following always forces round-robin CPU selection on unbound work items 376 * to uncover usages which depend on it. 377 */ 378 #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU 379 static bool wq_debug_force_rr_cpu = true; 380 #else 381 static bool wq_debug_force_rr_cpu = false; 382 #endif 383 module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644); 384 385 /* the per-cpu worker pools */ 386 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools); 387 388 static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */ 389 390 /* PL: hash of all unbound pools keyed by pool->attrs */ 391 static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER); 392 393 /* I: attributes used when instantiating standard unbound pools on demand */ 394 static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS]; 395 396 /* I: attributes used when instantiating ordered pools on demand */ 397 static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS]; 398 399 struct workqueue_struct *system_wq __read_mostly; 400 EXPORT_SYMBOL(system_wq); 401 struct workqueue_struct *system_highpri_wq __read_mostly; 402 EXPORT_SYMBOL_GPL(system_highpri_wq); 403 struct workqueue_struct *system_long_wq __read_mostly; 404 EXPORT_SYMBOL_GPL(system_long_wq); 405 struct workqueue_struct *system_unbound_wq __read_mostly; 406 EXPORT_SYMBOL_GPL(system_unbound_wq); 407 struct workqueue_struct *system_freezable_wq __read_mostly; 408 EXPORT_SYMBOL_GPL(system_freezable_wq); 409 struct workqueue_struct *system_power_efficient_wq __read_mostly; 410 EXPORT_SYMBOL_GPL(system_power_efficient_wq); 411 struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly; 412 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq); 413 414 static int worker_thread(void *__worker); 415 static void workqueue_sysfs_unregister(struct workqueue_struct *wq); 416 static void show_pwq(struct pool_workqueue *pwq); 417 static void show_one_worker_pool(struct worker_pool *pool); 418 419 #define CREATE_TRACE_POINTS 420 #include <trace/events/workqueue.h> 421 422 #define assert_rcu_or_pool_mutex() \ 423 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \ 424 !lockdep_is_held(&wq_pool_mutex), \ 425 "RCU or wq_pool_mutex should be held") 426 427 #define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \ 428 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \ 429 !lockdep_is_held(&wq->mutex) && \ 430 !lockdep_is_held(&wq_pool_mutex), \ 431 "RCU, wq->mutex or wq_pool_mutex should be held") 432 433 #define for_each_cpu_worker_pool(pool, cpu) \ 434 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \ 435 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \ 436 (pool)++) 437 438 /** 439 * for_each_pool - iterate through all worker_pools in the system 440 * @pool: iteration cursor 441 * @pi: integer used for iteration 442 * 443 * This must be called either with wq_pool_mutex held or RCU read 444 * locked. If the pool needs to be used beyond the locking in effect, the 445 * caller is responsible for guaranteeing that the pool stays online. 446 * 447 * The if/else clause exists only for the lockdep assertion and can be 448 * ignored. 449 */ 450 #define for_each_pool(pool, pi) \ 451 idr_for_each_entry(&worker_pool_idr, pool, pi) \ 452 if (({ assert_rcu_or_pool_mutex(); false; })) { } \ 453 else 454 455 /** 456 * for_each_pool_worker - iterate through all workers of a worker_pool 457 * @worker: iteration cursor 458 * @pool: worker_pool to iterate workers of 459 * 460 * This must be called with wq_pool_attach_mutex. 461 * 462 * The if/else clause exists only for the lockdep assertion and can be 463 * ignored. 464 */ 465 #define for_each_pool_worker(worker, pool) \ 466 list_for_each_entry((worker), &(pool)->workers, node) \ 467 if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \ 468 else 469 470 /** 471 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue 472 * @pwq: iteration cursor 473 * @wq: the target workqueue 474 * 475 * This must be called either with wq->mutex held or RCU read locked. 476 * If the pwq needs to be used beyond the locking in effect, the caller is 477 * responsible for guaranteeing that the pwq stays online. 478 * 479 * The if/else clause exists only for the lockdep assertion and can be 480 * ignored. 481 */ 482 #define for_each_pwq(pwq, wq) \ 483 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node, \ 484 lockdep_is_held(&(wq->mutex))) 485 486 #ifdef CONFIG_DEBUG_OBJECTS_WORK 487 488 static const struct debug_obj_descr work_debug_descr; 489 490 static void *work_debug_hint(void *addr) 491 { 492 return ((struct work_struct *) addr)->func; 493 } 494 495 static bool work_is_static_object(void *addr) 496 { 497 struct work_struct *work = addr; 498 499 return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work)); 500 } 501 502 /* 503 * fixup_init is called when: 504 * - an active object is initialized 505 */ 506 static bool work_fixup_init(void *addr, enum debug_obj_state state) 507 { 508 struct work_struct *work = addr; 509 510 switch (state) { 511 case ODEBUG_STATE_ACTIVE: 512 cancel_work_sync(work); 513 debug_object_init(work, &work_debug_descr); 514 return true; 515 default: 516 return false; 517 } 518 } 519 520 /* 521 * fixup_free is called when: 522 * - an active object is freed 523 */ 524 static bool work_fixup_free(void *addr, enum debug_obj_state state) 525 { 526 struct work_struct *work = addr; 527 528 switch (state) { 529 case ODEBUG_STATE_ACTIVE: 530 cancel_work_sync(work); 531 debug_object_free(work, &work_debug_descr); 532 return true; 533 default: 534 return false; 535 } 536 } 537 538 static const struct debug_obj_descr work_debug_descr = { 539 .name = "work_struct", 540 .debug_hint = work_debug_hint, 541 .is_static_object = work_is_static_object, 542 .fixup_init = work_fixup_init, 543 .fixup_free = work_fixup_free, 544 }; 545 546 static inline void debug_work_activate(struct work_struct *work) 547 { 548 debug_object_activate(work, &work_debug_descr); 549 } 550 551 static inline void debug_work_deactivate(struct work_struct *work) 552 { 553 debug_object_deactivate(work, &work_debug_descr); 554 } 555 556 void __init_work(struct work_struct *work, int onstack) 557 { 558 if (onstack) 559 debug_object_init_on_stack(work, &work_debug_descr); 560 else 561 debug_object_init(work, &work_debug_descr); 562 } 563 EXPORT_SYMBOL_GPL(__init_work); 564 565 void destroy_work_on_stack(struct work_struct *work) 566 { 567 debug_object_free(work, &work_debug_descr); 568 } 569 EXPORT_SYMBOL_GPL(destroy_work_on_stack); 570 571 void destroy_delayed_work_on_stack(struct delayed_work *work) 572 { 573 destroy_timer_on_stack(&work->timer); 574 debug_object_free(&work->work, &work_debug_descr); 575 } 576 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack); 577 578 #else 579 static inline void debug_work_activate(struct work_struct *work) { } 580 static inline void debug_work_deactivate(struct work_struct *work) { } 581 #endif 582 583 /** 584 * worker_pool_assign_id - allocate ID and assign it to @pool 585 * @pool: the pool pointer of interest 586 * 587 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned 588 * successfully, -errno on failure. 589 */ 590 static int worker_pool_assign_id(struct worker_pool *pool) 591 { 592 int ret; 593 594 lockdep_assert_held(&wq_pool_mutex); 595 596 ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE, 597 GFP_KERNEL); 598 if (ret >= 0) { 599 pool->id = ret; 600 return 0; 601 } 602 return ret; 603 } 604 605 /** 606 * unbound_pwq_by_node - return the unbound pool_workqueue for the given node 607 * @wq: the target workqueue 608 * @node: the node ID 609 * 610 * This must be called with any of wq_pool_mutex, wq->mutex or RCU 611 * read locked. 612 * If the pwq needs to be used beyond the locking in effect, the caller is 613 * responsible for guaranteeing that the pwq stays online. 614 * 615 * Return: The unbound pool_workqueue for @node. 616 */ 617 static struct pool_workqueue *unbound_pwq_by_node(struct workqueue_struct *wq, 618 int node) 619 { 620 assert_rcu_or_wq_mutex_or_pool_mutex(wq); 621 622 /* 623 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a 624 * delayed item is pending. The plan is to keep CPU -> NODE 625 * mapping valid and stable across CPU on/offlines. Once that 626 * happens, this workaround can be removed. 627 */ 628 if (unlikely(node == NUMA_NO_NODE)) 629 return wq->dfl_pwq; 630 631 return rcu_dereference_raw(wq->numa_pwq_tbl[node]); 632 } 633 634 static unsigned int work_color_to_flags(int color) 635 { 636 return color << WORK_STRUCT_COLOR_SHIFT; 637 } 638 639 static int get_work_color(unsigned long work_data) 640 { 641 return (work_data >> WORK_STRUCT_COLOR_SHIFT) & 642 ((1 << WORK_STRUCT_COLOR_BITS) - 1); 643 } 644 645 static int work_next_color(int color) 646 { 647 return (color + 1) % WORK_NR_COLORS; 648 } 649 650 /* 651 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data 652 * contain the pointer to the queued pwq. Once execution starts, the flag 653 * is cleared and the high bits contain OFFQ flags and pool ID. 654 * 655 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling() 656 * and clear_work_data() can be used to set the pwq, pool or clear 657 * work->data. These functions should only be called while the work is 658 * owned - ie. while the PENDING bit is set. 659 * 660 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq 661 * corresponding to a work. Pool is available once the work has been 662 * queued anywhere after initialization until it is sync canceled. pwq is 663 * available only while the work item is queued. 664 * 665 * %WORK_OFFQ_CANCELING is used to mark a work item which is being 666 * canceled. While being canceled, a work item may have its PENDING set 667 * but stay off timer and worklist for arbitrarily long and nobody should 668 * try to steal the PENDING bit. 669 */ 670 static inline void set_work_data(struct work_struct *work, unsigned long data, 671 unsigned long flags) 672 { 673 WARN_ON_ONCE(!work_pending(work)); 674 atomic_long_set(&work->data, data | flags | work_static(work)); 675 } 676 677 static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq, 678 unsigned long extra_flags) 679 { 680 set_work_data(work, (unsigned long)pwq, 681 WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags); 682 } 683 684 static void set_work_pool_and_keep_pending(struct work_struct *work, 685 int pool_id) 686 { 687 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 688 WORK_STRUCT_PENDING); 689 } 690 691 static void set_work_pool_and_clear_pending(struct work_struct *work, 692 int pool_id) 693 { 694 /* 695 * The following wmb is paired with the implied mb in 696 * test_and_set_bit(PENDING) and ensures all updates to @work made 697 * here are visible to and precede any updates by the next PENDING 698 * owner. 699 */ 700 smp_wmb(); 701 set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0); 702 /* 703 * The following mb guarantees that previous clear of a PENDING bit 704 * will not be reordered with any speculative LOADS or STORES from 705 * work->current_func, which is executed afterwards. This possible 706 * reordering can lead to a missed execution on attempt to queue 707 * the same @work. E.g. consider this case: 708 * 709 * CPU#0 CPU#1 710 * ---------------------------- -------------------------------- 711 * 712 * 1 STORE event_indicated 713 * 2 queue_work_on() { 714 * 3 test_and_set_bit(PENDING) 715 * 4 } set_..._and_clear_pending() { 716 * 5 set_work_data() # clear bit 717 * 6 smp_mb() 718 * 7 work->current_func() { 719 * 8 LOAD event_indicated 720 * } 721 * 722 * Without an explicit full barrier speculative LOAD on line 8 can 723 * be executed before CPU#0 does STORE on line 1. If that happens, 724 * CPU#0 observes the PENDING bit is still set and new execution of 725 * a @work is not queued in a hope, that CPU#1 will eventually 726 * finish the queued @work. Meanwhile CPU#1 does not see 727 * event_indicated is set, because speculative LOAD was executed 728 * before actual STORE. 729 */ 730 smp_mb(); 731 } 732 733 static void clear_work_data(struct work_struct *work) 734 { 735 smp_wmb(); /* see set_work_pool_and_clear_pending() */ 736 set_work_data(work, WORK_STRUCT_NO_POOL, 0); 737 } 738 739 static struct pool_workqueue *get_work_pwq(struct work_struct *work) 740 { 741 unsigned long data = atomic_long_read(&work->data); 742 743 if (data & WORK_STRUCT_PWQ) 744 return (void *)(data & WORK_STRUCT_WQ_DATA_MASK); 745 else 746 return NULL; 747 } 748 749 /** 750 * get_work_pool - return the worker_pool a given work was associated with 751 * @work: the work item of interest 752 * 753 * Pools are created and destroyed under wq_pool_mutex, and allows read 754 * access under RCU read lock. As such, this function should be 755 * called under wq_pool_mutex or inside of a rcu_read_lock() region. 756 * 757 * All fields of the returned pool are accessible as long as the above 758 * mentioned locking is in effect. If the returned pool needs to be used 759 * beyond the critical section, the caller is responsible for ensuring the 760 * returned pool is and stays online. 761 * 762 * Return: The worker_pool @work was last associated with. %NULL if none. 763 */ 764 static struct worker_pool *get_work_pool(struct work_struct *work) 765 { 766 unsigned long data = atomic_long_read(&work->data); 767 int pool_id; 768 769 assert_rcu_or_pool_mutex(); 770 771 if (data & WORK_STRUCT_PWQ) 772 return ((struct pool_workqueue *) 773 (data & WORK_STRUCT_WQ_DATA_MASK))->pool; 774 775 pool_id = data >> WORK_OFFQ_POOL_SHIFT; 776 if (pool_id == WORK_OFFQ_POOL_NONE) 777 return NULL; 778 779 return idr_find(&worker_pool_idr, pool_id); 780 } 781 782 /** 783 * get_work_pool_id - return the worker pool ID a given work is associated with 784 * @work: the work item of interest 785 * 786 * Return: The worker_pool ID @work was last associated with. 787 * %WORK_OFFQ_POOL_NONE if none. 788 */ 789 static int get_work_pool_id(struct work_struct *work) 790 { 791 unsigned long data = atomic_long_read(&work->data); 792 793 if (data & WORK_STRUCT_PWQ) 794 return ((struct pool_workqueue *) 795 (data & WORK_STRUCT_WQ_DATA_MASK))->pool->id; 796 797 return data >> WORK_OFFQ_POOL_SHIFT; 798 } 799 800 static void mark_work_canceling(struct work_struct *work) 801 { 802 unsigned long pool_id = get_work_pool_id(work); 803 804 pool_id <<= WORK_OFFQ_POOL_SHIFT; 805 set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING); 806 } 807 808 static bool work_is_canceling(struct work_struct *work) 809 { 810 unsigned long data = atomic_long_read(&work->data); 811 812 return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING); 813 } 814 815 /* 816 * Policy functions. These define the policies on how the global worker 817 * pools are managed. Unless noted otherwise, these functions assume that 818 * they're being called with pool->lock held. 819 */ 820 821 static bool __need_more_worker(struct worker_pool *pool) 822 { 823 return !pool->nr_running; 824 } 825 826 /* 827 * Need to wake up a worker? Called from anything but currently 828 * running workers. 829 * 830 * Note that, because unbound workers never contribute to nr_running, this 831 * function will always return %true for unbound pools as long as the 832 * worklist isn't empty. 833 */ 834 static bool need_more_worker(struct worker_pool *pool) 835 { 836 return !list_empty(&pool->worklist) && __need_more_worker(pool); 837 } 838 839 /* Can I start working? Called from busy but !running workers. */ 840 static bool may_start_working(struct worker_pool *pool) 841 { 842 return pool->nr_idle; 843 } 844 845 /* Do I need to keep working? Called from currently running workers. */ 846 static bool keep_working(struct worker_pool *pool) 847 { 848 return !list_empty(&pool->worklist) && (pool->nr_running <= 1); 849 } 850 851 /* Do we need a new worker? Called from manager. */ 852 static bool need_to_create_worker(struct worker_pool *pool) 853 { 854 return need_more_worker(pool) && !may_start_working(pool); 855 } 856 857 /* Do we have too many workers and should some go away? */ 858 static bool too_many_workers(struct worker_pool *pool) 859 { 860 bool managing = pool->flags & POOL_MANAGER_ACTIVE; 861 int nr_idle = pool->nr_idle + managing; /* manager is considered idle */ 862 int nr_busy = pool->nr_workers - nr_idle; 863 864 return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy; 865 } 866 867 /* 868 * Wake up functions. 869 */ 870 871 /* Return the first idle worker. Called with pool->lock held. */ 872 static struct worker *first_idle_worker(struct worker_pool *pool) 873 { 874 if (unlikely(list_empty(&pool->idle_list))) 875 return NULL; 876 877 return list_first_entry(&pool->idle_list, struct worker, entry); 878 } 879 880 /** 881 * wake_up_worker - wake up an idle worker 882 * @pool: worker pool to wake worker from 883 * 884 * Wake up the first idle worker of @pool. 885 * 886 * CONTEXT: 887 * raw_spin_lock_irq(pool->lock). 888 */ 889 static void wake_up_worker(struct worker_pool *pool) 890 { 891 struct worker *worker = first_idle_worker(pool); 892 893 if (likely(worker)) 894 wake_up_process(worker->task); 895 } 896 897 /** 898 * worker_set_flags - set worker flags and adjust nr_running accordingly 899 * @worker: self 900 * @flags: flags to set 901 * 902 * Set @flags in @worker->flags and adjust nr_running accordingly. 903 * 904 * CONTEXT: 905 * raw_spin_lock_irq(pool->lock) 906 */ 907 static inline void worker_set_flags(struct worker *worker, unsigned int flags) 908 { 909 struct worker_pool *pool = worker->pool; 910 911 WARN_ON_ONCE(worker->task != current); 912 913 /* If transitioning into NOT_RUNNING, adjust nr_running. */ 914 if ((flags & WORKER_NOT_RUNNING) && 915 !(worker->flags & WORKER_NOT_RUNNING)) { 916 pool->nr_running--; 917 } 918 919 worker->flags |= flags; 920 } 921 922 /** 923 * worker_clr_flags - clear worker flags and adjust nr_running accordingly 924 * @worker: self 925 * @flags: flags to clear 926 * 927 * Clear @flags in @worker->flags and adjust nr_running accordingly. 928 * 929 * CONTEXT: 930 * raw_spin_lock_irq(pool->lock) 931 */ 932 static inline void worker_clr_flags(struct worker *worker, unsigned int flags) 933 { 934 struct worker_pool *pool = worker->pool; 935 unsigned int oflags = worker->flags; 936 937 WARN_ON_ONCE(worker->task != current); 938 939 worker->flags &= ~flags; 940 941 /* 942 * If transitioning out of NOT_RUNNING, increment nr_running. Note 943 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask 944 * of multiple flags, not a single flag. 945 */ 946 if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING)) 947 if (!(worker->flags & WORKER_NOT_RUNNING)) 948 pool->nr_running++; 949 } 950 951 /** 952 * wq_worker_running - a worker is running again 953 * @task: task waking up 954 * 955 * This function is called when a worker returns from schedule() 956 */ 957 void wq_worker_running(struct task_struct *task) 958 { 959 struct worker *worker = kthread_data(task); 960 961 if (!worker->sleeping) 962 return; 963 964 /* 965 * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check 966 * and the nr_running increment below, we may ruin the nr_running reset 967 * and leave with an unexpected pool->nr_running == 1 on the newly unbound 968 * pool. Protect against such race. 969 */ 970 preempt_disable(); 971 if (!(worker->flags & WORKER_NOT_RUNNING)) 972 worker->pool->nr_running++; 973 preempt_enable(); 974 975 /* 976 * CPU intensive auto-detection cares about how long a work item hogged 977 * CPU without sleeping. Reset the starting timestamp on wakeup. 978 */ 979 worker->current_at = worker->task->se.sum_exec_runtime; 980 981 worker->sleeping = 0; 982 } 983 984 /** 985 * wq_worker_sleeping - a worker is going to sleep 986 * @task: task going to sleep 987 * 988 * This function is called from schedule() when a busy worker is 989 * going to sleep. 990 */ 991 void wq_worker_sleeping(struct task_struct *task) 992 { 993 struct worker *worker = kthread_data(task); 994 struct worker_pool *pool; 995 996 /* 997 * Rescuers, which may not have all the fields set up like normal 998 * workers, also reach here, let's not access anything before 999 * checking NOT_RUNNING. 1000 */ 1001 if (worker->flags & WORKER_NOT_RUNNING) 1002 return; 1003 1004 pool = worker->pool; 1005 1006 /* Return if preempted before wq_worker_running() was reached */ 1007 if (worker->sleeping) 1008 return; 1009 1010 worker->sleeping = 1; 1011 raw_spin_lock_irq(&pool->lock); 1012 1013 /* 1014 * Recheck in case unbind_workers() preempted us. We don't 1015 * want to decrement nr_running after the worker is unbound 1016 * and nr_running has been reset. 1017 */ 1018 if (worker->flags & WORKER_NOT_RUNNING) { 1019 raw_spin_unlock_irq(&pool->lock); 1020 return; 1021 } 1022 1023 pool->nr_running--; 1024 if (need_more_worker(pool)) { 1025 worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++; 1026 wake_up_worker(pool); 1027 } 1028 raw_spin_unlock_irq(&pool->lock); 1029 } 1030 1031 /** 1032 * wq_worker_tick - a scheduler tick occurred while a kworker is running 1033 * @task: task currently running 1034 * 1035 * Called from scheduler_tick(). We're in the IRQ context and the current 1036 * worker's fields which follow the 'K' locking rule can be accessed safely. 1037 */ 1038 void wq_worker_tick(struct task_struct *task) 1039 { 1040 struct worker *worker = kthread_data(task); 1041 struct pool_workqueue *pwq = worker->current_pwq; 1042 struct worker_pool *pool = worker->pool; 1043 1044 if (!pwq) 1045 return; 1046 1047 /* 1048 * If the current worker is concurrency managed and hogged the CPU for 1049 * longer than wq_cpu_intensive_thresh_us, it's automatically marked 1050 * CPU_INTENSIVE to avoid stalling other concurrency-managed work items. 1051 */ 1052 if ((worker->flags & WORKER_NOT_RUNNING) || 1053 worker->task->se.sum_exec_runtime - worker->current_at < 1054 wq_cpu_intensive_thresh_us * NSEC_PER_USEC) 1055 return; 1056 1057 raw_spin_lock(&pool->lock); 1058 1059 worker_set_flags(worker, WORKER_CPU_INTENSIVE); 1060 pwq->stats[PWQ_STAT_CPU_INTENSIVE]++; 1061 1062 if (need_more_worker(pool)) { 1063 pwq->stats[PWQ_STAT_CM_WAKEUP]++; 1064 wake_up_worker(pool); 1065 } 1066 1067 raw_spin_unlock(&pool->lock); 1068 } 1069 1070 /** 1071 * wq_worker_last_func - retrieve worker's last work function 1072 * @task: Task to retrieve last work function of. 1073 * 1074 * Determine the last function a worker executed. This is called from 1075 * the scheduler to get a worker's last known identity. 1076 * 1077 * CONTEXT: 1078 * raw_spin_lock_irq(rq->lock) 1079 * 1080 * This function is called during schedule() when a kworker is going 1081 * to sleep. It's used by psi to identify aggregation workers during 1082 * dequeuing, to allow periodic aggregation to shut-off when that 1083 * worker is the last task in the system or cgroup to go to sleep. 1084 * 1085 * As this function doesn't involve any workqueue-related locking, it 1086 * only returns stable values when called from inside the scheduler's 1087 * queuing and dequeuing paths, when @task, which must be a kworker, 1088 * is guaranteed to not be processing any works. 1089 * 1090 * Return: 1091 * The last work function %current executed as a worker, NULL if it 1092 * hasn't executed any work yet. 1093 */ 1094 work_func_t wq_worker_last_func(struct task_struct *task) 1095 { 1096 struct worker *worker = kthread_data(task); 1097 1098 return worker->last_func; 1099 } 1100 1101 /** 1102 * find_worker_executing_work - find worker which is executing a work 1103 * @pool: pool of interest 1104 * @work: work to find worker for 1105 * 1106 * Find a worker which is executing @work on @pool by searching 1107 * @pool->busy_hash which is keyed by the address of @work. For a worker 1108 * to match, its current execution should match the address of @work and 1109 * its work function. This is to avoid unwanted dependency between 1110 * unrelated work executions through a work item being recycled while still 1111 * being executed. 1112 * 1113 * This is a bit tricky. A work item may be freed once its execution 1114 * starts and nothing prevents the freed area from being recycled for 1115 * another work item. If the same work item address ends up being reused 1116 * before the original execution finishes, workqueue will identify the 1117 * recycled work item as currently executing and make it wait until the 1118 * current execution finishes, introducing an unwanted dependency. 1119 * 1120 * This function checks the work item address and work function to avoid 1121 * false positives. Note that this isn't complete as one may construct a 1122 * work function which can introduce dependency onto itself through a 1123 * recycled work item. Well, if somebody wants to shoot oneself in the 1124 * foot that badly, there's only so much we can do, and if such deadlock 1125 * actually occurs, it should be easy to locate the culprit work function. 1126 * 1127 * CONTEXT: 1128 * raw_spin_lock_irq(pool->lock). 1129 * 1130 * Return: 1131 * Pointer to worker which is executing @work if found, %NULL 1132 * otherwise. 1133 */ 1134 static struct worker *find_worker_executing_work(struct worker_pool *pool, 1135 struct work_struct *work) 1136 { 1137 struct worker *worker; 1138 1139 hash_for_each_possible(pool->busy_hash, worker, hentry, 1140 (unsigned long)work) 1141 if (worker->current_work == work && 1142 worker->current_func == work->func) 1143 return worker; 1144 1145 return NULL; 1146 } 1147 1148 /** 1149 * move_linked_works - move linked works to a list 1150 * @work: start of series of works to be scheduled 1151 * @head: target list to append @work to 1152 * @nextp: out parameter for nested worklist walking 1153 * 1154 * Schedule linked works starting from @work to @head. Work series to 1155 * be scheduled starts at @work and includes any consecutive work with 1156 * WORK_STRUCT_LINKED set in its predecessor. 1157 * 1158 * If @nextp is not NULL, it's updated to point to the next work of 1159 * the last scheduled work. This allows move_linked_works() to be 1160 * nested inside outer list_for_each_entry_safe(). 1161 * 1162 * CONTEXT: 1163 * raw_spin_lock_irq(pool->lock). 1164 */ 1165 static void move_linked_works(struct work_struct *work, struct list_head *head, 1166 struct work_struct **nextp) 1167 { 1168 struct work_struct *n; 1169 1170 /* 1171 * Linked worklist will always end before the end of the list, 1172 * use NULL for list head. 1173 */ 1174 list_for_each_entry_safe_from(work, n, NULL, entry) { 1175 list_move_tail(&work->entry, head); 1176 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED)) 1177 break; 1178 } 1179 1180 /* 1181 * If we're already inside safe list traversal and have moved 1182 * multiple works to the scheduled queue, the next position 1183 * needs to be updated. 1184 */ 1185 if (nextp) 1186 *nextp = n; 1187 } 1188 1189 /** 1190 * get_pwq - get an extra reference on the specified pool_workqueue 1191 * @pwq: pool_workqueue to get 1192 * 1193 * Obtain an extra reference on @pwq. The caller should guarantee that 1194 * @pwq has positive refcnt and be holding the matching pool->lock. 1195 */ 1196 static void get_pwq(struct pool_workqueue *pwq) 1197 { 1198 lockdep_assert_held(&pwq->pool->lock); 1199 WARN_ON_ONCE(pwq->refcnt <= 0); 1200 pwq->refcnt++; 1201 } 1202 1203 /** 1204 * put_pwq - put a pool_workqueue reference 1205 * @pwq: pool_workqueue to put 1206 * 1207 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its 1208 * destruction. The caller should be holding the matching pool->lock. 1209 */ 1210 static void put_pwq(struct pool_workqueue *pwq) 1211 { 1212 lockdep_assert_held(&pwq->pool->lock); 1213 if (likely(--pwq->refcnt)) 1214 return; 1215 if (WARN_ON_ONCE(!(pwq->wq->flags & WQ_UNBOUND))) 1216 return; 1217 /* 1218 * @pwq can't be released under pool->lock, bounce to 1219 * pwq_unbound_release_workfn(). This never recurses on the same 1220 * pool->lock as this path is taken only for unbound workqueues and 1221 * the release work item is scheduled on a per-cpu workqueue. To 1222 * avoid lockdep warning, unbound pool->locks are given lockdep 1223 * subclass of 1 in get_unbound_pool(). 1224 */ 1225 schedule_work(&pwq->unbound_release_work); 1226 } 1227 1228 /** 1229 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock 1230 * @pwq: pool_workqueue to put (can be %NULL) 1231 * 1232 * put_pwq() with locking. This function also allows %NULL @pwq. 1233 */ 1234 static void put_pwq_unlocked(struct pool_workqueue *pwq) 1235 { 1236 if (pwq) { 1237 /* 1238 * As both pwqs and pools are RCU protected, the 1239 * following lock operations are safe. 1240 */ 1241 raw_spin_lock_irq(&pwq->pool->lock); 1242 put_pwq(pwq); 1243 raw_spin_unlock_irq(&pwq->pool->lock); 1244 } 1245 } 1246 1247 static void pwq_activate_inactive_work(struct work_struct *work) 1248 { 1249 struct pool_workqueue *pwq = get_work_pwq(work); 1250 1251 trace_workqueue_activate_work(work); 1252 if (list_empty(&pwq->pool->worklist)) 1253 pwq->pool->watchdog_ts = jiffies; 1254 move_linked_works(work, &pwq->pool->worklist, NULL); 1255 __clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work)); 1256 pwq->nr_active++; 1257 } 1258 1259 static void pwq_activate_first_inactive(struct pool_workqueue *pwq) 1260 { 1261 struct work_struct *work = list_first_entry(&pwq->inactive_works, 1262 struct work_struct, entry); 1263 1264 pwq_activate_inactive_work(work); 1265 } 1266 1267 /** 1268 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight 1269 * @pwq: pwq of interest 1270 * @work_data: work_data of work which left the queue 1271 * 1272 * A work either has completed or is removed from pending queue, 1273 * decrement nr_in_flight of its pwq and handle workqueue flushing. 1274 * 1275 * CONTEXT: 1276 * raw_spin_lock_irq(pool->lock). 1277 */ 1278 static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data) 1279 { 1280 int color = get_work_color(work_data); 1281 1282 if (!(work_data & WORK_STRUCT_INACTIVE)) { 1283 pwq->nr_active--; 1284 if (!list_empty(&pwq->inactive_works)) { 1285 /* one down, submit an inactive one */ 1286 if (pwq->nr_active < pwq->max_active) 1287 pwq_activate_first_inactive(pwq); 1288 } 1289 } 1290 1291 pwq->nr_in_flight[color]--; 1292 1293 /* is flush in progress and are we at the flushing tip? */ 1294 if (likely(pwq->flush_color != color)) 1295 goto out_put; 1296 1297 /* are there still in-flight works? */ 1298 if (pwq->nr_in_flight[color]) 1299 goto out_put; 1300 1301 /* this pwq is done, clear flush_color */ 1302 pwq->flush_color = -1; 1303 1304 /* 1305 * If this was the last pwq, wake up the first flusher. It 1306 * will handle the rest. 1307 */ 1308 if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush)) 1309 complete(&pwq->wq->first_flusher->done); 1310 out_put: 1311 put_pwq(pwq); 1312 } 1313 1314 /** 1315 * try_to_grab_pending - steal work item from worklist and disable irq 1316 * @work: work item to steal 1317 * @is_dwork: @work is a delayed_work 1318 * @flags: place to store irq state 1319 * 1320 * Try to grab PENDING bit of @work. This function can handle @work in any 1321 * stable state - idle, on timer or on worklist. 1322 * 1323 * Return: 1324 * 1325 * ======== ================================================================ 1326 * 1 if @work was pending and we successfully stole PENDING 1327 * 0 if @work was idle and we claimed PENDING 1328 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry 1329 * -ENOENT if someone else is canceling @work, this state may persist 1330 * for arbitrarily long 1331 * ======== ================================================================ 1332 * 1333 * Note: 1334 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting 1335 * interrupted while holding PENDING and @work off queue, irq must be 1336 * disabled on entry. This, combined with delayed_work->timer being 1337 * irqsafe, ensures that we return -EAGAIN for finite short period of time. 1338 * 1339 * On successful return, >= 0, irq is disabled and the caller is 1340 * responsible for releasing it using local_irq_restore(*@flags). 1341 * 1342 * This function is safe to call from any context including IRQ handler. 1343 */ 1344 static int try_to_grab_pending(struct work_struct *work, bool is_dwork, 1345 unsigned long *flags) 1346 { 1347 struct worker_pool *pool; 1348 struct pool_workqueue *pwq; 1349 1350 local_irq_save(*flags); 1351 1352 /* try to steal the timer if it exists */ 1353 if (is_dwork) { 1354 struct delayed_work *dwork = to_delayed_work(work); 1355 1356 /* 1357 * dwork->timer is irqsafe. If del_timer() fails, it's 1358 * guaranteed that the timer is not queued anywhere and not 1359 * running on the local CPU. 1360 */ 1361 if (likely(del_timer(&dwork->timer))) 1362 return 1; 1363 } 1364 1365 /* try to claim PENDING the normal way */ 1366 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) 1367 return 0; 1368 1369 rcu_read_lock(); 1370 /* 1371 * The queueing is in progress, or it is already queued. Try to 1372 * steal it from ->worklist without clearing WORK_STRUCT_PENDING. 1373 */ 1374 pool = get_work_pool(work); 1375 if (!pool) 1376 goto fail; 1377 1378 raw_spin_lock(&pool->lock); 1379 /* 1380 * work->data is guaranteed to point to pwq only while the work 1381 * item is queued on pwq->wq, and both updating work->data to point 1382 * to pwq on queueing and to pool on dequeueing are done under 1383 * pwq->pool->lock. This in turn guarantees that, if work->data 1384 * points to pwq which is associated with a locked pool, the work 1385 * item is currently queued on that pool. 1386 */ 1387 pwq = get_work_pwq(work); 1388 if (pwq && pwq->pool == pool) { 1389 debug_work_deactivate(work); 1390 1391 /* 1392 * A cancelable inactive work item must be in the 1393 * pwq->inactive_works since a queued barrier can't be 1394 * canceled (see the comments in insert_wq_barrier()). 1395 * 1396 * An inactive work item cannot be grabbed directly because 1397 * it might have linked barrier work items which, if left 1398 * on the inactive_works list, will confuse pwq->nr_active 1399 * management later on and cause stall. Make sure the work 1400 * item is activated before grabbing. 1401 */ 1402 if (*work_data_bits(work) & WORK_STRUCT_INACTIVE) 1403 pwq_activate_inactive_work(work); 1404 1405 list_del_init(&work->entry); 1406 pwq_dec_nr_in_flight(pwq, *work_data_bits(work)); 1407 1408 /* work->data points to pwq iff queued, point to pool */ 1409 set_work_pool_and_keep_pending(work, pool->id); 1410 1411 raw_spin_unlock(&pool->lock); 1412 rcu_read_unlock(); 1413 return 1; 1414 } 1415 raw_spin_unlock(&pool->lock); 1416 fail: 1417 rcu_read_unlock(); 1418 local_irq_restore(*flags); 1419 if (work_is_canceling(work)) 1420 return -ENOENT; 1421 cpu_relax(); 1422 return -EAGAIN; 1423 } 1424 1425 /** 1426 * insert_work - insert a work into a pool 1427 * @pwq: pwq @work belongs to 1428 * @work: work to insert 1429 * @head: insertion point 1430 * @extra_flags: extra WORK_STRUCT_* flags to set 1431 * 1432 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to 1433 * work_struct flags. 1434 * 1435 * CONTEXT: 1436 * raw_spin_lock_irq(pool->lock). 1437 */ 1438 static void insert_work(struct pool_workqueue *pwq, struct work_struct *work, 1439 struct list_head *head, unsigned int extra_flags) 1440 { 1441 struct worker_pool *pool = pwq->pool; 1442 1443 /* record the work call stack in order to print it in KASAN reports */ 1444 kasan_record_aux_stack_noalloc(work); 1445 1446 /* we own @work, set data and link */ 1447 set_work_pwq(work, pwq, extra_flags); 1448 list_add_tail(&work->entry, head); 1449 get_pwq(pwq); 1450 1451 if (__need_more_worker(pool)) 1452 wake_up_worker(pool); 1453 } 1454 1455 /* 1456 * Test whether @work is being queued from another work executing on the 1457 * same workqueue. 1458 */ 1459 static bool is_chained_work(struct workqueue_struct *wq) 1460 { 1461 struct worker *worker; 1462 1463 worker = current_wq_worker(); 1464 /* 1465 * Return %true iff I'm a worker executing a work item on @wq. If 1466 * I'm @worker, it's safe to dereference it without locking. 1467 */ 1468 return worker && worker->current_pwq->wq == wq; 1469 } 1470 1471 /* 1472 * When queueing an unbound work item to a wq, prefer local CPU if allowed 1473 * by wq_unbound_cpumask. Otherwise, round robin among the allowed ones to 1474 * avoid perturbing sensitive tasks. 1475 */ 1476 static int wq_select_unbound_cpu(int cpu) 1477 { 1478 int new_cpu; 1479 1480 if (likely(!wq_debug_force_rr_cpu)) { 1481 if (cpumask_test_cpu(cpu, wq_unbound_cpumask)) 1482 return cpu; 1483 } else { 1484 pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n"); 1485 } 1486 1487 if (cpumask_empty(wq_unbound_cpumask)) 1488 return cpu; 1489 1490 new_cpu = __this_cpu_read(wq_rr_cpu_last); 1491 new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask); 1492 if (unlikely(new_cpu >= nr_cpu_ids)) { 1493 new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask); 1494 if (unlikely(new_cpu >= nr_cpu_ids)) 1495 return cpu; 1496 } 1497 __this_cpu_write(wq_rr_cpu_last, new_cpu); 1498 1499 return new_cpu; 1500 } 1501 1502 static void __queue_work(int cpu, struct workqueue_struct *wq, 1503 struct work_struct *work) 1504 { 1505 struct pool_workqueue *pwq; 1506 struct worker_pool *last_pool; 1507 struct list_head *worklist; 1508 unsigned int work_flags; 1509 unsigned int req_cpu = cpu; 1510 1511 /* 1512 * While a work item is PENDING && off queue, a task trying to 1513 * steal the PENDING will busy-loop waiting for it to either get 1514 * queued or lose PENDING. Grabbing PENDING and queueing should 1515 * happen with IRQ disabled. 1516 */ 1517 lockdep_assert_irqs_disabled(); 1518 1519 1520 /* 1521 * For a draining wq, only works from the same workqueue are 1522 * allowed. The __WQ_DESTROYING helps to spot the issue that 1523 * queues a new work item to a wq after destroy_workqueue(wq). 1524 */ 1525 if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) && 1526 WARN_ON_ONCE(!is_chained_work(wq)))) 1527 return; 1528 rcu_read_lock(); 1529 retry: 1530 /* pwq which will be used unless @work is executing elsewhere */ 1531 if (wq->flags & WQ_UNBOUND) { 1532 if (req_cpu == WORK_CPU_UNBOUND) 1533 cpu = wq_select_unbound_cpu(raw_smp_processor_id()); 1534 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu)); 1535 } else { 1536 if (req_cpu == WORK_CPU_UNBOUND) 1537 cpu = raw_smp_processor_id(); 1538 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu); 1539 } 1540 1541 /* 1542 * If @work was previously on a different pool, it might still be 1543 * running there, in which case the work needs to be queued on that 1544 * pool to guarantee non-reentrancy. 1545 */ 1546 last_pool = get_work_pool(work); 1547 if (last_pool && last_pool != pwq->pool) { 1548 struct worker *worker; 1549 1550 raw_spin_lock(&last_pool->lock); 1551 1552 worker = find_worker_executing_work(last_pool, work); 1553 1554 if (worker && worker->current_pwq->wq == wq) { 1555 pwq = worker->current_pwq; 1556 } else { 1557 /* meh... not running there, queue here */ 1558 raw_spin_unlock(&last_pool->lock); 1559 raw_spin_lock(&pwq->pool->lock); 1560 } 1561 } else { 1562 raw_spin_lock(&pwq->pool->lock); 1563 } 1564 1565 /* 1566 * pwq is determined and locked. For unbound pools, we could have 1567 * raced with pwq release and it could already be dead. If its 1568 * refcnt is zero, repeat pwq selection. Note that pwqs never die 1569 * without another pwq replacing it in the numa_pwq_tbl or while 1570 * work items are executing on it, so the retrying is guaranteed to 1571 * make forward-progress. 1572 */ 1573 if (unlikely(!pwq->refcnt)) { 1574 if (wq->flags & WQ_UNBOUND) { 1575 raw_spin_unlock(&pwq->pool->lock); 1576 cpu_relax(); 1577 goto retry; 1578 } 1579 /* oops */ 1580 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt", 1581 wq->name, cpu); 1582 } 1583 1584 /* pwq determined, queue */ 1585 trace_workqueue_queue_work(req_cpu, pwq, work); 1586 1587 if (WARN_ON(!list_empty(&work->entry))) 1588 goto out; 1589 1590 pwq->nr_in_flight[pwq->work_color]++; 1591 work_flags = work_color_to_flags(pwq->work_color); 1592 1593 if (likely(pwq->nr_active < pwq->max_active)) { 1594 trace_workqueue_activate_work(work); 1595 pwq->nr_active++; 1596 worklist = &pwq->pool->worklist; 1597 if (list_empty(worklist)) 1598 pwq->pool->watchdog_ts = jiffies; 1599 } else { 1600 work_flags |= WORK_STRUCT_INACTIVE; 1601 worklist = &pwq->inactive_works; 1602 } 1603 1604 debug_work_activate(work); 1605 insert_work(pwq, work, worklist, work_flags); 1606 1607 out: 1608 raw_spin_unlock(&pwq->pool->lock); 1609 rcu_read_unlock(); 1610 } 1611 1612 /** 1613 * queue_work_on - queue work on specific cpu 1614 * @cpu: CPU number to execute work on 1615 * @wq: workqueue to use 1616 * @work: work to queue 1617 * 1618 * We queue the work to a specific CPU, the caller must ensure it 1619 * can't go away. Callers that fail to ensure that the specified 1620 * CPU cannot go away will execute on a randomly chosen CPU. 1621 * But note well that callers specifying a CPU that never has been 1622 * online will get a splat. 1623 * 1624 * Return: %false if @work was already on a queue, %true otherwise. 1625 */ 1626 bool queue_work_on(int cpu, struct workqueue_struct *wq, 1627 struct work_struct *work) 1628 { 1629 bool ret = false; 1630 unsigned long flags; 1631 1632 local_irq_save(flags); 1633 1634 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) { 1635 __queue_work(cpu, wq, work); 1636 ret = true; 1637 } 1638 1639 local_irq_restore(flags); 1640 return ret; 1641 } 1642 EXPORT_SYMBOL(queue_work_on); 1643 1644 /** 1645 * workqueue_select_cpu_near - Select a CPU based on NUMA node 1646 * @node: NUMA node ID that we want to select a CPU from 1647 * 1648 * This function will attempt to find a "random" cpu available on a given 1649 * node. If there are no CPUs available on the given node it will return 1650 * WORK_CPU_UNBOUND indicating that we should just schedule to any 1651 * available CPU if we need to schedule this work. 1652 */ 1653 static int workqueue_select_cpu_near(int node) 1654 { 1655 int cpu; 1656 1657 /* No point in doing this if NUMA isn't enabled for workqueues */ 1658 if (!wq_numa_enabled) 1659 return WORK_CPU_UNBOUND; 1660 1661 /* Delay binding to CPU if node is not valid or online */ 1662 if (node < 0 || node >= MAX_NUMNODES || !node_online(node)) 1663 return WORK_CPU_UNBOUND; 1664 1665 /* Use local node/cpu if we are already there */ 1666 cpu = raw_smp_processor_id(); 1667 if (node == cpu_to_node(cpu)) 1668 return cpu; 1669 1670 /* Use "random" otherwise know as "first" online CPU of node */ 1671 cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask); 1672 1673 /* If CPU is valid return that, otherwise just defer */ 1674 return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND; 1675 } 1676 1677 /** 1678 * queue_work_node - queue work on a "random" cpu for a given NUMA node 1679 * @node: NUMA node that we are targeting the work for 1680 * @wq: workqueue to use 1681 * @work: work to queue 1682 * 1683 * We queue the work to a "random" CPU within a given NUMA node. The basic 1684 * idea here is to provide a way to somehow associate work with a given 1685 * NUMA node. 1686 * 1687 * This function will only make a best effort attempt at getting this onto 1688 * the right NUMA node. If no node is requested or the requested node is 1689 * offline then we just fall back to standard queue_work behavior. 1690 * 1691 * Currently the "random" CPU ends up being the first available CPU in the 1692 * intersection of cpu_online_mask and the cpumask of the node, unless we 1693 * are running on the node. In that case we just use the current CPU. 1694 * 1695 * Return: %false if @work was already on a queue, %true otherwise. 1696 */ 1697 bool queue_work_node(int node, struct workqueue_struct *wq, 1698 struct work_struct *work) 1699 { 1700 unsigned long flags; 1701 bool ret = false; 1702 1703 /* 1704 * This current implementation is specific to unbound workqueues. 1705 * Specifically we only return the first available CPU for a given 1706 * node instead of cycling through individual CPUs within the node. 1707 * 1708 * If this is used with a per-cpu workqueue then the logic in 1709 * workqueue_select_cpu_near would need to be updated to allow for 1710 * some round robin type logic. 1711 */ 1712 WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND)); 1713 1714 local_irq_save(flags); 1715 1716 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) { 1717 int cpu = workqueue_select_cpu_near(node); 1718 1719 __queue_work(cpu, wq, work); 1720 ret = true; 1721 } 1722 1723 local_irq_restore(flags); 1724 return ret; 1725 } 1726 EXPORT_SYMBOL_GPL(queue_work_node); 1727 1728 void delayed_work_timer_fn(struct timer_list *t) 1729 { 1730 struct delayed_work *dwork = from_timer(dwork, t, timer); 1731 1732 /* should have been called from irqsafe timer with irq already off */ 1733 __queue_work(dwork->cpu, dwork->wq, &dwork->work); 1734 } 1735 EXPORT_SYMBOL(delayed_work_timer_fn); 1736 1737 static void __queue_delayed_work(int cpu, struct workqueue_struct *wq, 1738 struct delayed_work *dwork, unsigned long delay) 1739 { 1740 struct timer_list *timer = &dwork->timer; 1741 struct work_struct *work = &dwork->work; 1742 1743 WARN_ON_ONCE(!wq); 1744 WARN_ON_ONCE(timer->function != delayed_work_timer_fn); 1745 WARN_ON_ONCE(timer_pending(timer)); 1746 WARN_ON_ONCE(!list_empty(&work->entry)); 1747 1748 /* 1749 * If @delay is 0, queue @dwork->work immediately. This is for 1750 * both optimization and correctness. The earliest @timer can 1751 * expire is on the closest next tick and delayed_work users depend 1752 * on that there's no such delay when @delay is 0. 1753 */ 1754 if (!delay) { 1755 __queue_work(cpu, wq, &dwork->work); 1756 return; 1757 } 1758 1759 dwork->wq = wq; 1760 dwork->cpu = cpu; 1761 timer->expires = jiffies + delay; 1762 1763 if (unlikely(cpu != WORK_CPU_UNBOUND)) 1764 add_timer_on(timer, cpu); 1765 else 1766 add_timer(timer); 1767 } 1768 1769 /** 1770 * queue_delayed_work_on - queue work on specific CPU after delay 1771 * @cpu: CPU number to execute work on 1772 * @wq: workqueue to use 1773 * @dwork: work to queue 1774 * @delay: number of jiffies to wait before queueing 1775 * 1776 * Return: %false if @work was already on a queue, %true otherwise. If 1777 * @delay is zero and @dwork is idle, it will be scheduled for immediate 1778 * execution. 1779 */ 1780 bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq, 1781 struct delayed_work *dwork, unsigned long delay) 1782 { 1783 struct work_struct *work = &dwork->work; 1784 bool ret = false; 1785 unsigned long flags; 1786 1787 /* read the comment in __queue_work() */ 1788 local_irq_save(flags); 1789 1790 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) { 1791 __queue_delayed_work(cpu, wq, dwork, delay); 1792 ret = true; 1793 } 1794 1795 local_irq_restore(flags); 1796 return ret; 1797 } 1798 EXPORT_SYMBOL(queue_delayed_work_on); 1799 1800 /** 1801 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU 1802 * @cpu: CPU number to execute work on 1803 * @wq: workqueue to use 1804 * @dwork: work to queue 1805 * @delay: number of jiffies to wait before queueing 1806 * 1807 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise, 1808 * modify @dwork's timer so that it expires after @delay. If @delay is 1809 * zero, @work is guaranteed to be scheduled immediately regardless of its 1810 * current state. 1811 * 1812 * Return: %false if @dwork was idle and queued, %true if @dwork was 1813 * pending and its timer was modified. 1814 * 1815 * This function is safe to call from any context including IRQ handler. 1816 * See try_to_grab_pending() for details. 1817 */ 1818 bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq, 1819 struct delayed_work *dwork, unsigned long delay) 1820 { 1821 unsigned long flags; 1822 int ret; 1823 1824 do { 1825 ret = try_to_grab_pending(&dwork->work, true, &flags); 1826 } while (unlikely(ret == -EAGAIN)); 1827 1828 if (likely(ret >= 0)) { 1829 __queue_delayed_work(cpu, wq, dwork, delay); 1830 local_irq_restore(flags); 1831 } 1832 1833 /* -ENOENT from try_to_grab_pending() becomes %true */ 1834 return ret; 1835 } 1836 EXPORT_SYMBOL_GPL(mod_delayed_work_on); 1837 1838 static void rcu_work_rcufn(struct rcu_head *rcu) 1839 { 1840 struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu); 1841 1842 /* read the comment in __queue_work() */ 1843 local_irq_disable(); 1844 __queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work); 1845 local_irq_enable(); 1846 } 1847 1848 /** 1849 * queue_rcu_work - queue work after a RCU grace period 1850 * @wq: workqueue to use 1851 * @rwork: work to queue 1852 * 1853 * Return: %false if @rwork was already pending, %true otherwise. Note 1854 * that a full RCU grace period is guaranteed only after a %true return. 1855 * While @rwork is guaranteed to be executed after a %false return, the 1856 * execution may happen before a full RCU grace period has passed. 1857 */ 1858 bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork) 1859 { 1860 struct work_struct *work = &rwork->work; 1861 1862 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) { 1863 rwork->wq = wq; 1864 call_rcu_hurry(&rwork->rcu, rcu_work_rcufn); 1865 return true; 1866 } 1867 1868 return false; 1869 } 1870 EXPORT_SYMBOL(queue_rcu_work); 1871 1872 /** 1873 * worker_enter_idle - enter idle state 1874 * @worker: worker which is entering idle state 1875 * 1876 * @worker is entering idle state. Update stats and idle timer if 1877 * necessary. 1878 * 1879 * LOCKING: 1880 * raw_spin_lock_irq(pool->lock). 1881 */ 1882 static void worker_enter_idle(struct worker *worker) 1883 { 1884 struct worker_pool *pool = worker->pool; 1885 1886 if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) || 1887 WARN_ON_ONCE(!list_empty(&worker->entry) && 1888 (worker->hentry.next || worker->hentry.pprev))) 1889 return; 1890 1891 /* can't use worker_set_flags(), also called from create_worker() */ 1892 worker->flags |= WORKER_IDLE; 1893 pool->nr_idle++; 1894 worker->last_active = jiffies; 1895 1896 /* idle_list is LIFO */ 1897 list_add(&worker->entry, &pool->idle_list); 1898 1899 if (too_many_workers(pool) && !timer_pending(&pool->idle_timer)) 1900 mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT); 1901 1902 /* Sanity check nr_running. */ 1903 WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running); 1904 } 1905 1906 /** 1907 * worker_leave_idle - leave idle state 1908 * @worker: worker which is leaving idle state 1909 * 1910 * @worker is leaving idle state. Update stats. 1911 * 1912 * LOCKING: 1913 * raw_spin_lock_irq(pool->lock). 1914 */ 1915 static void worker_leave_idle(struct worker *worker) 1916 { 1917 struct worker_pool *pool = worker->pool; 1918 1919 if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE))) 1920 return; 1921 worker_clr_flags(worker, WORKER_IDLE); 1922 pool->nr_idle--; 1923 list_del_init(&worker->entry); 1924 } 1925 1926 static struct worker *alloc_worker(int node) 1927 { 1928 struct worker *worker; 1929 1930 worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node); 1931 if (worker) { 1932 INIT_LIST_HEAD(&worker->entry); 1933 INIT_LIST_HEAD(&worker->scheduled); 1934 INIT_LIST_HEAD(&worker->node); 1935 /* on creation a worker is in !idle && prep state */ 1936 worker->flags = WORKER_PREP; 1937 } 1938 return worker; 1939 } 1940 1941 /** 1942 * worker_attach_to_pool() - attach a worker to a pool 1943 * @worker: worker to be attached 1944 * @pool: the target pool 1945 * 1946 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and 1947 * cpu-binding of @worker are kept coordinated with the pool across 1948 * cpu-[un]hotplugs. 1949 */ 1950 static void worker_attach_to_pool(struct worker *worker, 1951 struct worker_pool *pool) 1952 { 1953 mutex_lock(&wq_pool_attach_mutex); 1954 1955 /* 1956 * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains 1957 * stable across this function. See the comments above the flag 1958 * definition for details. 1959 */ 1960 if (pool->flags & POOL_DISASSOCIATED) 1961 worker->flags |= WORKER_UNBOUND; 1962 else 1963 kthread_set_per_cpu(worker->task, pool->cpu); 1964 1965 if (worker->rescue_wq) 1966 set_cpus_allowed_ptr(worker->task, pool->attrs->cpumask); 1967 1968 list_add_tail(&worker->node, &pool->workers); 1969 worker->pool = pool; 1970 1971 mutex_unlock(&wq_pool_attach_mutex); 1972 } 1973 1974 /** 1975 * worker_detach_from_pool() - detach a worker from its pool 1976 * @worker: worker which is attached to its pool 1977 * 1978 * Undo the attaching which had been done in worker_attach_to_pool(). The 1979 * caller worker shouldn't access to the pool after detached except it has 1980 * other reference to the pool. 1981 */ 1982 static void worker_detach_from_pool(struct worker *worker) 1983 { 1984 struct worker_pool *pool = worker->pool; 1985 struct completion *detach_completion = NULL; 1986 1987 mutex_lock(&wq_pool_attach_mutex); 1988 1989 kthread_set_per_cpu(worker->task, -1); 1990 list_del(&worker->node); 1991 worker->pool = NULL; 1992 1993 if (list_empty(&pool->workers) && list_empty(&pool->dying_workers)) 1994 detach_completion = pool->detach_completion; 1995 mutex_unlock(&wq_pool_attach_mutex); 1996 1997 /* clear leftover flags without pool->lock after it is detached */ 1998 worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND); 1999 2000 if (detach_completion) 2001 complete(detach_completion); 2002 } 2003 2004 /** 2005 * create_worker - create a new workqueue worker 2006 * @pool: pool the new worker will belong to 2007 * 2008 * Create and start a new worker which is attached to @pool. 2009 * 2010 * CONTEXT: 2011 * Might sleep. Does GFP_KERNEL allocations. 2012 * 2013 * Return: 2014 * Pointer to the newly created worker. 2015 */ 2016 static struct worker *create_worker(struct worker_pool *pool) 2017 { 2018 struct worker *worker; 2019 int id; 2020 char id_buf[16]; 2021 2022 /* ID is needed to determine kthread name */ 2023 id = ida_alloc(&pool->worker_ida, GFP_KERNEL); 2024 if (id < 0) { 2025 pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n", 2026 ERR_PTR(id)); 2027 return NULL; 2028 } 2029 2030 worker = alloc_worker(pool->node); 2031 if (!worker) { 2032 pr_err_once("workqueue: Failed to allocate a worker\n"); 2033 goto fail; 2034 } 2035 2036 worker->id = id; 2037 2038 if (pool->cpu >= 0) 2039 snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id, 2040 pool->attrs->nice < 0 ? "H" : ""); 2041 else 2042 snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id); 2043 2044 worker->task = kthread_create_on_node(worker_thread, worker, pool->node, 2045 "kworker/%s", id_buf); 2046 if (IS_ERR(worker->task)) { 2047 if (PTR_ERR(worker->task) == -EINTR) { 2048 pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n", 2049 id_buf); 2050 } else { 2051 pr_err_once("workqueue: Failed to create a worker thread: %pe", 2052 worker->task); 2053 } 2054 goto fail; 2055 } 2056 2057 set_user_nice(worker->task, pool->attrs->nice); 2058 kthread_bind_mask(worker->task, pool->attrs->cpumask); 2059 2060 /* successful, attach the worker to the pool */ 2061 worker_attach_to_pool(worker, pool); 2062 2063 /* start the newly created worker */ 2064 raw_spin_lock_irq(&pool->lock); 2065 worker->pool->nr_workers++; 2066 worker_enter_idle(worker); 2067 wake_up_process(worker->task); 2068 raw_spin_unlock_irq(&pool->lock); 2069 2070 return worker; 2071 2072 fail: 2073 ida_free(&pool->worker_ida, id); 2074 kfree(worker); 2075 return NULL; 2076 } 2077 2078 static void unbind_worker(struct worker *worker) 2079 { 2080 lockdep_assert_held(&wq_pool_attach_mutex); 2081 2082 kthread_set_per_cpu(worker->task, -1); 2083 if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask)) 2084 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0); 2085 else 2086 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0); 2087 } 2088 2089 static void wake_dying_workers(struct list_head *cull_list) 2090 { 2091 struct worker *worker, *tmp; 2092 2093 list_for_each_entry_safe(worker, tmp, cull_list, entry) { 2094 list_del_init(&worker->entry); 2095 unbind_worker(worker); 2096 /* 2097 * If the worker was somehow already running, then it had to be 2098 * in pool->idle_list when set_worker_dying() happened or we 2099 * wouldn't have gotten here. 2100 * 2101 * Thus, the worker must either have observed the WORKER_DIE 2102 * flag, or have set its state to TASK_IDLE. Either way, the 2103 * below will be observed by the worker and is safe to do 2104 * outside of pool->lock. 2105 */ 2106 wake_up_process(worker->task); 2107 } 2108 } 2109 2110 /** 2111 * set_worker_dying - Tag a worker for destruction 2112 * @worker: worker to be destroyed 2113 * @list: transfer worker away from its pool->idle_list and into list 2114 * 2115 * Tag @worker for destruction and adjust @pool stats accordingly. The worker 2116 * should be idle. 2117 * 2118 * CONTEXT: 2119 * raw_spin_lock_irq(pool->lock). 2120 */ 2121 static void set_worker_dying(struct worker *worker, struct list_head *list) 2122 { 2123 struct worker_pool *pool = worker->pool; 2124 2125 lockdep_assert_held(&pool->lock); 2126 lockdep_assert_held(&wq_pool_attach_mutex); 2127 2128 /* sanity check frenzy */ 2129 if (WARN_ON(worker->current_work) || 2130 WARN_ON(!list_empty(&worker->scheduled)) || 2131 WARN_ON(!(worker->flags & WORKER_IDLE))) 2132 return; 2133 2134 pool->nr_workers--; 2135 pool->nr_idle--; 2136 2137 worker->flags |= WORKER_DIE; 2138 2139 list_move(&worker->entry, list); 2140 list_move(&worker->node, &pool->dying_workers); 2141 } 2142 2143 /** 2144 * idle_worker_timeout - check if some idle workers can now be deleted. 2145 * @t: The pool's idle_timer that just expired 2146 * 2147 * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in 2148 * worker_leave_idle(), as a worker flicking between idle and active while its 2149 * pool is at the too_many_workers() tipping point would cause too much timer 2150 * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let 2151 * it expire and re-evaluate things from there. 2152 */ 2153 static void idle_worker_timeout(struct timer_list *t) 2154 { 2155 struct worker_pool *pool = from_timer(pool, t, idle_timer); 2156 bool do_cull = false; 2157 2158 if (work_pending(&pool->idle_cull_work)) 2159 return; 2160 2161 raw_spin_lock_irq(&pool->lock); 2162 2163 if (too_many_workers(pool)) { 2164 struct worker *worker; 2165 unsigned long expires; 2166 2167 /* idle_list is kept in LIFO order, check the last one */ 2168 worker = list_entry(pool->idle_list.prev, struct worker, entry); 2169 expires = worker->last_active + IDLE_WORKER_TIMEOUT; 2170 do_cull = !time_before(jiffies, expires); 2171 2172 if (!do_cull) 2173 mod_timer(&pool->idle_timer, expires); 2174 } 2175 raw_spin_unlock_irq(&pool->lock); 2176 2177 if (do_cull) 2178 queue_work(system_unbound_wq, &pool->idle_cull_work); 2179 } 2180 2181 /** 2182 * idle_cull_fn - cull workers that have been idle for too long. 2183 * @work: the pool's work for handling these idle workers 2184 * 2185 * This goes through a pool's idle workers and gets rid of those that have been 2186 * idle for at least IDLE_WORKER_TIMEOUT seconds. 2187 * 2188 * We don't want to disturb isolated CPUs because of a pcpu kworker being 2189 * culled, so this also resets worker affinity. This requires a sleepable 2190 * context, hence the split between timer callback and work item. 2191 */ 2192 static void idle_cull_fn(struct work_struct *work) 2193 { 2194 struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work); 2195 struct list_head cull_list; 2196 2197 INIT_LIST_HEAD(&cull_list); 2198 /* 2199 * Grabbing wq_pool_attach_mutex here ensures an already-running worker 2200 * cannot proceed beyong worker_detach_from_pool() in its self-destruct 2201 * path. This is required as a previously-preempted worker could run after 2202 * set_worker_dying() has happened but before wake_dying_workers() did. 2203 */ 2204 mutex_lock(&wq_pool_attach_mutex); 2205 raw_spin_lock_irq(&pool->lock); 2206 2207 while (too_many_workers(pool)) { 2208 struct worker *worker; 2209 unsigned long expires; 2210 2211 worker = list_entry(pool->idle_list.prev, struct worker, entry); 2212 expires = worker->last_active + IDLE_WORKER_TIMEOUT; 2213 2214 if (time_before(jiffies, expires)) { 2215 mod_timer(&pool->idle_timer, expires); 2216 break; 2217 } 2218 2219 set_worker_dying(worker, &cull_list); 2220 } 2221 2222 raw_spin_unlock_irq(&pool->lock); 2223 wake_dying_workers(&cull_list); 2224 mutex_unlock(&wq_pool_attach_mutex); 2225 } 2226 2227 static void send_mayday(struct work_struct *work) 2228 { 2229 struct pool_workqueue *pwq = get_work_pwq(work); 2230 struct workqueue_struct *wq = pwq->wq; 2231 2232 lockdep_assert_held(&wq_mayday_lock); 2233 2234 if (!wq->rescuer) 2235 return; 2236 2237 /* mayday mayday mayday */ 2238 if (list_empty(&pwq->mayday_node)) { 2239 /* 2240 * If @pwq is for an unbound wq, its base ref may be put at 2241 * any time due to an attribute change. Pin @pwq until the 2242 * rescuer is done with it. 2243 */ 2244 get_pwq(pwq); 2245 list_add_tail(&pwq->mayday_node, &wq->maydays); 2246 wake_up_process(wq->rescuer->task); 2247 pwq->stats[PWQ_STAT_MAYDAY]++; 2248 } 2249 } 2250 2251 static void pool_mayday_timeout(struct timer_list *t) 2252 { 2253 struct worker_pool *pool = from_timer(pool, t, mayday_timer); 2254 struct work_struct *work; 2255 2256 raw_spin_lock_irq(&pool->lock); 2257 raw_spin_lock(&wq_mayday_lock); /* for wq->maydays */ 2258 2259 if (need_to_create_worker(pool)) { 2260 /* 2261 * We've been trying to create a new worker but 2262 * haven't been successful. We might be hitting an 2263 * allocation deadlock. Send distress signals to 2264 * rescuers. 2265 */ 2266 list_for_each_entry(work, &pool->worklist, entry) 2267 send_mayday(work); 2268 } 2269 2270 raw_spin_unlock(&wq_mayday_lock); 2271 raw_spin_unlock_irq(&pool->lock); 2272 2273 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL); 2274 } 2275 2276 /** 2277 * maybe_create_worker - create a new worker if necessary 2278 * @pool: pool to create a new worker for 2279 * 2280 * Create a new worker for @pool if necessary. @pool is guaranteed to 2281 * have at least one idle worker on return from this function. If 2282 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is 2283 * sent to all rescuers with works scheduled on @pool to resolve 2284 * possible allocation deadlock. 2285 * 2286 * On return, need_to_create_worker() is guaranteed to be %false and 2287 * may_start_working() %true. 2288 * 2289 * LOCKING: 2290 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed 2291 * multiple times. Does GFP_KERNEL allocations. Called only from 2292 * manager. 2293 */ 2294 static void maybe_create_worker(struct worker_pool *pool) 2295 __releases(&pool->lock) 2296 __acquires(&pool->lock) 2297 { 2298 restart: 2299 raw_spin_unlock_irq(&pool->lock); 2300 2301 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */ 2302 mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT); 2303 2304 while (true) { 2305 if (create_worker(pool) || !need_to_create_worker(pool)) 2306 break; 2307 2308 schedule_timeout_interruptible(CREATE_COOLDOWN); 2309 2310 if (!need_to_create_worker(pool)) 2311 break; 2312 } 2313 2314 del_timer_sync(&pool->mayday_timer); 2315 raw_spin_lock_irq(&pool->lock); 2316 /* 2317 * This is necessary even after a new worker was just successfully 2318 * created as @pool->lock was dropped and the new worker might have 2319 * already become busy. 2320 */ 2321 if (need_to_create_worker(pool)) 2322 goto restart; 2323 } 2324 2325 /** 2326 * manage_workers - manage worker pool 2327 * @worker: self 2328 * 2329 * Assume the manager role and manage the worker pool @worker belongs 2330 * to. At any given time, there can be only zero or one manager per 2331 * pool. The exclusion is handled automatically by this function. 2332 * 2333 * The caller can safely start processing works on false return. On 2334 * true return, it's guaranteed that need_to_create_worker() is false 2335 * and may_start_working() is true. 2336 * 2337 * CONTEXT: 2338 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed 2339 * multiple times. Does GFP_KERNEL allocations. 2340 * 2341 * Return: 2342 * %false if the pool doesn't need management and the caller can safely 2343 * start processing works, %true if management function was performed and 2344 * the conditions that the caller verified before calling the function may 2345 * no longer be true. 2346 */ 2347 static bool manage_workers(struct worker *worker) 2348 { 2349 struct worker_pool *pool = worker->pool; 2350 2351 if (pool->flags & POOL_MANAGER_ACTIVE) 2352 return false; 2353 2354 pool->flags |= POOL_MANAGER_ACTIVE; 2355 pool->manager = worker; 2356 2357 maybe_create_worker(pool); 2358 2359 pool->manager = NULL; 2360 pool->flags &= ~POOL_MANAGER_ACTIVE; 2361 rcuwait_wake_up(&manager_wait); 2362 return true; 2363 } 2364 2365 /** 2366 * process_one_work - process single work 2367 * @worker: self 2368 * @work: work to process 2369 * 2370 * Process @work. This function contains all the logics necessary to 2371 * process a single work including synchronization against and 2372 * interaction with other workers on the same cpu, queueing and 2373 * flushing. As long as context requirement is met, any worker can 2374 * call this function to process a work. 2375 * 2376 * CONTEXT: 2377 * raw_spin_lock_irq(pool->lock) which is released and regrabbed. 2378 */ 2379 static void process_one_work(struct worker *worker, struct work_struct *work) 2380 __releases(&pool->lock) 2381 __acquires(&pool->lock) 2382 { 2383 struct pool_workqueue *pwq = get_work_pwq(work); 2384 struct worker_pool *pool = worker->pool; 2385 unsigned long work_data; 2386 struct worker *collision; 2387 #ifdef CONFIG_LOCKDEP 2388 /* 2389 * It is permissible to free the struct work_struct from 2390 * inside the function that is called from it, this we need to 2391 * take into account for lockdep too. To avoid bogus "held 2392 * lock freed" warnings as well as problems when looking into 2393 * work->lockdep_map, make a copy and use that here. 2394 */ 2395 struct lockdep_map lockdep_map; 2396 2397 lockdep_copy_map(&lockdep_map, &work->lockdep_map); 2398 #endif 2399 /* ensure we're on the correct CPU */ 2400 WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) && 2401 raw_smp_processor_id() != pool->cpu); 2402 2403 /* 2404 * A single work shouldn't be executed concurrently by 2405 * multiple workers on a single cpu. Check whether anyone is 2406 * already processing the work. If so, defer the work to the 2407 * currently executing one. 2408 */ 2409 collision = find_worker_executing_work(pool, work); 2410 if (unlikely(collision)) { 2411 move_linked_works(work, &collision->scheduled, NULL); 2412 return; 2413 } 2414 2415 /* claim and dequeue */ 2416 debug_work_deactivate(work); 2417 hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work); 2418 worker->current_work = work; 2419 worker->current_func = work->func; 2420 worker->current_pwq = pwq; 2421 worker->current_at = worker->task->se.sum_exec_runtime; 2422 work_data = *work_data_bits(work); 2423 worker->current_color = get_work_color(work_data); 2424 2425 /* 2426 * Record wq name for cmdline and debug reporting, may get 2427 * overridden through set_worker_desc(). 2428 */ 2429 strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN); 2430 2431 list_del_init(&work->entry); 2432 2433 /* 2434 * CPU intensive works don't participate in concurrency management. 2435 * They're the scheduler's responsibility. This takes @worker out 2436 * of concurrency management and the next code block will chain 2437 * execution of the pending work items. 2438 */ 2439 if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE)) 2440 worker_set_flags(worker, WORKER_CPU_INTENSIVE); 2441 2442 /* 2443 * Wake up another worker if necessary. The condition is always 2444 * false for normal per-cpu workers since nr_running would always 2445 * be >= 1 at this point. This is used to chain execution of the 2446 * pending work items for WORKER_NOT_RUNNING workers such as the 2447 * UNBOUND and CPU_INTENSIVE ones. 2448 */ 2449 if (need_more_worker(pool)) 2450 wake_up_worker(pool); 2451 2452 /* 2453 * Record the last pool and clear PENDING which should be the last 2454 * update to @work. Also, do this inside @pool->lock so that 2455 * PENDING and queued state changes happen together while IRQ is 2456 * disabled. 2457 */ 2458 set_work_pool_and_clear_pending(work, pool->id); 2459 2460 raw_spin_unlock_irq(&pool->lock); 2461 2462 lock_map_acquire(&pwq->wq->lockdep_map); 2463 lock_map_acquire(&lockdep_map); 2464 /* 2465 * Strictly speaking we should mark the invariant state without holding 2466 * any locks, that is, before these two lock_map_acquire()'s. 2467 * 2468 * However, that would result in: 2469 * 2470 * A(W1) 2471 * WFC(C) 2472 * A(W1) 2473 * C(C) 2474 * 2475 * Which would create W1->C->W1 dependencies, even though there is no 2476 * actual deadlock possible. There are two solutions, using a 2477 * read-recursive acquire on the work(queue) 'locks', but this will then 2478 * hit the lockdep limitation on recursive locks, or simply discard 2479 * these locks. 2480 * 2481 * AFAICT there is no possible deadlock scenario between the 2482 * flush_work() and complete() primitives (except for single-threaded 2483 * workqueues), so hiding them isn't a problem. 2484 */ 2485 lockdep_invariant_state(true); 2486 pwq->stats[PWQ_STAT_STARTED]++; 2487 trace_workqueue_execute_start(work); 2488 worker->current_func(work); 2489 /* 2490 * While we must be careful to not use "work" after this, the trace 2491 * point will only record its address. 2492 */ 2493 trace_workqueue_execute_end(work, worker->current_func); 2494 pwq->stats[PWQ_STAT_COMPLETED]++; 2495 lock_map_release(&lockdep_map); 2496 lock_map_release(&pwq->wq->lockdep_map); 2497 2498 if (unlikely(in_atomic() || lockdep_depth(current) > 0)) { 2499 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n" 2500 " last function: %ps\n", 2501 current->comm, preempt_count(), task_pid_nr(current), 2502 worker->current_func); 2503 debug_show_held_locks(current); 2504 dump_stack(); 2505 } 2506 2507 /* 2508 * The following prevents a kworker from hogging CPU on !PREEMPTION 2509 * kernels, where a requeueing work item waiting for something to 2510 * happen could deadlock with stop_machine as such work item could 2511 * indefinitely requeue itself while all other CPUs are trapped in 2512 * stop_machine. At the same time, report a quiescent RCU state so 2513 * the same condition doesn't freeze RCU. 2514 */ 2515 cond_resched(); 2516 2517 raw_spin_lock_irq(&pool->lock); 2518 2519 /* 2520 * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked 2521 * CPU intensive by wq_worker_tick() if @work hogged CPU longer than 2522 * wq_cpu_intensive_thresh_us. Clear it. 2523 */ 2524 worker_clr_flags(worker, WORKER_CPU_INTENSIVE); 2525 2526 /* tag the worker for identification in schedule() */ 2527 worker->last_func = worker->current_func; 2528 2529 /* we're done with it, release */ 2530 hash_del(&worker->hentry); 2531 worker->current_work = NULL; 2532 worker->current_func = NULL; 2533 worker->current_pwq = NULL; 2534 worker->current_color = INT_MAX; 2535 pwq_dec_nr_in_flight(pwq, work_data); 2536 } 2537 2538 /** 2539 * process_scheduled_works - process scheduled works 2540 * @worker: self 2541 * 2542 * Process all scheduled works. Please note that the scheduled list 2543 * may change while processing a work, so this function repeatedly 2544 * fetches a work from the top and executes it. 2545 * 2546 * CONTEXT: 2547 * raw_spin_lock_irq(pool->lock) which may be released and regrabbed 2548 * multiple times. 2549 */ 2550 static void process_scheduled_works(struct worker *worker) 2551 { 2552 while (!list_empty(&worker->scheduled)) { 2553 struct work_struct *work = list_first_entry(&worker->scheduled, 2554 struct work_struct, entry); 2555 process_one_work(worker, work); 2556 } 2557 } 2558 2559 static void set_pf_worker(bool val) 2560 { 2561 mutex_lock(&wq_pool_attach_mutex); 2562 if (val) 2563 current->flags |= PF_WQ_WORKER; 2564 else 2565 current->flags &= ~PF_WQ_WORKER; 2566 mutex_unlock(&wq_pool_attach_mutex); 2567 } 2568 2569 /** 2570 * worker_thread - the worker thread function 2571 * @__worker: self 2572 * 2573 * The worker thread function. All workers belong to a worker_pool - 2574 * either a per-cpu one or dynamic unbound one. These workers process all 2575 * work items regardless of their specific target workqueue. The only 2576 * exception is work items which belong to workqueues with a rescuer which 2577 * will be explained in rescuer_thread(). 2578 * 2579 * Return: 0 2580 */ 2581 static int worker_thread(void *__worker) 2582 { 2583 struct worker *worker = __worker; 2584 struct worker_pool *pool = worker->pool; 2585 2586 /* tell the scheduler that this is a workqueue worker */ 2587 set_pf_worker(true); 2588 woke_up: 2589 raw_spin_lock_irq(&pool->lock); 2590 2591 /* am I supposed to die? */ 2592 if (unlikely(worker->flags & WORKER_DIE)) { 2593 raw_spin_unlock_irq(&pool->lock); 2594 set_pf_worker(false); 2595 2596 set_task_comm(worker->task, "kworker/dying"); 2597 ida_free(&pool->worker_ida, worker->id); 2598 worker_detach_from_pool(worker); 2599 WARN_ON_ONCE(!list_empty(&worker->entry)); 2600 kfree(worker); 2601 return 0; 2602 } 2603 2604 worker_leave_idle(worker); 2605 recheck: 2606 /* no more worker necessary? */ 2607 if (!need_more_worker(pool)) 2608 goto sleep; 2609 2610 /* do we need to manage? */ 2611 if (unlikely(!may_start_working(pool)) && manage_workers(worker)) 2612 goto recheck; 2613 2614 /* 2615 * ->scheduled list can only be filled while a worker is 2616 * preparing to process a work or actually processing it. 2617 * Make sure nobody diddled with it while I was sleeping. 2618 */ 2619 WARN_ON_ONCE(!list_empty(&worker->scheduled)); 2620 2621 /* 2622 * Finish PREP stage. We're guaranteed to have at least one idle 2623 * worker or that someone else has already assumed the manager 2624 * role. This is where @worker starts participating in concurrency 2625 * management if applicable and concurrency management is restored 2626 * after being rebound. See rebind_workers() for details. 2627 */ 2628 worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND); 2629 2630 do { 2631 struct work_struct *work = 2632 list_first_entry(&pool->worklist, 2633 struct work_struct, entry); 2634 2635 pool->watchdog_ts = jiffies; 2636 2637 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) { 2638 /* optimization path, not strictly necessary */ 2639 process_one_work(worker, work); 2640 if (unlikely(!list_empty(&worker->scheduled))) 2641 process_scheduled_works(worker); 2642 } else { 2643 move_linked_works(work, &worker->scheduled, NULL); 2644 process_scheduled_works(worker); 2645 } 2646 } while (keep_working(pool)); 2647 2648 worker_set_flags(worker, WORKER_PREP); 2649 sleep: 2650 /* 2651 * pool->lock is held and there's no work to process and no need to 2652 * manage, sleep. Workers are woken up only while holding 2653 * pool->lock or from local cpu, so setting the current state 2654 * before releasing pool->lock is enough to prevent losing any 2655 * event. 2656 */ 2657 worker_enter_idle(worker); 2658 __set_current_state(TASK_IDLE); 2659 raw_spin_unlock_irq(&pool->lock); 2660 schedule(); 2661 goto woke_up; 2662 } 2663 2664 /** 2665 * rescuer_thread - the rescuer thread function 2666 * @__rescuer: self 2667 * 2668 * Workqueue rescuer thread function. There's one rescuer for each 2669 * workqueue which has WQ_MEM_RECLAIM set. 2670 * 2671 * Regular work processing on a pool may block trying to create a new 2672 * worker which uses GFP_KERNEL allocation which has slight chance of 2673 * developing into deadlock if some works currently on the same queue 2674 * need to be processed to satisfy the GFP_KERNEL allocation. This is 2675 * the problem rescuer solves. 2676 * 2677 * When such condition is possible, the pool summons rescuers of all 2678 * workqueues which have works queued on the pool and let them process 2679 * those works so that forward progress can be guaranteed. 2680 * 2681 * This should happen rarely. 2682 * 2683 * Return: 0 2684 */ 2685 static int rescuer_thread(void *__rescuer) 2686 { 2687 struct worker *rescuer = __rescuer; 2688 struct workqueue_struct *wq = rescuer->rescue_wq; 2689 struct list_head *scheduled = &rescuer->scheduled; 2690 bool should_stop; 2691 2692 set_user_nice(current, RESCUER_NICE_LEVEL); 2693 2694 /* 2695 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it 2696 * doesn't participate in concurrency management. 2697 */ 2698 set_pf_worker(true); 2699 repeat: 2700 set_current_state(TASK_IDLE); 2701 2702 /* 2703 * By the time the rescuer is requested to stop, the workqueue 2704 * shouldn't have any work pending, but @wq->maydays may still have 2705 * pwq(s) queued. This can happen by non-rescuer workers consuming 2706 * all the work items before the rescuer got to them. Go through 2707 * @wq->maydays processing before acting on should_stop so that the 2708 * list is always empty on exit. 2709 */ 2710 should_stop = kthread_should_stop(); 2711 2712 /* see whether any pwq is asking for help */ 2713 raw_spin_lock_irq(&wq_mayday_lock); 2714 2715 while (!list_empty(&wq->maydays)) { 2716 struct pool_workqueue *pwq = list_first_entry(&wq->maydays, 2717 struct pool_workqueue, mayday_node); 2718 struct worker_pool *pool = pwq->pool; 2719 struct work_struct *work, *n; 2720 bool first = true; 2721 2722 __set_current_state(TASK_RUNNING); 2723 list_del_init(&pwq->mayday_node); 2724 2725 raw_spin_unlock_irq(&wq_mayday_lock); 2726 2727 worker_attach_to_pool(rescuer, pool); 2728 2729 raw_spin_lock_irq(&pool->lock); 2730 2731 /* 2732 * Slurp in all works issued via this workqueue and 2733 * process'em. 2734 */ 2735 WARN_ON_ONCE(!list_empty(scheduled)); 2736 list_for_each_entry_safe(work, n, &pool->worklist, entry) { 2737 if (get_work_pwq(work) == pwq) { 2738 if (first) 2739 pool->watchdog_ts = jiffies; 2740 move_linked_works(work, scheduled, &n); 2741 pwq->stats[PWQ_STAT_RESCUED]++; 2742 } 2743 first = false; 2744 } 2745 2746 if (!list_empty(scheduled)) { 2747 process_scheduled_works(rescuer); 2748 2749 /* 2750 * The above execution of rescued work items could 2751 * have created more to rescue through 2752 * pwq_activate_first_inactive() or chained 2753 * queueing. Let's put @pwq back on mayday list so 2754 * that such back-to-back work items, which may be 2755 * being used to relieve memory pressure, don't 2756 * incur MAYDAY_INTERVAL delay inbetween. 2757 */ 2758 if (pwq->nr_active && need_to_create_worker(pool)) { 2759 raw_spin_lock(&wq_mayday_lock); 2760 /* 2761 * Queue iff we aren't racing destruction 2762 * and somebody else hasn't queued it already. 2763 */ 2764 if (wq->rescuer && list_empty(&pwq->mayday_node)) { 2765 get_pwq(pwq); 2766 list_add_tail(&pwq->mayday_node, &wq->maydays); 2767 } 2768 raw_spin_unlock(&wq_mayday_lock); 2769 } 2770 } 2771 2772 /* 2773 * Put the reference grabbed by send_mayday(). @pool won't 2774 * go away while we're still attached to it. 2775 */ 2776 put_pwq(pwq); 2777 2778 /* 2779 * Leave this pool. If need_more_worker() is %true, notify a 2780 * regular worker; otherwise, we end up with 0 concurrency 2781 * and stalling the execution. 2782 */ 2783 if (need_more_worker(pool)) 2784 wake_up_worker(pool); 2785 2786 raw_spin_unlock_irq(&pool->lock); 2787 2788 worker_detach_from_pool(rescuer); 2789 2790 raw_spin_lock_irq(&wq_mayday_lock); 2791 } 2792 2793 raw_spin_unlock_irq(&wq_mayday_lock); 2794 2795 if (should_stop) { 2796 __set_current_state(TASK_RUNNING); 2797 set_pf_worker(false); 2798 return 0; 2799 } 2800 2801 /* rescuers should never participate in concurrency management */ 2802 WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING)); 2803 schedule(); 2804 goto repeat; 2805 } 2806 2807 /** 2808 * check_flush_dependency - check for flush dependency sanity 2809 * @target_wq: workqueue being flushed 2810 * @target_work: work item being flushed (NULL for workqueue flushes) 2811 * 2812 * %current is trying to flush the whole @target_wq or @target_work on it. 2813 * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not 2814 * reclaiming memory or running on a workqueue which doesn't have 2815 * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to 2816 * a deadlock. 2817 */ 2818 static void check_flush_dependency(struct workqueue_struct *target_wq, 2819 struct work_struct *target_work) 2820 { 2821 work_func_t target_func = target_work ? target_work->func : NULL; 2822 struct worker *worker; 2823 2824 if (target_wq->flags & WQ_MEM_RECLAIM) 2825 return; 2826 2827 worker = current_wq_worker(); 2828 2829 WARN_ONCE(current->flags & PF_MEMALLOC, 2830 "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps", 2831 current->pid, current->comm, target_wq->name, target_func); 2832 WARN_ONCE(worker && ((worker->current_pwq->wq->flags & 2833 (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM), 2834 "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps", 2835 worker->current_pwq->wq->name, worker->current_func, 2836 target_wq->name, target_func); 2837 } 2838 2839 struct wq_barrier { 2840 struct work_struct work; 2841 struct completion done; 2842 struct task_struct *task; /* purely informational */ 2843 }; 2844 2845 static void wq_barrier_func(struct work_struct *work) 2846 { 2847 struct wq_barrier *barr = container_of(work, struct wq_barrier, work); 2848 complete(&barr->done); 2849 } 2850 2851 /** 2852 * insert_wq_barrier - insert a barrier work 2853 * @pwq: pwq to insert barrier into 2854 * @barr: wq_barrier to insert 2855 * @target: target work to attach @barr to 2856 * @worker: worker currently executing @target, NULL if @target is not executing 2857 * 2858 * @barr is linked to @target such that @barr is completed only after 2859 * @target finishes execution. Please note that the ordering 2860 * guarantee is observed only with respect to @target and on the local 2861 * cpu. 2862 * 2863 * Currently, a queued barrier can't be canceled. This is because 2864 * try_to_grab_pending() can't determine whether the work to be 2865 * grabbed is at the head of the queue and thus can't clear LINKED 2866 * flag of the previous work while there must be a valid next work 2867 * after a work with LINKED flag set. 2868 * 2869 * Note that when @worker is non-NULL, @target may be modified 2870 * underneath us, so we can't reliably determine pwq from @target. 2871 * 2872 * CONTEXT: 2873 * raw_spin_lock_irq(pool->lock). 2874 */ 2875 static void insert_wq_barrier(struct pool_workqueue *pwq, 2876 struct wq_barrier *barr, 2877 struct work_struct *target, struct worker *worker) 2878 { 2879 unsigned int work_flags = 0; 2880 unsigned int work_color; 2881 struct list_head *head; 2882 2883 /* 2884 * debugobject calls are safe here even with pool->lock locked 2885 * as we know for sure that this will not trigger any of the 2886 * checks and call back into the fixup functions where we 2887 * might deadlock. 2888 */ 2889 INIT_WORK_ONSTACK(&barr->work, wq_barrier_func); 2890 __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work)); 2891 2892 init_completion_map(&barr->done, &target->lockdep_map); 2893 2894 barr->task = current; 2895 2896 /* The barrier work item does not participate in pwq->nr_active. */ 2897 work_flags |= WORK_STRUCT_INACTIVE; 2898 2899 /* 2900 * If @target is currently being executed, schedule the 2901 * barrier to the worker; otherwise, put it after @target. 2902 */ 2903 if (worker) { 2904 head = worker->scheduled.next; 2905 work_color = worker->current_color; 2906 } else { 2907 unsigned long *bits = work_data_bits(target); 2908 2909 head = target->entry.next; 2910 /* there can already be other linked works, inherit and set */ 2911 work_flags |= *bits & WORK_STRUCT_LINKED; 2912 work_color = get_work_color(*bits); 2913 __set_bit(WORK_STRUCT_LINKED_BIT, bits); 2914 } 2915 2916 pwq->nr_in_flight[work_color]++; 2917 work_flags |= work_color_to_flags(work_color); 2918 2919 debug_work_activate(&barr->work); 2920 insert_work(pwq, &barr->work, head, work_flags); 2921 } 2922 2923 /** 2924 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing 2925 * @wq: workqueue being flushed 2926 * @flush_color: new flush color, < 0 for no-op 2927 * @work_color: new work color, < 0 for no-op 2928 * 2929 * Prepare pwqs for workqueue flushing. 2930 * 2931 * If @flush_color is non-negative, flush_color on all pwqs should be 2932 * -1. If no pwq has in-flight commands at the specified color, all 2933 * pwq->flush_color's stay at -1 and %false is returned. If any pwq 2934 * has in flight commands, its pwq->flush_color is set to 2935 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq 2936 * wakeup logic is armed and %true is returned. 2937 * 2938 * The caller should have initialized @wq->first_flusher prior to 2939 * calling this function with non-negative @flush_color. If 2940 * @flush_color is negative, no flush color update is done and %false 2941 * is returned. 2942 * 2943 * If @work_color is non-negative, all pwqs should have the same 2944 * work_color which is previous to @work_color and all will be 2945 * advanced to @work_color. 2946 * 2947 * CONTEXT: 2948 * mutex_lock(wq->mutex). 2949 * 2950 * Return: 2951 * %true if @flush_color >= 0 and there's something to flush. %false 2952 * otherwise. 2953 */ 2954 static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq, 2955 int flush_color, int work_color) 2956 { 2957 bool wait = false; 2958 struct pool_workqueue *pwq; 2959 2960 if (flush_color >= 0) { 2961 WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush)); 2962 atomic_set(&wq->nr_pwqs_to_flush, 1); 2963 } 2964 2965 for_each_pwq(pwq, wq) { 2966 struct worker_pool *pool = pwq->pool; 2967 2968 raw_spin_lock_irq(&pool->lock); 2969 2970 if (flush_color >= 0) { 2971 WARN_ON_ONCE(pwq->flush_color != -1); 2972 2973 if (pwq->nr_in_flight[flush_color]) { 2974 pwq->flush_color = flush_color; 2975 atomic_inc(&wq->nr_pwqs_to_flush); 2976 wait = true; 2977 } 2978 } 2979 2980 if (work_color >= 0) { 2981 WARN_ON_ONCE(work_color != work_next_color(pwq->work_color)); 2982 pwq->work_color = work_color; 2983 } 2984 2985 raw_spin_unlock_irq(&pool->lock); 2986 } 2987 2988 if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush)) 2989 complete(&wq->first_flusher->done); 2990 2991 return wait; 2992 } 2993 2994 /** 2995 * __flush_workqueue - ensure that any scheduled work has run to completion. 2996 * @wq: workqueue to flush 2997 * 2998 * This function sleeps until all work items which were queued on entry 2999 * have finished execution, but it is not livelocked by new incoming ones. 3000 */ 3001 void __flush_workqueue(struct workqueue_struct *wq) 3002 { 3003 struct wq_flusher this_flusher = { 3004 .list = LIST_HEAD_INIT(this_flusher.list), 3005 .flush_color = -1, 3006 .done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map), 3007 }; 3008 int next_color; 3009 3010 if (WARN_ON(!wq_online)) 3011 return; 3012 3013 lock_map_acquire(&wq->lockdep_map); 3014 lock_map_release(&wq->lockdep_map); 3015 3016 mutex_lock(&wq->mutex); 3017 3018 /* 3019 * Start-to-wait phase 3020 */ 3021 next_color = work_next_color(wq->work_color); 3022 3023 if (next_color != wq->flush_color) { 3024 /* 3025 * Color space is not full. The current work_color 3026 * becomes our flush_color and work_color is advanced 3027 * by one. 3028 */ 3029 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow)); 3030 this_flusher.flush_color = wq->work_color; 3031 wq->work_color = next_color; 3032 3033 if (!wq->first_flusher) { 3034 /* no flush in progress, become the first flusher */ 3035 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color); 3036 3037 wq->first_flusher = &this_flusher; 3038 3039 if (!flush_workqueue_prep_pwqs(wq, wq->flush_color, 3040 wq->work_color)) { 3041 /* nothing to flush, done */ 3042 wq->flush_color = next_color; 3043 wq->first_flusher = NULL; 3044 goto out_unlock; 3045 } 3046 } else { 3047 /* wait in queue */ 3048 WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color); 3049 list_add_tail(&this_flusher.list, &wq->flusher_queue); 3050 flush_workqueue_prep_pwqs(wq, -1, wq->work_color); 3051 } 3052 } else { 3053 /* 3054 * Oops, color space is full, wait on overflow queue. 3055 * The next flush completion will assign us 3056 * flush_color and transfer to flusher_queue. 3057 */ 3058 list_add_tail(&this_flusher.list, &wq->flusher_overflow); 3059 } 3060 3061 check_flush_dependency(wq, NULL); 3062 3063 mutex_unlock(&wq->mutex); 3064 3065 wait_for_completion(&this_flusher.done); 3066 3067 /* 3068 * Wake-up-and-cascade phase 3069 * 3070 * First flushers are responsible for cascading flushes and 3071 * handling overflow. Non-first flushers can simply return. 3072 */ 3073 if (READ_ONCE(wq->first_flusher) != &this_flusher) 3074 return; 3075 3076 mutex_lock(&wq->mutex); 3077 3078 /* we might have raced, check again with mutex held */ 3079 if (wq->first_flusher != &this_flusher) 3080 goto out_unlock; 3081 3082 WRITE_ONCE(wq->first_flusher, NULL); 3083 3084 WARN_ON_ONCE(!list_empty(&this_flusher.list)); 3085 WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color); 3086 3087 while (true) { 3088 struct wq_flusher *next, *tmp; 3089 3090 /* complete all the flushers sharing the current flush color */ 3091 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) { 3092 if (next->flush_color != wq->flush_color) 3093 break; 3094 list_del_init(&next->list); 3095 complete(&next->done); 3096 } 3097 3098 WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) && 3099 wq->flush_color != work_next_color(wq->work_color)); 3100 3101 /* this flush_color is finished, advance by one */ 3102 wq->flush_color = work_next_color(wq->flush_color); 3103 3104 /* one color has been freed, handle overflow queue */ 3105 if (!list_empty(&wq->flusher_overflow)) { 3106 /* 3107 * Assign the same color to all overflowed 3108 * flushers, advance work_color and append to 3109 * flusher_queue. This is the start-to-wait 3110 * phase for these overflowed flushers. 3111 */ 3112 list_for_each_entry(tmp, &wq->flusher_overflow, list) 3113 tmp->flush_color = wq->work_color; 3114 3115 wq->work_color = work_next_color(wq->work_color); 3116 3117 list_splice_tail_init(&wq->flusher_overflow, 3118 &wq->flusher_queue); 3119 flush_workqueue_prep_pwqs(wq, -1, wq->work_color); 3120 } 3121 3122 if (list_empty(&wq->flusher_queue)) { 3123 WARN_ON_ONCE(wq->flush_color != wq->work_color); 3124 break; 3125 } 3126 3127 /* 3128 * Need to flush more colors. Make the next flusher 3129 * the new first flusher and arm pwqs. 3130 */ 3131 WARN_ON_ONCE(wq->flush_color == wq->work_color); 3132 WARN_ON_ONCE(wq->flush_color != next->flush_color); 3133 3134 list_del_init(&next->list); 3135 wq->first_flusher = next; 3136 3137 if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1)) 3138 break; 3139 3140 /* 3141 * Meh... this color is already done, clear first 3142 * flusher and repeat cascading. 3143 */ 3144 wq->first_flusher = NULL; 3145 } 3146 3147 out_unlock: 3148 mutex_unlock(&wq->mutex); 3149 } 3150 EXPORT_SYMBOL(__flush_workqueue); 3151 3152 /** 3153 * drain_workqueue - drain a workqueue 3154 * @wq: workqueue to drain 3155 * 3156 * Wait until the workqueue becomes empty. While draining is in progress, 3157 * only chain queueing is allowed. IOW, only currently pending or running 3158 * work items on @wq can queue further work items on it. @wq is flushed 3159 * repeatedly until it becomes empty. The number of flushing is determined 3160 * by the depth of chaining and should be relatively short. Whine if it 3161 * takes too long. 3162 */ 3163 void drain_workqueue(struct workqueue_struct *wq) 3164 { 3165 unsigned int flush_cnt = 0; 3166 struct pool_workqueue *pwq; 3167 3168 /* 3169 * __queue_work() needs to test whether there are drainers, is much 3170 * hotter than drain_workqueue() and already looks at @wq->flags. 3171 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers. 3172 */ 3173 mutex_lock(&wq->mutex); 3174 if (!wq->nr_drainers++) 3175 wq->flags |= __WQ_DRAINING; 3176 mutex_unlock(&wq->mutex); 3177 reflush: 3178 __flush_workqueue(wq); 3179 3180 mutex_lock(&wq->mutex); 3181 3182 for_each_pwq(pwq, wq) { 3183 bool drained; 3184 3185 raw_spin_lock_irq(&pwq->pool->lock); 3186 drained = !pwq->nr_active && list_empty(&pwq->inactive_works); 3187 raw_spin_unlock_irq(&pwq->pool->lock); 3188 3189 if (drained) 3190 continue; 3191 3192 if (++flush_cnt == 10 || 3193 (flush_cnt % 100 == 0 && flush_cnt <= 1000)) 3194 pr_warn("workqueue %s: %s() isn't complete after %u tries\n", 3195 wq->name, __func__, flush_cnt); 3196 3197 mutex_unlock(&wq->mutex); 3198 goto reflush; 3199 } 3200 3201 if (!--wq->nr_drainers) 3202 wq->flags &= ~__WQ_DRAINING; 3203 mutex_unlock(&wq->mutex); 3204 } 3205 EXPORT_SYMBOL_GPL(drain_workqueue); 3206 3207 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr, 3208 bool from_cancel) 3209 { 3210 struct worker *worker = NULL; 3211 struct worker_pool *pool; 3212 struct pool_workqueue *pwq; 3213 3214 might_sleep(); 3215 3216 rcu_read_lock(); 3217 pool = get_work_pool(work); 3218 if (!pool) { 3219 rcu_read_unlock(); 3220 return false; 3221 } 3222 3223 raw_spin_lock_irq(&pool->lock); 3224 /* see the comment in try_to_grab_pending() with the same code */ 3225 pwq = get_work_pwq(work); 3226 if (pwq) { 3227 if (unlikely(pwq->pool != pool)) 3228 goto already_gone; 3229 } else { 3230 worker = find_worker_executing_work(pool, work); 3231 if (!worker) 3232 goto already_gone; 3233 pwq = worker->current_pwq; 3234 } 3235 3236 check_flush_dependency(pwq->wq, work); 3237 3238 insert_wq_barrier(pwq, barr, work, worker); 3239 raw_spin_unlock_irq(&pool->lock); 3240 3241 /* 3242 * Force a lock recursion deadlock when using flush_work() inside a 3243 * single-threaded or rescuer equipped workqueue. 3244 * 3245 * For single threaded workqueues the deadlock happens when the work 3246 * is after the work issuing the flush_work(). For rescuer equipped 3247 * workqueues the deadlock happens when the rescuer stalls, blocking 3248 * forward progress. 3249 */ 3250 if (!from_cancel && 3251 (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) { 3252 lock_map_acquire(&pwq->wq->lockdep_map); 3253 lock_map_release(&pwq->wq->lockdep_map); 3254 } 3255 rcu_read_unlock(); 3256 return true; 3257 already_gone: 3258 raw_spin_unlock_irq(&pool->lock); 3259 rcu_read_unlock(); 3260 return false; 3261 } 3262 3263 static bool __flush_work(struct work_struct *work, bool from_cancel) 3264 { 3265 struct wq_barrier barr; 3266 3267 if (WARN_ON(!wq_online)) 3268 return false; 3269 3270 if (WARN_ON(!work->func)) 3271 return false; 3272 3273 lock_map_acquire(&work->lockdep_map); 3274 lock_map_release(&work->lockdep_map); 3275 3276 if (start_flush_work(work, &barr, from_cancel)) { 3277 wait_for_completion(&barr.done); 3278 destroy_work_on_stack(&barr.work); 3279 return true; 3280 } else { 3281 return false; 3282 } 3283 } 3284 3285 /** 3286 * flush_work - wait for a work to finish executing the last queueing instance 3287 * @work: the work to flush 3288 * 3289 * Wait until @work has finished execution. @work is guaranteed to be idle 3290 * on return if it hasn't been requeued since flush started. 3291 * 3292 * Return: 3293 * %true if flush_work() waited for the work to finish execution, 3294 * %false if it was already idle. 3295 */ 3296 bool flush_work(struct work_struct *work) 3297 { 3298 return __flush_work(work, false); 3299 } 3300 EXPORT_SYMBOL_GPL(flush_work); 3301 3302 struct cwt_wait { 3303 wait_queue_entry_t wait; 3304 struct work_struct *work; 3305 }; 3306 3307 static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key) 3308 { 3309 struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait); 3310 3311 if (cwait->work != key) 3312 return 0; 3313 return autoremove_wake_function(wait, mode, sync, key); 3314 } 3315 3316 static bool __cancel_work_timer(struct work_struct *work, bool is_dwork) 3317 { 3318 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq); 3319 unsigned long flags; 3320 int ret; 3321 3322 do { 3323 ret = try_to_grab_pending(work, is_dwork, &flags); 3324 /* 3325 * If someone else is already canceling, wait for it to 3326 * finish. flush_work() doesn't work for PREEMPT_NONE 3327 * because we may get scheduled between @work's completion 3328 * and the other canceling task resuming and clearing 3329 * CANCELING - flush_work() will return false immediately 3330 * as @work is no longer busy, try_to_grab_pending() will 3331 * return -ENOENT as @work is still being canceled and the 3332 * other canceling task won't be able to clear CANCELING as 3333 * we're hogging the CPU. 3334 * 3335 * Let's wait for completion using a waitqueue. As this 3336 * may lead to the thundering herd problem, use a custom 3337 * wake function which matches @work along with exclusive 3338 * wait and wakeup. 3339 */ 3340 if (unlikely(ret == -ENOENT)) { 3341 struct cwt_wait cwait; 3342 3343 init_wait(&cwait.wait); 3344 cwait.wait.func = cwt_wakefn; 3345 cwait.work = work; 3346 3347 prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait, 3348 TASK_UNINTERRUPTIBLE); 3349 if (work_is_canceling(work)) 3350 schedule(); 3351 finish_wait(&cancel_waitq, &cwait.wait); 3352 } 3353 } while (unlikely(ret < 0)); 3354 3355 /* tell other tasks trying to grab @work to back off */ 3356 mark_work_canceling(work); 3357 local_irq_restore(flags); 3358 3359 /* 3360 * This allows canceling during early boot. We know that @work 3361 * isn't executing. 3362 */ 3363 if (wq_online) 3364 __flush_work(work, true); 3365 3366 clear_work_data(work); 3367 3368 /* 3369 * Paired with prepare_to_wait() above so that either 3370 * waitqueue_active() is visible here or !work_is_canceling() is 3371 * visible there. 3372 */ 3373 smp_mb(); 3374 if (waitqueue_active(&cancel_waitq)) 3375 __wake_up(&cancel_waitq, TASK_NORMAL, 1, work); 3376 3377 return ret; 3378 } 3379 3380 /** 3381 * cancel_work_sync - cancel a work and wait for it to finish 3382 * @work: the work to cancel 3383 * 3384 * Cancel @work and wait for its execution to finish. This function 3385 * can be used even if the work re-queues itself or migrates to 3386 * another workqueue. On return from this function, @work is 3387 * guaranteed to be not pending or executing on any CPU. 3388 * 3389 * cancel_work_sync(&delayed_work->work) must not be used for 3390 * delayed_work's. Use cancel_delayed_work_sync() instead. 3391 * 3392 * The caller must ensure that the workqueue on which @work was last 3393 * queued can't be destroyed before this function returns. 3394 * 3395 * Return: 3396 * %true if @work was pending, %false otherwise. 3397 */ 3398 bool cancel_work_sync(struct work_struct *work) 3399 { 3400 return __cancel_work_timer(work, false); 3401 } 3402 EXPORT_SYMBOL_GPL(cancel_work_sync); 3403 3404 /** 3405 * flush_delayed_work - wait for a dwork to finish executing the last queueing 3406 * @dwork: the delayed work to flush 3407 * 3408 * Delayed timer is cancelled and the pending work is queued for 3409 * immediate execution. Like flush_work(), this function only 3410 * considers the last queueing instance of @dwork. 3411 * 3412 * Return: 3413 * %true if flush_work() waited for the work to finish execution, 3414 * %false if it was already idle. 3415 */ 3416 bool flush_delayed_work(struct delayed_work *dwork) 3417 { 3418 local_irq_disable(); 3419 if (del_timer_sync(&dwork->timer)) 3420 __queue_work(dwork->cpu, dwork->wq, &dwork->work); 3421 local_irq_enable(); 3422 return flush_work(&dwork->work); 3423 } 3424 EXPORT_SYMBOL(flush_delayed_work); 3425 3426 /** 3427 * flush_rcu_work - wait for a rwork to finish executing the last queueing 3428 * @rwork: the rcu work to flush 3429 * 3430 * Return: 3431 * %true if flush_rcu_work() waited for the work to finish execution, 3432 * %false if it was already idle. 3433 */ 3434 bool flush_rcu_work(struct rcu_work *rwork) 3435 { 3436 if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) { 3437 rcu_barrier(); 3438 flush_work(&rwork->work); 3439 return true; 3440 } else { 3441 return flush_work(&rwork->work); 3442 } 3443 } 3444 EXPORT_SYMBOL(flush_rcu_work); 3445 3446 static bool __cancel_work(struct work_struct *work, bool is_dwork) 3447 { 3448 unsigned long flags; 3449 int ret; 3450 3451 do { 3452 ret = try_to_grab_pending(work, is_dwork, &flags); 3453 } while (unlikely(ret == -EAGAIN)); 3454 3455 if (unlikely(ret < 0)) 3456 return false; 3457 3458 set_work_pool_and_clear_pending(work, get_work_pool_id(work)); 3459 local_irq_restore(flags); 3460 return ret; 3461 } 3462 3463 /* 3464 * See cancel_delayed_work() 3465 */ 3466 bool cancel_work(struct work_struct *work) 3467 { 3468 return __cancel_work(work, false); 3469 } 3470 EXPORT_SYMBOL(cancel_work); 3471 3472 /** 3473 * cancel_delayed_work - cancel a delayed work 3474 * @dwork: delayed_work to cancel 3475 * 3476 * Kill off a pending delayed_work. 3477 * 3478 * Return: %true if @dwork was pending and canceled; %false if it wasn't 3479 * pending. 3480 * 3481 * Note: 3482 * The work callback function may still be running on return, unless 3483 * it returns %true and the work doesn't re-arm itself. Explicitly flush or 3484 * use cancel_delayed_work_sync() to wait on it. 3485 * 3486 * This function is safe to call from any context including IRQ handler. 3487 */ 3488 bool cancel_delayed_work(struct delayed_work *dwork) 3489 { 3490 return __cancel_work(&dwork->work, true); 3491 } 3492 EXPORT_SYMBOL(cancel_delayed_work); 3493 3494 /** 3495 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish 3496 * @dwork: the delayed work cancel 3497 * 3498 * This is cancel_work_sync() for delayed works. 3499 * 3500 * Return: 3501 * %true if @dwork was pending, %false otherwise. 3502 */ 3503 bool cancel_delayed_work_sync(struct delayed_work *dwork) 3504 { 3505 return __cancel_work_timer(&dwork->work, true); 3506 } 3507 EXPORT_SYMBOL(cancel_delayed_work_sync); 3508 3509 /** 3510 * schedule_on_each_cpu - execute a function synchronously on each online CPU 3511 * @func: the function to call 3512 * 3513 * schedule_on_each_cpu() executes @func on each online CPU using the 3514 * system workqueue and blocks until all CPUs have completed. 3515 * schedule_on_each_cpu() is very slow. 3516 * 3517 * Return: 3518 * 0 on success, -errno on failure. 3519 */ 3520 int schedule_on_each_cpu(work_func_t func) 3521 { 3522 int cpu; 3523 struct work_struct __percpu *works; 3524 3525 works = alloc_percpu(struct work_struct); 3526 if (!works) 3527 return -ENOMEM; 3528 3529 cpus_read_lock(); 3530 3531 for_each_online_cpu(cpu) { 3532 struct work_struct *work = per_cpu_ptr(works, cpu); 3533 3534 INIT_WORK(work, func); 3535 schedule_work_on(cpu, work); 3536 } 3537 3538 for_each_online_cpu(cpu) 3539 flush_work(per_cpu_ptr(works, cpu)); 3540 3541 cpus_read_unlock(); 3542 free_percpu(works); 3543 return 0; 3544 } 3545 3546 /** 3547 * execute_in_process_context - reliably execute the routine with user context 3548 * @fn: the function to execute 3549 * @ew: guaranteed storage for the execute work structure (must 3550 * be available when the work executes) 3551 * 3552 * Executes the function immediately if process context is available, 3553 * otherwise schedules the function for delayed execution. 3554 * 3555 * Return: 0 - function was executed 3556 * 1 - function was scheduled for execution 3557 */ 3558 int execute_in_process_context(work_func_t fn, struct execute_work *ew) 3559 { 3560 if (!in_interrupt()) { 3561 fn(&ew->work); 3562 return 0; 3563 } 3564 3565 INIT_WORK(&ew->work, fn); 3566 schedule_work(&ew->work); 3567 3568 return 1; 3569 } 3570 EXPORT_SYMBOL_GPL(execute_in_process_context); 3571 3572 /** 3573 * free_workqueue_attrs - free a workqueue_attrs 3574 * @attrs: workqueue_attrs to free 3575 * 3576 * Undo alloc_workqueue_attrs(). 3577 */ 3578 void free_workqueue_attrs(struct workqueue_attrs *attrs) 3579 { 3580 if (attrs) { 3581 free_cpumask_var(attrs->cpumask); 3582 kfree(attrs); 3583 } 3584 } 3585 3586 /** 3587 * alloc_workqueue_attrs - allocate a workqueue_attrs 3588 * 3589 * Allocate a new workqueue_attrs, initialize with default settings and 3590 * return it. 3591 * 3592 * Return: The allocated new workqueue_attr on success. %NULL on failure. 3593 */ 3594 struct workqueue_attrs *alloc_workqueue_attrs(void) 3595 { 3596 struct workqueue_attrs *attrs; 3597 3598 attrs = kzalloc(sizeof(*attrs), GFP_KERNEL); 3599 if (!attrs) 3600 goto fail; 3601 if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL)) 3602 goto fail; 3603 3604 cpumask_copy(attrs->cpumask, cpu_possible_mask); 3605 return attrs; 3606 fail: 3607 free_workqueue_attrs(attrs); 3608 return NULL; 3609 } 3610 3611 static void copy_workqueue_attrs(struct workqueue_attrs *to, 3612 const struct workqueue_attrs *from) 3613 { 3614 to->nice = from->nice; 3615 cpumask_copy(to->cpumask, from->cpumask); 3616 /* 3617 * Unlike hash and equality test, this function doesn't ignore 3618 * ->no_numa as it is used for both pool and wq attrs. Instead, 3619 * get_unbound_pool() explicitly clears ->no_numa after copying. 3620 */ 3621 to->no_numa = from->no_numa; 3622 } 3623 3624 /* hash value of the content of @attr */ 3625 static u32 wqattrs_hash(const struct workqueue_attrs *attrs) 3626 { 3627 u32 hash = 0; 3628 3629 hash = jhash_1word(attrs->nice, hash); 3630 hash = jhash(cpumask_bits(attrs->cpumask), 3631 BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash); 3632 return hash; 3633 } 3634 3635 /* content equality test */ 3636 static bool wqattrs_equal(const struct workqueue_attrs *a, 3637 const struct workqueue_attrs *b) 3638 { 3639 if (a->nice != b->nice) 3640 return false; 3641 if (!cpumask_equal(a->cpumask, b->cpumask)) 3642 return false; 3643 return true; 3644 } 3645 3646 /** 3647 * init_worker_pool - initialize a newly zalloc'd worker_pool 3648 * @pool: worker_pool to initialize 3649 * 3650 * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs. 3651 * 3652 * Return: 0 on success, -errno on failure. Even on failure, all fields 3653 * inside @pool proper are initialized and put_unbound_pool() can be called 3654 * on @pool safely to release it. 3655 */ 3656 static int init_worker_pool(struct worker_pool *pool) 3657 { 3658 raw_spin_lock_init(&pool->lock); 3659 pool->id = -1; 3660 pool->cpu = -1; 3661 pool->node = NUMA_NO_NODE; 3662 pool->flags |= POOL_DISASSOCIATED; 3663 pool->watchdog_ts = jiffies; 3664 INIT_LIST_HEAD(&pool->worklist); 3665 INIT_LIST_HEAD(&pool->idle_list); 3666 hash_init(pool->busy_hash); 3667 3668 timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE); 3669 INIT_WORK(&pool->idle_cull_work, idle_cull_fn); 3670 3671 timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0); 3672 3673 INIT_LIST_HEAD(&pool->workers); 3674 INIT_LIST_HEAD(&pool->dying_workers); 3675 3676 ida_init(&pool->worker_ida); 3677 INIT_HLIST_NODE(&pool->hash_node); 3678 pool->refcnt = 1; 3679 3680 /* shouldn't fail above this point */ 3681 pool->attrs = alloc_workqueue_attrs(); 3682 if (!pool->attrs) 3683 return -ENOMEM; 3684 return 0; 3685 } 3686 3687 #ifdef CONFIG_LOCKDEP 3688 static void wq_init_lockdep(struct workqueue_struct *wq) 3689 { 3690 char *lock_name; 3691 3692 lockdep_register_key(&wq->key); 3693 lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name); 3694 if (!lock_name) 3695 lock_name = wq->name; 3696 3697 wq->lock_name = lock_name; 3698 lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0); 3699 } 3700 3701 static void wq_unregister_lockdep(struct workqueue_struct *wq) 3702 { 3703 lockdep_unregister_key(&wq->key); 3704 } 3705 3706 static void wq_free_lockdep(struct workqueue_struct *wq) 3707 { 3708 if (wq->lock_name != wq->name) 3709 kfree(wq->lock_name); 3710 } 3711 #else 3712 static void wq_init_lockdep(struct workqueue_struct *wq) 3713 { 3714 } 3715 3716 static void wq_unregister_lockdep(struct workqueue_struct *wq) 3717 { 3718 } 3719 3720 static void wq_free_lockdep(struct workqueue_struct *wq) 3721 { 3722 } 3723 #endif 3724 3725 static void rcu_free_wq(struct rcu_head *rcu) 3726 { 3727 struct workqueue_struct *wq = 3728 container_of(rcu, struct workqueue_struct, rcu); 3729 3730 wq_free_lockdep(wq); 3731 3732 if (!(wq->flags & WQ_UNBOUND)) 3733 free_percpu(wq->cpu_pwqs); 3734 else 3735 free_workqueue_attrs(wq->unbound_attrs); 3736 3737 kfree(wq); 3738 } 3739 3740 static void rcu_free_pool(struct rcu_head *rcu) 3741 { 3742 struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu); 3743 3744 ida_destroy(&pool->worker_ida); 3745 free_workqueue_attrs(pool->attrs); 3746 kfree(pool); 3747 } 3748 3749 /** 3750 * put_unbound_pool - put a worker_pool 3751 * @pool: worker_pool to put 3752 * 3753 * Put @pool. If its refcnt reaches zero, it gets destroyed in RCU 3754 * safe manner. get_unbound_pool() calls this function on its failure path 3755 * and this function should be able to release pools which went through, 3756 * successfully or not, init_worker_pool(). 3757 * 3758 * Should be called with wq_pool_mutex held. 3759 */ 3760 static void put_unbound_pool(struct worker_pool *pool) 3761 { 3762 DECLARE_COMPLETION_ONSTACK(detach_completion); 3763 struct list_head cull_list; 3764 struct worker *worker; 3765 3766 INIT_LIST_HEAD(&cull_list); 3767 3768 lockdep_assert_held(&wq_pool_mutex); 3769 3770 if (--pool->refcnt) 3771 return; 3772 3773 /* sanity checks */ 3774 if (WARN_ON(!(pool->cpu < 0)) || 3775 WARN_ON(!list_empty(&pool->worklist))) 3776 return; 3777 3778 /* release id and unhash */ 3779 if (pool->id >= 0) 3780 idr_remove(&worker_pool_idr, pool->id); 3781 hash_del(&pool->hash_node); 3782 3783 /* 3784 * Become the manager and destroy all workers. This prevents 3785 * @pool's workers from blocking on attach_mutex. We're the last 3786 * manager and @pool gets freed with the flag set. 3787 * 3788 * Having a concurrent manager is quite unlikely to happen as we can 3789 * only get here with 3790 * pwq->refcnt == pool->refcnt == 0 3791 * which implies no work queued to the pool, which implies no worker can 3792 * become the manager. However a worker could have taken the role of 3793 * manager before the refcnts dropped to 0, since maybe_create_worker() 3794 * drops pool->lock 3795 */ 3796 while (true) { 3797 rcuwait_wait_event(&manager_wait, 3798 !(pool->flags & POOL_MANAGER_ACTIVE), 3799 TASK_UNINTERRUPTIBLE); 3800 3801 mutex_lock(&wq_pool_attach_mutex); 3802 raw_spin_lock_irq(&pool->lock); 3803 if (!(pool->flags & POOL_MANAGER_ACTIVE)) { 3804 pool->flags |= POOL_MANAGER_ACTIVE; 3805 break; 3806 } 3807 raw_spin_unlock_irq(&pool->lock); 3808 mutex_unlock(&wq_pool_attach_mutex); 3809 } 3810 3811 while ((worker = first_idle_worker(pool))) 3812 set_worker_dying(worker, &cull_list); 3813 WARN_ON(pool->nr_workers || pool->nr_idle); 3814 raw_spin_unlock_irq(&pool->lock); 3815 3816 wake_dying_workers(&cull_list); 3817 3818 if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers)) 3819 pool->detach_completion = &detach_completion; 3820 mutex_unlock(&wq_pool_attach_mutex); 3821 3822 if (pool->detach_completion) 3823 wait_for_completion(pool->detach_completion); 3824 3825 /* shut down the timers */ 3826 del_timer_sync(&pool->idle_timer); 3827 cancel_work_sync(&pool->idle_cull_work); 3828 del_timer_sync(&pool->mayday_timer); 3829 3830 /* RCU protected to allow dereferences from get_work_pool() */ 3831 call_rcu(&pool->rcu, rcu_free_pool); 3832 } 3833 3834 /** 3835 * get_unbound_pool - get a worker_pool with the specified attributes 3836 * @attrs: the attributes of the worker_pool to get 3837 * 3838 * Obtain a worker_pool which has the same attributes as @attrs, bump the 3839 * reference count and return it. If there already is a matching 3840 * worker_pool, it will be used; otherwise, this function attempts to 3841 * create a new one. 3842 * 3843 * Should be called with wq_pool_mutex held. 3844 * 3845 * Return: On success, a worker_pool with the same attributes as @attrs. 3846 * On failure, %NULL. 3847 */ 3848 static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs) 3849 { 3850 u32 hash = wqattrs_hash(attrs); 3851 struct worker_pool *pool; 3852 int node; 3853 int target_node = NUMA_NO_NODE; 3854 3855 lockdep_assert_held(&wq_pool_mutex); 3856 3857 /* do we already have a matching pool? */ 3858 hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) { 3859 if (wqattrs_equal(pool->attrs, attrs)) { 3860 pool->refcnt++; 3861 return pool; 3862 } 3863 } 3864 3865 /* if cpumask is contained inside a NUMA node, we belong to that node */ 3866 if (wq_numa_enabled) { 3867 for_each_node(node) { 3868 if (cpumask_subset(attrs->cpumask, 3869 wq_numa_possible_cpumask[node])) { 3870 target_node = node; 3871 break; 3872 } 3873 } 3874 } 3875 3876 /* nope, create a new one */ 3877 pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, target_node); 3878 if (!pool || init_worker_pool(pool) < 0) 3879 goto fail; 3880 3881 lockdep_set_subclass(&pool->lock, 1); /* see put_pwq() */ 3882 copy_workqueue_attrs(pool->attrs, attrs); 3883 pool->node = target_node; 3884 3885 /* 3886 * no_numa isn't a worker_pool attribute, always clear it. See 3887 * 'struct workqueue_attrs' comments for detail. 3888 */ 3889 pool->attrs->no_numa = false; 3890 3891 if (worker_pool_assign_id(pool) < 0) 3892 goto fail; 3893 3894 /* create and start the initial worker */ 3895 if (wq_online && !create_worker(pool)) 3896 goto fail; 3897 3898 /* install */ 3899 hash_add(unbound_pool_hash, &pool->hash_node, hash); 3900 3901 return pool; 3902 fail: 3903 if (pool) 3904 put_unbound_pool(pool); 3905 return NULL; 3906 } 3907 3908 static void rcu_free_pwq(struct rcu_head *rcu) 3909 { 3910 kmem_cache_free(pwq_cache, 3911 container_of(rcu, struct pool_workqueue, rcu)); 3912 } 3913 3914 /* 3915 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt 3916 * and needs to be destroyed. 3917 */ 3918 static void pwq_unbound_release_workfn(struct work_struct *work) 3919 { 3920 struct pool_workqueue *pwq = container_of(work, struct pool_workqueue, 3921 unbound_release_work); 3922 struct workqueue_struct *wq = pwq->wq; 3923 struct worker_pool *pool = pwq->pool; 3924 bool is_last = false; 3925 3926 /* 3927 * when @pwq is not linked, it doesn't hold any reference to the 3928 * @wq, and @wq is invalid to access. 3929 */ 3930 if (!list_empty(&pwq->pwqs_node)) { 3931 if (WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND))) 3932 return; 3933 3934 mutex_lock(&wq->mutex); 3935 list_del_rcu(&pwq->pwqs_node); 3936 is_last = list_empty(&wq->pwqs); 3937 mutex_unlock(&wq->mutex); 3938 } 3939 3940 mutex_lock(&wq_pool_mutex); 3941 put_unbound_pool(pool); 3942 mutex_unlock(&wq_pool_mutex); 3943 3944 call_rcu(&pwq->rcu, rcu_free_pwq); 3945 3946 /* 3947 * If we're the last pwq going away, @wq is already dead and no one 3948 * is gonna access it anymore. Schedule RCU free. 3949 */ 3950 if (is_last) { 3951 wq_unregister_lockdep(wq); 3952 call_rcu(&wq->rcu, rcu_free_wq); 3953 } 3954 } 3955 3956 /** 3957 * pwq_adjust_max_active - update a pwq's max_active to the current setting 3958 * @pwq: target pool_workqueue 3959 * 3960 * If @pwq isn't freezing, set @pwq->max_active to the associated 3961 * workqueue's saved_max_active and activate inactive work items 3962 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero. 3963 */ 3964 static void pwq_adjust_max_active(struct pool_workqueue *pwq) 3965 { 3966 struct workqueue_struct *wq = pwq->wq; 3967 bool freezable = wq->flags & WQ_FREEZABLE; 3968 unsigned long flags; 3969 3970 /* for @wq->saved_max_active */ 3971 lockdep_assert_held(&wq->mutex); 3972 3973 /* fast exit for non-freezable wqs */ 3974 if (!freezable && pwq->max_active == wq->saved_max_active) 3975 return; 3976 3977 /* this function can be called during early boot w/ irq disabled */ 3978 raw_spin_lock_irqsave(&pwq->pool->lock, flags); 3979 3980 /* 3981 * During [un]freezing, the caller is responsible for ensuring that 3982 * this function is called at least once after @workqueue_freezing 3983 * is updated and visible. 3984 */ 3985 if (!freezable || !workqueue_freezing) { 3986 bool kick = false; 3987 3988 pwq->max_active = wq->saved_max_active; 3989 3990 while (!list_empty(&pwq->inactive_works) && 3991 pwq->nr_active < pwq->max_active) { 3992 pwq_activate_first_inactive(pwq); 3993 kick = true; 3994 } 3995 3996 /* 3997 * Need to kick a worker after thawed or an unbound wq's 3998 * max_active is bumped. In realtime scenarios, always kicking a 3999 * worker will cause interference on the isolated cpu cores, so 4000 * let's kick iff work items were activated. 4001 */ 4002 if (kick) 4003 wake_up_worker(pwq->pool); 4004 } else { 4005 pwq->max_active = 0; 4006 } 4007 4008 raw_spin_unlock_irqrestore(&pwq->pool->lock, flags); 4009 } 4010 4011 /* initialize newly allocated @pwq which is associated with @wq and @pool */ 4012 static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq, 4013 struct worker_pool *pool) 4014 { 4015 BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK); 4016 4017 memset(pwq, 0, sizeof(*pwq)); 4018 4019 pwq->pool = pool; 4020 pwq->wq = wq; 4021 pwq->flush_color = -1; 4022 pwq->refcnt = 1; 4023 INIT_LIST_HEAD(&pwq->inactive_works); 4024 INIT_LIST_HEAD(&pwq->pwqs_node); 4025 INIT_LIST_HEAD(&pwq->mayday_node); 4026 INIT_WORK(&pwq->unbound_release_work, pwq_unbound_release_workfn); 4027 } 4028 4029 /* sync @pwq with the current state of its associated wq and link it */ 4030 static void link_pwq(struct pool_workqueue *pwq) 4031 { 4032 struct workqueue_struct *wq = pwq->wq; 4033 4034 lockdep_assert_held(&wq->mutex); 4035 4036 /* may be called multiple times, ignore if already linked */ 4037 if (!list_empty(&pwq->pwqs_node)) 4038 return; 4039 4040 /* set the matching work_color */ 4041 pwq->work_color = wq->work_color; 4042 4043 /* sync max_active to the current setting */ 4044 pwq_adjust_max_active(pwq); 4045 4046 /* link in @pwq */ 4047 list_add_rcu(&pwq->pwqs_node, &wq->pwqs); 4048 } 4049 4050 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */ 4051 static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq, 4052 const struct workqueue_attrs *attrs) 4053 { 4054 struct worker_pool *pool; 4055 struct pool_workqueue *pwq; 4056 4057 lockdep_assert_held(&wq_pool_mutex); 4058 4059 pool = get_unbound_pool(attrs); 4060 if (!pool) 4061 return NULL; 4062 4063 pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node); 4064 if (!pwq) { 4065 put_unbound_pool(pool); 4066 return NULL; 4067 } 4068 4069 init_pwq(pwq, wq, pool); 4070 return pwq; 4071 } 4072 4073 /** 4074 * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node 4075 * @attrs: the wq_attrs of the default pwq of the target workqueue 4076 * @node: the target NUMA node 4077 * @cpu_going_down: if >= 0, the CPU to consider as offline 4078 * @cpumask: outarg, the resulting cpumask 4079 * 4080 * Calculate the cpumask a workqueue with @attrs should use on @node. If 4081 * @cpu_going_down is >= 0, that cpu is considered offline during 4082 * calculation. The result is stored in @cpumask. 4083 * 4084 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If 4085 * enabled and @node has online CPUs requested by @attrs, the returned 4086 * cpumask is the intersection of the possible CPUs of @node and 4087 * @attrs->cpumask. 4088 * 4089 * The caller is responsible for ensuring that the cpumask of @node stays 4090 * stable. 4091 * 4092 * Return: %true if the resulting @cpumask is different from @attrs->cpumask, 4093 * %false if equal. 4094 */ 4095 static bool wq_calc_node_cpumask(const struct workqueue_attrs *attrs, int node, 4096 int cpu_going_down, cpumask_t *cpumask) 4097 { 4098 if (!wq_numa_enabled || attrs->no_numa) 4099 goto use_dfl; 4100 4101 /* does @node have any online CPUs @attrs wants? */ 4102 cpumask_and(cpumask, cpumask_of_node(node), attrs->cpumask); 4103 if (cpu_going_down >= 0) 4104 cpumask_clear_cpu(cpu_going_down, cpumask); 4105 4106 if (cpumask_empty(cpumask)) 4107 goto use_dfl; 4108 4109 /* yeap, return possible CPUs in @node that @attrs wants */ 4110 cpumask_and(cpumask, attrs->cpumask, wq_numa_possible_cpumask[node]); 4111 4112 if (cpumask_empty(cpumask)) { 4113 pr_warn_once("WARNING: workqueue cpumask: online intersect > " 4114 "possible intersect\n"); 4115 return false; 4116 } 4117 4118 return !cpumask_equal(cpumask, attrs->cpumask); 4119 4120 use_dfl: 4121 cpumask_copy(cpumask, attrs->cpumask); 4122 return false; 4123 } 4124 4125 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */ 4126 static struct pool_workqueue *numa_pwq_tbl_install(struct workqueue_struct *wq, 4127 int node, 4128 struct pool_workqueue *pwq) 4129 { 4130 struct pool_workqueue *old_pwq; 4131 4132 lockdep_assert_held(&wq_pool_mutex); 4133 lockdep_assert_held(&wq->mutex); 4134 4135 /* link_pwq() can handle duplicate calls */ 4136 link_pwq(pwq); 4137 4138 old_pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]); 4139 rcu_assign_pointer(wq->numa_pwq_tbl[node], pwq); 4140 return old_pwq; 4141 } 4142 4143 /* context to store the prepared attrs & pwqs before applying */ 4144 struct apply_wqattrs_ctx { 4145 struct workqueue_struct *wq; /* target workqueue */ 4146 struct workqueue_attrs *attrs; /* attrs to apply */ 4147 struct list_head list; /* queued for batching commit */ 4148 struct pool_workqueue *dfl_pwq; 4149 struct pool_workqueue *pwq_tbl[]; 4150 }; 4151 4152 /* free the resources after success or abort */ 4153 static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx) 4154 { 4155 if (ctx) { 4156 int node; 4157 4158 for_each_node(node) 4159 put_pwq_unlocked(ctx->pwq_tbl[node]); 4160 put_pwq_unlocked(ctx->dfl_pwq); 4161 4162 free_workqueue_attrs(ctx->attrs); 4163 4164 kfree(ctx); 4165 } 4166 } 4167 4168 /* allocate the attrs and pwqs for later installation */ 4169 static struct apply_wqattrs_ctx * 4170 apply_wqattrs_prepare(struct workqueue_struct *wq, 4171 const struct workqueue_attrs *attrs, 4172 const cpumask_var_t unbound_cpumask) 4173 { 4174 struct apply_wqattrs_ctx *ctx; 4175 struct workqueue_attrs *new_attrs, *tmp_attrs; 4176 int node; 4177 4178 lockdep_assert_held(&wq_pool_mutex); 4179 4180 ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_node_ids), GFP_KERNEL); 4181 4182 new_attrs = alloc_workqueue_attrs(); 4183 tmp_attrs = alloc_workqueue_attrs(); 4184 if (!ctx || !new_attrs || !tmp_attrs) 4185 goto out_free; 4186 4187 /* 4188 * Calculate the attrs of the default pwq with unbound_cpumask 4189 * which is wq_unbound_cpumask or to set to wq_unbound_cpumask. 4190 * If the user configured cpumask doesn't overlap with the 4191 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask. 4192 */ 4193 copy_workqueue_attrs(new_attrs, attrs); 4194 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, unbound_cpumask); 4195 if (unlikely(cpumask_empty(new_attrs->cpumask))) 4196 cpumask_copy(new_attrs->cpumask, unbound_cpumask); 4197 4198 /* 4199 * We may create multiple pwqs with differing cpumasks. Make a 4200 * copy of @new_attrs which will be modified and used to obtain 4201 * pools. 4202 */ 4203 copy_workqueue_attrs(tmp_attrs, new_attrs); 4204 4205 /* 4206 * If something goes wrong during CPU up/down, we'll fall back to 4207 * the default pwq covering whole @attrs->cpumask. Always create 4208 * it even if we don't use it immediately. 4209 */ 4210 ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs); 4211 if (!ctx->dfl_pwq) 4212 goto out_free; 4213 4214 for_each_node(node) { 4215 if (wq_calc_node_cpumask(new_attrs, node, -1, tmp_attrs->cpumask)) { 4216 ctx->pwq_tbl[node] = alloc_unbound_pwq(wq, tmp_attrs); 4217 if (!ctx->pwq_tbl[node]) 4218 goto out_free; 4219 } else { 4220 ctx->dfl_pwq->refcnt++; 4221 ctx->pwq_tbl[node] = ctx->dfl_pwq; 4222 } 4223 } 4224 4225 /* save the user configured attrs and sanitize it. */ 4226 copy_workqueue_attrs(new_attrs, attrs); 4227 cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask); 4228 ctx->attrs = new_attrs; 4229 4230 ctx->wq = wq; 4231 free_workqueue_attrs(tmp_attrs); 4232 return ctx; 4233 4234 out_free: 4235 free_workqueue_attrs(tmp_attrs); 4236 free_workqueue_attrs(new_attrs); 4237 apply_wqattrs_cleanup(ctx); 4238 return NULL; 4239 } 4240 4241 /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */ 4242 static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx) 4243 { 4244 int node; 4245 4246 /* all pwqs have been created successfully, let's install'em */ 4247 mutex_lock(&ctx->wq->mutex); 4248 4249 copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs); 4250 4251 /* save the previous pwq and install the new one */ 4252 for_each_node(node) 4253 ctx->pwq_tbl[node] = numa_pwq_tbl_install(ctx->wq, node, 4254 ctx->pwq_tbl[node]); 4255 4256 /* @dfl_pwq might not have been used, ensure it's linked */ 4257 link_pwq(ctx->dfl_pwq); 4258 swap(ctx->wq->dfl_pwq, ctx->dfl_pwq); 4259 4260 mutex_unlock(&ctx->wq->mutex); 4261 } 4262 4263 static void apply_wqattrs_lock(void) 4264 { 4265 /* CPUs should stay stable across pwq creations and installations */ 4266 cpus_read_lock(); 4267 mutex_lock(&wq_pool_mutex); 4268 } 4269 4270 static void apply_wqattrs_unlock(void) 4271 { 4272 mutex_unlock(&wq_pool_mutex); 4273 cpus_read_unlock(); 4274 } 4275 4276 static int apply_workqueue_attrs_locked(struct workqueue_struct *wq, 4277 const struct workqueue_attrs *attrs) 4278 { 4279 struct apply_wqattrs_ctx *ctx; 4280 4281 /* only unbound workqueues can change attributes */ 4282 if (WARN_ON(!(wq->flags & WQ_UNBOUND))) 4283 return -EINVAL; 4284 4285 /* creating multiple pwqs breaks ordering guarantee */ 4286 if (!list_empty(&wq->pwqs)) { 4287 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT)) 4288 return -EINVAL; 4289 4290 wq->flags &= ~__WQ_ORDERED; 4291 } 4292 4293 ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask); 4294 if (!ctx) 4295 return -ENOMEM; 4296 4297 /* the ctx has been prepared successfully, let's commit it */ 4298 apply_wqattrs_commit(ctx); 4299 apply_wqattrs_cleanup(ctx); 4300 4301 return 0; 4302 } 4303 4304 /** 4305 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue 4306 * @wq: the target workqueue 4307 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs() 4308 * 4309 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA 4310 * machines, this function maps a separate pwq to each NUMA node with 4311 * possibles CPUs in @attrs->cpumask so that work items are affine to the 4312 * NUMA node it was issued on. Older pwqs are released as in-flight work 4313 * items finish. Note that a work item which repeatedly requeues itself 4314 * back-to-back will stay on its current pwq. 4315 * 4316 * Performs GFP_KERNEL allocations. 4317 * 4318 * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock(). 4319 * 4320 * Return: 0 on success and -errno on failure. 4321 */ 4322 int apply_workqueue_attrs(struct workqueue_struct *wq, 4323 const struct workqueue_attrs *attrs) 4324 { 4325 int ret; 4326 4327 lockdep_assert_cpus_held(); 4328 4329 mutex_lock(&wq_pool_mutex); 4330 ret = apply_workqueue_attrs_locked(wq, attrs); 4331 mutex_unlock(&wq_pool_mutex); 4332 4333 return ret; 4334 } 4335 4336 /** 4337 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug 4338 * @wq: the target workqueue 4339 * @cpu: the CPU coming up or going down 4340 * @online: whether @cpu is coming up or going down 4341 * 4342 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and 4343 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of 4344 * @wq accordingly. 4345 * 4346 * If NUMA affinity can't be adjusted due to memory allocation failure, it 4347 * falls back to @wq->dfl_pwq which may not be optimal but is always 4348 * correct. 4349 * 4350 * Note that when the last allowed CPU of a NUMA node goes offline for a 4351 * workqueue with a cpumask spanning multiple nodes, the workers which were 4352 * already executing the work items for the workqueue will lose their CPU 4353 * affinity and may execute on any CPU. This is similar to how per-cpu 4354 * workqueues behave on CPU_DOWN. If a workqueue user wants strict 4355 * affinity, it's the user's responsibility to flush the work item from 4356 * CPU_DOWN_PREPARE. 4357 */ 4358 static void wq_update_unbound_numa(struct workqueue_struct *wq, int cpu, 4359 bool online) 4360 { 4361 int node = cpu_to_node(cpu); 4362 int cpu_off = online ? -1 : cpu; 4363 struct pool_workqueue *old_pwq = NULL, *pwq; 4364 struct workqueue_attrs *target_attrs; 4365 cpumask_t *cpumask; 4366 4367 lockdep_assert_held(&wq_pool_mutex); 4368 4369 if (!wq_numa_enabled || !(wq->flags & WQ_UNBOUND) || 4370 wq->unbound_attrs->no_numa) 4371 return; 4372 4373 /* 4374 * We don't wanna alloc/free wq_attrs for each wq for each CPU. 4375 * Let's use a preallocated one. The following buf is protected by 4376 * CPU hotplug exclusion. 4377 */ 4378 target_attrs = wq_update_unbound_numa_attrs_buf; 4379 cpumask = target_attrs->cpumask; 4380 4381 copy_workqueue_attrs(target_attrs, wq->unbound_attrs); 4382 pwq = unbound_pwq_by_node(wq, node); 4383 4384 /* 4385 * Let's determine what needs to be done. If the target cpumask is 4386 * different from the default pwq's, we need to compare it to @pwq's 4387 * and create a new one if they don't match. If the target cpumask 4388 * equals the default pwq's, the default pwq should be used. 4389 */ 4390 if (wq_calc_node_cpumask(wq->dfl_pwq->pool->attrs, node, cpu_off, cpumask)) { 4391 if (cpumask_equal(cpumask, pwq->pool->attrs->cpumask)) 4392 return; 4393 } else { 4394 goto use_dfl_pwq; 4395 } 4396 4397 /* create a new pwq */ 4398 pwq = alloc_unbound_pwq(wq, target_attrs); 4399 if (!pwq) { 4400 pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n", 4401 wq->name); 4402 goto use_dfl_pwq; 4403 } 4404 4405 /* Install the new pwq. */ 4406 mutex_lock(&wq->mutex); 4407 old_pwq = numa_pwq_tbl_install(wq, node, pwq); 4408 goto out_unlock; 4409 4410 use_dfl_pwq: 4411 mutex_lock(&wq->mutex); 4412 raw_spin_lock_irq(&wq->dfl_pwq->pool->lock); 4413 get_pwq(wq->dfl_pwq); 4414 raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock); 4415 old_pwq = numa_pwq_tbl_install(wq, node, wq->dfl_pwq); 4416 out_unlock: 4417 mutex_unlock(&wq->mutex); 4418 put_pwq_unlocked(old_pwq); 4419 } 4420 4421 static int alloc_and_link_pwqs(struct workqueue_struct *wq) 4422 { 4423 bool highpri = wq->flags & WQ_HIGHPRI; 4424 int cpu, ret; 4425 4426 if (!(wq->flags & WQ_UNBOUND)) { 4427 wq->cpu_pwqs = alloc_percpu(struct pool_workqueue); 4428 if (!wq->cpu_pwqs) 4429 return -ENOMEM; 4430 4431 for_each_possible_cpu(cpu) { 4432 struct pool_workqueue *pwq = 4433 per_cpu_ptr(wq->cpu_pwqs, cpu); 4434 struct worker_pool *cpu_pools = 4435 per_cpu(cpu_worker_pools, cpu); 4436 4437 init_pwq(pwq, wq, &cpu_pools[highpri]); 4438 4439 mutex_lock(&wq->mutex); 4440 link_pwq(pwq); 4441 mutex_unlock(&wq->mutex); 4442 } 4443 return 0; 4444 } 4445 4446 cpus_read_lock(); 4447 if (wq->flags & __WQ_ORDERED) { 4448 ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]); 4449 /* there should only be single pwq for ordering guarantee */ 4450 WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node || 4451 wq->pwqs.prev != &wq->dfl_pwq->pwqs_node), 4452 "ordering guarantee broken for workqueue %s\n", wq->name); 4453 } else { 4454 ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]); 4455 } 4456 cpus_read_unlock(); 4457 4458 return ret; 4459 } 4460 4461 static int wq_clamp_max_active(int max_active, unsigned int flags, 4462 const char *name) 4463 { 4464 int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE; 4465 4466 if (max_active < 1 || max_active > lim) 4467 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n", 4468 max_active, name, 1, lim); 4469 4470 return clamp_val(max_active, 1, lim); 4471 } 4472 4473 /* 4474 * Workqueues which may be used during memory reclaim should have a rescuer 4475 * to guarantee forward progress. 4476 */ 4477 static int init_rescuer(struct workqueue_struct *wq) 4478 { 4479 struct worker *rescuer; 4480 int ret; 4481 4482 if (!(wq->flags & WQ_MEM_RECLAIM)) 4483 return 0; 4484 4485 rescuer = alloc_worker(NUMA_NO_NODE); 4486 if (!rescuer) { 4487 pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n", 4488 wq->name); 4489 return -ENOMEM; 4490 } 4491 4492 rescuer->rescue_wq = wq; 4493 rescuer->task = kthread_create(rescuer_thread, rescuer, "%s", wq->name); 4494 if (IS_ERR(rescuer->task)) { 4495 ret = PTR_ERR(rescuer->task); 4496 pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe", 4497 wq->name, ERR_PTR(ret)); 4498 kfree(rescuer); 4499 return ret; 4500 } 4501 4502 wq->rescuer = rescuer; 4503 kthread_bind_mask(rescuer->task, cpu_possible_mask); 4504 wake_up_process(rescuer->task); 4505 4506 return 0; 4507 } 4508 4509 __printf(1, 4) 4510 struct workqueue_struct *alloc_workqueue(const char *fmt, 4511 unsigned int flags, 4512 int max_active, ...) 4513 { 4514 size_t tbl_size = 0; 4515 va_list args; 4516 struct workqueue_struct *wq; 4517 struct pool_workqueue *pwq; 4518 4519 /* 4520 * Unbound && max_active == 1 used to imply ordered, which is no 4521 * longer the case on NUMA machines due to per-node pools. While 4522 * alloc_ordered_workqueue() is the right way to create an ordered 4523 * workqueue, keep the previous behavior to avoid subtle breakages 4524 * on NUMA. 4525 */ 4526 if ((flags & WQ_UNBOUND) && max_active == 1) 4527 flags |= __WQ_ORDERED; 4528 4529 /* see the comment above the definition of WQ_POWER_EFFICIENT */ 4530 if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient) 4531 flags |= WQ_UNBOUND; 4532 4533 /* allocate wq and format name */ 4534 if (flags & WQ_UNBOUND) 4535 tbl_size = nr_node_ids * sizeof(wq->numa_pwq_tbl[0]); 4536 4537 wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL); 4538 if (!wq) 4539 return NULL; 4540 4541 if (flags & WQ_UNBOUND) { 4542 wq->unbound_attrs = alloc_workqueue_attrs(); 4543 if (!wq->unbound_attrs) 4544 goto err_free_wq; 4545 } 4546 4547 va_start(args, max_active); 4548 vsnprintf(wq->name, sizeof(wq->name), fmt, args); 4549 va_end(args); 4550 4551 max_active = max_active ?: WQ_DFL_ACTIVE; 4552 max_active = wq_clamp_max_active(max_active, flags, wq->name); 4553 4554 /* init wq */ 4555 wq->flags = flags; 4556 wq->saved_max_active = max_active; 4557 mutex_init(&wq->mutex); 4558 atomic_set(&wq->nr_pwqs_to_flush, 0); 4559 INIT_LIST_HEAD(&wq->pwqs); 4560 INIT_LIST_HEAD(&wq->flusher_queue); 4561 INIT_LIST_HEAD(&wq->flusher_overflow); 4562 INIT_LIST_HEAD(&wq->maydays); 4563 4564 wq_init_lockdep(wq); 4565 INIT_LIST_HEAD(&wq->list); 4566 4567 if (alloc_and_link_pwqs(wq) < 0) 4568 goto err_unreg_lockdep; 4569 4570 if (wq_online && init_rescuer(wq) < 0) 4571 goto err_destroy; 4572 4573 if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq)) 4574 goto err_destroy; 4575 4576 /* 4577 * wq_pool_mutex protects global freeze state and workqueues list. 4578 * Grab it, adjust max_active and add the new @wq to workqueues 4579 * list. 4580 */ 4581 mutex_lock(&wq_pool_mutex); 4582 4583 mutex_lock(&wq->mutex); 4584 for_each_pwq(pwq, wq) 4585 pwq_adjust_max_active(pwq); 4586 mutex_unlock(&wq->mutex); 4587 4588 list_add_tail_rcu(&wq->list, &workqueues); 4589 4590 mutex_unlock(&wq_pool_mutex); 4591 4592 return wq; 4593 4594 err_unreg_lockdep: 4595 wq_unregister_lockdep(wq); 4596 wq_free_lockdep(wq); 4597 err_free_wq: 4598 free_workqueue_attrs(wq->unbound_attrs); 4599 kfree(wq); 4600 return NULL; 4601 err_destroy: 4602 destroy_workqueue(wq); 4603 return NULL; 4604 } 4605 EXPORT_SYMBOL_GPL(alloc_workqueue); 4606 4607 static bool pwq_busy(struct pool_workqueue *pwq) 4608 { 4609 int i; 4610 4611 for (i = 0; i < WORK_NR_COLORS; i++) 4612 if (pwq->nr_in_flight[i]) 4613 return true; 4614 4615 if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1)) 4616 return true; 4617 if (pwq->nr_active || !list_empty(&pwq->inactive_works)) 4618 return true; 4619 4620 return false; 4621 } 4622 4623 /** 4624 * destroy_workqueue - safely terminate a workqueue 4625 * @wq: target workqueue 4626 * 4627 * Safely destroy a workqueue. All work currently pending will be done first. 4628 */ 4629 void destroy_workqueue(struct workqueue_struct *wq) 4630 { 4631 struct pool_workqueue *pwq; 4632 int node; 4633 4634 /* 4635 * Remove it from sysfs first so that sanity check failure doesn't 4636 * lead to sysfs name conflicts. 4637 */ 4638 workqueue_sysfs_unregister(wq); 4639 4640 /* mark the workqueue destruction is in progress */ 4641 mutex_lock(&wq->mutex); 4642 wq->flags |= __WQ_DESTROYING; 4643 mutex_unlock(&wq->mutex); 4644 4645 /* drain it before proceeding with destruction */ 4646 drain_workqueue(wq); 4647 4648 /* kill rescuer, if sanity checks fail, leave it w/o rescuer */ 4649 if (wq->rescuer) { 4650 struct worker *rescuer = wq->rescuer; 4651 4652 /* this prevents new queueing */ 4653 raw_spin_lock_irq(&wq_mayday_lock); 4654 wq->rescuer = NULL; 4655 raw_spin_unlock_irq(&wq_mayday_lock); 4656 4657 /* rescuer will empty maydays list before exiting */ 4658 kthread_stop(rescuer->task); 4659 kfree(rescuer); 4660 } 4661 4662 /* 4663 * Sanity checks - grab all the locks so that we wait for all 4664 * in-flight operations which may do put_pwq(). 4665 */ 4666 mutex_lock(&wq_pool_mutex); 4667 mutex_lock(&wq->mutex); 4668 for_each_pwq(pwq, wq) { 4669 raw_spin_lock_irq(&pwq->pool->lock); 4670 if (WARN_ON(pwq_busy(pwq))) { 4671 pr_warn("%s: %s has the following busy pwq\n", 4672 __func__, wq->name); 4673 show_pwq(pwq); 4674 raw_spin_unlock_irq(&pwq->pool->lock); 4675 mutex_unlock(&wq->mutex); 4676 mutex_unlock(&wq_pool_mutex); 4677 show_one_workqueue(wq); 4678 return; 4679 } 4680 raw_spin_unlock_irq(&pwq->pool->lock); 4681 } 4682 mutex_unlock(&wq->mutex); 4683 4684 /* 4685 * wq list is used to freeze wq, remove from list after 4686 * flushing is complete in case freeze races us. 4687 */ 4688 list_del_rcu(&wq->list); 4689 mutex_unlock(&wq_pool_mutex); 4690 4691 if (!(wq->flags & WQ_UNBOUND)) { 4692 wq_unregister_lockdep(wq); 4693 /* 4694 * The base ref is never dropped on per-cpu pwqs. Directly 4695 * schedule RCU free. 4696 */ 4697 call_rcu(&wq->rcu, rcu_free_wq); 4698 } else { 4699 /* 4700 * We're the sole accessor of @wq at this point. Directly 4701 * access numa_pwq_tbl[] and dfl_pwq to put the base refs. 4702 * @wq will be freed when the last pwq is released. 4703 */ 4704 for_each_node(node) { 4705 pwq = rcu_access_pointer(wq->numa_pwq_tbl[node]); 4706 RCU_INIT_POINTER(wq->numa_pwq_tbl[node], NULL); 4707 put_pwq_unlocked(pwq); 4708 } 4709 4710 /* 4711 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is 4712 * put. Don't access it afterwards. 4713 */ 4714 pwq = wq->dfl_pwq; 4715 wq->dfl_pwq = NULL; 4716 put_pwq_unlocked(pwq); 4717 } 4718 } 4719 EXPORT_SYMBOL_GPL(destroy_workqueue); 4720 4721 /** 4722 * workqueue_set_max_active - adjust max_active of a workqueue 4723 * @wq: target workqueue 4724 * @max_active: new max_active value. 4725 * 4726 * Set max_active of @wq to @max_active. 4727 * 4728 * CONTEXT: 4729 * Don't call from IRQ context. 4730 */ 4731 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active) 4732 { 4733 struct pool_workqueue *pwq; 4734 4735 /* disallow meddling with max_active for ordered workqueues */ 4736 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT)) 4737 return; 4738 4739 max_active = wq_clamp_max_active(max_active, wq->flags, wq->name); 4740 4741 mutex_lock(&wq->mutex); 4742 4743 wq->flags &= ~__WQ_ORDERED; 4744 wq->saved_max_active = max_active; 4745 4746 for_each_pwq(pwq, wq) 4747 pwq_adjust_max_active(pwq); 4748 4749 mutex_unlock(&wq->mutex); 4750 } 4751 EXPORT_SYMBOL_GPL(workqueue_set_max_active); 4752 4753 /** 4754 * current_work - retrieve %current task's work struct 4755 * 4756 * Determine if %current task is a workqueue worker and what it's working on. 4757 * Useful to find out the context that the %current task is running in. 4758 * 4759 * Return: work struct if %current task is a workqueue worker, %NULL otherwise. 4760 */ 4761 struct work_struct *current_work(void) 4762 { 4763 struct worker *worker = current_wq_worker(); 4764 4765 return worker ? worker->current_work : NULL; 4766 } 4767 EXPORT_SYMBOL(current_work); 4768 4769 /** 4770 * current_is_workqueue_rescuer - is %current workqueue rescuer? 4771 * 4772 * Determine whether %current is a workqueue rescuer. Can be used from 4773 * work functions to determine whether it's being run off the rescuer task. 4774 * 4775 * Return: %true if %current is a workqueue rescuer. %false otherwise. 4776 */ 4777 bool current_is_workqueue_rescuer(void) 4778 { 4779 struct worker *worker = current_wq_worker(); 4780 4781 return worker && worker->rescue_wq; 4782 } 4783 4784 /** 4785 * workqueue_congested - test whether a workqueue is congested 4786 * @cpu: CPU in question 4787 * @wq: target workqueue 4788 * 4789 * Test whether @wq's cpu workqueue for @cpu is congested. There is 4790 * no synchronization around this function and the test result is 4791 * unreliable and only useful as advisory hints or for debugging. 4792 * 4793 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU. 4794 * Note that both per-cpu and unbound workqueues may be associated with 4795 * multiple pool_workqueues which have separate congested states. A 4796 * workqueue being congested on one CPU doesn't mean the workqueue is also 4797 * contested on other CPUs / NUMA nodes. 4798 * 4799 * Return: 4800 * %true if congested, %false otherwise. 4801 */ 4802 bool workqueue_congested(int cpu, struct workqueue_struct *wq) 4803 { 4804 struct pool_workqueue *pwq; 4805 bool ret; 4806 4807 rcu_read_lock(); 4808 preempt_disable(); 4809 4810 if (cpu == WORK_CPU_UNBOUND) 4811 cpu = smp_processor_id(); 4812 4813 if (!(wq->flags & WQ_UNBOUND)) 4814 pwq = per_cpu_ptr(wq->cpu_pwqs, cpu); 4815 else 4816 pwq = unbound_pwq_by_node(wq, cpu_to_node(cpu)); 4817 4818 ret = !list_empty(&pwq->inactive_works); 4819 preempt_enable(); 4820 rcu_read_unlock(); 4821 4822 return ret; 4823 } 4824 EXPORT_SYMBOL_GPL(workqueue_congested); 4825 4826 /** 4827 * work_busy - test whether a work is currently pending or running 4828 * @work: the work to be tested 4829 * 4830 * Test whether @work is currently pending or running. There is no 4831 * synchronization around this function and the test result is 4832 * unreliable and only useful as advisory hints or for debugging. 4833 * 4834 * Return: 4835 * OR'd bitmask of WORK_BUSY_* bits. 4836 */ 4837 unsigned int work_busy(struct work_struct *work) 4838 { 4839 struct worker_pool *pool; 4840 unsigned long flags; 4841 unsigned int ret = 0; 4842 4843 if (work_pending(work)) 4844 ret |= WORK_BUSY_PENDING; 4845 4846 rcu_read_lock(); 4847 pool = get_work_pool(work); 4848 if (pool) { 4849 raw_spin_lock_irqsave(&pool->lock, flags); 4850 if (find_worker_executing_work(pool, work)) 4851 ret |= WORK_BUSY_RUNNING; 4852 raw_spin_unlock_irqrestore(&pool->lock, flags); 4853 } 4854 rcu_read_unlock(); 4855 4856 return ret; 4857 } 4858 EXPORT_SYMBOL_GPL(work_busy); 4859 4860 /** 4861 * set_worker_desc - set description for the current work item 4862 * @fmt: printf-style format string 4863 * @...: arguments for the format string 4864 * 4865 * This function can be called by a running work function to describe what 4866 * the work item is about. If the worker task gets dumped, this 4867 * information will be printed out together to help debugging. The 4868 * description can be at most WORKER_DESC_LEN including the trailing '\0'. 4869 */ 4870 void set_worker_desc(const char *fmt, ...) 4871 { 4872 struct worker *worker = current_wq_worker(); 4873 va_list args; 4874 4875 if (worker) { 4876 va_start(args, fmt); 4877 vsnprintf(worker->desc, sizeof(worker->desc), fmt, args); 4878 va_end(args); 4879 } 4880 } 4881 EXPORT_SYMBOL_GPL(set_worker_desc); 4882 4883 /** 4884 * print_worker_info - print out worker information and description 4885 * @log_lvl: the log level to use when printing 4886 * @task: target task 4887 * 4888 * If @task is a worker and currently executing a work item, print out the 4889 * name of the workqueue being serviced and worker description set with 4890 * set_worker_desc() by the currently executing work item. 4891 * 4892 * This function can be safely called on any task as long as the 4893 * task_struct itself is accessible. While safe, this function isn't 4894 * synchronized and may print out mixups or garbages of limited length. 4895 */ 4896 void print_worker_info(const char *log_lvl, struct task_struct *task) 4897 { 4898 work_func_t *fn = NULL; 4899 char name[WQ_NAME_LEN] = { }; 4900 char desc[WORKER_DESC_LEN] = { }; 4901 struct pool_workqueue *pwq = NULL; 4902 struct workqueue_struct *wq = NULL; 4903 struct worker *worker; 4904 4905 if (!(task->flags & PF_WQ_WORKER)) 4906 return; 4907 4908 /* 4909 * This function is called without any synchronization and @task 4910 * could be in any state. Be careful with dereferences. 4911 */ 4912 worker = kthread_probe_data(task); 4913 4914 /* 4915 * Carefully copy the associated workqueue's workfn, name and desc. 4916 * Keep the original last '\0' in case the original is garbage. 4917 */ 4918 copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn)); 4919 copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq)); 4920 copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq)); 4921 copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1); 4922 copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1); 4923 4924 if (fn || name[0] || desc[0]) { 4925 printk("%sWorkqueue: %s %ps", log_lvl, name, fn); 4926 if (strcmp(name, desc)) 4927 pr_cont(" (%s)", desc); 4928 pr_cont("\n"); 4929 } 4930 } 4931 4932 static void pr_cont_pool_info(struct worker_pool *pool) 4933 { 4934 pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask); 4935 if (pool->node != NUMA_NO_NODE) 4936 pr_cont(" node=%d", pool->node); 4937 pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice); 4938 } 4939 4940 struct pr_cont_work_struct { 4941 bool comma; 4942 work_func_t func; 4943 long ctr; 4944 }; 4945 4946 static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp) 4947 { 4948 if (!pcwsp->ctr) 4949 goto out_record; 4950 if (func == pcwsp->func) { 4951 pcwsp->ctr++; 4952 return; 4953 } 4954 if (pcwsp->ctr == 1) 4955 pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func); 4956 else 4957 pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func); 4958 pcwsp->ctr = 0; 4959 out_record: 4960 if ((long)func == -1L) 4961 return; 4962 pcwsp->comma = comma; 4963 pcwsp->func = func; 4964 pcwsp->ctr = 1; 4965 } 4966 4967 static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp) 4968 { 4969 if (work->func == wq_barrier_func) { 4970 struct wq_barrier *barr; 4971 4972 barr = container_of(work, struct wq_barrier, work); 4973 4974 pr_cont_work_flush(comma, (work_func_t)-1, pcwsp); 4975 pr_cont("%s BAR(%d)", comma ? "," : "", 4976 task_pid_nr(barr->task)); 4977 } else { 4978 if (!comma) 4979 pr_cont_work_flush(comma, (work_func_t)-1, pcwsp); 4980 pr_cont_work_flush(comma, work->func, pcwsp); 4981 } 4982 } 4983 4984 static void show_pwq(struct pool_workqueue *pwq) 4985 { 4986 struct pr_cont_work_struct pcws = { .ctr = 0, }; 4987 struct worker_pool *pool = pwq->pool; 4988 struct work_struct *work; 4989 struct worker *worker; 4990 bool has_in_flight = false, has_pending = false; 4991 int bkt; 4992 4993 pr_info(" pwq %d:", pool->id); 4994 pr_cont_pool_info(pool); 4995 4996 pr_cont(" active=%d/%d refcnt=%d%s\n", 4997 pwq->nr_active, pwq->max_active, pwq->refcnt, 4998 !list_empty(&pwq->mayday_node) ? " MAYDAY" : ""); 4999 5000 hash_for_each(pool->busy_hash, bkt, worker, hentry) { 5001 if (worker->current_pwq == pwq) { 5002 has_in_flight = true; 5003 break; 5004 } 5005 } 5006 if (has_in_flight) { 5007 bool comma = false; 5008 5009 pr_info(" in-flight:"); 5010 hash_for_each(pool->busy_hash, bkt, worker, hentry) { 5011 if (worker->current_pwq != pwq) 5012 continue; 5013 5014 pr_cont("%s %d%s:%ps", comma ? "," : "", 5015 task_pid_nr(worker->task), 5016 worker->rescue_wq ? "(RESCUER)" : "", 5017 worker->current_func); 5018 list_for_each_entry(work, &worker->scheduled, entry) 5019 pr_cont_work(false, work, &pcws); 5020 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws); 5021 comma = true; 5022 } 5023 pr_cont("\n"); 5024 } 5025 5026 list_for_each_entry(work, &pool->worklist, entry) { 5027 if (get_work_pwq(work) == pwq) { 5028 has_pending = true; 5029 break; 5030 } 5031 } 5032 if (has_pending) { 5033 bool comma = false; 5034 5035 pr_info(" pending:"); 5036 list_for_each_entry(work, &pool->worklist, entry) { 5037 if (get_work_pwq(work) != pwq) 5038 continue; 5039 5040 pr_cont_work(comma, work, &pcws); 5041 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED); 5042 } 5043 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws); 5044 pr_cont("\n"); 5045 } 5046 5047 if (!list_empty(&pwq->inactive_works)) { 5048 bool comma = false; 5049 5050 pr_info(" inactive:"); 5051 list_for_each_entry(work, &pwq->inactive_works, entry) { 5052 pr_cont_work(comma, work, &pcws); 5053 comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED); 5054 } 5055 pr_cont_work_flush(comma, (work_func_t)-1L, &pcws); 5056 pr_cont("\n"); 5057 } 5058 } 5059 5060 /** 5061 * show_one_workqueue - dump state of specified workqueue 5062 * @wq: workqueue whose state will be printed 5063 */ 5064 void show_one_workqueue(struct workqueue_struct *wq) 5065 { 5066 struct pool_workqueue *pwq; 5067 bool idle = true; 5068 unsigned long flags; 5069 5070 for_each_pwq(pwq, wq) { 5071 if (pwq->nr_active || !list_empty(&pwq->inactive_works)) { 5072 idle = false; 5073 break; 5074 } 5075 } 5076 if (idle) /* Nothing to print for idle workqueue */ 5077 return; 5078 5079 pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags); 5080 5081 for_each_pwq(pwq, wq) { 5082 raw_spin_lock_irqsave(&pwq->pool->lock, flags); 5083 if (pwq->nr_active || !list_empty(&pwq->inactive_works)) { 5084 /* 5085 * Defer printing to avoid deadlocks in console 5086 * drivers that queue work while holding locks 5087 * also taken in their write paths. 5088 */ 5089 printk_deferred_enter(); 5090 show_pwq(pwq); 5091 printk_deferred_exit(); 5092 } 5093 raw_spin_unlock_irqrestore(&pwq->pool->lock, flags); 5094 /* 5095 * We could be printing a lot from atomic context, e.g. 5096 * sysrq-t -> show_all_workqueues(). Avoid triggering 5097 * hard lockup. 5098 */ 5099 touch_nmi_watchdog(); 5100 } 5101 5102 } 5103 5104 /** 5105 * show_one_worker_pool - dump state of specified worker pool 5106 * @pool: worker pool whose state will be printed 5107 */ 5108 static void show_one_worker_pool(struct worker_pool *pool) 5109 { 5110 struct worker *worker; 5111 bool first = true; 5112 unsigned long flags; 5113 unsigned long hung = 0; 5114 5115 raw_spin_lock_irqsave(&pool->lock, flags); 5116 if (pool->nr_workers == pool->nr_idle) 5117 goto next_pool; 5118 5119 /* How long the first pending work is waiting for a worker. */ 5120 if (!list_empty(&pool->worklist)) 5121 hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000; 5122 5123 /* 5124 * Defer printing to avoid deadlocks in console drivers that 5125 * queue work while holding locks also taken in their write 5126 * paths. 5127 */ 5128 printk_deferred_enter(); 5129 pr_info("pool %d:", pool->id); 5130 pr_cont_pool_info(pool); 5131 pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers); 5132 if (pool->manager) 5133 pr_cont(" manager: %d", 5134 task_pid_nr(pool->manager->task)); 5135 list_for_each_entry(worker, &pool->idle_list, entry) { 5136 pr_cont(" %s%d", first ? "idle: " : "", 5137 task_pid_nr(worker->task)); 5138 first = false; 5139 } 5140 pr_cont("\n"); 5141 printk_deferred_exit(); 5142 next_pool: 5143 raw_spin_unlock_irqrestore(&pool->lock, flags); 5144 /* 5145 * We could be printing a lot from atomic context, e.g. 5146 * sysrq-t -> show_all_workqueues(). Avoid triggering 5147 * hard lockup. 5148 */ 5149 touch_nmi_watchdog(); 5150 5151 } 5152 5153 /** 5154 * show_all_workqueues - dump workqueue state 5155 * 5156 * Called from a sysrq handler and prints out all busy workqueues and pools. 5157 */ 5158 void show_all_workqueues(void) 5159 { 5160 struct workqueue_struct *wq; 5161 struct worker_pool *pool; 5162 int pi; 5163 5164 rcu_read_lock(); 5165 5166 pr_info("Showing busy workqueues and worker pools:\n"); 5167 5168 list_for_each_entry_rcu(wq, &workqueues, list) 5169 show_one_workqueue(wq); 5170 5171 for_each_pool(pool, pi) 5172 show_one_worker_pool(pool); 5173 5174 rcu_read_unlock(); 5175 } 5176 5177 /** 5178 * show_freezable_workqueues - dump freezable workqueue state 5179 * 5180 * Called from try_to_freeze_tasks() and prints out all freezable workqueues 5181 * still busy. 5182 */ 5183 void show_freezable_workqueues(void) 5184 { 5185 struct workqueue_struct *wq; 5186 5187 rcu_read_lock(); 5188 5189 pr_info("Showing freezable workqueues that are still busy:\n"); 5190 5191 list_for_each_entry_rcu(wq, &workqueues, list) { 5192 if (!(wq->flags & WQ_FREEZABLE)) 5193 continue; 5194 show_one_workqueue(wq); 5195 } 5196 5197 rcu_read_unlock(); 5198 } 5199 5200 /* used to show worker information through /proc/PID/{comm,stat,status} */ 5201 void wq_worker_comm(char *buf, size_t size, struct task_struct *task) 5202 { 5203 int off; 5204 5205 /* always show the actual comm */ 5206 off = strscpy(buf, task->comm, size); 5207 if (off < 0) 5208 return; 5209 5210 /* stabilize PF_WQ_WORKER and worker pool association */ 5211 mutex_lock(&wq_pool_attach_mutex); 5212 5213 if (task->flags & PF_WQ_WORKER) { 5214 struct worker *worker = kthread_data(task); 5215 struct worker_pool *pool = worker->pool; 5216 5217 if (pool) { 5218 raw_spin_lock_irq(&pool->lock); 5219 /* 5220 * ->desc tracks information (wq name or 5221 * set_worker_desc()) for the latest execution. If 5222 * current, prepend '+', otherwise '-'. 5223 */ 5224 if (worker->desc[0] != '\0') { 5225 if (worker->current_work) 5226 scnprintf(buf + off, size - off, "+%s", 5227 worker->desc); 5228 else 5229 scnprintf(buf + off, size - off, "-%s", 5230 worker->desc); 5231 } 5232 raw_spin_unlock_irq(&pool->lock); 5233 } 5234 } 5235 5236 mutex_unlock(&wq_pool_attach_mutex); 5237 } 5238 5239 #ifdef CONFIG_SMP 5240 5241 /* 5242 * CPU hotplug. 5243 * 5244 * There are two challenges in supporting CPU hotplug. Firstly, there 5245 * are a lot of assumptions on strong associations among work, pwq and 5246 * pool which make migrating pending and scheduled works very 5247 * difficult to implement without impacting hot paths. Secondly, 5248 * worker pools serve mix of short, long and very long running works making 5249 * blocked draining impractical. 5250 * 5251 * This is solved by allowing the pools to be disassociated from the CPU 5252 * running as an unbound one and allowing it to be reattached later if the 5253 * cpu comes back online. 5254 */ 5255 5256 static void unbind_workers(int cpu) 5257 { 5258 struct worker_pool *pool; 5259 struct worker *worker; 5260 5261 for_each_cpu_worker_pool(pool, cpu) { 5262 mutex_lock(&wq_pool_attach_mutex); 5263 raw_spin_lock_irq(&pool->lock); 5264 5265 /* 5266 * We've blocked all attach/detach operations. Make all workers 5267 * unbound and set DISASSOCIATED. Before this, all workers 5268 * must be on the cpu. After this, they may become diasporas. 5269 * And the preemption disabled section in their sched callbacks 5270 * are guaranteed to see WORKER_UNBOUND since the code here 5271 * is on the same cpu. 5272 */ 5273 for_each_pool_worker(worker, pool) 5274 worker->flags |= WORKER_UNBOUND; 5275 5276 pool->flags |= POOL_DISASSOCIATED; 5277 5278 /* 5279 * The handling of nr_running in sched callbacks are disabled 5280 * now. Zap nr_running. After this, nr_running stays zero and 5281 * need_more_worker() and keep_working() are always true as 5282 * long as the worklist is not empty. This pool now behaves as 5283 * an unbound (in terms of concurrency management) pool which 5284 * are served by workers tied to the pool. 5285 */ 5286 pool->nr_running = 0; 5287 5288 /* 5289 * With concurrency management just turned off, a busy 5290 * worker blocking could lead to lengthy stalls. Kick off 5291 * unbound chain execution of currently pending work items. 5292 */ 5293 wake_up_worker(pool); 5294 5295 raw_spin_unlock_irq(&pool->lock); 5296 5297 for_each_pool_worker(worker, pool) 5298 unbind_worker(worker); 5299 5300 mutex_unlock(&wq_pool_attach_mutex); 5301 } 5302 } 5303 5304 /** 5305 * rebind_workers - rebind all workers of a pool to the associated CPU 5306 * @pool: pool of interest 5307 * 5308 * @pool->cpu is coming online. Rebind all workers to the CPU. 5309 */ 5310 static void rebind_workers(struct worker_pool *pool) 5311 { 5312 struct worker *worker; 5313 5314 lockdep_assert_held(&wq_pool_attach_mutex); 5315 5316 /* 5317 * Restore CPU affinity of all workers. As all idle workers should 5318 * be on the run-queue of the associated CPU before any local 5319 * wake-ups for concurrency management happen, restore CPU affinity 5320 * of all workers first and then clear UNBOUND. As we're called 5321 * from CPU_ONLINE, the following shouldn't fail. 5322 */ 5323 for_each_pool_worker(worker, pool) { 5324 kthread_set_per_cpu(worker->task, pool->cpu); 5325 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, 5326 pool->attrs->cpumask) < 0); 5327 } 5328 5329 raw_spin_lock_irq(&pool->lock); 5330 5331 pool->flags &= ~POOL_DISASSOCIATED; 5332 5333 for_each_pool_worker(worker, pool) { 5334 unsigned int worker_flags = worker->flags; 5335 5336 /* 5337 * We want to clear UNBOUND but can't directly call 5338 * worker_clr_flags() or adjust nr_running. Atomically 5339 * replace UNBOUND with another NOT_RUNNING flag REBOUND. 5340 * @worker will clear REBOUND using worker_clr_flags() when 5341 * it initiates the next execution cycle thus restoring 5342 * concurrency management. Note that when or whether 5343 * @worker clears REBOUND doesn't affect correctness. 5344 * 5345 * WRITE_ONCE() is necessary because @worker->flags may be 5346 * tested without holding any lock in 5347 * wq_worker_running(). Without it, NOT_RUNNING test may 5348 * fail incorrectly leading to premature concurrency 5349 * management operations. 5350 */ 5351 WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND)); 5352 worker_flags |= WORKER_REBOUND; 5353 worker_flags &= ~WORKER_UNBOUND; 5354 WRITE_ONCE(worker->flags, worker_flags); 5355 } 5356 5357 raw_spin_unlock_irq(&pool->lock); 5358 } 5359 5360 /** 5361 * restore_unbound_workers_cpumask - restore cpumask of unbound workers 5362 * @pool: unbound pool of interest 5363 * @cpu: the CPU which is coming up 5364 * 5365 * An unbound pool may end up with a cpumask which doesn't have any online 5366 * CPUs. When a worker of such pool get scheduled, the scheduler resets 5367 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any 5368 * online CPU before, cpus_allowed of all its workers should be restored. 5369 */ 5370 static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu) 5371 { 5372 static cpumask_t cpumask; 5373 struct worker *worker; 5374 5375 lockdep_assert_held(&wq_pool_attach_mutex); 5376 5377 /* is @cpu allowed for @pool? */ 5378 if (!cpumask_test_cpu(cpu, pool->attrs->cpumask)) 5379 return; 5380 5381 cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask); 5382 5383 /* as we're called from CPU_ONLINE, the following shouldn't fail */ 5384 for_each_pool_worker(worker, pool) 5385 WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0); 5386 } 5387 5388 int workqueue_prepare_cpu(unsigned int cpu) 5389 { 5390 struct worker_pool *pool; 5391 5392 for_each_cpu_worker_pool(pool, cpu) { 5393 if (pool->nr_workers) 5394 continue; 5395 if (!create_worker(pool)) 5396 return -ENOMEM; 5397 } 5398 return 0; 5399 } 5400 5401 int workqueue_online_cpu(unsigned int cpu) 5402 { 5403 struct worker_pool *pool; 5404 struct workqueue_struct *wq; 5405 int pi; 5406 5407 mutex_lock(&wq_pool_mutex); 5408 5409 for_each_pool(pool, pi) { 5410 mutex_lock(&wq_pool_attach_mutex); 5411 5412 if (pool->cpu == cpu) 5413 rebind_workers(pool); 5414 else if (pool->cpu < 0) 5415 restore_unbound_workers_cpumask(pool, cpu); 5416 5417 mutex_unlock(&wq_pool_attach_mutex); 5418 } 5419 5420 /* update NUMA affinity of unbound workqueues */ 5421 list_for_each_entry(wq, &workqueues, list) 5422 wq_update_unbound_numa(wq, cpu, true); 5423 5424 mutex_unlock(&wq_pool_mutex); 5425 return 0; 5426 } 5427 5428 int workqueue_offline_cpu(unsigned int cpu) 5429 { 5430 struct workqueue_struct *wq; 5431 5432 /* unbinding per-cpu workers should happen on the local CPU */ 5433 if (WARN_ON(cpu != smp_processor_id())) 5434 return -1; 5435 5436 unbind_workers(cpu); 5437 5438 /* update NUMA affinity of unbound workqueues */ 5439 mutex_lock(&wq_pool_mutex); 5440 list_for_each_entry(wq, &workqueues, list) 5441 wq_update_unbound_numa(wq, cpu, false); 5442 mutex_unlock(&wq_pool_mutex); 5443 5444 return 0; 5445 } 5446 5447 struct work_for_cpu { 5448 struct work_struct work; 5449 long (*fn)(void *); 5450 void *arg; 5451 long ret; 5452 }; 5453 5454 static void work_for_cpu_fn(struct work_struct *work) 5455 { 5456 struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work); 5457 5458 wfc->ret = wfc->fn(wfc->arg); 5459 } 5460 5461 /** 5462 * work_on_cpu - run a function in thread context on a particular cpu 5463 * @cpu: the cpu to run on 5464 * @fn: the function to run 5465 * @arg: the function arg 5466 * 5467 * It is up to the caller to ensure that the cpu doesn't go offline. 5468 * The caller must not hold any locks which would prevent @fn from completing. 5469 * 5470 * Return: The value @fn returns. 5471 */ 5472 long work_on_cpu(int cpu, long (*fn)(void *), void *arg) 5473 { 5474 struct work_for_cpu wfc = { .fn = fn, .arg = arg }; 5475 5476 INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn); 5477 schedule_work_on(cpu, &wfc.work); 5478 flush_work(&wfc.work); 5479 destroy_work_on_stack(&wfc.work); 5480 return wfc.ret; 5481 } 5482 EXPORT_SYMBOL_GPL(work_on_cpu); 5483 5484 /** 5485 * work_on_cpu_safe - run a function in thread context on a particular cpu 5486 * @cpu: the cpu to run on 5487 * @fn: the function to run 5488 * @arg: the function argument 5489 * 5490 * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold 5491 * any locks which would prevent @fn from completing. 5492 * 5493 * Return: The value @fn returns. 5494 */ 5495 long work_on_cpu_safe(int cpu, long (*fn)(void *), void *arg) 5496 { 5497 long ret = -ENODEV; 5498 5499 cpus_read_lock(); 5500 if (cpu_online(cpu)) 5501 ret = work_on_cpu(cpu, fn, arg); 5502 cpus_read_unlock(); 5503 return ret; 5504 } 5505 EXPORT_SYMBOL_GPL(work_on_cpu_safe); 5506 #endif /* CONFIG_SMP */ 5507 5508 #ifdef CONFIG_FREEZER 5509 5510 /** 5511 * freeze_workqueues_begin - begin freezing workqueues 5512 * 5513 * Start freezing workqueues. After this function returns, all freezable 5514 * workqueues will queue new works to their inactive_works list instead of 5515 * pool->worklist. 5516 * 5517 * CONTEXT: 5518 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's. 5519 */ 5520 void freeze_workqueues_begin(void) 5521 { 5522 struct workqueue_struct *wq; 5523 struct pool_workqueue *pwq; 5524 5525 mutex_lock(&wq_pool_mutex); 5526 5527 WARN_ON_ONCE(workqueue_freezing); 5528 workqueue_freezing = true; 5529 5530 list_for_each_entry(wq, &workqueues, list) { 5531 mutex_lock(&wq->mutex); 5532 for_each_pwq(pwq, wq) 5533 pwq_adjust_max_active(pwq); 5534 mutex_unlock(&wq->mutex); 5535 } 5536 5537 mutex_unlock(&wq_pool_mutex); 5538 } 5539 5540 /** 5541 * freeze_workqueues_busy - are freezable workqueues still busy? 5542 * 5543 * Check whether freezing is complete. This function must be called 5544 * between freeze_workqueues_begin() and thaw_workqueues(). 5545 * 5546 * CONTEXT: 5547 * Grabs and releases wq_pool_mutex. 5548 * 5549 * Return: 5550 * %true if some freezable workqueues are still busy. %false if freezing 5551 * is complete. 5552 */ 5553 bool freeze_workqueues_busy(void) 5554 { 5555 bool busy = false; 5556 struct workqueue_struct *wq; 5557 struct pool_workqueue *pwq; 5558 5559 mutex_lock(&wq_pool_mutex); 5560 5561 WARN_ON_ONCE(!workqueue_freezing); 5562 5563 list_for_each_entry(wq, &workqueues, list) { 5564 if (!(wq->flags & WQ_FREEZABLE)) 5565 continue; 5566 /* 5567 * nr_active is monotonically decreasing. It's safe 5568 * to peek without lock. 5569 */ 5570 rcu_read_lock(); 5571 for_each_pwq(pwq, wq) { 5572 WARN_ON_ONCE(pwq->nr_active < 0); 5573 if (pwq->nr_active) { 5574 busy = true; 5575 rcu_read_unlock(); 5576 goto out_unlock; 5577 } 5578 } 5579 rcu_read_unlock(); 5580 } 5581 out_unlock: 5582 mutex_unlock(&wq_pool_mutex); 5583 return busy; 5584 } 5585 5586 /** 5587 * thaw_workqueues - thaw workqueues 5588 * 5589 * Thaw workqueues. Normal queueing is restored and all collected 5590 * frozen works are transferred to their respective pool worklists. 5591 * 5592 * CONTEXT: 5593 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's. 5594 */ 5595 void thaw_workqueues(void) 5596 { 5597 struct workqueue_struct *wq; 5598 struct pool_workqueue *pwq; 5599 5600 mutex_lock(&wq_pool_mutex); 5601 5602 if (!workqueue_freezing) 5603 goto out_unlock; 5604 5605 workqueue_freezing = false; 5606 5607 /* restore max_active and repopulate worklist */ 5608 list_for_each_entry(wq, &workqueues, list) { 5609 mutex_lock(&wq->mutex); 5610 for_each_pwq(pwq, wq) 5611 pwq_adjust_max_active(pwq); 5612 mutex_unlock(&wq->mutex); 5613 } 5614 5615 out_unlock: 5616 mutex_unlock(&wq_pool_mutex); 5617 } 5618 #endif /* CONFIG_FREEZER */ 5619 5620 static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask) 5621 { 5622 LIST_HEAD(ctxs); 5623 int ret = 0; 5624 struct workqueue_struct *wq; 5625 struct apply_wqattrs_ctx *ctx, *n; 5626 5627 lockdep_assert_held(&wq_pool_mutex); 5628 5629 list_for_each_entry(wq, &workqueues, list) { 5630 if (!(wq->flags & WQ_UNBOUND)) 5631 continue; 5632 /* creating multiple pwqs breaks ordering guarantee */ 5633 if (wq->flags & __WQ_ORDERED) 5634 continue; 5635 5636 ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask); 5637 if (!ctx) { 5638 ret = -ENOMEM; 5639 break; 5640 } 5641 5642 list_add_tail(&ctx->list, &ctxs); 5643 } 5644 5645 list_for_each_entry_safe(ctx, n, &ctxs, list) { 5646 if (!ret) 5647 apply_wqattrs_commit(ctx); 5648 apply_wqattrs_cleanup(ctx); 5649 } 5650 5651 if (!ret) { 5652 mutex_lock(&wq_pool_attach_mutex); 5653 cpumask_copy(wq_unbound_cpumask, unbound_cpumask); 5654 mutex_unlock(&wq_pool_attach_mutex); 5655 } 5656 return ret; 5657 } 5658 5659 /** 5660 * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask 5661 * @cpumask: the cpumask to set 5662 * 5663 * The low-level workqueues cpumask is a global cpumask that limits 5664 * the affinity of all unbound workqueues. This function check the @cpumask 5665 * and apply it to all unbound workqueues and updates all pwqs of them. 5666 * 5667 * Return: 0 - Success 5668 * -EINVAL - Invalid @cpumask 5669 * -ENOMEM - Failed to allocate memory for attrs or pwqs. 5670 */ 5671 int workqueue_set_unbound_cpumask(cpumask_var_t cpumask) 5672 { 5673 int ret = -EINVAL; 5674 5675 /* 5676 * Not excluding isolated cpus on purpose. 5677 * If the user wishes to include them, we allow that. 5678 */ 5679 cpumask_and(cpumask, cpumask, cpu_possible_mask); 5680 if (!cpumask_empty(cpumask)) { 5681 apply_wqattrs_lock(); 5682 if (cpumask_equal(cpumask, wq_unbound_cpumask)) { 5683 ret = 0; 5684 goto out_unlock; 5685 } 5686 5687 ret = workqueue_apply_unbound_cpumask(cpumask); 5688 5689 out_unlock: 5690 apply_wqattrs_unlock(); 5691 } 5692 5693 return ret; 5694 } 5695 5696 #ifdef CONFIG_SYSFS 5697 /* 5698 * Workqueues with WQ_SYSFS flag set is visible to userland via 5699 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the 5700 * following attributes. 5701 * 5702 * per_cpu RO bool : whether the workqueue is per-cpu or unbound 5703 * max_active RW int : maximum number of in-flight work items 5704 * 5705 * Unbound workqueues have the following extra attributes. 5706 * 5707 * pool_ids RO int : the associated pool IDs for each node 5708 * nice RW int : nice value of the workers 5709 * cpumask RW mask : bitmask of allowed CPUs for the workers 5710 * numa RW bool : whether enable NUMA affinity 5711 */ 5712 struct wq_device { 5713 struct workqueue_struct *wq; 5714 struct device dev; 5715 }; 5716 5717 static struct workqueue_struct *dev_to_wq(struct device *dev) 5718 { 5719 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev); 5720 5721 return wq_dev->wq; 5722 } 5723 5724 static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr, 5725 char *buf) 5726 { 5727 struct workqueue_struct *wq = dev_to_wq(dev); 5728 5729 return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND)); 5730 } 5731 static DEVICE_ATTR_RO(per_cpu); 5732 5733 static ssize_t max_active_show(struct device *dev, 5734 struct device_attribute *attr, char *buf) 5735 { 5736 struct workqueue_struct *wq = dev_to_wq(dev); 5737 5738 return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active); 5739 } 5740 5741 static ssize_t max_active_store(struct device *dev, 5742 struct device_attribute *attr, const char *buf, 5743 size_t count) 5744 { 5745 struct workqueue_struct *wq = dev_to_wq(dev); 5746 int val; 5747 5748 if (sscanf(buf, "%d", &val) != 1 || val <= 0) 5749 return -EINVAL; 5750 5751 workqueue_set_max_active(wq, val); 5752 return count; 5753 } 5754 static DEVICE_ATTR_RW(max_active); 5755 5756 static struct attribute *wq_sysfs_attrs[] = { 5757 &dev_attr_per_cpu.attr, 5758 &dev_attr_max_active.attr, 5759 NULL, 5760 }; 5761 ATTRIBUTE_GROUPS(wq_sysfs); 5762 5763 static ssize_t wq_pool_ids_show(struct device *dev, 5764 struct device_attribute *attr, char *buf) 5765 { 5766 struct workqueue_struct *wq = dev_to_wq(dev); 5767 const char *delim = ""; 5768 int node, written = 0; 5769 5770 cpus_read_lock(); 5771 rcu_read_lock(); 5772 for_each_node(node) { 5773 written += scnprintf(buf + written, PAGE_SIZE - written, 5774 "%s%d:%d", delim, node, 5775 unbound_pwq_by_node(wq, node)->pool->id); 5776 delim = " "; 5777 } 5778 written += scnprintf(buf + written, PAGE_SIZE - written, "\n"); 5779 rcu_read_unlock(); 5780 cpus_read_unlock(); 5781 5782 return written; 5783 } 5784 5785 static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr, 5786 char *buf) 5787 { 5788 struct workqueue_struct *wq = dev_to_wq(dev); 5789 int written; 5790 5791 mutex_lock(&wq->mutex); 5792 written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice); 5793 mutex_unlock(&wq->mutex); 5794 5795 return written; 5796 } 5797 5798 /* prepare workqueue_attrs for sysfs store operations */ 5799 static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq) 5800 { 5801 struct workqueue_attrs *attrs; 5802 5803 lockdep_assert_held(&wq_pool_mutex); 5804 5805 attrs = alloc_workqueue_attrs(); 5806 if (!attrs) 5807 return NULL; 5808 5809 copy_workqueue_attrs(attrs, wq->unbound_attrs); 5810 return attrs; 5811 } 5812 5813 static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr, 5814 const char *buf, size_t count) 5815 { 5816 struct workqueue_struct *wq = dev_to_wq(dev); 5817 struct workqueue_attrs *attrs; 5818 int ret = -ENOMEM; 5819 5820 apply_wqattrs_lock(); 5821 5822 attrs = wq_sysfs_prep_attrs(wq); 5823 if (!attrs) 5824 goto out_unlock; 5825 5826 if (sscanf(buf, "%d", &attrs->nice) == 1 && 5827 attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE) 5828 ret = apply_workqueue_attrs_locked(wq, attrs); 5829 else 5830 ret = -EINVAL; 5831 5832 out_unlock: 5833 apply_wqattrs_unlock(); 5834 free_workqueue_attrs(attrs); 5835 return ret ?: count; 5836 } 5837 5838 static ssize_t wq_cpumask_show(struct device *dev, 5839 struct device_attribute *attr, char *buf) 5840 { 5841 struct workqueue_struct *wq = dev_to_wq(dev); 5842 int written; 5843 5844 mutex_lock(&wq->mutex); 5845 written = scnprintf(buf, PAGE_SIZE, "%*pb\n", 5846 cpumask_pr_args(wq->unbound_attrs->cpumask)); 5847 mutex_unlock(&wq->mutex); 5848 return written; 5849 } 5850 5851 static ssize_t wq_cpumask_store(struct device *dev, 5852 struct device_attribute *attr, 5853 const char *buf, size_t count) 5854 { 5855 struct workqueue_struct *wq = dev_to_wq(dev); 5856 struct workqueue_attrs *attrs; 5857 int ret = -ENOMEM; 5858 5859 apply_wqattrs_lock(); 5860 5861 attrs = wq_sysfs_prep_attrs(wq); 5862 if (!attrs) 5863 goto out_unlock; 5864 5865 ret = cpumask_parse(buf, attrs->cpumask); 5866 if (!ret) 5867 ret = apply_workqueue_attrs_locked(wq, attrs); 5868 5869 out_unlock: 5870 apply_wqattrs_unlock(); 5871 free_workqueue_attrs(attrs); 5872 return ret ?: count; 5873 } 5874 5875 static ssize_t wq_numa_show(struct device *dev, struct device_attribute *attr, 5876 char *buf) 5877 { 5878 struct workqueue_struct *wq = dev_to_wq(dev); 5879 int written; 5880 5881 mutex_lock(&wq->mutex); 5882 written = scnprintf(buf, PAGE_SIZE, "%d\n", 5883 !wq->unbound_attrs->no_numa); 5884 mutex_unlock(&wq->mutex); 5885 5886 return written; 5887 } 5888 5889 static ssize_t wq_numa_store(struct device *dev, struct device_attribute *attr, 5890 const char *buf, size_t count) 5891 { 5892 struct workqueue_struct *wq = dev_to_wq(dev); 5893 struct workqueue_attrs *attrs; 5894 int v, ret = -ENOMEM; 5895 5896 apply_wqattrs_lock(); 5897 5898 attrs = wq_sysfs_prep_attrs(wq); 5899 if (!attrs) 5900 goto out_unlock; 5901 5902 ret = -EINVAL; 5903 if (sscanf(buf, "%d", &v) == 1) { 5904 attrs->no_numa = !v; 5905 ret = apply_workqueue_attrs_locked(wq, attrs); 5906 } 5907 5908 out_unlock: 5909 apply_wqattrs_unlock(); 5910 free_workqueue_attrs(attrs); 5911 return ret ?: count; 5912 } 5913 5914 static struct device_attribute wq_sysfs_unbound_attrs[] = { 5915 __ATTR(pool_ids, 0444, wq_pool_ids_show, NULL), 5916 __ATTR(nice, 0644, wq_nice_show, wq_nice_store), 5917 __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store), 5918 __ATTR(numa, 0644, wq_numa_show, wq_numa_store), 5919 __ATTR_NULL, 5920 }; 5921 5922 static struct bus_type wq_subsys = { 5923 .name = "workqueue", 5924 .dev_groups = wq_sysfs_groups, 5925 }; 5926 5927 static ssize_t wq_unbound_cpumask_show(struct device *dev, 5928 struct device_attribute *attr, char *buf) 5929 { 5930 int written; 5931 5932 mutex_lock(&wq_pool_mutex); 5933 written = scnprintf(buf, PAGE_SIZE, "%*pb\n", 5934 cpumask_pr_args(wq_unbound_cpumask)); 5935 mutex_unlock(&wq_pool_mutex); 5936 5937 return written; 5938 } 5939 5940 static ssize_t wq_unbound_cpumask_store(struct device *dev, 5941 struct device_attribute *attr, const char *buf, size_t count) 5942 { 5943 cpumask_var_t cpumask; 5944 int ret; 5945 5946 if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL)) 5947 return -ENOMEM; 5948 5949 ret = cpumask_parse(buf, cpumask); 5950 if (!ret) 5951 ret = workqueue_set_unbound_cpumask(cpumask); 5952 5953 free_cpumask_var(cpumask); 5954 return ret ? ret : count; 5955 } 5956 5957 static struct device_attribute wq_sysfs_cpumask_attr = 5958 __ATTR(cpumask, 0644, wq_unbound_cpumask_show, 5959 wq_unbound_cpumask_store); 5960 5961 static int __init wq_sysfs_init(void) 5962 { 5963 struct device *dev_root; 5964 int err; 5965 5966 err = subsys_virtual_register(&wq_subsys, NULL); 5967 if (err) 5968 return err; 5969 5970 dev_root = bus_get_dev_root(&wq_subsys); 5971 if (dev_root) { 5972 err = device_create_file(dev_root, &wq_sysfs_cpumask_attr); 5973 put_device(dev_root); 5974 } 5975 return err; 5976 } 5977 core_initcall(wq_sysfs_init); 5978 5979 static void wq_device_release(struct device *dev) 5980 { 5981 struct wq_device *wq_dev = container_of(dev, struct wq_device, dev); 5982 5983 kfree(wq_dev); 5984 } 5985 5986 /** 5987 * workqueue_sysfs_register - make a workqueue visible in sysfs 5988 * @wq: the workqueue to register 5989 * 5990 * Expose @wq in sysfs under /sys/bus/workqueue/devices. 5991 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set 5992 * which is the preferred method. 5993 * 5994 * Workqueue user should use this function directly iff it wants to apply 5995 * workqueue_attrs before making the workqueue visible in sysfs; otherwise, 5996 * apply_workqueue_attrs() may race against userland updating the 5997 * attributes. 5998 * 5999 * Return: 0 on success, -errno on failure. 6000 */ 6001 int workqueue_sysfs_register(struct workqueue_struct *wq) 6002 { 6003 struct wq_device *wq_dev; 6004 int ret; 6005 6006 /* 6007 * Adjusting max_active or creating new pwqs by applying 6008 * attributes breaks ordering guarantee. Disallow exposing ordered 6009 * workqueues. 6010 */ 6011 if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT)) 6012 return -EINVAL; 6013 6014 wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL); 6015 if (!wq_dev) 6016 return -ENOMEM; 6017 6018 wq_dev->wq = wq; 6019 wq_dev->dev.bus = &wq_subsys; 6020 wq_dev->dev.release = wq_device_release; 6021 dev_set_name(&wq_dev->dev, "%s", wq->name); 6022 6023 /* 6024 * unbound_attrs are created separately. Suppress uevent until 6025 * everything is ready. 6026 */ 6027 dev_set_uevent_suppress(&wq_dev->dev, true); 6028 6029 ret = device_register(&wq_dev->dev); 6030 if (ret) { 6031 put_device(&wq_dev->dev); 6032 wq->wq_dev = NULL; 6033 return ret; 6034 } 6035 6036 if (wq->flags & WQ_UNBOUND) { 6037 struct device_attribute *attr; 6038 6039 for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) { 6040 ret = device_create_file(&wq_dev->dev, attr); 6041 if (ret) { 6042 device_unregister(&wq_dev->dev); 6043 wq->wq_dev = NULL; 6044 return ret; 6045 } 6046 } 6047 } 6048 6049 dev_set_uevent_suppress(&wq_dev->dev, false); 6050 kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD); 6051 return 0; 6052 } 6053 6054 /** 6055 * workqueue_sysfs_unregister - undo workqueue_sysfs_register() 6056 * @wq: the workqueue to unregister 6057 * 6058 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister. 6059 */ 6060 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) 6061 { 6062 struct wq_device *wq_dev = wq->wq_dev; 6063 6064 if (!wq->wq_dev) 6065 return; 6066 6067 wq->wq_dev = NULL; 6068 device_unregister(&wq_dev->dev); 6069 } 6070 #else /* CONFIG_SYSFS */ 6071 static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { } 6072 #endif /* CONFIG_SYSFS */ 6073 6074 /* 6075 * Workqueue watchdog. 6076 * 6077 * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal 6078 * flush dependency, a concurrency managed work item which stays RUNNING 6079 * indefinitely. Workqueue stalls can be very difficult to debug as the 6080 * usual warning mechanisms don't trigger and internal workqueue state is 6081 * largely opaque. 6082 * 6083 * Workqueue watchdog monitors all worker pools periodically and dumps 6084 * state if some pools failed to make forward progress for a while where 6085 * forward progress is defined as the first item on ->worklist changing. 6086 * 6087 * This mechanism is controlled through the kernel parameter 6088 * "workqueue.watchdog_thresh" which can be updated at runtime through the 6089 * corresponding sysfs parameter file. 6090 */ 6091 #ifdef CONFIG_WQ_WATCHDOG 6092 6093 static unsigned long wq_watchdog_thresh = 30; 6094 static struct timer_list wq_watchdog_timer; 6095 6096 static unsigned long wq_watchdog_touched = INITIAL_JIFFIES; 6097 static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES; 6098 6099 /* 6100 * Show workers that might prevent the processing of pending work items. 6101 * The only candidates are CPU-bound workers in the running state. 6102 * Pending work items should be handled by another idle worker 6103 * in all other situations. 6104 */ 6105 static void show_cpu_pool_hog(struct worker_pool *pool) 6106 { 6107 struct worker *worker; 6108 unsigned long flags; 6109 int bkt; 6110 6111 raw_spin_lock_irqsave(&pool->lock, flags); 6112 6113 hash_for_each(pool->busy_hash, bkt, worker, hentry) { 6114 if (task_is_running(worker->task)) { 6115 /* 6116 * Defer printing to avoid deadlocks in console 6117 * drivers that queue work while holding locks 6118 * also taken in their write paths. 6119 */ 6120 printk_deferred_enter(); 6121 6122 pr_info("pool %d:\n", pool->id); 6123 sched_show_task(worker->task); 6124 6125 printk_deferred_exit(); 6126 } 6127 } 6128 6129 raw_spin_unlock_irqrestore(&pool->lock, flags); 6130 } 6131 6132 static void show_cpu_pools_hogs(void) 6133 { 6134 struct worker_pool *pool; 6135 int pi; 6136 6137 pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n"); 6138 6139 rcu_read_lock(); 6140 6141 for_each_pool(pool, pi) { 6142 if (pool->cpu_stall) 6143 show_cpu_pool_hog(pool); 6144 6145 } 6146 6147 rcu_read_unlock(); 6148 } 6149 6150 static void wq_watchdog_reset_touched(void) 6151 { 6152 int cpu; 6153 6154 wq_watchdog_touched = jiffies; 6155 for_each_possible_cpu(cpu) 6156 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies; 6157 } 6158 6159 static void wq_watchdog_timer_fn(struct timer_list *unused) 6160 { 6161 unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ; 6162 bool lockup_detected = false; 6163 bool cpu_pool_stall = false; 6164 unsigned long now = jiffies; 6165 struct worker_pool *pool; 6166 int pi; 6167 6168 if (!thresh) 6169 return; 6170 6171 rcu_read_lock(); 6172 6173 for_each_pool(pool, pi) { 6174 unsigned long pool_ts, touched, ts; 6175 6176 pool->cpu_stall = false; 6177 if (list_empty(&pool->worklist)) 6178 continue; 6179 6180 /* 6181 * If a virtual machine is stopped by the host it can look to 6182 * the watchdog like a stall. 6183 */ 6184 kvm_check_and_clear_guest_paused(); 6185 6186 /* get the latest of pool and touched timestamps */ 6187 if (pool->cpu >= 0) 6188 touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu)); 6189 else 6190 touched = READ_ONCE(wq_watchdog_touched); 6191 pool_ts = READ_ONCE(pool->watchdog_ts); 6192 6193 if (time_after(pool_ts, touched)) 6194 ts = pool_ts; 6195 else 6196 ts = touched; 6197 6198 /* did we stall? */ 6199 if (time_after(now, ts + thresh)) { 6200 lockup_detected = true; 6201 if (pool->cpu >= 0) { 6202 pool->cpu_stall = true; 6203 cpu_pool_stall = true; 6204 } 6205 pr_emerg("BUG: workqueue lockup - pool"); 6206 pr_cont_pool_info(pool); 6207 pr_cont(" stuck for %us!\n", 6208 jiffies_to_msecs(now - pool_ts) / 1000); 6209 } 6210 6211 6212 } 6213 6214 rcu_read_unlock(); 6215 6216 if (lockup_detected) 6217 show_all_workqueues(); 6218 6219 if (cpu_pool_stall) 6220 show_cpu_pools_hogs(); 6221 6222 wq_watchdog_reset_touched(); 6223 mod_timer(&wq_watchdog_timer, jiffies + thresh); 6224 } 6225 6226 notrace void wq_watchdog_touch(int cpu) 6227 { 6228 if (cpu >= 0) 6229 per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies; 6230 6231 wq_watchdog_touched = jiffies; 6232 } 6233 6234 static void wq_watchdog_set_thresh(unsigned long thresh) 6235 { 6236 wq_watchdog_thresh = 0; 6237 del_timer_sync(&wq_watchdog_timer); 6238 6239 if (thresh) { 6240 wq_watchdog_thresh = thresh; 6241 wq_watchdog_reset_touched(); 6242 mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ); 6243 } 6244 } 6245 6246 static int wq_watchdog_param_set_thresh(const char *val, 6247 const struct kernel_param *kp) 6248 { 6249 unsigned long thresh; 6250 int ret; 6251 6252 ret = kstrtoul(val, 0, &thresh); 6253 if (ret) 6254 return ret; 6255 6256 if (system_wq) 6257 wq_watchdog_set_thresh(thresh); 6258 else 6259 wq_watchdog_thresh = thresh; 6260 6261 return 0; 6262 } 6263 6264 static const struct kernel_param_ops wq_watchdog_thresh_ops = { 6265 .set = wq_watchdog_param_set_thresh, 6266 .get = param_get_ulong, 6267 }; 6268 6269 module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh, 6270 0644); 6271 6272 static void wq_watchdog_init(void) 6273 { 6274 timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE); 6275 wq_watchdog_set_thresh(wq_watchdog_thresh); 6276 } 6277 6278 #else /* CONFIG_WQ_WATCHDOG */ 6279 6280 static inline void wq_watchdog_init(void) { } 6281 6282 #endif /* CONFIG_WQ_WATCHDOG */ 6283 6284 static void __init wq_numa_init(void) 6285 { 6286 cpumask_var_t *tbl; 6287 int node, cpu; 6288 6289 if (num_possible_nodes() <= 1) 6290 return; 6291 6292 if (wq_disable_numa) { 6293 pr_info("workqueue: NUMA affinity support disabled\n"); 6294 return; 6295 } 6296 6297 for_each_possible_cpu(cpu) { 6298 if (WARN_ON(cpu_to_node(cpu) == NUMA_NO_NODE)) { 6299 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu); 6300 return; 6301 } 6302 } 6303 6304 wq_update_unbound_numa_attrs_buf = alloc_workqueue_attrs(); 6305 BUG_ON(!wq_update_unbound_numa_attrs_buf); 6306 6307 /* 6308 * We want masks of possible CPUs of each node which isn't readily 6309 * available. Build one from cpu_to_node() which should have been 6310 * fully initialized by now. 6311 */ 6312 tbl = kcalloc(nr_node_ids, sizeof(tbl[0]), GFP_KERNEL); 6313 BUG_ON(!tbl); 6314 6315 for_each_node(node) 6316 BUG_ON(!zalloc_cpumask_var_node(&tbl[node], GFP_KERNEL, 6317 node_online(node) ? node : NUMA_NO_NODE)); 6318 6319 for_each_possible_cpu(cpu) { 6320 node = cpu_to_node(cpu); 6321 cpumask_set_cpu(cpu, tbl[node]); 6322 } 6323 6324 wq_numa_possible_cpumask = tbl; 6325 wq_numa_enabled = true; 6326 } 6327 6328 /** 6329 * workqueue_init_early - early init for workqueue subsystem 6330 * 6331 * This is the first half of two-staged workqueue subsystem initialization 6332 * and invoked as soon as the bare basics - memory allocation, cpumasks and 6333 * idr are up. It sets up all the data structures and system workqueues 6334 * and allows early boot code to create workqueues and queue/cancel work 6335 * items. Actual work item execution starts only after kthreads can be 6336 * created and scheduled right before early initcalls. 6337 */ 6338 void __init workqueue_init_early(void) 6339 { 6340 int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL }; 6341 int i, cpu; 6342 6343 BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long)); 6344 6345 BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL)); 6346 cpumask_copy(wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_WQ)); 6347 cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, housekeeping_cpumask(HK_TYPE_DOMAIN)); 6348 6349 pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC); 6350 6351 /* initialize CPU pools */ 6352 for_each_possible_cpu(cpu) { 6353 struct worker_pool *pool; 6354 6355 i = 0; 6356 for_each_cpu_worker_pool(pool, cpu) { 6357 BUG_ON(init_worker_pool(pool)); 6358 pool->cpu = cpu; 6359 cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu)); 6360 pool->attrs->nice = std_nice[i++]; 6361 pool->node = cpu_to_node(cpu); 6362 6363 /* alloc pool ID */ 6364 mutex_lock(&wq_pool_mutex); 6365 BUG_ON(worker_pool_assign_id(pool)); 6366 mutex_unlock(&wq_pool_mutex); 6367 } 6368 } 6369 6370 /* create default unbound and ordered wq attrs */ 6371 for (i = 0; i < NR_STD_WORKER_POOLS; i++) { 6372 struct workqueue_attrs *attrs; 6373 6374 BUG_ON(!(attrs = alloc_workqueue_attrs())); 6375 attrs->nice = std_nice[i]; 6376 unbound_std_wq_attrs[i] = attrs; 6377 6378 /* 6379 * An ordered wq should have only one pwq as ordering is 6380 * guaranteed by max_active which is enforced by pwqs. 6381 * Turn off NUMA so that dfl_pwq is used for all nodes. 6382 */ 6383 BUG_ON(!(attrs = alloc_workqueue_attrs())); 6384 attrs->nice = std_nice[i]; 6385 attrs->no_numa = true; 6386 ordered_wq_attrs[i] = attrs; 6387 } 6388 6389 system_wq = alloc_workqueue("events", 0, 0); 6390 system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0); 6391 system_long_wq = alloc_workqueue("events_long", 0, 0); 6392 system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND, 6393 WQ_UNBOUND_MAX_ACTIVE); 6394 system_freezable_wq = alloc_workqueue("events_freezable", 6395 WQ_FREEZABLE, 0); 6396 system_power_efficient_wq = alloc_workqueue("events_power_efficient", 6397 WQ_POWER_EFFICIENT, 0); 6398 system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient", 6399 WQ_FREEZABLE | WQ_POWER_EFFICIENT, 6400 0); 6401 BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq || 6402 !system_unbound_wq || !system_freezable_wq || 6403 !system_power_efficient_wq || 6404 !system_freezable_power_efficient_wq); 6405 } 6406 6407 /** 6408 * workqueue_init - bring workqueue subsystem fully online 6409 * 6410 * This is the latter half of two-staged workqueue subsystem initialization 6411 * and invoked as soon as kthreads can be created and scheduled. 6412 * Workqueues have been created and work items queued on them, but there 6413 * are no kworkers executing the work items yet. Populate the worker pools 6414 * with the initial workers and enable future kworker creations. 6415 */ 6416 void __init workqueue_init(void) 6417 { 6418 struct workqueue_struct *wq; 6419 struct worker_pool *pool; 6420 int cpu, bkt; 6421 6422 /* 6423 * It'd be simpler to initialize NUMA in workqueue_init_early() but 6424 * CPU to node mapping may not be available that early on some 6425 * archs such as power and arm64. As per-cpu pools created 6426 * previously could be missing node hint and unbound pools NUMA 6427 * affinity, fix them up. 6428 * 6429 * Also, while iterating workqueues, create rescuers if requested. 6430 */ 6431 wq_numa_init(); 6432 6433 mutex_lock(&wq_pool_mutex); 6434 6435 for_each_possible_cpu(cpu) { 6436 for_each_cpu_worker_pool(pool, cpu) { 6437 pool->node = cpu_to_node(cpu); 6438 } 6439 } 6440 6441 list_for_each_entry(wq, &workqueues, list) { 6442 wq_update_unbound_numa(wq, smp_processor_id(), true); 6443 WARN(init_rescuer(wq), 6444 "workqueue: failed to create early rescuer for %s", 6445 wq->name); 6446 } 6447 6448 mutex_unlock(&wq_pool_mutex); 6449 6450 /* create the initial workers */ 6451 for_each_online_cpu(cpu) { 6452 for_each_cpu_worker_pool(pool, cpu) { 6453 pool->flags &= ~POOL_DISASSOCIATED; 6454 BUG_ON(!create_worker(pool)); 6455 } 6456 } 6457 6458 hash_for_each(unbound_pool_hash, bkt, pool, hash_node) 6459 BUG_ON(!create_worker(pool)); 6460 6461 wq_online = true; 6462 wq_watchdog_init(); 6463 } 6464 6465 /* 6466 * Despite the naming, this is a no-op function which is here only for avoiding 6467 * link error. Since compile-time warning may fail to catch, we will need to 6468 * emit run-time warning from __flush_workqueue(). 6469 */ 6470 void __warn_flushing_systemwide_wq(void) { } 6471 EXPORT_SYMBOL(__warn_flushing_systemwide_wq); 6472