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