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