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