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