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