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