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