OSDN Git Service

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