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