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