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