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