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