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