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