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