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