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