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