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