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