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