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