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