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