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