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