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