workqueue: consider work function when searching for busy work items
[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         list_del_init(&worker->entry);
1478         worker->flags |= WORKER_DIE;
1479
1480         spin_unlock_irq(&gcwq->lock);
1481
1482         kthread_stop(worker->task);
1483         kfree(worker);
1484
1485         spin_lock_irq(&gcwq->lock);
1486         ida_remove(&gcwq->worker_ida, id);
1487 }
1488
1489 static void idle_worker_timeout(unsigned long __gcwq)
1490 {
1491         struct global_cwq *gcwq = (void *)__gcwq;
1492
1493         spin_lock_irq(&gcwq->lock);
1494
1495         if (too_many_workers(gcwq)) {
1496                 struct worker *worker;
1497                 unsigned long expires;
1498
1499                 /* idle_list is kept in LIFO order, check the last one */
1500                 worker = list_entry(gcwq->idle_list.prev, struct worker, entry);
1501                 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1502
1503                 if (time_before(jiffies, expires))
1504                         mod_timer(&gcwq->idle_timer, expires);
1505                 else {
1506                         /* it's been idle for too long, wake up manager */
1507                         gcwq->flags |= GCWQ_MANAGE_WORKERS;
1508                         wake_up_worker(gcwq);
1509                 }
1510         }
1511
1512         spin_unlock_irq(&gcwq->lock);
1513 }
1514
1515 static bool send_mayday(struct work_struct *work)
1516 {
1517         struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1518         struct workqueue_struct *wq = cwq->wq;
1519         unsigned int cpu;
1520
1521         if (!(wq->flags & WQ_RESCUER))
1522                 return false;
1523
1524         /* mayday mayday mayday */
1525         cpu = cwq->gcwq->cpu;
1526         /* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
1527         if (cpu == WORK_CPU_UNBOUND)
1528                 cpu = 0;
1529         if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
1530                 wake_up_process(wq->rescuer->task);
1531         return true;
1532 }
1533
1534 static void gcwq_mayday_timeout(unsigned long __gcwq)
1535 {
1536         struct global_cwq *gcwq = (void *)__gcwq;
1537         struct work_struct *work;
1538
1539         spin_lock_irq(&gcwq->lock);
1540
1541         if (need_to_create_worker(gcwq)) {
1542                 /*
1543                  * We've been trying to create a new worker but
1544                  * haven't been successful.  We might be hitting an
1545                  * allocation deadlock.  Send distress signals to
1546                  * rescuers.
1547                  */
1548                 list_for_each_entry(work, &gcwq->worklist, entry)
1549                         send_mayday(work);
1550         }
1551
1552         spin_unlock_irq(&gcwq->lock);
1553
1554         mod_timer(&gcwq->mayday_timer, jiffies + MAYDAY_INTERVAL);
1555 }
1556
1557 /**
1558  * maybe_create_worker - create a new worker if necessary
1559  * @gcwq: gcwq to create a new worker for
1560  *
1561  * Create a new worker for @gcwq if necessary.  @gcwq is guaranteed to
1562  * have at least one idle worker on return from this function.  If
1563  * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1564  * sent to all rescuers with works scheduled on @gcwq to resolve
1565  * possible allocation deadlock.
1566  *
1567  * On return, need_to_create_worker() is guaranteed to be false and
1568  * may_start_working() true.
1569  *
1570  * LOCKING:
1571  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1572  * multiple times.  Does GFP_KERNEL allocations.  Called only from
1573  * manager.
1574  *
1575  * RETURNS:
1576  * false if no action was taken and gcwq->lock stayed locked, true
1577  * otherwise.
1578  */
1579 static bool maybe_create_worker(struct global_cwq *gcwq)
1580 __releases(&gcwq->lock)
1581 __acquires(&gcwq->lock)
1582 {
1583         if (!need_to_create_worker(gcwq))
1584                 return false;
1585 restart:
1586         spin_unlock_irq(&gcwq->lock);
1587
1588         /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1589         mod_timer(&gcwq->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
1590
1591         while (true) {
1592                 struct worker *worker;
1593
1594                 worker = create_worker(gcwq, true);
1595                 if (worker) {
1596                         del_timer_sync(&gcwq->mayday_timer);
1597                         spin_lock_irq(&gcwq->lock);
1598                         start_worker(worker);
1599                         BUG_ON(need_to_create_worker(gcwq));
1600                         return true;
1601                 }
1602
1603                 if (!need_to_create_worker(gcwq))
1604                         break;
1605
1606                 __set_current_state(TASK_INTERRUPTIBLE);
1607                 schedule_timeout(CREATE_COOLDOWN);
1608
1609                 if (!need_to_create_worker(gcwq))
1610                         break;
1611         }
1612
1613         del_timer_sync(&gcwq->mayday_timer);
1614         spin_lock_irq(&gcwq->lock);
1615         if (need_to_create_worker(gcwq))
1616                 goto restart;
1617         return true;
1618 }
1619
1620 /**
1621  * maybe_destroy_worker - destroy workers which have been idle for a while
1622  * @gcwq: gcwq to destroy workers for
1623  *
1624  * Destroy @gcwq workers which have been idle for longer than
1625  * IDLE_WORKER_TIMEOUT.
1626  *
1627  * LOCKING:
1628  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1629  * multiple times.  Called only from manager.
1630  *
1631  * RETURNS:
1632  * false if no action was taken and gcwq->lock stayed locked, true
1633  * otherwise.
1634  */
1635 static bool maybe_destroy_workers(struct global_cwq *gcwq)
1636 {
1637         bool ret = false;
1638
1639         while (too_many_workers(gcwq)) {
1640                 struct worker *worker;
1641                 unsigned long expires;
1642
1643                 worker = list_entry(gcwq->idle_list.prev, struct worker, entry);
1644                 expires = worker->last_active + IDLE_WORKER_TIMEOUT;
1645
1646                 if (time_before(jiffies, expires)) {
1647                         mod_timer(&gcwq->idle_timer, expires);
1648                         break;
1649                 }
1650
1651                 destroy_worker(worker);
1652                 ret = true;
1653         }
1654
1655         return ret;
1656 }
1657
1658 /**
1659  * manage_workers - manage worker pool
1660  * @worker: self
1661  *
1662  * Assume the manager role and manage gcwq worker pool @worker belongs
1663  * to.  At any given time, there can be only zero or one manager per
1664  * gcwq.  The exclusion is handled automatically by this function.
1665  *
1666  * The caller can safely start processing works on false return.  On
1667  * true return, it's guaranteed that need_to_create_worker() is false
1668  * and may_start_working() is true.
1669  *
1670  * CONTEXT:
1671  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1672  * multiple times.  Does GFP_KERNEL allocations.
1673  *
1674  * RETURNS:
1675  * false if no action was taken and gcwq->lock stayed locked, true if
1676  * some action was taken.
1677  */
1678 static bool manage_workers(struct worker *worker)
1679 {
1680         struct global_cwq *gcwq = worker->gcwq;
1681         bool ret = false;
1682
1683         if (gcwq->flags & GCWQ_MANAGING_WORKERS)
1684                 return ret;
1685
1686         gcwq->flags &= ~GCWQ_MANAGE_WORKERS;
1687         gcwq->flags |= GCWQ_MANAGING_WORKERS;
1688
1689         /*
1690          * Destroy and then create so that may_start_working() is true
1691          * on return.
1692          */
1693         ret |= maybe_destroy_workers(gcwq);
1694         ret |= maybe_create_worker(gcwq);
1695
1696         gcwq->flags &= ~GCWQ_MANAGING_WORKERS;
1697
1698         /*
1699          * The trustee might be waiting to take over the manager
1700          * position, tell it we're done.
1701          */
1702         if (unlikely(gcwq->trustee))
1703                 wake_up_all(&gcwq->trustee_wait);
1704
1705         return ret;
1706 }
1707
1708 /**
1709  * move_linked_works - move linked works to a list
1710  * @work: start of series of works to be scheduled
1711  * @head: target list to append @work to
1712  * @nextp: out paramter for nested worklist walking
1713  *
1714  * Schedule linked works starting from @work to @head.  Work series to
1715  * be scheduled starts at @work and includes any consecutive work with
1716  * WORK_STRUCT_LINKED set in its predecessor.
1717  *
1718  * If @nextp is not NULL, it's updated to point to the next work of
1719  * the last scheduled work.  This allows move_linked_works() to be
1720  * nested inside outer list_for_each_entry_safe().
1721  *
1722  * CONTEXT:
1723  * spin_lock_irq(gcwq->lock).
1724  */
1725 static void move_linked_works(struct work_struct *work, struct list_head *head,
1726                               struct work_struct **nextp)
1727 {
1728         struct work_struct *n;
1729
1730         /*
1731          * Linked worklist will always end before the end of the list,
1732          * use NULL for list head.
1733          */
1734         list_for_each_entry_safe_from(work, n, NULL, entry) {
1735                 list_move_tail(&work->entry, head);
1736                 if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1737                         break;
1738         }
1739
1740         /*
1741          * If we're already inside safe list traversal and have moved
1742          * multiple works to the scheduled queue, the next position
1743          * needs to be updated.
1744          */
1745         if (nextp)
1746                 *nextp = n;
1747 }
1748
1749 static void cwq_activate_delayed_work(struct work_struct *work)
1750 {
1751         struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1752         struct list_head *pos = gcwq_determine_ins_pos(cwq->gcwq, cwq);
1753
1754         trace_workqueue_activate_work(work);
1755         move_linked_works(work, pos, NULL);
1756         __clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
1757         cwq->nr_active++;
1758 }
1759
1760 static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
1761 {
1762         struct work_struct *work = list_first_entry(&cwq->delayed_works,
1763                                                     struct work_struct, entry);
1764
1765         cwq_activate_delayed_work(work);
1766 }
1767
1768 /**
1769  * cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
1770  * @cwq: cwq of interest
1771  * @color: color of work which left the queue
1772  * @delayed: for a delayed work
1773  *
1774  * A work either has completed or is removed from pending queue,
1775  * decrement nr_in_flight of its cwq and handle workqueue flushing.
1776  *
1777  * CONTEXT:
1778  * spin_lock_irq(gcwq->lock).
1779  */
1780 static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color,
1781                                  bool delayed)
1782 {
1783         /* ignore uncolored works */
1784         if (color == WORK_NO_COLOR)
1785                 return;
1786
1787         cwq->nr_in_flight[color]--;
1788
1789         if (!delayed) {
1790                 cwq->nr_active--;
1791                 if (!list_empty(&cwq->delayed_works)) {
1792                         /* one down, submit a delayed one */
1793                         if (cwq->nr_active < cwq->max_active)
1794                                 cwq_activate_first_delayed(cwq);
1795                 }
1796         }
1797
1798         /* is flush in progress and are we at the flushing tip? */
1799         if (likely(cwq->flush_color != color))
1800                 return;
1801
1802         /* are there still in-flight works? */
1803         if (cwq->nr_in_flight[color])
1804                 return;
1805
1806         /* this cwq is done, clear flush_color */
1807         cwq->flush_color = -1;
1808
1809         /*
1810          * If this was the last cwq, wake up the first flusher.  It
1811          * will handle the rest.
1812          */
1813         if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
1814                 complete(&cwq->wq->first_flusher->done);
1815 }
1816
1817 /**
1818  * process_one_work - process single work
1819  * @worker: self
1820  * @work: work to process
1821  *
1822  * Process @work.  This function contains all the logics necessary to
1823  * process a single work including synchronization against and
1824  * interaction with other workers on the same cpu, queueing and
1825  * flushing.  As long as context requirement is met, any worker can
1826  * call this function to process a work.
1827  *
1828  * CONTEXT:
1829  * spin_lock_irq(gcwq->lock) which is released and regrabbed.
1830  */
1831 static void process_one_work(struct worker *worker, struct work_struct *work)
1832 __releases(&gcwq->lock)
1833 __acquires(&gcwq->lock)
1834 {
1835         struct cpu_workqueue_struct *cwq = get_work_cwq(work);
1836         struct global_cwq *gcwq = cwq->gcwq;
1837         struct hlist_head *bwh = busy_worker_head(gcwq, work);
1838         bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
1839         int work_color;
1840         struct worker *collision;
1841 #ifdef CONFIG_LOCKDEP
1842         /*
1843          * It is permissible to free the struct work_struct from
1844          * inside the function that is called from it, this we need to
1845          * take into account for lockdep too.  To avoid bogus "held
1846          * lock freed" warnings as well as problems when looking into
1847          * work->lockdep_map, make a copy and use that here.
1848          */
1849         struct lockdep_map lockdep_map = work->lockdep_map;
1850 #endif
1851         /*
1852          * A single work shouldn't be executed concurrently by
1853          * multiple workers on a single cpu.  Check whether anyone is
1854          * already processing the work.  If so, defer the work to the
1855          * currently executing one.
1856          */
1857         collision = __find_worker_executing_work(gcwq, bwh, work);
1858         if (unlikely(collision)) {
1859                 move_linked_works(work, &collision->scheduled, NULL);
1860                 return;
1861         }
1862
1863         /* claim and process */
1864         debug_work_deactivate(work);
1865         hlist_add_head(&worker->hentry, bwh);
1866         worker->current_work = work;
1867         worker->current_func = work->func;
1868         worker->current_cwq = cwq;
1869         work_color = get_work_color(work);
1870
1871         /* record the current cpu number in the work data and dequeue */
1872         set_work_cpu(work, gcwq->cpu);
1873         list_del_init(&work->entry);
1874
1875         /*
1876          * If HIGHPRI_PENDING, check the next work, and, if HIGHPRI,
1877          * wake up another worker; otherwise, clear HIGHPRI_PENDING.
1878          */
1879         if (unlikely(gcwq->flags & GCWQ_HIGHPRI_PENDING)) {
1880                 struct work_struct *nwork = list_first_entry(&gcwq->worklist,
1881                                                 struct work_struct, entry);
1882
1883                 if (!list_empty(&gcwq->worklist) &&
1884                     get_work_cwq(nwork)->wq->flags & WQ_HIGHPRI)
1885                         wake_up_worker(gcwq);
1886                 else
1887                         gcwq->flags &= ~GCWQ_HIGHPRI_PENDING;
1888         }
1889
1890         /*
1891          * CPU intensive works don't participate in concurrency
1892          * management.  They're the scheduler's responsibility.
1893          */
1894         if (unlikely(cpu_intensive))
1895                 worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
1896
1897         spin_unlock_irq(&gcwq->lock);
1898
1899         smp_wmb();      /* paired with test_and_set_bit(PENDING) */
1900         work_clear_pending(work);
1901
1902         lock_map_acquire_read(&cwq->wq->lockdep_map);
1903         lock_map_acquire(&lockdep_map);
1904         trace_workqueue_execute_start(work);
1905         worker->current_func(work);
1906         /*
1907          * While we must be careful to not use "work" after this, the trace
1908          * point will only record its address.
1909          */
1910         trace_workqueue_execute_end(work);
1911         lock_map_release(&lockdep_map);
1912         lock_map_release(&cwq->wq->lockdep_map);
1913
1914         if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
1915                 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
1916                        "     last function: %pf\n",
1917                        current->comm, preempt_count(), task_pid_nr(current),
1918                        worker->current_func);
1919                 debug_show_held_locks(current);
1920                 dump_stack();
1921         }
1922
1923         spin_lock_irq(&gcwq->lock);
1924
1925         /* clear cpu intensive status */
1926         if (unlikely(cpu_intensive))
1927                 worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
1928
1929         /* we're done with it, release */
1930         hlist_del_init(&worker->hentry);
1931         worker->current_work = NULL;
1932         worker->current_func = NULL;
1933         worker->current_cwq = NULL;
1934         cwq_dec_nr_in_flight(cwq, work_color, false);
1935 }
1936
1937 /**
1938  * process_scheduled_works - process scheduled works
1939  * @worker: self
1940  *
1941  * Process all scheduled works.  Please note that the scheduled list
1942  * may change while processing a work, so this function repeatedly
1943  * fetches a work from the top and executes it.
1944  *
1945  * CONTEXT:
1946  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
1947  * multiple times.
1948  */
1949 static void process_scheduled_works(struct worker *worker)
1950 {
1951         while (!list_empty(&worker->scheduled)) {
1952                 struct work_struct *work = list_first_entry(&worker->scheduled,
1953                                                 struct work_struct, entry);
1954                 process_one_work(worker, work);
1955         }
1956 }
1957
1958 /**
1959  * worker_thread - the worker thread function
1960  * @__worker: self
1961  *
1962  * The gcwq worker thread function.  There's a single dynamic pool of
1963  * these per each cpu.  These workers process all works regardless of
1964  * their specific target workqueue.  The only exception is works which
1965  * belong to workqueues with a rescuer which will be explained in
1966  * rescuer_thread().
1967  */
1968 static int worker_thread(void *__worker)
1969 {
1970         struct worker *worker = __worker;
1971         struct global_cwq *gcwq = worker->gcwq;
1972
1973         /* tell the scheduler that this is a workqueue worker */
1974         worker->task->flags |= PF_WQ_WORKER;
1975 woke_up:
1976         spin_lock_irq(&gcwq->lock);
1977
1978         /* DIE can be set only while we're idle, checking here is enough */
1979         if (worker->flags & WORKER_DIE) {
1980                 spin_unlock_irq(&gcwq->lock);
1981                 worker->task->flags &= ~PF_WQ_WORKER;
1982                 return 0;
1983         }
1984
1985         worker_leave_idle(worker);
1986 recheck:
1987         /* no more worker necessary? */
1988         if (!need_more_worker(gcwq))
1989                 goto sleep;
1990
1991         /* do we need to manage? */
1992         if (unlikely(!may_start_working(gcwq)) && manage_workers(worker))
1993                 goto recheck;
1994
1995         /*
1996          * ->scheduled list can only be filled while a worker is
1997          * preparing to process a work or actually processing it.
1998          * Make sure nobody diddled with it while I was sleeping.
1999          */
2000         BUG_ON(!list_empty(&worker->scheduled));
2001
2002         /*
2003          * When control reaches this point, we're guaranteed to have
2004          * at least one idle worker or that someone else has already
2005          * assumed the manager role.
2006          */
2007         worker_clr_flags(worker, WORKER_PREP);
2008
2009         do {
2010                 struct work_struct *work =
2011                         list_first_entry(&gcwq->worklist,
2012                                          struct work_struct, entry);
2013
2014                 if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
2015                         /* optimization path, not strictly necessary */
2016                         process_one_work(worker, work);
2017                         if (unlikely(!list_empty(&worker->scheduled)))
2018                                 process_scheduled_works(worker);
2019                 } else {
2020                         move_linked_works(work, &worker->scheduled, NULL);
2021                         process_scheduled_works(worker);
2022                 }
2023         } while (keep_working(gcwq));
2024
2025         worker_set_flags(worker, WORKER_PREP, false);
2026 sleep:
2027         if (unlikely(need_to_manage_workers(gcwq)) && manage_workers(worker))
2028                 goto recheck;
2029
2030         /*
2031          * gcwq->lock is held and there's no work to process and no
2032          * need to manage, sleep.  Workers are woken up only while
2033          * holding gcwq->lock or from local cpu, so setting the
2034          * current state before releasing gcwq->lock is enough to
2035          * prevent losing any event.
2036          */
2037         worker_enter_idle(worker);
2038         __set_current_state(TASK_INTERRUPTIBLE);
2039         spin_unlock_irq(&gcwq->lock);
2040         schedule();
2041         goto woke_up;
2042 }
2043
2044 /**
2045  * rescuer_thread - the rescuer thread function
2046  * @__wq: the associated workqueue
2047  *
2048  * Workqueue rescuer thread function.  There's one rescuer for each
2049  * workqueue which has WQ_RESCUER set.
2050  *
2051  * Regular work processing on a gcwq may block trying to create a new
2052  * worker which uses GFP_KERNEL allocation which has slight chance of
2053  * developing into deadlock if some works currently on the same queue
2054  * need to be processed to satisfy the GFP_KERNEL allocation.  This is
2055  * the problem rescuer solves.
2056  *
2057  * When such condition is possible, the gcwq summons rescuers of all
2058  * workqueues which have works queued on the gcwq and let them process
2059  * those works so that forward progress can be guaranteed.
2060  *
2061  * This should happen rarely.
2062  */
2063 static int rescuer_thread(void *__wq)
2064 {
2065         struct workqueue_struct *wq = __wq;
2066         struct worker *rescuer = wq->rescuer;
2067         struct list_head *scheduled = &rescuer->scheduled;
2068         bool is_unbound = wq->flags & WQ_UNBOUND;
2069         unsigned int cpu;
2070
2071         set_user_nice(current, RESCUER_NICE_LEVEL);
2072 repeat:
2073         set_current_state(TASK_INTERRUPTIBLE);
2074
2075         if (kthread_should_stop()) {
2076                 __set_current_state(TASK_RUNNING);
2077                 return 0;
2078         }
2079
2080         /*
2081          * See whether any cpu is asking for help.  Unbounded
2082          * workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
2083          */
2084         for_each_mayday_cpu(cpu, wq->mayday_mask) {
2085                 unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
2086                 struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
2087                 struct global_cwq *gcwq = cwq->gcwq;
2088                 struct work_struct *work, *n;
2089
2090                 __set_current_state(TASK_RUNNING);
2091                 mayday_clear_cpu(cpu, wq->mayday_mask);
2092
2093                 /* migrate to the target cpu if possible */
2094                 rescuer->gcwq = gcwq;
2095                 worker_maybe_bind_and_lock(rescuer);
2096
2097                 /*
2098                  * Slurp in all works issued via this workqueue and
2099                  * process'em.
2100                  */
2101                 BUG_ON(!list_empty(&rescuer->scheduled));
2102                 list_for_each_entry_safe(work, n, &gcwq->worklist, entry)
2103                         if (get_work_cwq(work) == cwq)
2104                                 move_linked_works(work, scheduled, &n);
2105
2106                 process_scheduled_works(rescuer);
2107
2108                 /*
2109                  * Leave this gcwq.  If keep_working() is %true, notify a
2110                  * regular worker; otherwise, we end up with 0 concurrency
2111                  * and stalling the execution.
2112                  */
2113                 if (keep_working(gcwq))
2114                         wake_up_worker(gcwq);
2115
2116                 spin_unlock_irq(&gcwq->lock);
2117         }
2118
2119         schedule();
2120         goto repeat;
2121 }
2122
2123 struct wq_barrier {
2124         struct work_struct      work;
2125         struct completion       done;
2126 };
2127
2128 static void wq_barrier_func(struct work_struct *work)
2129 {
2130         struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2131         complete(&barr->done);
2132 }
2133
2134 /**
2135  * insert_wq_barrier - insert a barrier work
2136  * @cwq: cwq to insert barrier into
2137  * @barr: wq_barrier to insert
2138  * @target: target work to attach @barr to
2139  * @worker: worker currently executing @target, NULL if @target is not executing
2140  *
2141  * @barr is linked to @target such that @barr is completed only after
2142  * @target finishes execution.  Please note that the ordering
2143  * guarantee is observed only with respect to @target and on the local
2144  * cpu.
2145  *
2146  * Currently, a queued barrier can't be canceled.  This is because
2147  * try_to_grab_pending() can't determine whether the work to be
2148  * grabbed is at the head of the queue and thus can't clear LINKED
2149  * flag of the previous work while there must be a valid next work
2150  * after a work with LINKED flag set.
2151  *
2152  * Note that when @worker is non-NULL, @target may be modified
2153  * underneath us, so we can't reliably determine cwq from @target.
2154  *
2155  * CONTEXT:
2156  * spin_lock_irq(gcwq->lock).
2157  */
2158 static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
2159                               struct wq_barrier *barr,
2160                               struct work_struct *target, struct worker *worker)
2161 {
2162         struct list_head *head;
2163         unsigned int linked = 0;
2164
2165         /*
2166          * debugobject calls are safe here even with gcwq->lock locked
2167          * as we know for sure that this will not trigger any of the
2168          * checks and call back into the fixup functions where we
2169          * might deadlock.
2170          */
2171         INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
2172         __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
2173         init_completion(&barr->done);
2174
2175         /*
2176          * If @target is currently being executed, schedule the
2177          * barrier to the worker; otherwise, put it after @target.
2178          */
2179         if (worker)
2180                 head = worker->scheduled.next;
2181         else {
2182                 unsigned long *bits = work_data_bits(target);
2183
2184                 head = target->entry.next;
2185                 /* there can already be other linked works, inherit and set */
2186                 linked = *bits & WORK_STRUCT_LINKED;
2187                 __set_bit(WORK_STRUCT_LINKED_BIT, bits);
2188         }
2189
2190         debug_work_activate(&barr->work);
2191         insert_work(cwq, &barr->work, head,
2192                     work_color_to_flags(WORK_NO_COLOR) | linked);
2193 }
2194
2195 /**
2196  * flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
2197  * @wq: workqueue being flushed
2198  * @flush_color: new flush color, < 0 for no-op
2199  * @work_color: new work color, < 0 for no-op
2200  *
2201  * Prepare cwqs for workqueue flushing.
2202  *
2203  * If @flush_color is non-negative, flush_color on all cwqs should be
2204  * -1.  If no cwq has in-flight commands at the specified color, all
2205  * cwq->flush_color's stay at -1 and %false is returned.  If any cwq
2206  * has in flight commands, its cwq->flush_color is set to
2207  * @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
2208  * wakeup logic is armed and %true is returned.
2209  *
2210  * The caller should have initialized @wq->first_flusher prior to
2211  * calling this function with non-negative @flush_color.  If
2212  * @flush_color is negative, no flush color update is done and %false
2213  * is returned.
2214  *
2215  * If @work_color is non-negative, all cwqs should have the same
2216  * work_color which is previous to @work_color and all will be
2217  * advanced to @work_color.
2218  *
2219  * CONTEXT:
2220  * mutex_lock(wq->flush_mutex).
2221  *
2222  * RETURNS:
2223  * %true if @flush_color >= 0 and there's something to flush.  %false
2224  * otherwise.
2225  */
2226 static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
2227                                       int flush_color, int work_color)
2228 {
2229         bool wait = false;
2230         unsigned int cpu;
2231
2232         if (flush_color >= 0) {
2233                 BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
2234                 atomic_set(&wq->nr_cwqs_to_flush, 1);
2235         }
2236
2237         for_each_cwq_cpu(cpu, wq) {
2238                 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2239                 struct global_cwq *gcwq = cwq->gcwq;
2240
2241                 spin_lock_irq(&gcwq->lock);
2242
2243                 if (flush_color >= 0) {
2244                         BUG_ON(cwq->flush_color != -1);
2245
2246                         if (cwq->nr_in_flight[flush_color]) {
2247                                 cwq->flush_color = flush_color;
2248                                 atomic_inc(&wq->nr_cwqs_to_flush);
2249                                 wait = true;
2250                         }
2251                 }
2252
2253                 if (work_color >= 0) {
2254                         BUG_ON(work_color != work_next_color(cwq->work_color));
2255                         cwq->work_color = work_color;
2256                 }
2257
2258                 spin_unlock_irq(&gcwq->lock);
2259         }
2260
2261         if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
2262                 complete(&wq->first_flusher->done);
2263
2264         return wait;
2265 }
2266
2267 /**
2268  * flush_workqueue - ensure that any scheduled work has run to completion.
2269  * @wq: workqueue to flush
2270  *
2271  * Forces execution of the workqueue and blocks until its completion.
2272  * This is typically used in driver shutdown handlers.
2273  *
2274  * We sleep until all works which were queued on entry have been handled,
2275  * but we are not livelocked by new incoming ones.
2276  */
2277 void flush_workqueue(struct workqueue_struct *wq)
2278 {
2279         struct wq_flusher this_flusher = {
2280                 .list = LIST_HEAD_INIT(this_flusher.list),
2281                 .flush_color = -1,
2282                 .done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
2283         };
2284         int next_color;
2285
2286         lock_map_acquire(&wq->lockdep_map);
2287         lock_map_release(&wq->lockdep_map);
2288
2289         mutex_lock(&wq->flush_mutex);
2290
2291         /*
2292          * Start-to-wait phase
2293          */
2294         next_color = work_next_color(wq->work_color);
2295
2296         if (next_color != wq->flush_color) {
2297                 /*
2298                  * Color space is not full.  The current work_color
2299                  * becomes our flush_color and work_color is advanced
2300                  * by one.
2301                  */
2302                 BUG_ON(!list_empty(&wq->flusher_overflow));
2303                 this_flusher.flush_color = wq->work_color;
2304                 wq->work_color = next_color;
2305
2306                 if (!wq->first_flusher) {
2307                         /* no flush in progress, become the first flusher */
2308                         BUG_ON(wq->flush_color != this_flusher.flush_color);
2309
2310                         wq->first_flusher = &this_flusher;
2311
2312                         if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
2313                                                        wq->work_color)) {
2314                                 /* nothing to flush, done */
2315                                 wq->flush_color = next_color;
2316                                 wq->first_flusher = NULL;
2317                                 goto out_unlock;
2318                         }
2319                 } else {
2320                         /* wait in queue */
2321                         BUG_ON(wq->flush_color == this_flusher.flush_color);
2322                         list_add_tail(&this_flusher.list, &wq->flusher_queue);
2323                         flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2324                 }
2325         } else {
2326                 /*
2327                  * Oops, color space is full, wait on overflow queue.
2328                  * The next flush completion will assign us
2329                  * flush_color and transfer to flusher_queue.
2330                  */
2331                 list_add_tail(&this_flusher.list, &wq->flusher_overflow);
2332         }
2333
2334         mutex_unlock(&wq->flush_mutex);
2335
2336         wait_for_completion(&this_flusher.done);
2337
2338         /*
2339          * Wake-up-and-cascade phase
2340          *
2341          * First flushers are responsible for cascading flushes and
2342          * handling overflow.  Non-first flushers can simply return.
2343          */
2344         if (wq->first_flusher != &this_flusher)
2345                 return;
2346
2347         mutex_lock(&wq->flush_mutex);
2348
2349         /* we might have raced, check again with mutex held */
2350         if (wq->first_flusher != &this_flusher)
2351                 goto out_unlock;
2352
2353         wq->first_flusher = NULL;
2354
2355         BUG_ON(!list_empty(&this_flusher.list));
2356         BUG_ON(wq->flush_color != this_flusher.flush_color);
2357
2358         while (true) {
2359                 struct wq_flusher *next, *tmp;
2360
2361                 /* complete all the flushers sharing the current flush color */
2362                 list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
2363                         if (next->flush_color != wq->flush_color)
2364                                 break;
2365                         list_del_init(&next->list);
2366                         complete(&next->done);
2367                 }
2368
2369                 BUG_ON(!list_empty(&wq->flusher_overflow) &&
2370                        wq->flush_color != work_next_color(wq->work_color));
2371
2372                 /* this flush_color is finished, advance by one */
2373                 wq->flush_color = work_next_color(wq->flush_color);
2374
2375                 /* one color has been freed, handle overflow queue */
2376                 if (!list_empty(&wq->flusher_overflow)) {
2377                         /*
2378                          * Assign the same color to all overflowed
2379                          * flushers, advance work_color and append to
2380                          * flusher_queue.  This is the start-to-wait
2381                          * phase for these overflowed flushers.
2382                          */
2383                         list_for_each_entry(tmp, &wq->flusher_overflow, list)
2384                                 tmp->flush_color = wq->work_color;
2385
2386                         wq->work_color = work_next_color(wq->work_color);
2387
2388                         list_splice_tail_init(&wq->flusher_overflow,
2389                                               &wq->flusher_queue);
2390                         flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
2391                 }
2392
2393                 if (list_empty(&wq->flusher_queue)) {
2394                         BUG_ON(wq->flush_color != wq->work_color);
2395                         break;
2396                 }
2397
2398                 /*
2399                  * Need to flush more colors.  Make the next flusher
2400                  * the new first flusher and arm cwqs.
2401                  */
2402                 BUG_ON(wq->flush_color == wq->work_color);
2403                 BUG_ON(wq->flush_color != next->flush_color);
2404
2405                 list_del_init(&next->list);
2406                 wq->first_flusher = next;
2407
2408                 if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
2409                         break;
2410
2411                 /*
2412                  * Meh... this color is already done, clear first
2413                  * flusher and repeat cascading.
2414                  */
2415                 wq->first_flusher = NULL;
2416         }
2417
2418 out_unlock:
2419         mutex_unlock(&wq->flush_mutex);
2420 }
2421 EXPORT_SYMBOL_GPL(flush_workqueue);
2422
2423 /**
2424  * drain_workqueue - drain a workqueue
2425  * @wq: workqueue to drain
2426  *
2427  * Wait until the workqueue becomes empty.  While draining is in progress,
2428  * only chain queueing is allowed.  IOW, only currently pending or running
2429  * work items on @wq can queue further work items on it.  @wq is flushed
2430  * repeatedly until it becomes empty.  The number of flushing is detemined
2431  * by the depth of chaining and should be relatively short.  Whine if it
2432  * takes too long.
2433  */
2434 void drain_workqueue(struct workqueue_struct *wq)
2435 {
2436         unsigned int flush_cnt = 0;
2437         unsigned int cpu;
2438
2439         /*
2440          * __queue_work() needs to test whether there are drainers, is much
2441          * hotter than drain_workqueue() and already looks at @wq->flags.
2442          * Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
2443          */
2444         spin_lock(&workqueue_lock);
2445         if (!wq->nr_drainers++)
2446                 wq->flags |= WQ_DRAINING;
2447         spin_unlock(&workqueue_lock);
2448 reflush:
2449         flush_workqueue(wq);
2450
2451         for_each_cwq_cpu(cpu, wq) {
2452                 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
2453                 bool drained;
2454
2455                 spin_lock_irq(&cwq->gcwq->lock);
2456                 drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
2457                 spin_unlock_irq(&cwq->gcwq->lock);
2458
2459                 if (drained)
2460                         continue;
2461
2462                 if (++flush_cnt == 10 ||
2463                     (flush_cnt % 100 == 0 && flush_cnt <= 1000))
2464                         pr_warning("workqueue %s: flush on destruction isn't complete after %u tries\n",
2465                                    wq->name, flush_cnt);
2466                 goto reflush;
2467         }
2468
2469         spin_lock(&workqueue_lock);
2470         if (!--wq->nr_drainers)
2471                 wq->flags &= ~WQ_DRAINING;
2472         spin_unlock(&workqueue_lock);
2473 }
2474 EXPORT_SYMBOL_GPL(drain_workqueue);
2475
2476 static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
2477                              bool wait_executing)
2478 {
2479         struct worker *worker = NULL;
2480         struct global_cwq *gcwq;
2481         struct cpu_workqueue_struct *cwq;
2482
2483         might_sleep();
2484         gcwq = get_work_gcwq(work);
2485         if (!gcwq)
2486                 return false;
2487
2488         spin_lock_irq(&gcwq->lock);
2489         if (!list_empty(&work->entry)) {
2490                 /*
2491                  * See the comment near try_to_grab_pending()->smp_rmb().
2492                  * If it was re-queued to a different gcwq under us, we
2493                  * are not going to wait.
2494                  */
2495                 smp_rmb();
2496                 cwq = get_work_cwq(work);
2497                 if (unlikely(!cwq || gcwq != cwq->gcwq))
2498                         goto already_gone;
2499         } else if (wait_executing) {
2500                 worker = find_worker_executing_work(gcwq, work);
2501                 if (!worker)
2502                         goto already_gone;
2503                 cwq = worker->current_cwq;
2504         } else
2505                 goto already_gone;
2506
2507         insert_wq_barrier(cwq, barr, work, worker);
2508         spin_unlock_irq(&gcwq->lock);
2509
2510         /*
2511          * If @max_active is 1 or rescuer is in use, flushing another work
2512          * item on the same workqueue may lead to deadlock.  Make sure the
2513          * flusher is not running on the same workqueue by verifying write
2514          * access.
2515          */
2516         if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
2517                 lock_map_acquire(&cwq->wq->lockdep_map);
2518         else
2519                 lock_map_acquire_read(&cwq->wq->lockdep_map);
2520         lock_map_release(&cwq->wq->lockdep_map);
2521
2522         return true;
2523 already_gone:
2524         spin_unlock_irq(&gcwq->lock);
2525         return false;
2526 }
2527
2528 /**
2529  * flush_work - wait for a work to finish executing the last queueing instance
2530  * @work: the work to flush
2531  *
2532  * Wait until @work has finished execution.  This function considers
2533  * only the last queueing instance of @work.  If @work has been
2534  * enqueued across different CPUs on a non-reentrant workqueue or on
2535  * multiple workqueues, @work might still be executing on return on
2536  * some of the CPUs from earlier queueing.
2537  *
2538  * If @work was queued only on a non-reentrant, ordered or unbound
2539  * workqueue, @work is guaranteed to be idle on return if it hasn't
2540  * been requeued since flush started.
2541  *
2542  * RETURNS:
2543  * %true if flush_work() waited for the work to finish execution,
2544  * %false if it was already idle.
2545  */
2546 bool flush_work(struct work_struct *work)
2547 {
2548         struct wq_barrier barr;
2549
2550         if (start_flush_work(work, &barr, true)) {
2551                 wait_for_completion(&barr.done);
2552                 destroy_work_on_stack(&barr.work);
2553                 return true;
2554         } else
2555                 return false;
2556 }
2557 EXPORT_SYMBOL_GPL(flush_work);
2558
2559 static bool wait_on_cpu_work(struct global_cwq *gcwq, struct work_struct *work)
2560 {
2561         struct wq_barrier barr;
2562         struct worker *worker;
2563
2564         spin_lock_irq(&gcwq->lock);
2565
2566         worker = find_worker_executing_work(gcwq, work);
2567         if (unlikely(worker))
2568                 insert_wq_barrier(worker->current_cwq, &barr, work, worker);
2569
2570         spin_unlock_irq(&gcwq->lock);
2571
2572         if (unlikely(worker)) {
2573                 wait_for_completion(&barr.done);
2574                 destroy_work_on_stack(&barr.work);
2575                 return true;
2576         } else
2577                 return false;
2578 }
2579
2580 static bool wait_on_work(struct work_struct *work)
2581 {
2582         bool ret = false;
2583         int cpu;
2584
2585         might_sleep();
2586
2587         lock_map_acquire(&work->lockdep_map);
2588         lock_map_release(&work->lockdep_map);
2589
2590         for_each_gcwq_cpu(cpu)
2591                 ret |= wait_on_cpu_work(get_gcwq(cpu), work);
2592         return ret;
2593 }
2594
2595 /**
2596  * flush_work_sync - wait until a work has finished execution
2597  * @work: the work to flush
2598  *
2599  * Wait until @work has finished execution.  On return, it's
2600  * guaranteed that all queueing instances of @work which happened
2601  * before this function is called are finished.  In other words, if
2602  * @work hasn't been requeued since this function was called, @work is
2603  * guaranteed to be idle on return.
2604  *
2605  * RETURNS:
2606  * %true if flush_work_sync() waited for the work to finish execution,
2607  * %false if it was already idle.
2608  */
2609 bool flush_work_sync(struct work_struct *work)
2610 {
2611         struct wq_barrier barr;
2612         bool pending, waited;
2613
2614         /* we'll wait for executions separately, queue barr only if pending */
2615         pending = start_flush_work(work, &barr, false);
2616
2617         /* wait for executions to finish */
2618         waited = wait_on_work(work);
2619
2620         /* wait for the pending one */
2621         if (pending) {
2622                 wait_for_completion(&barr.done);
2623                 destroy_work_on_stack(&barr.work);
2624         }
2625
2626         return pending || waited;
2627 }
2628 EXPORT_SYMBOL_GPL(flush_work_sync);
2629
2630 /*
2631  * Upon a successful return (>= 0), the caller "owns" WORK_STRUCT_PENDING bit,
2632  * so this work can't be re-armed in any way.
2633  */
2634 static int try_to_grab_pending(struct work_struct *work)
2635 {
2636         struct global_cwq *gcwq;
2637         int ret = -1;
2638
2639         if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
2640                 return 0;
2641
2642         /*
2643          * The queueing is in progress, or it is already queued. Try to
2644          * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
2645          */
2646         gcwq = get_work_gcwq(work);
2647         if (!gcwq)
2648                 return ret;
2649
2650         spin_lock_irq(&gcwq->lock);
2651         if (!list_empty(&work->entry)) {
2652                 /*
2653                  * This work is queued, but perhaps we locked the wrong gcwq.
2654                  * In that case we must see the new value after rmb(), see
2655                  * insert_work()->wmb().
2656                  */
2657                 smp_rmb();
2658                 if (gcwq == get_work_gcwq(work)) {
2659                         debug_work_deactivate(work);
2660
2661                         /*
2662                          * A delayed work item cannot be grabbed directly
2663                          * because it might have linked NO_COLOR work items
2664                          * which, if left on the delayed_list, will confuse
2665                          * cwq->nr_active management later on and cause
2666                          * stall.  Make sure the work item is activated
2667                          * before grabbing.
2668                          */
2669                         if (*work_data_bits(work) & WORK_STRUCT_DELAYED)
2670                                 cwq_activate_delayed_work(work);
2671
2672                         list_del_init(&work->entry);
2673                         cwq_dec_nr_in_flight(get_work_cwq(work),
2674                                 get_work_color(work),
2675                                 *work_data_bits(work) & WORK_STRUCT_DELAYED);
2676                         ret = 1;
2677                 }
2678         }
2679         spin_unlock_irq(&gcwq->lock);
2680
2681         return ret;
2682 }
2683
2684 static bool __cancel_work_timer(struct work_struct *work,
2685                                 struct timer_list* timer)
2686 {
2687         int ret;
2688
2689         do {
2690                 ret = (timer && likely(del_timer(timer)));
2691                 if (!ret)
2692                         ret = try_to_grab_pending(work);
2693                 wait_on_work(work);
2694         } while (unlikely(ret < 0));
2695
2696         clear_work_data(work);
2697         return ret;
2698 }
2699
2700 /**
2701  * cancel_work_sync - cancel a work and wait for it to finish
2702  * @work: the work to cancel
2703  *
2704  * Cancel @work and wait for its execution to finish.  This function
2705  * can be used even if the work re-queues itself or migrates to
2706  * another workqueue.  On return from this function, @work is
2707  * guaranteed to be not pending or executing on any CPU.
2708  *
2709  * cancel_work_sync(&delayed_work->work) must not be used for
2710  * delayed_work's.  Use cancel_delayed_work_sync() instead.
2711  *
2712  * The caller must ensure that the workqueue on which @work was last
2713  * queued can't be destroyed before this function returns.
2714  *
2715  * RETURNS:
2716  * %true if @work was pending, %false otherwise.
2717  */
2718 bool cancel_work_sync(struct work_struct *work)
2719 {
2720         return __cancel_work_timer(work, NULL);
2721 }
2722 EXPORT_SYMBOL_GPL(cancel_work_sync);
2723
2724 /**
2725  * flush_delayed_work - wait for a dwork to finish executing the last queueing
2726  * @dwork: the delayed work to flush
2727  *
2728  * Delayed timer is cancelled and the pending work is queued for
2729  * immediate execution.  Like flush_work(), this function only
2730  * considers the last queueing instance of @dwork.
2731  *
2732  * RETURNS:
2733  * %true if flush_work() waited for the work to finish execution,
2734  * %false if it was already idle.
2735  */
2736 bool flush_delayed_work(struct delayed_work *dwork)
2737 {
2738         if (del_timer_sync(&dwork->timer))
2739                 __queue_work(raw_smp_processor_id(),
2740                              get_work_cwq(&dwork->work)->wq, &dwork->work);
2741         return flush_work(&dwork->work);
2742 }
2743 EXPORT_SYMBOL(flush_delayed_work);
2744
2745 /**
2746  * flush_delayed_work_sync - wait for a dwork to finish
2747  * @dwork: the delayed work to flush
2748  *
2749  * Delayed timer is cancelled and the pending work is queued for
2750  * execution immediately.  Other than timer handling, its behavior
2751  * is identical to flush_work_sync().
2752  *
2753  * RETURNS:
2754  * %true if flush_work_sync() waited for the work to finish execution,
2755  * %false if it was already idle.
2756  */
2757 bool flush_delayed_work_sync(struct delayed_work *dwork)
2758 {
2759         if (del_timer_sync(&dwork->timer))
2760                 __queue_work(raw_smp_processor_id(),
2761                              get_work_cwq(&dwork->work)->wq, &dwork->work);
2762         return flush_work_sync(&dwork->work);
2763 }
2764 EXPORT_SYMBOL(flush_delayed_work_sync);
2765
2766 /**
2767  * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2768  * @dwork: the delayed work cancel
2769  *
2770  * This is cancel_work_sync() for delayed works.
2771  *
2772  * RETURNS:
2773  * %true if @dwork was pending, %false otherwise.
2774  */
2775 bool cancel_delayed_work_sync(struct delayed_work *dwork)
2776 {
2777         return __cancel_work_timer(&dwork->work, &dwork->timer);
2778 }
2779 EXPORT_SYMBOL(cancel_delayed_work_sync);
2780
2781 /**
2782  * schedule_work - put work task in global workqueue
2783  * @work: job to be done
2784  *
2785  * Returns zero if @work was already on the kernel-global workqueue and
2786  * non-zero otherwise.
2787  *
2788  * This puts a job in the kernel-global workqueue if it was not already
2789  * queued and leaves it in the same position on the kernel-global
2790  * workqueue otherwise.
2791  */
2792 int schedule_work(struct work_struct *work)
2793 {
2794         return queue_work(system_wq, work);
2795 }
2796 EXPORT_SYMBOL(schedule_work);
2797
2798 /*
2799  * schedule_work_on - put work task on a specific cpu
2800  * @cpu: cpu to put the work task on
2801  * @work: job to be done
2802  *
2803  * This puts a job on a specific cpu
2804  */
2805 int schedule_work_on(int cpu, struct work_struct *work)
2806 {
2807         return queue_work_on(cpu, system_wq, work);
2808 }
2809 EXPORT_SYMBOL(schedule_work_on);
2810
2811 /**
2812  * schedule_delayed_work - put work task in global workqueue after delay
2813  * @dwork: job to be done
2814  * @delay: number of jiffies to wait or 0 for immediate execution
2815  *
2816  * After waiting for a given time this puts a job in the kernel-global
2817  * workqueue.
2818  */
2819 int schedule_delayed_work(struct delayed_work *dwork,
2820                                         unsigned long delay)
2821 {
2822         return queue_delayed_work(system_wq, dwork, delay);
2823 }
2824 EXPORT_SYMBOL(schedule_delayed_work);
2825
2826 /**
2827  * schedule_delayed_work_on - queue work in global workqueue on CPU after delay
2828  * @cpu: cpu to use
2829  * @dwork: job to be done
2830  * @delay: number of jiffies to wait
2831  *
2832  * After waiting for a given time this puts a job in the kernel-global
2833  * workqueue on the specified CPU.
2834  */
2835 int schedule_delayed_work_on(int cpu,
2836                         struct delayed_work *dwork, unsigned long delay)
2837 {
2838         return queue_delayed_work_on(cpu, system_wq, dwork, delay);
2839 }
2840 EXPORT_SYMBOL(schedule_delayed_work_on);
2841
2842 /**
2843  * schedule_on_each_cpu - execute a function synchronously on each online CPU
2844  * @func: the function to call
2845  *
2846  * schedule_on_each_cpu() executes @func on each online CPU using the
2847  * system workqueue and blocks until all CPUs have completed.
2848  * schedule_on_each_cpu() is very slow.
2849  *
2850  * RETURNS:
2851  * 0 on success, -errno on failure.
2852  */
2853 int schedule_on_each_cpu(work_func_t func)
2854 {
2855         int cpu;
2856         struct work_struct __percpu *works;
2857
2858         works = alloc_percpu(struct work_struct);
2859         if (!works)
2860                 return -ENOMEM;
2861
2862         get_online_cpus();
2863
2864         for_each_online_cpu(cpu) {
2865                 struct work_struct *work = per_cpu_ptr(works, cpu);
2866
2867                 INIT_WORK(work, func);
2868                 schedule_work_on(cpu, work);
2869         }
2870
2871         for_each_online_cpu(cpu)
2872                 flush_work(per_cpu_ptr(works, cpu));
2873
2874         put_online_cpus();
2875         free_percpu(works);
2876         return 0;
2877 }
2878
2879 /**
2880  * flush_scheduled_work - ensure that any scheduled work has run to completion.
2881  *
2882  * Forces execution of the kernel-global workqueue and blocks until its
2883  * completion.
2884  *
2885  * Think twice before calling this function!  It's very easy to get into
2886  * trouble if you don't take great care.  Either of the following situations
2887  * will lead to deadlock:
2888  *
2889  *      One of the work items currently on the workqueue needs to acquire
2890  *      a lock held by your code or its caller.
2891  *
2892  *      Your code is running in the context of a work routine.
2893  *
2894  * They will be detected by lockdep when they occur, but the first might not
2895  * occur very often.  It depends on what work items are on the workqueue and
2896  * what locks they need, which you have no control over.
2897  *
2898  * In most situations flushing the entire workqueue is overkill; you merely
2899  * need to know that a particular work item isn't queued and isn't running.
2900  * In such cases you should use cancel_delayed_work_sync() or
2901  * cancel_work_sync() instead.
2902  */
2903 void flush_scheduled_work(void)
2904 {
2905         flush_workqueue(system_wq);
2906 }
2907 EXPORT_SYMBOL(flush_scheduled_work);
2908
2909 /**
2910  * execute_in_process_context - reliably execute the routine with user context
2911  * @fn:         the function to execute
2912  * @ew:         guaranteed storage for the execute work structure (must
2913  *              be available when the work executes)
2914  *
2915  * Executes the function immediately if process context is available,
2916  * otherwise schedules the function for delayed execution.
2917  *
2918  * Returns:     0 - function was executed
2919  *              1 - function was scheduled for execution
2920  */
2921 int execute_in_process_context(work_func_t fn, struct execute_work *ew)
2922 {
2923         if (!in_interrupt()) {
2924                 fn(&ew->work);
2925                 return 0;
2926         }
2927
2928         INIT_WORK(&ew->work, fn);
2929         schedule_work(&ew->work);
2930
2931         return 1;
2932 }
2933 EXPORT_SYMBOL_GPL(execute_in_process_context);
2934
2935 int keventd_up(void)
2936 {
2937         return system_wq != NULL;
2938 }
2939
2940 static int alloc_cwqs(struct workqueue_struct *wq)
2941 {
2942         /*
2943          * cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
2944          * Make sure that the alignment isn't lower than that of
2945          * unsigned long long.
2946          */
2947         const size_t size = sizeof(struct cpu_workqueue_struct);
2948         const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
2949                                    __alignof__(unsigned long long));
2950 #ifdef CONFIG_SMP
2951         bool percpu = !(wq->flags & WQ_UNBOUND);
2952 #else
2953         bool percpu = false;
2954 #endif
2955
2956         if (percpu)
2957                 wq->cpu_wq.pcpu = __alloc_percpu(size, align);
2958         else {
2959                 void *ptr;
2960
2961                 /*
2962                  * Allocate enough room to align cwq and put an extra
2963                  * pointer at the end pointing back to the originally
2964                  * allocated pointer which will be used for free.
2965                  */
2966                 ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
2967                 if (ptr) {
2968                         wq->cpu_wq.single = PTR_ALIGN(ptr, align);
2969                         *(void **)(wq->cpu_wq.single + 1) = ptr;
2970                 }
2971         }
2972
2973         /* just in case, make sure it's actually aligned */
2974         BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
2975         return wq->cpu_wq.v ? 0 : -ENOMEM;
2976 }
2977
2978 static void free_cwqs(struct workqueue_struct *wq)
2979 {
2980 #ifdef CONFIG_SMP
2981         bool percpu = !(wq->flags & WQ_UNBOUND);
2982 #else
2983         bool percpu = false;
2984 #endif
2985
2986         if (percpu)
2987                 free_percpu(wq->cpu_wq.pcpu);
2988         else if (wq->cpu_wq.single) {
2989                 /* the pointer to free is stored right after the cwq */
2990                 kfree(*(void **)(wq->cpu_wq.single + 1));
2991         }
2992 }
2993
2994 static int wq_clamp_max_active(int max_active, unsigned int flags,
2995                                const char *name)
2996 {
2997         int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
2998
2999         if (max_active < 1 || max_active > lim)
3000                 printk(KERN_WARNING "workqueue: max_active %d requested for %s "
3001                        "is out of range, clamping between %d and %d\n",
3002                        max_active, name, 1, lim);
3003
3004         return clamp_val(max_active, 1, lim);
3005 }
3006
3007 struct workqueue_struct *__alloc_workqueue_key(const char *name,
3008                                                unsigned int flags,
3009                                                int max_active,
3010                                                struct lock_class_key *key,
3011                                                const char *lock_name)
3012 {
3013         struct workqueue_struct *wq;
3014         unsigned int cpu;
3015
3016         /*
3017          * Workqueues which may be used during memory reclaim should
3018          * have a rescuer to guarantee forward progress.
3019          */
3020         if (flags & WQ_MEM_RECLAIM)
3021                 flags |= WQ_RESCUER;
3022
3023         /*
3024          * Unbound workqueues aren't concurrency managed and should be
3025          * dispatched to workers immediately.
3026          */
3027         if (flags & WQ_UNBOUND)
3028                 flags |= WQ_HIGHPRI;
3029
3030         max_active = max_active ?: WQ_DFL_ACTIVE;
3031         max_active = wq_clamp_max_active(max_active, flags, name);
3032
3033         wq = kzalloc(sizeof(*wq), GFP_KERNEL);
3034         if (!wq)
3035                 goto err;
3036
3037         wq->flags = flags;
3038         wq->saved_max_active = max_active;
3039         mutex_init(&wq->flush_mutex);
3040         atomic_set(&wq->nr_cwqs_to_flush, 0);
3041         INIT_LIST_HEAD(&wq->flusher_queue);
3042         INIT_LIST_HEAD(&wq->flusher_overflow);
3043
3044         wq->name = name;
3045         lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
3046         INIT_LIST_HEAD(&wq->list);
3047
3048         if (alloc_cwqs(wq) < 0)
3049                 goto err;
3050
3051         for_each_cwq_cpu(cpu, wq) {
3052                 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3053                 struct global_cwq *gcwq = get_gcwq(cpu);
3054
3055                 BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
3056                 cwq->gcwq = gcwq;
3057                 cwq->wq = wq;
3058                 cwq->flush_color = -1;
3059                 cwq->max_active = max_active;
3060                 INIT_LIST_HEAD(&cwq->delayed_works);
3061         }
3062
3063         if (flags & WQ_RESCUER) {
3064                 struct worker *rescuer;
3065
3066                 if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
3067                         goto err;
3068
3069                 wq->rescuer = rescuer = alloc_worker();
3070                 if (!rescuer)
3071                         goto err;
3072
3073                 rescuer->task = kthread_create(rescuer_thread, wq, "%s", name);
3074                 if (IS_ERR(rescuer->task))
3075                         goto err;
3076
3077                 rescuer->task->flags |= PF_THREAD_BOUND;
3078                 wake_up_process(rescuer->task);
3079         }
3080
3081         /*
3082          * workqueue_lock protects global freeze state and workqueues
3083          * list.  Grab it, set max_active accordingly and add the new
3084          * workqueue to workqueues list.
3085          */
3086         spin_lock(&workqueue_lock);
3087
3088         if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
3089                 for_each_cwq_cpu(cpu, wq)
3090                         get_cwq(cpu, wq)->max_active = 0;
3091
3092         list_add(&wq->list, &workqueues);
3093
3094         spin_unlock(&workqueue_lock);
3095
3096         return wq;
3097 err:
3098         if (wq) {
3099                 free_cwqs(wq);
3100                 free_mayday_mask(wq->mayday_mask);
3101                 kfree(wq->rescuer);
3102                 kfree(wq);
3103         }
3104         return NULL;
3105 }
3106 EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
3107
3108 /**
3109  * destroy_workqueue - safely terminate a workqueue
3110  * @wq: target workqueue
3111  *
3112  * Safely destroy a workqueue. All work currently pending will be done first.
3113  */
3114 void destroy_workqueue(struct workqueue_struct *wq)
3115 {
3116         unsigned int cpu;
3117
3118         /* drain it before proceeding with destruction */
3119         drain_workqueue(wq);
3120
3121         /*
3122          * wq list is used to freeze wq, remove from list after
3123          * flushing is complete in case freeze races us.
3124          */
3125         spin_lock(&workqueue_lock);
3126         list_del(&wq->list);
3127         spin_unlock(&workqueue_lock);
3128
3129         /* sanity check */
3130         for_each_cwq_cpu(cpu, wq) {
3131                 struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3132                 int i;
3133
3134                 for (i = 0; i < WORK_NR_COLORS; i++)
3135                         BUG_ON(cwq->nr_in_flight[i]);
3136                 BUG_ON(cwq->nr_active);
3137                 BUG_ON(!list_empty(&cwq->delayed_works));
3138         }
3139
3140         if (wq->flags & WQ_RESCUER) {
3141                 kthread_stop(wq->rescuer->task);
3142                 free_mayday_mask(wq->mayday_mask);
3143                 kfree(wq->rescuer);
3144         }
3145
3146         free_cwqs(wq);
3147         kfree(wq);
3148 }
3149 EXPORT_SYMBOL_GPL(destroy_workqueue);
3150
3151 /**
3152  * workqueue_set_max_active - adjust max_active of a workqueue
3153  * @wq: target workqueue
3154  * @max_active: new max_active value.
3155  *
3156  * Set max_active of @wq to @max_active.
3157  *
3158  * CONTEXT:
3159  * Don't call from IRQ context.
3160  */
3161 void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
3162 {
3163         unsigned int cpu;
3164
3165         max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
3166
3167         spin_lock(&workqueue_lock);
3168
3169         wq->saved_max_active = max_active;
3170
3171         for_each_cwq_cpu(cpu, wq) {
3172                 struct global_cwq *gcwq = get_gcwq(cpu);
3173
3174                 spin_lock_irq(&gcwq->lock);
3175
3176                 if (!(wq->flags & WQ_FREEZABLE) ||
3177                     !(gcwq->flags & GCWQ_FREEZING))
3178                         get_cwq(gcwq->cpu, wq)->max_active = max_active;
3179
3180                 spin_unlock_irq(&gcwq->lock);
3181         }
3182
3183         spin_unlock(&workqueue_lock);
3184 }
3185 EXPORT_SYMBOL_GPL(workqueue_set_max_active);
3186
3187 /**
3188  * workqueue_congested - test whether a workqueue is congested
3189  * @cpu: CPU in question
3190  * @wq: target workqueue
3191  *
3192  * Test whether @wq's cpu workqueue for @cpu is congested.  There is
3193  * no synchronization around this function and the test result is
3194  * unreliable and only useful as advisory hints or for debugging.
3195  *
3196  * RETURNS:
3197  * %true if congested, %false otherwise.
3198  */
3199 bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
3200 {
3201         struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3202
3203         return !list_empty(&cwq->delayed_works);
3204 }
3205 EXPORT_SYMBOL_GPL(workqueue_congested);
3206
3207 /**
3208  * work_cpu - return the last known associated cpu for @work
3209  * @work: the work of interest
3210  *
3211  * RETURNS:
3212  * CPU number if @work was ever queued.  WORK_CPU_NONE otherwise.
3213  */
3214 unsigned int work_cpu(struct work_struct *work)
3215 {
3216         struct global_cwq *gcwq = get_work_gcwq(work);
3217
3218         return gcwq ? gcwq->cpu : WORK_CPU_NONE;
3219 }
3220 EXPORT_SYMBOL_GPL(work_cpu);
3221
3222 /**
3223  * work_busy - test whether a work is currently pending or running
3224  * @work: the work to be tested
3225  *
3226  * Test whether @work is currently pending or running.  There is no
3227  * synchronization around this function and the test result is
3228  * unreliable and only useful as advisory hints or for debugging.
3229  * Especially for reentrant wqs, the pending state might hide the
3230  * running state.
3231  *
3232  * RETURNS:
3233  * OR'd bitmask of WORK_BUSY_* bits.
3234  */
3235 unsigned int work_busy(struct work_struct *work)
3236 {
3237         struct global_cwq *gcwq = get_work_gcwq(work);
3238         unsigned long flags;
3239         unsigned int ret = 0;
3240
3241         if (!gcwq)
3242                 return false;
3243
3244         spin_lock_irqsave(&gcwq->lock, flags);
3245
3246         if (work_pending(work))
3247                 ret |= WORK_BUSY_PENDING;
3248         if (find_worker_executing_work(gcwq, work))
3249                 ret |= WORK_BUSY_RUNNING;
3250
3251         spin_unlock_irqrestore(&gcwq->lock, flags);
3252
3253         return ret;
3254 }
3255 EXPORT_SYMBOL_GPL(work_busy);
3256
3257 /*
3258  * CPU hotplug.
3259  *
3260  * There are two challenges in supporting CPU hotplug.  Firstly, there
3261  * are a lot of assumptions on strong associations among work, cwq and
3262  * gcwq which make migrating pending and scheduled works very
3263  * difficult to implement without impacting hot paths.  Secondly,
3264  * gcwqs serve mix of short, long and very long running works making
3265  * blocked draining impractical.
3266  *
3267  * This is solved by allowing a gcwq to be detached from CPU, running
3268  * it with unbound (rogue) workers and allowing it to be reattached
3269  * later if the cpu comes back online.  A separate thread is created
3270  * to govern a gcwq in such state and is called the trustee of the
3271  * gcwq.
3272  *
3273  * Trustee states and their descriptions.
3274  *
3275  * START        Command state used on startup.  On CPU_DOWN_PREPARE, a
3276  *              new trustee is started with this state.
3277  *
3278  * IN_CHARGE    Once started, trustee will enter this state after
3279  *              assuming the manager role and making all existing
3280  *              workers rogue.  DOWN_PREPARE waits for trustee to
3281  *              enter this state.  After reaching IN_CHARGE, trustee
3282  *              tries to execute the pending worklist until it's empty
3283  *              and the state is set to BUTCHER, or the state is set
3284  *              to RELEASE.
3285  *
3286  * BUTCHER      Command state which is set by the cpu callback after
3287  *              the cpu has went down.  Once this state is set trustee
3288  *              knows that there will be no new works on the worklist
3289  *              and once the worklist is empty it can proceed to
3290  *              killing idle workers.
3291  *
3292  * RELEASE      Command state which is set by the cpu callback if the
3293  *              cpu down has been canceled or it has come online
3294  *              again.  After recognizing this state, trustee stops
3295  *              trying to drain or butcher and clears ROGUE, rebinds
3296  *              all remaining workers back to the cpu and releases
3297  *              manager role.
3298  *
3299  * DONE         Trustee will enter this state after BUTCHER or RELEASE
3300  *              is complete.
3301  *
3302  *          trustee                 CPU                draining
3303  *         took over                down               complete
3304  * START -----------> IN_CHARGE -----------> BUTCHER -----------> DONE
3305  *                        |                     |                  ^
3306  *                        | CPU is back online  v   return workers |
3307  *                         ----------------> RELEASE --------------
3308  */
3309
3310 /**
3311  * trustee_wait_event_timeout - timed event wait for trustee
3312  * @cond: condition to wait for
3313  * @timeout: timeout in jiffies
3314  *
3315  * wait_event_timeout() for trustee to use.  Handles locking and
3316  * checks for RELEASE request.
3317  *
3318  * CONTEXT:
3319  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3320  * multiple times.  To be used by trustee.
3321  *
3322  * RETURNS:
3323  * Positive indicating left time if @cond is satisfied, 0 if timed
3324  * out, -1 if canceled.
3325  */
3326 #define trustee_wait_event_timeout(cond, timeout) ({                    \
3327         long __ret = (timeout);                                         \
3328         while (!((cond) || (gcwq->trustee_state == TRUSTEE_RELEASE)) && \
3329                __ret) {                                                 \
3330                 spin_unlock_irq(&gcwq->lock);                           \
3331                 __wait_event_timeout(gcwq->trustee_wait, (cond) ||      \
3332                         (gcwq->trustee_state == TRUSTEE_RELEASE),       \
3333                         __ret);                                         \
3334                 spin_lock_irq(&gcwq->lock);                             \
3335         }                                                               \
3336         gcwq->trustee_state == TRUSTEE_RELEASE ? -1 : (__ret);          \
3337 })
3338
3339 /**
3340  * trustee_wait_event - event wait for trustee
3341  * @cond: condition to wait for
3342  *
3343  * wait_event() for trustee to use.  Automatically handles locking and
3344  * checks for CANCEL request.
3345  *
3346  * CONTEXT:
3347  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3348  * multiple times.  To be used by trustee.
3349  *
3350  * RETURNS:
3351  * 0 if @cond is satisfied, -1 if canceled.
3352  */
3353 #define trustee_wait_event(cond) ({                                     \
3354         long __ret1;                                                    \
3355         __ret1 = trustee_wait_event_timeout(cond, MAX_SCHEDULE_TIMEOUT);\
3356         __ret1 < 0 ? -1 : 0;                                            \
3357 })
3358
3359 static int __cpuinit trustee_thread(void *__gcwq)
3360 {
3361         struct global_cwq *gcwq = __gcwq;
3362         struct worker *worker;
3363         struct work_struct *work;
3364         struct hlist_node *pos;
3365         long rc;
3366         int i;
3367
3368         BUG_ON(gcwq->cpu != smp_processor_id());
3369
3370         spin_lock_irq(&gcwq->lock);
3371         /*
3372          * Claim the manager position and make all workers rogue.
3373          * Trustee must be bound to the target cpu and can't be
3374          * cancelled.
3375          */
3376         BUG_ON(gcwq->cpu != smp_processor_id());
3377         rc = trustee_wait_event(!(gcwq->flags & GCWQ_MANAGING_WORKERS));
3378         BUG_ON(rc < 0);
3379
3380         gcwq->flags |= GCWQ_MANAGING_WORKERS;
3381
3382         list_for_each_entry(worker, &gcwq->idle_list, entry)
3383                 worker->flags |= WORKER_ROGUE;
3384
3385         for_each_busy_worker(worker, i, pos, gcwq)
3386                 worker->flags |= WORKER_ROGUE;
3387
3388         /*
3389          * Call schedule() so that we cross rq->lock and thus can
3390          * guarantee sched callbacks see the rogue flag.  This is
3391          * necessary as scheduler callbacks may be invoked from other
3392          * cpus.
3393          */
3394         spin_unlock_irq(&gcwq->lock);
3395         schedule();
3396         spin_lock_irq(&gcwq->lock);
3397
3398         /*
3399          * Sched callbacks are disabled now.  Zap nr_running.  After
3400          * this, nr_running stays zero and need_more_worker() and
3401          * keep_working() are always true as long as the worklist is
3402          * not empty.
3403          */
3404         atomic_set(get_gcwq_nr_running(gcwq->cpu), 0);
3405
3406         spin_unlock_irq(&gcwq->lock);
3407         del_timer_sync(&gcwq->idle_timer);
3408         spin_lock_irq(&gcwq->lock);
3409
3410         /*
3411          * We're now in charge.  Notify and proceed to drain.  We need
3412          * to keep the gcwq running during the whole CPU down
3413          * procedure as other cpu hotunplug callbacks may need to
3414          * flush currently running tasks.
3415          */
3416         gcwq->trustee_state = TRUSTEE_IN_CHARGE;
3417         wake_up_all(&gcwq->trustee_wait);
3418
3419         /*
3420          * The original cpu is in the process of dying and may go away
3421          * anytime now.  When that happens, we and all workers would
3422          * be migrated to other cpus.  Try draining any left work.  We
3423          * want to get it over with ASAP - spam rescuers, wake up as
3424          * many idlers as necessary and create new ones till the
3425          * worklist is empty.  Note that if the gcwq is frozen, there
3426          * may be frozen works in freezable cwqs.  Don't declare
3427          * completion while frozen.
3428          */
3429         while (gcwq->nr_workers != gcwq->nr_idle ||
3430                gcwq->flags & GCWQ_FREEZING ||
3431                gcwq->trustee_state == TRUSTEE_IN_CHARGE) {
3432                 int nr_works = 0;
3433
3434                 list_for_each_entry(work, &gcwq->worklist, entry) {
3435                         send_mayday(work);
3436                         nr_works++;
3437                 }
3438
3439                 list_for_each_entry(worker, &gcwq->idle_list, entry) {
3440                         if (!nr_works--)
3441                                 break;
3442                         wake_up_process(worker->task);
3443                 }
3444
3445                 if (need_to_create_worker(gcwq)) {
3446                         spin_unlock_irq(&gcwq->lock);
3447                         worker = create_worker(gcwq, false);
3448                         spin_lock_irq(&gcwq->lock);
3449                         if (worker) {
3450                                 worker->flags |= WORKER_ROGUE;
3451                                 start_worker(worker);
3452                         }
3453                 }
3454
3455                 /* give a breather */
3456                 if (trustee_wait_event_timeout(false, TRUSTEE_COOLDOWN) < 0)
3457                         break;
3458         }
3459
3460         /*
3461          * Either all works have been scheduled and cpu is down, or
3462          * cpu down has already been canceled.  Wait for and butcher
3463          * all workers till we're canceled.
3464          */
3465         do {
3466                 rc = trustee_wait_event(!list_empty(&gcwq->idle_list));
3467                 while (!list_empty(&gcwq->idle_list))
3468                         destroy_worker(list_first_entry(&gcwq->idle_list,
3469                                                         struct worker, entry));
3470         } while (gcwq->nr_workers && rc >= 0);
3471
3472         /*
3473          * At this point, either draining has completed and no worker
3474          * is left, or cpu down has been canceled or the cpu is being
3475          * brought back up.  There shouldn't be any idle one left.
3476          * Tell the remaining busy ones to rebind once it finishes the
3477          * currently scheduled works by scheduling the rebind_work.
3478          */
3479         WARN_ON(!list_empty(&gcwq->idle_list));
3480
3481         for_each_busy_worker(worker, i, pos, gcwq) {
3482                 struct work_struct *rebind_work = &worker->rebind_work;
3483                 unsigned long worker_flags = worker->flags;
3484
3485                 /*
3486                  * Rebind_work may race with future cpu hotplug
3487                  * operations.  Use a separate flag to mark that
3488                  * rebinding is scheduled.  The morphing should
3489                  * be atomic.
3490                  */
3491                 worker_flags |= WORKER_REBIND;
3492                 worker_flags &= ~WORKER_ROGUE;
3493                 ACCESS_ONCE(worker->flags) = worker_flags;
3494
3495                 /* queue rebind_work, wq doesn't matter, use the default one */
3496                 if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
3497                                      work_data_bits(rebind_work)))
3498                         continue;
3499
3500                 debug_work_activate(rebind_work);
3501                 insert_work(get_cwq(gcwq->cpu, system_wq), rebind_work,
3502                             worker->scheduled.next,
3503                             work_color_to_flags(WORK_NO_COLOR));
3504         }
3505
3506         /* relinquish manager role */
3507         gcwq->flags &= ~GCWQ_MANAGING_WORKERS;
3508
3509         /* notify completion */
3510         gcwq->trustee = NULL;
3511         gcwq->trustee_state = TRUSTEE_DONE;
3512         wake_up_all(&gcwq->trustee_wait);
3513         spin_unlock_irq(&gcwq->lock);
3514         return 0;
3515 }
3516
3517 /**
3518  * wait_trustee_state - wait for trustee to enter the specified state
3519  * @gcwq: gcwq the trustee of interest belongs to
3520  * @state: target state to wait for
3521  *
3522  * Wait for the trustee to reach @state.  DONE is already matched.
3523  *
3524  * CONTEXT:
3525  * spin_lock_irq(gcwq->lock) which may be released and regrabbed
3526  * multiple times.  To be used by cpu_callback.
3527  */
3528 static void __cpuinit wait_trustee_state(struct global_cwq *gcwq, int state)
3529 __releases(&gcwq->lock)
3530 __acquires(&gcwq->lock)
3531 {
3532         if (!(gcwq->trustee_state == state ||
3533               gcwq->trustee_state == TRUSTEE_DONE)) {
3534                 spin_unlock_irq(&gcwq->lock);
3535                 __wait_event(gcwq->trustee_wait,
3536                              gcwq->trustee_state == state ||
3537                              gcwq->trustee_state == TRUSTEE_DONE);
3538                 spin_lock_irq(&gcwq->lock);
3539         }
3540 }
3541
3542 static int __devinit workqueue_cpu_callback(struct notifier_block *nfb,
3543                                                 unsigned long action,
3544                                                 void *hcpu)
3545 {
3546         unsigned int cpu = (unsigned long)hcpu;
3547         struct global_cwq *gcwq = get_gcwq(cpu);
3548         struct task_struct *new_trustee = NULL;
3549         struct worker *uninitialized_var(new_worker);
3550         unsigned long flags;
3551
3552         action &= ~CPU_TASKS_FROZEN;
3553
3554         switch (action) {
3555         case CPU_DOWN_PREPARE:
3556                 new_trustee = kthread_create(trustee_thread, gcwq,
3557                                              "workqueue_trustee/%d\n", cpu);
3558                 if (IS_ERR(new_trustee))
3559                         return notifier_from_errno(PTR_ERR(new_trustee));
3560                 kthread_bind(new_trustee, cpu);
3561                 /* fall through */
3562         case CPU_UP_PREPARE:
3563                 BUG_ON(gcwq->first_idle);
3564                 new_worker = create_worker(gcwq, false);
3565                 if (!new_worker) {
3566                         if (new_trustee)
3567                                 kthread_stop(new_trustee);
3568                         return NOTIFY_BAD;
3569                 }
3570         }
3571
3572         /* some are called w/ irq disabled, don't disturb irq status */
3573         spin_lock_irqsave(&gcwq->lock, flags);
3574
3575         switch (action) {
3576         case CPU_DOWN_PREPARE:
3577                 /* initialize trustee and tell it to acquire the gcwq */
3578                 BUG_ON(gcwq->trustee || gcwq->trustee_state != TRUSTEE_DONE);
3579                 gcwq->trustee = new_trustee;
3580                 gcwq->trustee_state = TRUSTEE_START;
3581                 wake_up_process(gcwq->trustee);
3582                 wait_trustee_state(gcwq, TRUSTEE_IN_CHARGE);
3583                 /* fall through */
3584         case CPU_UP_PREPARE:
3585                 BUG_ON(gcwq->first_idle);
3586                 gcwq->first_idle = new_worker;
3587                 break;
3588
3589         case CPU_DYING:
3590                 /*
3591                  * Before this, the trustee and all workers except for
3592                  * the ones which are still executing works from
3593                  * before the last CPU down must be on the cpu.  After
3594                  * this, they'll all be diasporas.
3595                  */
3596                 gcwq->flags |= GCWQ_DISASSOCIATED;
3597                 break;
3598
3599         case CPU_POST_DEAD:
3600                 gcwq->trustee_state = TRUSTEE_BUTCHER;
3601                 /* fall through */
3602         case CPU_UP_CANCELED:
3603                 destroy_worker(gcwq->first_idle);
3604                 gcwq->first_idle = NULL;
3605                 break;
3606
3607         case CPU_DOWN_FAILED:
3608         case CPU_ONLINE:
3609                 gcwq->flags &= ~GCWQ_DISASSOCIATED;
3610                 if (gcwq->trustee_state != TRUSTEE_DONE) {
3611                         gcwq->trustee_state = TRUSTEE_RELEASE;
3612                         wake_up_process(gcwq->trustee);
3613                         wait_trustee_state(gcwq, TRUSTEE_DONE);
3614                 }
3615
3616                 /*
3617                  * Trustee is done and there might be no worker left.
3618                  * Put the first_idle in and request a real manager to
3619                  * take a look.
3620                  */
3621                 spin_unlock_irq(&gcwq->lock);
3622                 kthread_bind(gcwq->first_idle->task, cpu);
3623                 spin_lock_irq(&gcwq->lock);
3624                 gcwq->flags |= GCWQ_MANAGE_WORKERS;
3625                 start_worker(gcwq->first_idle);
3626                 gcwq->first_idle = NULL;
3627                 break;
3628         }
3629
3630         spin_unlock_irqrestore(&gcwq->lock, flags);
3631
3632         return notifier_from_errno(0);
3633 }
3634
3635 /*
3636  * Workqueues should be brought up before normal priority CPU notifiers.
3637  * This will be registered high priority CPU notifier.
3638  */
3639 static int __devinit workqueue_cpu_up_callback(struct notifier_block *nfb,
3640                                                unsigned long action,
3641                                                void *hcpu)
3642 {
3643         switch (action & ~CPU_TASKS_FROZEN) {
3644         case CPU_UP_PREPARE:
3645         case CPU_UP_CANCELED:
3646         case CPU_DOWN_FAILED:
3647         case CPU_ONLINE:
3648                 return workqueue_cpu_callback(nfb, action, hcpu);
3649         }
3650         return NOTIFY_OK;
3651 }
3652
3653 /*
3654  * Workqueues should be brought down after normal priority CPU notifiers.
3655  * This will be registered as low priority CPU notifier.
3656  */
3657 static int __devinit workqueue_cpu_down_callback(struct notifier_block *nfb,
3658                                                  unsigned long action,
3659                                                  void *hcpu)
3660 {
3661         switch (action & ~CPU_TASKS_FROZEN) {
3662         case CPU_DOWN_PREPARE:
3663         case CPU_DYING:
3664         case CPU_POST_DEAD:
3665                 return workqueue_cpu_callback(nfb, action, hcpu);
3666         }
3667         return NOTIFY_OK;
3668 }
3669
3670 #ifdef CONFIG_SMP
3671
3672 struct work_for_cpu {
3673         struct work_struct work;
3674         long (*fn)(void *);
3675         void *arg;
3676         long ret;
3677 };
3678
3679 static void work_for_cpu_fn(struct work_struct *work)
3680 {
3681         struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
3682
3683         wfc->ret = wfc->fn(wfc->arg);
3684 }
3685
3686 /**
3687  * work_on_cpu - run a function in user context on a particular cpu
3688  * @cpu: the cpu to run on
3689  * @fn: the function to run
3690  * @arg: the function arg
3691  *
3692  * This will return the value @fn returns.
3693  * It is up to the caller to ensure that the cpu doesn't go offline.
3694  * The caller must not hold any locks which would prevent @fn from completing.
3695  */
3696 long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
3697 {
3698         struct work_for_cpu wfc = { .fn = fn, .arg = arg };
3699
3700         INIT_WORK_ONSTACK(&wfc.work, work_for_cpu_fn);
3701         schedule_work_on(cpu, &wfc.work);
3702         flush_work(&wfc.work);
3703         return wfc.ret;
3704 }
3705 EXPORT_SYMBOL_GPL(work_on_cpu);
3706 #endif /* CONFIG_SMP */
3707
3708 #ifdef CONFIG_FREEZER
3709
3710 /**
3711  * freeze_workqueues_begin - begin freezing workqueues
3712  *
3713  * Start freezing workqueues.  After this function returns, all freezable
3714  * workqueues will queue new works to their frozen_works list instead of
3715  * gcwq->worklist.
3716  *
3717  * CONTEXT:
3718  * Grabs and releases workqueue_lock and gcwq->lock's.
3719  */
3720 void freeze_workqueues_begin(void)
3721 {
3722         unsigned int cpu;
3723
3724         spin_lock(&workqueue_lock);
3725
3726         BUG_ON(workqueue_freezing);
3727         workqueue_freezing = true;
3728
3729         for_each_gcwq_cpu(cpu) {
3730                 struct global_cwq *gcwq = get_gcwq(cpu);
3731                 struct workqueue_struct *wq;
3732
3733                 spin_lock_irq(&gcwq->lock);
3734
3735                 BUG_ON(gcwq->flags & GCWQ_FREEZING);
3736                 gcwq->flags |= GCWQ_FREEZING;
3737
3738                 list_for_each_entry(wq, &workqueues, list) {
3739                         struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3740
3741                         if (cwq && wq->flags & WQ_FREEZABLE)
3742                                 cwq->max_active = 0;
3743                 }
3744
3745                 spin_unlock_irq(&gcwq->lock);
3746         }
3747
3748         spin_unlock(&workqueue_lock);
3749 }
3750
3751 /**
3752  * freeze_workqueues_busy - are freezable workqueues still busy?
3753  *
3754  * Check whether freezing is complete.  This function must be called
3755  * between freeze_workqueues_begin() and thaw_workqueues().
3756  *
3757  * CONTEXT:
3758  * Grabs and releases workqueue_lock.
3759  *
3760  * RETURNS:
3761  * %true if some freezable workqueues are still busy.  %false if freezing
3762  * is complete.
3763  */
3764 bool freeze_workqueues_busy(void)
3765 {
3766         unsigned int cpu;
3767         bool busy = false;
3768
3769         spin_lock(&workqueue_lock);
3770
3771         BUG_ON(!workqueue_freezing);
3772
3773         for_each_gcwq_cpu(cpu) {
3774                 struct workqueue_struct *wq;
3775                 /*
3776                  * nr_active is monotonically decreasing.  It's safe
3777                  * to peek without lock.
3778                  */
3779                 list_for_each_entry(wq, &workqueues, list) {
3780                         struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3781
3782                         if (!cwq || !(wq->flags & WQ_FREEZABLE))
3783                                 continue;
3784
3785                         BUG_ON(cwq->nr_active < 0);
3786                         if (cwq->nr_active) {
3787                                 busy = true;
3788                                 goto out_unlock;
3789                         }
3790                 }
3791         }
3792 out_unlock:
3793         spin_unlock(&workqueue_lock);
3794         return busy;
3795 }
3796
3797 /**
3798  * thaw_workqueues - thaw workqueues
3799  *
3800  * Thaw workqueues.  Normal queueing is restored and all collected
3801  * frozen works are transferred to their respective gcwq worklists.
3802  *
3803  * CONTEXT:
3804  * Grabs and releases workqueue_lock and gcwq->lock's.
3805  */
3806 void thaw_workqueues(void)
3807 {
3808         unsigned int cpu;
3809
3810         spin_lock(&workqueue_lock);
3811
3812         if (!workqueue_freezing)
3813                 goto out_unlock;
3814
3815         for_each_gcwq_cpu(cpu) {
3816                 struct global_cwq *gcwq = get_gcwq(cpu);
3817                 struct workqueue_struct *wq;
3818
3819                 spin_lock_irq(&gcwq->lock);
3820
3821                 BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
3822                 gcwq->flags &= ~GCWQ_FREEZING;
3823
3824                 list_for_each_entry(wq, &workqueues, list) {
3825                         struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
3826
3827                         if (!cwq || !(wq->flags & WQ_FREEZABLE))
3828                                 continue;
3829
3830                         /* restore max_active and repopulate worklist */
3831                         cwq->max_active = wq->saved_max_active;
3832
3833                         while (!list_empty(&cwq->delayed_works) &&
3834                                cwq->nr_active < cwq->max_active)
3835                                 cwq_activate_first_delayed(cwq);
3836                 }
3837
3838                 wake_up_worker(gcwq);
3839
3840                 spin_unlock_irq(&gcwq->lock);
3841         }
3842
3843         workqueue_freezing = false;
3844 out_unlock:
3845         spin_unlock(&workqueue_lock);
3846 }
3847 #endif /* CONFIG_FREEZER */
3848
3849 static int __init init_workqueues(void)
3850 {
3851         unsigned int cpu;
3852         int i;
3853
3854         cpu_notifier(workqueue_cpu_up_callback, CPU_PRI_WORKQUEUE_UP);
3855         cpu_notifier(workqueue_cpu_down_callback, CPU_PRI_WORKQUEUE_DOWN);
3856
3857         /* initialize gcwqs */
3858         for_each_gcwq_cpu(cpu) {
3859                 struct global_cwq *gcwq = get_gcwq(cpu);
3860
3861                 spin_lock_init(&gcwq->lock);
3862                 INIT_LIST_HEAD(&gcwq->worklist);
3863                 gcwq->cpu = cpu;
3864                 gcwq->flags |= GCWQ_DISASSOCIATED;
3865
3866                 INIT_LIST_HEAD(&gcwq->idle_list);
3867                 for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
3868                         INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
3869
3870                 init_timer_deferrable(&gcwq->idle_timer);
3871                 gcwq->idle_timer.function = idle_worker_timeout;
3872                 gcwq->idle_timer.data = (unsigned long)gcwq;
3873
3874                 setup_timer(&gcwq->mayday_timer, gcwq_mayday_timeout,
3875                             (unsigned long)gcwq);
3876
3877                 ida_init(&gcwq->worker_ida);
3878
3879                 gcwq->trustee_state = TRUSTEE_DONE;
3880                 init_waitqueue_head(&gcwq->trustee_wait);
3881         }
3882
3883         /* create the initial worker */
3884         for_each_online_gcwq_cpu(cpu) {
3885                 struct global_cwq *gcwq = get_gcwq(cpu);
3886                 struct worker *worker;
3887
3888                 if (cpu != WORK_CPU_UNBOUND)
3889                         gcwq->flags &= ~GCWQ_DISASSOCIATED;
3890                 worker = create_worker(gcwq, true);
3891                 BUG_ON(!worker);
3892                 spin_lock_irq(&gcwq->lock);
3893                 start_worker(worker);
3894                 spin_unlock_irq(&gcwq->lock);
3895         }
3896
3897         system_wq = alloc_workqueue("events", 0, 0);
3898         system_long_wq = alloc_workqueue("events_long", 0, 0);
3899         system_nrt_wq = alloc_workqueue("events_nrt", WQ_NON_REENTRANT, 0);
3900         system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
3901                                             WQ_UNBOUND_MAX_ACTIVE);
3902         system_freezable_wq = alloc_workqueue("events_freezable",
3903                                               WQ_FREEZABLE, 0);
3904         system_nrt_freezable_wq = alloc_workqueue("events_nrt_freezable",
3905                         WQ_NON_REENTRANT | WQ_FREEZABLE, 0);
3906         BUG_ON(!system_wq || !system_long_wq || !system_nrt_wq ||
3907                !system_unbound_wq || !system_freezable_wq ||
3908                 !system_nrt_freezable_wq);
3909         return 0;
3910 }
3911 early_initcall(init_workqueues);