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