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