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