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