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