OSDN Git Service

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