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