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