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