2 * kernel/workqueue.c - generic async execution with shared worker pool
4 * Copyright (C) 2002 Ingo Molnar
6 * Derived from the taskqueue/keventd code by:
7 * David Woodhouse <dwmw2@infradead.org>
9 * Kai Petzke <wpp@marie.physik.tu-berlin.de>
10 * Theodore Ts'o <tytso@mit.edu>
12 * Made to use alloc_percpu by Christoph Lameter.
14 * Copyright (C) 2010 SUSE Linux Products GmbH
15 * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
17 * This is the generic async execution mechanism. Work items as are
18 * executed in process context. The worker pool is shared and
19 * automatically managed. There are two worker pools for each CPU (one for
20 * normal work items and the other for high priority ones) and some extra
21 * pools for workqueues which are not bound to any specific CPU - the
22 * number of these backing pools is dynamic.
24 * Please read Documentation/workqueue.txt for details.
27 #include <linux/export.h>
28 #include <linux/kernel.h>
29 #include <linux/sched.h>
30 #include <linux/init.h>
31 #include <linux/signal.h>
32 #include <linux/completion.h>
33 #include <linux/workqueue.h>
34 #include <linux/slab.h>
35 #include <linux/cpu.h>
36 #include <linux/notifier.h>
37 #include <linux/kthread.h>
38 #include <linux/hardirq.h>
39 #include <linux/mempolicy.h>
40 #include <linux/freezer.h>
41 #include <linux/kallsyms.h>
42 #include <linux/debug_locks.h>
43 #include <linux/lockdep.h>
44 #include <linux/idr.h>
45 #include <linux/jhash.h>
46 #include <linux/hashtable.h>
47 #include <linux/rculist.h>
48 #include <linux/nodemask.h>
49 #include <linux/moduleparam.h>
50 #include <linux/uaccess.h>
52 #include "workqueue_internal.h"
58 * A bound pool is either associated or disassociated with its CPU.
59 * While associated (!DISASSOCIATED), all workers are bound to the
60 * CPU and none has %WORKER_UNBOUND set and concurrency management
63 * While DISASSOCIATED, the cpu may be offline and all workers have
64 * %WORKER_UNBOUND set and concurrency management disabled, and may
65 * be executing on any CPU. The pool behaves as an unbound one.
67 * Note that DISASSOCIATED should be flipped only while holding
68 * attach_mutex to avoid changing binding state while
69 * worker_attach_to_pool() is in progress.
71 POOL_DISASSOCIATED
= 1 << 2, /* cpu can't serve workers */
74 WORKER_DIE
= 1 << 1, /* die die die */
75 WORKER_IDLE
= 1 << 2, /* is idle */
76 WORKER_PREP
= 1 << 3, /* preparing to run works */
77 WORKER_CPU_INTENSIVE
= 1 << 6, /* cpu intensive */
78 WORKER_UNBOUND
= 1 << 7, /* worker is unbound */
79 WORKER_REBOUND
= 1 << 8, /* worker was rebound */
81 WORKER_NOT_RUNNING
= WORKER_PREP
| WORKER_CPU_INTENSIVE
|
82 WORKER_UNBOUND
| WORKER_REBOUND
,
84 NR_STD_WORKER_POOLS
= 2, /* # standard pools per cpu */
86 UNBOUND_POOL_HASH_ORDER
= 6, /* hashed by pool->attrs */
87 BUSY_WORKER_HASH_ORDER
= 6, /* 64 pointers */
89 MAX_IDLE_WORKERS_RATIO
= 4, /* 1/4 of busy can be idle */
90 IDLE_WORKER_TIMEOUT
= 300 * HZ
, /* keep idle ones for 5 mins */
92 MAYDAY_INITIAL_TIMEOUT
= HZ
/ 100 >= 2 ? HZ
/ 100 : 2,
93 /* call for help after 10ms
95 MAYDAY_INTERVAL
= HZ
/ 10, /* and then every 100ms */
96 CREATE_COOLDOWN
= HZ
, /* time to breath after fail */
99 * Rescue workers are used only on emergencies and shared by
100 * all cpus. Give MIN_NICE.
102 RESCUER_NICE_LEVEL
= MIN_NICE
,
103 HIGHPRI_NICE_LEVEL
= MIN_NICE
,
109 * Structure fields follow one of the following exclusion rules.
111 * I: Modifiable by initialization/destruction paths and read-only for
114 * P: Preemption protected. Disabling preemption is enough and should
115 * only be modified and accessed from the local cpu.
117 * L: pool->lock protected. Access with pool->lock held.
119 * X: During normal operation, modification requires pool->lock and should
120 * be done only from local cpu. Either disabling preemption on local
121 * cpu or grabbing pool->lock is enough for read access. If
122 * POOL_DISASSOCIATED is set, it's identical to L.
124 * A: pool->attach_mutex protected.
126 * PL: wq_pool_mutex protected.
128 * PR: wq_pool_mutex protected for writes. Sched-RCU protected for reads.
130 * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
132 * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
133 * sched-RCU for reads.
135 * WQ: wq->mutex protected.
137 * WR: wq->mutex protected for writes. Sched-RCU protected for reads.
139 * MD: wq_mayday_lock protected.
142 /* struct worker is defined in workqueue_internal.h */
145 spinlock_t lock
; /* the pool lock */
146 int cpu
; /* I: the associated cpu */
147 int node
; /* I: the associated node ID */
148 int id
; /* I: pool ID */
149 unsigned int flags
; /* X: flags */
151 struct list_head worklist
; /* L: list of pending works */
152 int nr_workers
; /* L: total number of workers */
154 /* nr_idle includes the ones off idle_list for rebinding */
155 int nr_idle
; /* L: currently idle ones */
157 struct list_head idle_list
; /* X: list of idle workers */
158 struct timer_list idle_timer
; /* L: worker idle timeout */
159 struct timer_list mayday_timer
; /* L: SOS timer for workers */
161 /* a workers is either on busy_hash or idle_list, or the manager */
162 DECLARE_HASHTABLE(busy_hash
, BUSY_WORKER_HASH_ORDER
);
163 /* L: hash of busy workers */
165 /* see manage_workers() for details on the two manager mutexes */
166 struct mutex manager_arb
; /* manager arbitration */
167 struct worker
*manager
; /* L: purely informational */
168 struct mutex attach_mutex
; /* attach/detach exclusion */
169 struct list_head workers
; /* A: attached workers */
170 struct completion
*detach_completion
; /* all workers detached */
172 struct ida worker_ida
; /* worker IDs for task name */
174 struct workqueue_attrs
*attrs
; /* I: worker attributes */
175 struct hlist_node hash_node
; /* PL: unbound_pool_hash node */
176 int refcnt
; /* PL: refcnt for unbound pools */
179 * The current concurrency level. As it's likely to be accessed
180 * from other CPUs during try_to_wake_up(), put it in a separate
183 atomic_t nr_running ____cacheline_aligned_in_smp
;
186 * Destruction of pool is sched-RCU protected to allow dereferences
187 * from get_work_pool().
190 } ____cacheline_aligned_in_smp
;
193 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
194 * of work_struct->data are used for flags and the remaining high bits
195 * point to the pwq; thus, pwqs need to be aligned at two's power of the
196 * number of flag bits.
198 struct pool_workqueue
{
199 struct worker_pool
*pool
; /* I: the associated pool */
200 struct workqueue_struct
*wq
; /* I: the owning workqueue */
201 int work_color
; /* L: current color */
202 int flush_color
; /* L: flushing color */
203 int refcnt
; /* L: reference count */
204 int nr_in_flight
[WORK_NR_COLORS
];
205 /* L: nr of in_flight works */
206 int nr_active
; /* L: nr of active works */
207 int max_active
; /* L: max active works */
208 struct list_head delayed_works
; /* L: delayed works */
209 struct list_head pwqs_node
; /* WR: node on wq->pwqs */
210 struct list_head mayday_node
; /* MD: node on wq->maydays */
213 * Release of unbound pwq is punted to system_wq. See put_pwq()
214 * and pwq_unbound_release_workfn() for details. pool_workqueue
215 * itself is also sched-RCU protected so that the first pwq can be
216 * determined without grabbing wq->mutex.
218 struct work_struct unbound_release_work
;
220 } __aligned(1 << WORK_STRUCT_FLAG_BITS
);
223 * Structure used to wait for workqueue flush.
226 struct list_head list
; /* WQ: list of flushers */
227 int flush_color
; /* WQ: flush color waiting for */
228 struct completion done
; /* flush completion */
234 * The externally visible workqueue. It relays the issued work items to
235 * the appropriate worker_pool through its pool_workqueues.
237 struct workqueue_struct
{
238 struct list_head pwqs
; /* WR: all pwqs of this wq */
239 struct list_head list
; /* PR: list of all workqueues */
241 struct mutex mutex
; /* protects this wq */
242 int work_color
; /* WQ: current work color */
243 int flush_color
; /* WQ: current flush color */
244 atomic_t nr_pwqs_to_flush
; /* flush in progress */
245 struct wq_flusher
*first_flusher
; /* WQ: first flusher */
246 struct list_head flusher_queue
; /* WQ: flush waiters */
247 struct list_head flusher_overflow
; /* WQ: flush overflow list */
249 struct list_head maydays
; /* MD: pwqs requesting rescue */
250 struct worker
*rescuer
; /* I: rescue worker */
252 int nr_drainers
; /* WQ: drain in progress */
253 int saved_max_active
; /* WQ: saved pwq max_active */
255 struct workqueue_attrs
*unbound_attrs
; /* PW: only for unbound wqs */
256 struct pool_workqueue
*dfl_pwq
; /* PW: only for unbound wqs */
259 struct wq_device
*wq_dev
; /* I: for sysfs interface */
261 #ifdef CONFIG_LOCKDEP
262 struct lockdep_map lockdep_map
;
264 char name
[WQ_NAME_LEN
]; /* I: workqueue name */
267 * Destruction of workqueue_struct is sched-RCU protected to allow
268 * walking the workqueues list without grabbing wq_pool_mutex.
269 * This is used to dump all workqueues from sysrq.
273 /* hot fields used during command issue, aligned to cacheline */
274 unsigned int flags ____cacheline_aligned
; /* WQ: WQ_* flags */
275 struct pool_workqueue __percpu
*cpu_pwqs
; /* I: per-cpu pwqs */
276 struct pool_workqueue __rcu
*numa_pwq_tbl
[]; /* PWR: unbound pwqs indexed by node */
279 static struct kmem_cache
*pwq_cache
;
281 static cpumask_var_t
*wq_numa_possible_cpumask
;
282 /* possible CPUs of each node */
284 static bool wq_disable_numa
;
285 module_param_named(disable_numa
, wq_disable_numa
, bool, 0444);
287 /* see the comment above the definition of WQ_POWER_EFFICIENT */
288 static bool wq_power_efficient
= IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT
);
289 module_param_named(power_efficient
, wq_power_efficient
, bool, 0444);
291 static bool wq_numa_enabled
; /* unbound NUMA affinity enabled */
293 /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
294 static struct workqueue_attrs
*wq_update_unbound_numa_attrs_buf
;
296 static DEFINE_MUTEX(wq_pool_mutex
); /* protects pools and workqueues list */
297 static DEFINE_SPINLOCK(wq_mayday_lock
); /* protects wq->maydays list */
299 static LIST_HEAD(workqueues
); /* PR: list of all workqueues */
300 static bool workqueue_freezing
; /* PL: have wqs started freezing? */
302 static cpumask_var_t wq_unbound_cpumask
; /* PL: low level cpumask for all unbound wqs */
304 /* the per-cpu worker pools */
305 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool
[NR_STD_WORKER_POOLS
],
308 static DEFINE_IDR(worker_pool_idr
); /* PR: idr of all pools */
310 /* PL: hash of all unbound pools keyed by pool->attrs */
311 static DEFINE_HASHTABLE(unbound_pool_hash
, UNBOUND_POOL_HASH_ORDER
);
313 /* I: attributes used when instantiating standard unbound pools on demand */
314 static struct workqueue_attrs
*unbound_std_wq_attrs
[NR_STD_WORKER_POOLS
];
316 /* I: attributes used when instantiating ordered pools on demand */
317 static struct workqueue_attrs
*ordered_wq_attrs
[NR_STD_WORKER_POOLS
];
319 struct workqueue_struct
*system_wq __read_mostly
;
320 EXPORT_SYMBOL(system_wq
);
321 struct workqueue_struct
*system_highpri_wq __read_mostly
;
322 EXPORT_SYMBOL_GPL(system_highpri_wq
);
323 struct workqueue_struct
*system_long_wq __read_mostly
;
324 EXPORT_SYMBOL_GPL(system_long_wq
);
325 struct workqueue_struct
*system_unbound_wq __read_mostly
;
326 EXPORT_SYMBOL_GPL(system_unbound_wq
);
327 struct workqueue_struct
*system_freezable_wq __read_mostly
;
328 EXPORT_SYMBOL_GPL(system_freezable_wq
);
329 struct workqueue_struct
*system_power_efficient_wq __read_mostly
;
330 EXPORT_SYMBOL_GPL(system_power_efficient_wq
);
331 struct workqueue_struct
*system_freezable_power_efficient_wq __read_mostly
;
332 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq
);
334 static int worker_thread(void *__worker
);
335 static void workqueue_sysfs_unregister(struct workqueue_struct
*wq
);
337 #define CREATE_TRACE_POINTS
338 #include <trace/events/workqueue.h>
340 #define assert_rcu_or_pool_mutex() \
341 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() && \
342 !lockdep_is_held(&wq_pool_mutex), \
343 "sched RCU or wq_pool_mutex should be held")
345 #define assert_rcu_or_wq_mutex(wq) \
346 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() && \
347 !lockdep_is_held(&wq->mutex), \
348 "sched RCU or wq->mutex should be held")
350 #define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \
351 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() && \
352 !lockdep_is_held(&wq->mutex) && \
353 !lockdep_is_held(&wq_pool_mutex), \
354 "sched RCU, wq->mutex or wq_pool_mutex should be held")
356 #define for_each_cpu_worker_pool(pool, cpu) \
357 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
358 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
362 * for_each_pool - iterate through all worker_pools in the system
363 * @pool: iteration cursor
364 * @pi: integer used for iteration
366 * This must be called either with wq_pool_mutex held or sched RCU read
367 * locked. If the pool needs to be used beyond the locking in effect, the
368 * caller is responsible for guaranteeing that the pool stays online.
370 * The if/else clause exists only for the lockdep assertion and can be
373 #define for_each_pool(pool, pi) \
374 idr_for_each_entry(&worker_pool_idr, pool, pi) \
375 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
379 * for_each_pool_worker - iterate through all workers of a worker_pool
380 * @worker: iteration cursor
381 * @pool: worker_pool to iterate workers of
383 * This must be called with @pool->attach_mutex.
385 * The if/else clause exists only for the lockdep assertion and can be
388 #define for_each_pool_worker(worker, pool) \
389 list_for_each_entry((worker), &(pool)->workers, node) \
390 if (({ lockdep_assert_held(&pool->attach_mutex); false; })) { } \
394 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
395 * @pwq: iteration cursor
396 * @wq: the target workqueue
398 * This must be called either with wq->mutex held or sched RCU read locked.
399 * If the pwq needs to be used beyond the locking in effect, the caller is
400 * responsible for guaranteeing that the pwq stays online.
402 * The if/else clause exists only for the lockdep assertion and can be
405 #define for_each_pwq(pwq, wq) \
406 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
407 if (({ assert_rcu_or_wq_mutex(wq); false; })) { } \
410 #ifdef CONFIG_DEBUG_OBJECTS_WORK
412 static struct debug_obj_descr work_debug_descr
;
414 static void *work_debug_hint(void *addr
)
416 return ((struct work_struct
*) addr
)->func
;
420 * fixup_init is called when:
421 * - an active object is initialized
423 static int work_fixup_init(void *addr
, enum debug_obj_state state
)
425 struct work_struct
*work
= addr
;
428 case ODEBUG_STATE_ACTIVE
:
429 cancel_work_sync(work
);
430 debug_object_init(work
, &work_debug_descr
);
438 * fixup_activate is called when:
439 * - an active object is activated
440 * - an unknown object is activated (might be a statically initialized object)
442 static int work_fixup_activate(void *addr
, enum debug_obj_state state
)
444 struct work_struct
*work
= addr
;
448 case ODEBUG_STATE_NOTAVAILABLE
:
450 * This is not really a fixup. The work struct was
451 * statically initialized. We just make sure that it
452 * is tracked in the object tracker.
454 if (test_bit(WORK_STRUCT_STATIC_BIT
, work_data_bits(work
))) {
455 debug_object_init(work
, &work_debug_descr
);
456 debug_object_activate(work
, &work_debug_descr
);
462 case ODEBUG_STATE_ACTIVE
:
471 * fixup_free is called when:
472 * - an active object is freed
474 static int work_fixup_free(void *addr
, enum debug_obj_state state
)
476 struct work_struct
*work
= addr
;
479 case ODEBUG_STATE_ACTIVE
:
480 cancel_work_sync(work
);
481 debug_object_free(work
, &work_debug_descr
);
488 static struct debug_obj_descr work_debug_descr
= {
489 .name
= "work_struct",
490 .debug_hint
= work_debug_hint
,
491 .fixup_init
= work_fixup_init
,
492 .fixup_activate
= work_fixup_activate
,
493 .fixup_free
= work_fixup_free
,
496 static inline void debug_work_activate(struct work_struct
*work
)
498 debug_object_activate(work
, &work_debug_descr
);
501 static inline void debug_work_deactivate(struct work_struct
*work
)
503 debug_object_deactivate(work
, &work_debug_descr
);
506 void __init_work(struct work_struct
*work
, int onstack
)
509 debug_object_init_on_stack(work
, &work_debug_descr
);
511 debug_object_init(work
, &work_debug_descr
);
513 EXPORT_SYMBOL_GPL(__init_work
);
515 void destroy_work_on_stack(struct work_struct
*work
)
517 debug_object_free(work
, &work_debug_descr
);
519 EXPORT_SYMBOL_GPL(destroy_work_on_stack
);
521 void destroy_delayed_work_on_stack(struct delayed_work
*work
)
523 destroy_timer_on_stack(&work
->timer
);
524 debug_object_free(&work
->work
, &work_debug_descr
);
526 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack
);
529 static inline void debug_work_activate(struct work_struct
*work
) { }
530 static inline void debug_work_deactivate(struct work_struct
*work
) { }
534 * worker_pool_assign_id - allocate ID and assing it to @pool
535 * @pool: the pool pointer of interest
537 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
538 * successfully, -errno on failure.
540 static int worker_pool_assign_id(struct worker_pool
*pool
)
544 lockdep_assert_held(&wq_pool_mutex
);
546 ret
= idr_alloc(&worker_pool_idr
, pool
, 0, WORK_OFFQ_POOL_NONE
,
556 * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
557 * @wq: the target workqueue
560 * This must be called with any of wq_pool_mutex, wq->mutex or sched RCU
562 * If the pwq needs to be used beyond the locking in effect, the caller is
563 * responsible for guaranteeing that the pwq stays online.
565 * Return: The unbound pool_workqueue for @node.
567 static struct pool_workqueue
*unbound_pwq_by_node(struct workqueue_struct
*wq
,
570 assert_rcu_or_wq_mutex_or_pool_mutex(wq
);
573 * XXX: @node can be NUMA_NO_NODE if CPU goes offline while a
574 * delayed item is pending. The plan is to keep CPU -> NODE
575 * mapping valid and stable across CPU on/offlines. Once that
576 * happens, this workaround can be removed.
578 if (unlikely(node
== NUMA_NO_NODE
))
581 return rcu_dereference_raw(wq
->numa_pwq_tbl
[node
]);
584 static unsigned int work_color_to_flags(int color
)
586 return color
<< WORK_STRUCT_COLOR_SHIFT
;
589 static int get_work_color(struct work_struct
*work
)
591 return (*work_data_bits(work
) >> WORK_STRUCT_COLOR_SHIFT
) &
592 ((1 << WORK_STRUCT_COLOR_BITS
) - 1);
595 static int work_next_color(int color
)
597 return (color
+ 1) % WORK_NR_COLORS
;
601 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
602 * contain the pointer to the queued pwq. Once execution starts, the flag
603 * is cleared and the high bits contain OFFQ flags and pool ID.
605 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
606 * and clear_work_data() can be used to set the pwq, pool or clear
607 * work->data. These functions should only be called while the work is
608 * owned - ie. while the PENDING bit is set.
610 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
611 * corresponding to a work. Pool is available once the work has been
612 * queued anywhere after initialization until it is sync canceled. pwq is
613 * available only while the work item is queued.
615 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
616 * canceled. While being canceled, a work item may have its PENDING set
617 * but stay off timer and worklist for arbitrarily long and nobody should
618 * try to steal the PENDING bit.
620 static inline void set_work_data(struct work_struct
*work
, unsigned long data
,
623 WARN_ON_ONCE(!work_pending(work
));
624 atomic_long_set(&work
->data
, data
| flags
| work_static(work
));
627 static void set_work_pwq(struct work_struct
*work
, struct pool_workqueue
*pwq
,
628 unsigned long extra_flags
)
630 set_work_data(work
, (unsigned long)pwq
,
631 WORK_STRUCT_PENDING
| WORK_STRUCT_PWQ
| extra_flags
);
634 static void set_work_pool_and_keep_pending(struct work_struct
*work
,
637 set_work_data(work
, (unsigned long)pool_id
<< WORK_OFFQ_POOL_SHIFT
,
638 WORK_STRUCT_PENDING
);
641 static void set_work_pool_and_clear_pending(struct work_struct
*work
,
645 * The following wmb is paired with the implied mb in
646 * test_and_set_bit(PENDING) and ensures all updates to @work made
647 * here are visible to and precede any updates by the next PENDING
651 set_work_data(work
, (unsigned long)pool_id
<< WORK_OFFQ_POOL_SHIFT
, 0);
653 * The following mb guarantees that previous clear of a PENDING bit
654 * will not be reordered with any speculative LOADS or STORES from
655 * work->current_func, which is executed afterwards. This possible
656 * reordering can lead to a missed execution on attempt to qeueue
657 * the same @work. E.g. consider this case:
660 * ---------------------------- --------------------------------
662 * 1 STORE event_indicated
663 * 2 queue_work_on() {
664 * 3 test_and_set_bit(PENDING)
665 * 4 } set_..._and_clear_pending() {
666 * 5 set_work_data() # clear bit
668 * 7 work->current_func() {
669 * 8 LOAD event_indicated
672 * Without an explicit full barrier speculative LOAD on line 8 can
673 * be executed before CPU#0 does STORE on line 1. If that happens,
674 * CPU#0 observes the PENDING bit is still set and new execution of
675 * a @work is not queued in a hope, that CPU#1 will eventually
676 * finish the queued @work. Meanwhile CPU#1 does not see
677 * event_indicated is set, because speculative LOAD was executed
678 * before actual STORE.
683 static void clear_work_data(struct work_struct
*work
)
685 smp_wmb(); /* see set_work_pool_and_clear_pending() */
686 set_work_data(work
, WORK_STRUCT_NO_POOL
, 0);
689 static struct pool_workqueue
*get_work_pwq(struct work_struct
*work
)
691 unsigned long data
= atomic_long_read(&work
->data
);
693 if (data
& WORK_STRUCT_PWQ
)
694 return (void *)(data
& WORK_STRUCT_WQ_DATA_MASK
);
700 * get_work_pool - return the worker_pool a given work was associated with
701 * @work: the work item of interest
703 * Pools are created and destroyed under wq_pool_mutex, and allows read
704 * access under sched-RCU read lock. As such, this function should be
705 * called under wq_pool_mutex or with preemption disabled.
707 * All fields of the returned pool are accessible as long as the above
708 * mentioned locking is in effect. If the returned pool needs to be used
709 * beyond the critical section, the caller is responsible for ensuring the
710 * returned pool is and stays online.
712 * Return: The worker_pool @work was last associated with. %NULL if none.
714 static struct worker_pool
*get_work_pool(struct work_struct
*work
)
716 unsigned long data
= atomic_long_read(&work
->data
);
719 assert_rcu_or_pool_mutex();
721 if (data
& WORK_STRUCT_PWQ
)
722 return ((struct pool_workqueue
*)
723 (data
& WORK_STRUCT_WQ_DATA_MASK
))->pool
;
725 pool_id
= data
>> WORK_OFFQ_POOL_SHIFT
;
726 if (pool_id
== WORK_OFFQ_POOL_NONE
)
729 return idr_find(&worker_pool_idr
, pool_id
);
733 * get_work_pool_id - return the worker pool ID a given work is associated with
734 * @work: the work item of interest
736 * Return: The worker_pool ID @work was last associated with.
737 * %WORK_OFFQ_POOL_NONE if none.
739 static int get_work_pool_id(struct work_struct
*work
)
741 unsigned long data
= atomic_long_read(&work
->data
);
743 if (data
& WORK_STRUCT_PWQ
)
744 return ((struct pool_workqueue
*)
745 (data
& WORK_STRUCT_WQ_DATA_MASK
))->pool
->id
;
747 return data
>> WORK_OFFQ_POOL_SHIFT
;
750 static void mark_work_canceling(struct work_struct
*work
)
752 unsigned long pool_id
= get_work_pool_id(work
);
754 pool_id
<<= WORK_OFFQ_POOL_SHIFT
;
755 set_work_data(work
, pool_id
| WORK_OFFQ_CANCELING
, WORK_STRUCT_PENDING
);
758 static bool work_is_canceling(struct work_struct
*work
)
760 unsigned long data
= atomic_long_read(&work
->data
);
762 return !(data
& WORK_STRUCT_PWQ
) && (data
& WORK_OFFQ_CANCELING
);
766 * Policy functions. These define the policies on how the global worker
767 * pools are managed. Unless noted otherwise, these functions assume that
768 * they're being called with pool->lock held.
771 static bool __need_more_worker(struct worker_pool
*pool
)
773 return !atomic_read(&pool
->nr_running
);
777 * Need to wake up a worker? Called from anything but currently
780 * Note that, because unbound workers never contribute to nr_running, this
781 * function will always return %true for unbound pools as long as the
782 * worklist isn't empty.
784 static bool need_more_worker(struct worker_pool
*pool
)
786 return !list_empty(&pool
->worklist
) && __need_more_worker(pool
);
789 /* Can I start working? Called from busy but !running workers. */
790 static bool may_start_working(struct worker_pool
*pool
)
792 return pool
->nr_idle
;
795 /* Do I need to keep working? Called from currently running workers. */
796 static bool keep_working(struct worker_pool
*pool
)
798 return !list_empty(&pool
->worklist
) &&
799 atomic_read(&pool
->nr_running
) <= 1;
802 /* Do we need a new worker? Called from manager. */
803 static bool need_to_create_worker(struct worker_pool
*pool
)
805 return need_more_worker(pool
) && !may_start_working(pool
);
808 /* Do we have too many workers and should some go away? */
809 static bool too_many_workers(struct worker_pool
*pool
)
811 bool managing
= mutex_is_locked(&pool
->manager_arb
);
812 int nr_idle
= pool
->nr_idle
+ managing
; /* manager is considered idle */
813 int nr_busy
= pool
->nr_workers
- nr_idle
;
815 return nr_idle
> 2 && (nr_idle
- 2) * MAX_IDLE_WORKERS_RATIO
>= nr_busy
;
822 /* Return the first idle worker. Safe with preemption disabled */
823 static struct worker
*first_idle_worker(struct worker_pool
*pool
)
825 if (unlikely(list_empty(&pool
->idle_list
)))
828 return list_first_entry(&pool
->idle_list
, struct worker
, entry
);
832 * wake_up_worker - wake up an idle worker
833 * @pool: worker pool to wake worker from
835 * Wake up the first idle worker of @pool.
838 * spin_lock_irq(pool->lock).
840 static void wake_up_worker(struct worker_pool
*pool
)
842 struct worker
*worker
= first_idle_worker(pool
);
845 wake_up_process(worker
->task
);
849 * wq_worker_waking_up - a worker is waking up
850 * @task: task waking up
851 * @cpu: CPU @task is waking up to
853 * This function is called during try_to_wake_up() when a worker is
857 * spin_lock_irq(rq->lock)
859 void wq_worker_waking_up(struct task_struct
*task
, int cpu
)
861 struct worker
*worker
= kthread_data(task
);
863 if (!(worker
->flags
& WORKER_NOT_RUNNING
)) {
864 WARN_ON_ONCE(worker
->pool
->cpu
!= cpu
);
865 atomic_inc(&worker
->pool
->nr_running
);
870 * wq_worker_sleeping - a worker is going to sleep
871 * @task: task going to sleep
872 * @cpu: CPU in question, must be the current CPU number
874 * This function is called during schedule() when a busy worker is
875 * going to sleep. Worker on the same cpu can be woken up by
876 * returning pointer to its task.
879 * spin_lock_irq(rq->lock)
882 * Worker task on @cpu to wake up, %NULL if none.
884 struct task_struct
*wq_worker_sleeping(struct task_struct
*task
, int cpu
)
886 struct worker
*worker
= kthread_data(task
), *to_wakeup
= NULL
;
887 struct worker_pool
*pool
;
890 * Rescuers, which may not have all the fields set up like normal
891 * workers, also reach here, let's not access anything before
892 * checking NOT_RUNNING.
894 if (worker
->flags
& WORKER_NOT_RUNNING
)
899 /* this can only happen on the local cpu */
900 if (WARN_ON_ONCE(cpu
!= raw_smp_processor_id() || pool
->cpu
!= cpu
))
904 * The counterpart of the following dec_and_test, implied mb,
905 * worklist not empty test sequence is in insert_work().
906 * Please read comment there.
908 * NOT_RUNNING is clear. This means that we're bound to and
909 * running on the local cpu w/ rq lock held and preemption
910 * disabled, which in turn means that none else could be
911 * manipulating idle_list, so dereferencing idle_list without pool
914 if (atomic_dec_and_test(&pool
->nr_running
) &&
915 !list_empty(&pool
->worklist
))
916 to_wakeup
= first_idle_worker(pool
);
917 return to_wakeup
? to_wakeup
->task
: NULL
;
921 * worker_set_flags - set worker flags and adjust nr_running accordingly
923 * @flags: flags to set
925 * Set @flags in @worker->flags and adjust nr_running accordingly.
928 * spin_lock_irq(pool->lock)
930 static inline void worker_set_flags(struct worker
*worker
, unsigned int flags
)
932 struct worker_pool
*pool
= worker
->pool
;
934 WARN_ON_ONCE(worker
->task
!= current
);
936 /* If transitioning into NOT_RUNNING, adjust nr_running. */
937 if ((flags
& WORKER_NOT_RUNNING
) &&
938 !(worker
->flags
& WORKER_NOT_RUNNING
)) {
939 atomic_dec(&pool
->nr_running
);
942 worker
->flags
|= flags
;
946 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
948 * @flags: flags to clear
950 * Clear @flags in @worker->flags and adjust nr_running accordingly.
953 * spin_lock_irq(pool->lock)
955 static inline void worker_clr_flags(struct worker
*worker
, unsigned int flags
)
957 struct worker_pool
*pool
= worker
->pool
;
958 unsigned int oflags
= worker
->flags
;
960 WARN_ON_ONCE(worker
->task
!= current
);
962 worker
->flags
&= ~flags
;
965 * If transitioning out of NOT_RUNNING, increment nr_running. Note
966 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
967 * of multiple flags, not a single flag.
969 if ((flags
& WORKER_NOT_RUNNING
) && (oflags
& WORKER_NOT_RUNNING
))
970 if (!(worker
->flags
& WORKER_NOT_RUNNING
))
971 atomic_inc(&pool
->nr_running
);
975 * find_worker_executing_work - find worker which is executing a work
976 * @pool: pool of interest
977 * @work: work to find worker for
979 * Find a worker which is executing @work on @pool by searching
980 * @pool->busy_hash which is keyed by the address of @work. For a worker
981 * to match, its current execution should match the address of @work and
982 * its work function. This is to avoid unwanted dependency between
983 * unrelated work executions through a work item being recycled while still
986 * This is a bit tricky. A work item may be freed once its execution
987 * starts and nothing prevents the freed area from being recycled for
988 * another work item. If the same work item address ends up being reused
989 * before the original execution finishes, workqueue will identify the
990 * recycled work item as currently executing and make it wait until the
991 * current execution finishes, introducing an unwanted dependency.
993 * This function checks the work item address and work function to avoid
994 * false positives. Note that this isn't complete as one may construct a
995 * work function which can introduce dependency onto itself through a
996 * recycled work item. Well, if somebody wants to shoot oneself in the
997 * foot that badly, there's only so much we can do, and if such deadlock
998 * actually occurs, it should be easy to locate the culprit work function.
1001 * spin_lock_irq(pool->lock).
1004 * Pointer to worker which is executing @work if found, %NULL
1007 static struct worker
*find_worker_executing_work(struct worker_pool
*pool
,
1008 struct work_struct
*work
)
1010 struct worker
*worker
;
1012 hash_for_each_possible(pool
->busy_hash
, worker
, hentry
,
1013 (unsigned long)work
)
1014 if (worker
->current_work
== work
&&
1015 worker
->current_func
== work
->func
)
1022 * move_linked_works - move linked works to a list
1023 * @work: start of series of works to be scheduled
1024 * @head: target list to append @work to
1025 * @nextp: out parameter for nested worklist walking
1027 * Schedule linked works starting from @work to @head. Work series to
1028 * be scheduled starts at @work and includes any consecutive work with
1029 * WORK_STRUCT_LINKED set in its predecessor.
1031 * If @nextp is not NULL, it's updated to point to the next work of
1032 * the last scheduled work. This allows move_linked_works() to be
1033 * nested inside outer list_for_each_entry_safe().
1036 * spin_lock_irq(pool->lock).
1038 static void move_linked_works(struct work_struct
*work
, struct list_head
*head
,
1039 struct work_struct
**nextp
)
1041 struct work_struct
*n
;
1044 * Linked worklist will always end before the end of the list,
1045 * use NULL for list head.
1047 list_for_each_entry_safe_from(work
, n
, NULL
, entry
) {
1048 list_move_tail(&work
->entry
, head
);
1049 if (!(*work_data_bits(work
) & WORK_STRUCT_LINKED
))
1054 * If we're already inside safe list traversal and have moved
1055 * multiple works to the scheduled queue, the next position
1056 * needs to be updated.
1063 * get_pwq - get an extra reference on the specified pool_workqueue
1064 * @pwq: pool_workqueue to get
1066 * Obtain an extra reference on @pwq. The caller should guarantee that
1067 * @pwq has positive refcnt and be holding the matching pool->lock.
1069 static void get_pwq(struct pool_workqueue
*pwq
)
1071 lockdep_assert_held(&pwq
->pool
->lock
);
1072 WARN_ON_ONCE(pwq
->refcnt
<= 0);
1077 * put_pwq - put a pool_workqueue reference
1078 * @pwq: pool_workqueue to put
1080 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1081 * destruction. The caller should be holding the matching pool->lock.
1083 static void put_pwq(struct pool_workqueue
*pwq
)
1085 lockdep_assert_held(&pwq
->pool
->lock
);
1086 if (likely(--pwq
->refcnt
))
1088 if (WARN_ON_ONCE(!(pwq
->wq
->flags
& WQ_UNBOUND
)))
1091 * @pwq can't be released under pool->lock, bounce to
1092 * pwq_unbound_release_workfn(). This never recurses on the same
1093 * pool->lock as this path is taken only for unbound workqueues and
1094 * the release work item is scheduled on a per-cpu workqueue. To
1095 * avoid lockdep warning, unbound pool->locks are given lockdep
1096 * subclass of 1 in get_unbound_pool().
1098 schedule_work(&pwq
->unbound_release_work
);
1102 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1103 * @pwq: pool_workqueue to put (can be %NULL)
1105 * put_pwq() with locking. This function also allows %NULL @pwq.
1107 static void put_pwq_unlocked(struct pool_workqueue
*pwq
)
1111 * As both pwqs and pools are sched-RCU protected, the
1112 * following lock operations are safe.
1114 spin_lock_irq(&pwq
->pool
->lock
);
1116 spin_unlock_irq(&pwq
->pool
->lock
);
1120 static void pwq_activate_delayed_work(struct work_struct
*work
)
1122 struct pool_workqueue
*pwq
= get_work_pwq(work
);
1124 trace_workqueue_activate_work(work
);
1125 move_linked_works(work
, &pwq
->pool
->worklist
, NULL
);
1126 __clear_bit(WORK_STRUCT_DELAYED_BIT
, work_data_bits(work
));
1130 static void pwq_activate_first_delayed(struct pool_workqueue
*pwq
)
1132 struct work_struct
*work
= list_first_entry(&pwq
->delayed_works
,
1133 struct work_struct
, entry
);
1135 pwq_activate_delayed_work(work
);
1139 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1140 * @pwq: pwq of interest
1141 * @color: color of work which left the queue
1143 * A work either has completed or is removed from pending queue,
1144 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1147 * spin_lock_irq(pool->lock).
1149 static void pwq_dec_nr_in_flight(struct pool_workqueue
*pwq
, int color
)
1151 /* uncolored work items don't participate in flushing or nr_active */
1152 if (color
== WORK_NO_COLOR
)
1155 pwq
->nr_in_flight
[color
]--;
1158 if (!list_empty(&pwq
->delayed_works
)) {
1159 /* one down, submit a delayed one */
1160 if (pwq
->nr_active
< pwq
->max_active
)
1161 pwq_activate_first_delayed(pwq
);
1164 /* is flush in progress and are we at the flushing tip? */
1165 if (likely(pwq
->flush_color
!= color
))
1168 /* are there still in-flight works? */
1169 if (pwq
->nr_in_flight
[color
])
1172 /* this pwq is done, clear flush_color */
1173 pwq
->flush_color
= -1;
1176 * If this was the last pwq, wake up the first flusher. It
1177 * will handle the rest.
1179 if (atomic_dec_and_test(&pwq
->wq
->nr_pwqs_to_flush
))
1180 complete(&pwq
->wq
->first_flusher
->done
);
1186 * try_to_grab_pending - steal work item from worklist and disable irq
1187 * @work: work item to steal
1188 * @is_dwork: @work is a delayed_work
1189 * @flags: place to store irq state
1191 * Try to grab PENDING bit of @work. This function can handle @work in any
1192 * stable state - idle, on timer or on worklist.
1195 * 1 if @work was pending and we successfully stole PENDING
1196 * 0 if @work was idle and we claimed PENDING
1197 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1198 * -ENOENT if someone else is canceling @work, this state may persist
1199 * for arbitrarily long
1202 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1203 * interrupted while holding PENDING and @work off queue, irq must be
1204 * disabled on entry. This, combined with delayed_work->timer being
1205 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1207 * On successful return, >= 0, irq is disabled and the caller is
1208 * responsible for releasing it using local_irq_restore(*@flags).
1210 * This function is safe to call from any context including IRQ handler.
1212 static int try_to_grab_pending(struct work_struct
*work
, bool is_dwork
,
1213 unsigned long *flags
)
1215 struct worker_pool
*pool
;
1216 struct pool_workqueue
*pwq
;
1218 local_irq_save(*flags
);
1220 /* try to steal the timer if it exists */
1222 struct delayed_work
*dwork
= to_delayed_work(work
);
1225 * dwork->timer is irqsafe. If del_timer() fails, it's
1226 * guaranteed that the timer is not queued anywhere and not
1227 * running on the local CPU.
1229 if (likely(del_timer(&dwork
->timer
)))
1233 /* try to claim PENDING the normal way */
1234 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
)))
1238 * The queueing is in progress, or it is already queued. Try to
1239 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1241 pool
= get_work_pool(work
);
1245 spin_lock(&pool
->lock
);
1247 * work->data is guaranteed to point to pwq only while the work
1248 * item is queued on pwq->wq, and both updating work->data to point
1249 * to pwq on queueing and to pool on dequeueing are done under
1250 * pwq->pool->lock. This in turn guarantees that, if work->data
1251 * points to pwq which is associated with a locked pool, the work
1252 * item is currently queued on that pool.
1254 pwq
= get_work_pwq(work
);
1255 if (pwq
&& pwq
->pool
== pool
) {
1256 debug_work_deactivate(work
);
1259 * A delayed work item cannot be grabbed directly because
1260 * it might have linked NO_COLOR work items which, if left
1261 * on the delayed_list, will confuse pwq->nr_active
1262 * management later on and cause stall. Make sure the work
1263 * item is activated before grabbing.
1265 if (*work_data_bits(work
) & WORK_STRUCT_DELAYED
)
1266 pwq_activate_delayed_work(work
);
1268 list_del_init(&work
->entry
);
1269 pwq_dec_nr_in_flight(pwq
, get_work_color(work
));
1271 /* work->data points to pwq iff queued, point to pool */
1272 set_work_pool_and_keep_pending(work
, pool
->id
);
1274 spin_unlock(&pool
->lock
);
1277 spin_unlock(&pool
->lock
);
1279 local_irq_restore(*flags
);
1280 if (work_is_canceling(work
))
1287 * insert_work - insert a work into a pool
1288 * @pwq: pwq @work belongs to
1289 * @work: work to insert
1290 * @head: insertion point
1291 * @extra_flags: extra WORK_STRUCT_* flags to set
1293 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1294 * work_struct flags.
1297 * spin_lock_irq(pool->lock).
1299 static void insert_work(struct pool_workqueue
*pwq
, struct work_struct
*work
,
1300 struct list_head
*head
, unsigned int extra_flags
)
1302 struct worker_pool
*pool
= pwq
->pool
;
1304 /* we own @work, set data and link */
1305 set_work_pwq(work
, pwq
, extra_flags
);
1306 list_add_tail(&work
->entry
, head
);
1310 * Ensure either wq_worker_sleeping() sees the above
1311 * list_add_tail() or we see zero nr_running to avoid workers lying
1312 * around lazily while there are works to be processed.
1316 if (__need_more_worker(pool
))
1317 wake_up_worker(pool
);
1321 * Test whether @work is being queued from another work executing on the
1324 static bool is_chained_work(struct workqueue_struct
*wq
)
1326 struct worker
*worker
;
1328 worker
= current_wq_worker();
1330 * Return %true iff I'm a worker execuing a work item on @wq. If
1331 * I'm @worker, it's safe to dereference it without locking.
1333 return worker
&& worker
->current_pwq
->wq
== wq
;
1336 static void __queue_work(int cpu
, struct workqueue_struct
*wq
,
1337 struct work_struct
*work
)
1339 struct pool_workqueue
*pwq
;
1340 struct worker_pool
*last_pool
;
1341 struct list_head
*worklist
;
1342 unsigned int work_flags
;
1343 unsigned int req_cpu
= cpu
;
1346 * While a work item is PENDING && off queue, a task trying to
1347 * steal the PENDING will busy-loop waiting for it to either get
1348 * queued or lose PENDING. Grabbing PENDING and queueing should
1349 * happen with IRQ disabled.
1351 WARN_ON_ONCE(!irqs_disabled());
1353 debug_work_activate(work
);
1355 /* if draining, only works from the same workqueue are allowed */
1356 if (unlikely(wq
->flags
& __WQ_DRAINING
) &&
1357 WARN_ON_ONCE(!is_chained_work(wq
)))
1360 if (req_cpu
== WORK_CPU_UNBOUND
)
1361 cpu
= raw_smp_processor_id();
1363 /* pwq which will be used unless @work is executing elsewhere */
1364 if (!(wq
->flags
& WQ_UNBOUND
))
1365 pwq
= per_cpu_ptr(wq
->cpu_pwqs
, cpu
);
1367 pwq
= unbound_pwq_by_node(wq
, cpu_to_node(cpu
));
1370 * If @work was previously on a different pool, it might still be
1371 * running there, in which case the work needs to be queued on that
1372 * pool to guarantee non-reentrancy.
1374 last_pool
= get_work_pool(work
);
1375 if (last_pool
&& last_pool
!= pwq
->pool
) {
1376 struct worker
*worker
;
1378 spin_lock(&last_pool
->lock
);
1380 worker
= find_worker_executing_work(last_pool
, work
);
1382 if (worker
&& worker
->current_pwq
->wq
== wq
) {
1383 pwq
= worker
->current_pwq
;
1385 /* meh... not running there, queue here */
1386 spin_unlock(&last_pool
->lock
);
1387 spin_lock(&pwq
->pool
->lock
);
1390 spin_lock(&pwq
->pool
->lock
);
1394 * pwq is determined and locked. For unbound pools, we could have
1395 * raced with pwq release and it could already be dead. If its
1396 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1397 * without another pwq replacing it in the numa_pwq_tbl or while
1398 * work items are executing on it, so the retrying is guaranteed to
1399 * make forward-progress.
1401 if (unlikely(!pwq
->refcnt
)) {
1402 if (wq
->flags
& WQ_UNBOUND
) {
1403 spin_unlock(&pwq
->pool
->lock
);
1408 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1412 /* pwq determined, queue */
1413 trace_workqueue_queue_work(req_cpu
, pwq
, work
);
1415 if (WARN_ON(!list_empty(&work
->entry
))) {
1416 spin_unlock(&pwq
->pool
->lock
);
1420 pwq
->nr_in_flight
[pwq
->work_color
]++;
1421 work_flags
= work_color_to_flags(pwq
->work_color
);
1423 if (likely(pwq
->nr_active
< pwq
->max_active
)) {
1424 trace_workqueue_activate_work(work
);
1426 worklist
= &pwq
->pool
->worklist
;
1428 work_flags
|= WORK_STRUCT_DELAYED
;
1429 worklist
= &pwq
->delayed_works
;
1432 insert_work(pwq
, work
, worklist
, work_flags
);
1434 spin_unlock(&pwq
->pool
->lock
);
1438 * queue_work_on - queue work on specific cpu
1439 * @cpu: CPU number to execute work on
1440 * @wq: workqueue to use
1441 * @work: work to queue
1443 * We queue the work to a specific CPU, the caller must ensure it
1446 * Return: %false if @work was already on a queue, %true otherwise.
1448 bool queue_work_on(int cpu
, struct workqueue_struct
*wq
,
1449 struct work_struct
*work
)
1452 unsigned long flags
;
1454 local_irq_save(flags
);
1456 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
))) {
1457 __queue_work(cpu
, wq
, work
);
1461 local_irq_restore(flags
);
1464 EXPORT_SYMBOL(queue_work_on
);
1466 void delayed_work_timer_fn(unsigned long __data
)
1468 struct delayed_work
*dwork
= (struct delayed_work
*)__data
;
1470 /* should have been called from irqsafe timer with irq already off */
1471 __queue_work(dwork
->cpu
, dwork
->wq
, &dwork
->work
);
1473 EXPORT_SYMBOL(delayed_work_timer_fn
);
1475 static void __queue_delayed_work(int cpu
, struct workqueue_struct
*wq
,
1476 struct delayed_work
*dwork
, unsigned long delay
)
1478 struct timer_list
*timer
= &dwork
->timer
;
1479 struct work_struct
*work
= &dwork
->work
;
1481 WARN_ON_ONCE(timer
->function
!= delayed_work_timer_fn
||
1482 timer
->data
!= (unsigned long)dwork
);
1483 WARN_ON_ONCE(timer_pending(timer
));
1484 WARN_ON_ONCE(!list_empty(&work
->entry
));
1487 * If @delay is 0, queue @dwork->work immediately. This is for
1488 * both optimization and correctness. The earliest @timer can
1489 * expire is on the closest next tick and delayed_work users depend
1490 * on that there's no such delay when @delay is 0.
1493 __queue_work(cpu
, wq
, &dwork
->work
);
1497 timer_stats_timer_set_start_info(&dwork
->timer
);
1501 timer
->expires
= jiffies
+ delay
;
1503 if (unlikely(cpu
!= WORK_CPU_UNBOUND
))
1504 add_timer_on(timer
, cpu
);
1510 * queue_delayed_work_on - queue work on specific CPU after delay
1511 * @cpu: CPU number to execute work on
1512 * @wq: workqueue to use
1513 * @dwork: work to queue
1514 * @delay: number of jiffies to wait before queueing
1516 * Return: %false if @work was already on a queue, %true otherwise. If
1517 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1520 bool queue_delayed_work_on(int cpu
, struct workqueue_struct
*wq
,
1521 struct delayed_work
*dwork
, unsigned long delay
)
1523 struct work_struct
*work
= &dwork
->work
;
1525 unsigned long flags
;
1527 /* read the comment in __queue_work() */
1528 local_irq_save(flags
);
1530 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
))) {
1531 __queue_delayed_work(cpu
, wq
, dwork
, delay
);
1535 local_irq_restore(flags
);
1538 EXPORT_SYMBOL(queue_delayed_work_on
);
1541 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1542 * @cpu: CPU number to execute work on
1543 * @wq: workqueue to use
1544 * @dwork: work to queue
1545 * @delay: number of jiffies to wait before queueing
1547 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1548 * modify @dwork's timer so that it expires after @delay. If @delay is
1549 * zero, @work is guaranteed to be scheduled immediately regardless of its
1552 * Return: %false if @dwork was idle and queued, %true if @dwork was
1553 * pending and its timer was modified.
1555 * This function is safe to call from any context including IRQ handler.
1556 * See try_to_grab_pending() for details.
1558 bool mod_delayed_work_on(int cpu
, struct workqueue_struct
*wq
,
1559 struct delayed_work
*dwork
, unsigned long delay
)
1561 unsigned long flags
;
1565 ret
= try_to_grab_pending(&dwork
->work
, true, &flags
);
1566 } while (unlikely(ret
== -EAGAIN
));
1568 if (likely(ret
>= 0)) {
1569 __queue_delayed_work(cpu
, wq
, dwork
, delay
);
1570 local_irq_restore(flags
);
1573 /* -ENOENT from try_to_grab_pending() becomes %true */
1576 EXPORT_SYMBOL_GPL(mod_delayed_work_on
);
1579 * worker_enter_idle - enter idle state
1580 * @worker: worker which is entering idle state
1582 * @worker is entering idle state. Update stats and idle timer if
1586 * spin_lock_irq(pool->lock).
1588 static void worker_enter_idle(struct worker
*worker
)
1590 struct worker_pool
*pool
= worker
->pool
;
1592 if (WARN_ON_ONCE(worker
->flags
& WORKER_IDLE
) ||
1593 WARN_ON_ONCE(!list_empty(&worker
->entry
) &&
1594 (worker
->hentry
.next
|| worker
->hentry
.pprev
)))
1597 /* can't use worker_set_flags(), also called from create_worker() */
1598 worker
->flags
|= WORKER_IDLE
;
1600 worker
->last_active
= jiffies
;
1602 /* idle_list is LIFO */
1603 list_add(&worker
->entry
, &pool
->idle_list
);
1605 if (too_many_workers(pool
) && !timer_pending(&pool
->idle_timer
))
1606 mod_timer(&pool
->idle_timer
, jiffies
+ IDLE_WORKER_TIMEOUT
);
1609 * Sanity check nr_running. Because wq_unbind_fn() releases
1610 * pool->lock between setting %WORKER_UNBOUND and zapping
1611 * nr_running, the warning may trigger spuriously. Check iff
1612 * unbind is not in progress.
1614 WARN_ON_ONCE(!(pool
->flags
& POOL_DISASSOCIATED
) &&
1615 pool
->nr_workers
== pool
->nr_idle
&&
1616 atomic_read(&pool
->nr_running
));
1620 * worker_leave_idle - leave idle state
1621 * @worker: worker which is leaving idle state
1623 * @worker is leaving idle state. Update stats.
1626 * spin_lock_irq(pool->lock).
1628 static void worker_leave_idle(struct worker
*worker
)
1630 struct worker_pool
*pool
= worker
->pool
;
1632 if (WARN_ON_ONCE(!(worker
->flags
& WORKER_IDLE
)))
1634 worker_clr_flags(worker
, WORKER_IDLE
);
1636 list_del_init(&worker
->entry
);
1639 static struct worker
*alloc_worker(int node
)
1641 struct worker
*worker
;
1643 worker
= kzalloc_node(sizeof(*worker
), GFP_KERNEL
, node
);
1645 INIT_LIST_HEAD(&worker
->entry
);
1646 INIT_LIST_HEAD(&worker
->scheduled
);
1647 INIT_LIST_HEAD(&worker
->node
);
1648 /* on creation a worker is in !idle && prep state */
1649 worker
->flags
= WORKER_PREP
;
1655 * worker_attach_to_pool() - attach a worker to a pool
1656 * @worker: worker to be attached
1657 * @pool: the target pool
1659 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
1660 * cpu-binding of @worker are kept coordinated with the pool across
1663 static void worker_attach_to_pool(struct worker
*worker
,
1664 struct worker_pool
*pool
)
1666 mutex_lock(&pool
->attach_mutex
);
1669 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1670 * online CPUs. It'll be re-applied when any of the CPUs come up.
1672 set_cpus_allowed_ptr(worker
->task
, pool
->attrs
->cpumask
);
1675 * The pool->attach_mutex ensures %POOL_DISASSOCIATED remains
1676 * stable across this function. See the comments above the
1677 * flag definition for details.
1679 if (pool
->flags
& POOL_DISASSOCIATED
)
1680 worker
->flags
|= WORKER_UNBOUND
;
1682 list_add_tail(&worker
->node
, &pool
->workers
);
1684 mutex_unlock(&pool
->attach_mutex
);
1688 * worker_detach_from_pool() - detach a worker from its pool
1689 * @worker: worker which is attached to its pool
1690 * @pool: the pool @worker is attached to
1692 * Undo the attaching which had been done in worker_attach_to_pool(). The
1693 * caller worker shouldn't access to the pool after detached except it has
1694 * other reference to the pool.
1696 static void worker_detach_from_pool(struct worker
*worker
,
1697 struct worker_pool
*pool
)
1699 struct completion
*detach_completion
= NULL
;
1701 mutex_lock(&pool
->attach_mutex
);
1702 list_del(&worker
->node
);
1703 if (list_empty(&pool
->workers
))
1704 detach_completion
= pool
->detach_completion
;
1705 mutex_unlock(&pool
->attach_mutex
);
1707 /* clear leftover flags without pool->lock after it is detached */
1708 worker
->flags
&= ~(WORKER_UNBOUND
| WORKER_REBOUND
);
1710 if (detach_completion
)
1711 complete(detach_completion
);
1715 * create_worker - create a new workqueue worker
1716 * @pool: pool the new worker will belong to
1718 * Create and start a new worker which is attached to @pool.
1721 * Might sleep. Does GFP_KERNEL allocations.
1724 * Pointer to the newly created worker.
1726 static struct worker
*create_worker(struct worker_pool
*pool
)
1728 struct worker
*worker
= NULL
;
1732 /* ID is needed to determine kthread name */
1733 id
= ida_simple_get(&pool
->worker_ida
, 0, 0, GFP_KERNEL
);
1737 worker
= alloc_worker(pool
->node
);
1741 worker
->pool
= pool
;
1745 snprintf(id_buf
, sizeof(id_buf
), "%d:%d%s", pool
->cpu
, id
,
1746 pool
->attrs
->nice
< 0 ? "H" : "");
1748 snprintf(id_buf
, sizeof(id_buf
), "u%d:%d", pool
->id
, id
);
1750 worker
->task
= kthread_create_on_node(worker_thread
, worker
, pool
->node
,
1751 "kworker/%s", id_buf
);
1752 if (IS_ERR(worker
->task
))
1755 set_user_nice(worker
->task
, pool
->attrs
->nice
);
1756 kthread_bind_mask(worker
->task
, pool
->attrs
->cpumask
);
1758 /* successful, attach the worker to the pool */
1759 worker_attach_to_pool(worker
, pool
);
1761 /* start the newly created worker */
1762 spin_lock_irq(&pool
->lock
);
1763 worker
->pool
->nr_workers
++;
1764 worker_enter_idle(worker
);
1765 wake_up_process(worker
->task
);
1766 spin_unlock_irq(&pool
->lock
);
1772 ida_simple_remove(&pool
->worker_ida
, id
);
1778 * destroy_worker - destroy a workqueue worker
1779 * @worker: worker to be destroyed
1781 * Destroy @worker and adjust @pool stats accordingly. The worker should
1785 * spin_lock_irq(pool->lock).
1787 static void destroy_worker(struct worker
*worker
)
1789 struct worker_pool
*pool
= worker
->pool
;
1791 lockdep_assert_held(&pool
->lock
);
1793 /* sanity check frenzy */
1794 if (WARN_ON(worker
->current_work
) ||
1795 WARN_ON(!list_empty(&worker
->scheduled
)) ||
1796 WARN_ON(!(worker
->flags
& WORKER_IDLE
)))
1802 list_del_init(&worker
->entry
);
1803 worker
->flags
|= WORKER_DIE
;
1804 wake_up_process(worker
->task
);
1807 static void idle_worker_timeout(unsigned long __pool
)
1809 struct worker_pool
*pool
= (void *)__pool
;
1811 spin_lock_irq(&pool
->lock
);
1813 while (too_many_workers(pool
)) {
1814 struct worker
*worker
;
1815 unsigned long expires
;
1817 /* idle_list is kept in LIFO order, check the last one */
1818 worker
= list_entry(pool
->idle_list
.prev
, struct worker
, entry
);
1819 expires
= worker
->last_active
+ IDLE_WORKER_TIMEOUT
;
1821 if (time_before(jiffies
, expires
)) {
1822 mod_timer(&pool
->idle_timer
, expires
);
1826 destroy_worker(worker
);
1829 spin_unlock_irq(&pool
->lock
);
1832 static void send_mayday(struct work_struct
*work
)
1834 struct pool_workqueue
*pwq
= get_work_pwq(work
);
1835 struct workqueue_struct
*wq
= pwq
->wq
;
1837 lockdep_assert_held(&wq_mayday_lock
);
1842 /* mayday mayday mayday */
1843 if (list_empty(&pwq
->mayday_node
)) {
1845 * If @pwq is for an unbound wq, its base ref may be put at
1846 * any time due to an attribute change. Pin @pwq until the
1847 * rescuer is done with it.
1850 list_add_tail(&pwq
->mayday_node
, &wq
->maydays
);
1851 wake_up_process(wq
->rescuer
->task
);
1855 static void pool_mayday_timeout(unsigned long __pool
)
1857 struct worker_pool
*pool
= (void *)__pool
;
1858 struct work_struct
*work
;
1860 spin_lock_irq(&pool
->lock
);
1861 spin_lock(&wq_mayday_lock
); /* for wq->maydays */
1863 if (need_to_create_worker(pool
)) {
1865 * We've been trying to create a new worker but
1866 * haven't been successful. We might be hitting an
1867 * allocation deadlock. Send distress signals to
1870 list_for_each_entry(work
, &pool
->worklist
, entry
)
1874 spin_unlock(&wq_mayday_lock
);
1875 spin_unlock_irq(&pool
->lock
);
1877 mod_timer(&pool
->mayday_timer
, jiffies
+ MAYDAY_INTERVAL
);
1881 * maybe_create_worker - create a new worker if necessary
1882 * @pool: pool to create a new worker for
1884 * Create a new worker for @pool if necessary. @pool is guaranteed to
1885 * have at least one idle worker on return from this function. If
1886 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1887 * sent to all rescuers with works scheduled on @pool to resolve
1888 * possible allocation deadlock.
1890 * On return, need_to_create_worker() is guaranteed to be %false and
1891 * may_start_working() %true.
1894 * spin_lock_irq(pool->lock) which may be released and regrabbed
1895 * multiple times. Does GFP_KERNEL allocations. Called only from
1898 static void maybe_create_worker(struct worker_pool
*pool
)
1899 __releases(&pool
->lock
)
1900 __acquires(&pool
->lock
)
1903 spin_unlock_irq(&pool
->lock
);
1905 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1906 mod_timer(&pool
->mayday_timer
, jiffies
+ MAYDAY_INITIAL_TIMEOUT
);
1909 if (create_worker(pool
) || !need_to_create_worker(pool
))
1912 schedule_timeout_interruptible(CREATE_COOLDOWN
);
1914 if (!need_to_create_worker(pool
))
1918 del_timer_sync(&pool
->mayday_timer
);
1919 spin_lock_irq(&pool
->lock
);
1921 * This is necessary even after a new worker was just successfully
1922 * created as @pool->lock was dropped and the new worker might have
1923 * already become busy.
1925 if (need_to_create_worker(pool
))
1930 * manage_workers - manage worker pool
1933 * Assume the manager role and manage the worker pool @worker belongs
1934 * to. At any given time, there can be only zero or one manager per
1935 * pool. The exclusion is handled automatically by this function.
1937 * The caller can safely start processing works on false return. On
1938 * true return, it's guaranteed that need_to_create_worker() is false
1939 * and may_start_working() is true.
1942 * spin_lock_irq(pool->lock) which may be released and regrabbed
1943 * multiple times. Does GFP_KERNEL allocations.
1946 * %false if the pool doesn't need management and the caller can safely
1947 * start processing works, %true if management function was performed and
1948 * the conditions that the caller verified before calling the function may
1949 * no longer be true.
1951 static bool manage_workers(struct worker
*worker
)
1953 struct worker_pool
*pool
= worker
->pool
;
1956 * Anyone who successfully grabs manager_arb wins the arbitration
1957 * and becomes the manager. mutex_trylock() on pool->manager_arb
1958 * failure while holding pool->lock reliably indicates that someone
1959 * else is managing the pool and the worker which failed trylock
1960 * can proceed to executing work items. This means that anyone
1961 * grabbing manager_arb is responsible for actually performing
1962 * manager duties. If manager_arb is grabbed and released without
1963 * actual management, the pool may stall indefinitely.
1965 if (!mutex_trylock(&pool
->manager_arb
))
1967 pool
->manager
= worker
;
1969 maybe_create_worker(pool
);
1971 pool
->manager
= NULL
;
1972 mutex_unlock(&pool
->manager_arb
);
1977 * process_one_work - process single work
1979 * @work: work to process
1981 * Process @work. This function contains all the logics necessary to
1982 * process a single work including synchronization against and
1983 * interaction with other workers on the same cpu, queueing and
1984 * flushing. As long as context requirement is met, any worker can
1985 * call this function to process a work.
1988 * spin_lock_irq(pool->lock) which is released and regrabbed.
1990 static void process_one_work(struct worker
*worker
, struct work_struct
*work
)
1991 __releases(&pool
->lock
)
1992 __acquires(&pool
->lock
)
1994 struct pool_workqueue
*pwq
= get_work_pwq(work
);
1995 struct worker_pool
*pool
= worker
->pool
;
1996 bool cpu_intensive
= pwq
->wq
->flags
& WQ_CPU_INTENSIVE
;
1998 struct worker
*collision
;
1999 #ifdef CONFIG_LOCKDEP
2001 * It is permissible to free the struct work_struct from
2002 * inside the function that is called from it, this we need to
2003 * take into account for lockdep too. To avoid bogus "held
2004 * lock freed" warnings as well as problems when looking into
2005 * work->lockdep_map, make a copy and use that here.
2007 struct lockdep_map lockdep_map
;
2009 lockdep_copy_map(&lockdep_map
, &work
->lockdep_map
);
2011 /* ensure we're on the correct CPU */
2012 WARN_ON_ONCE(!(pool
->flags
& POOL_DISASSOCIATED
) &&
2013 raw_smp_processor_id() != pool
->cpu
);
2016 * A single work shouldn't be executed concurrently by
2017 * multiple workers on a single cpu. Check whether anyone is
2018 * already processing the work. If so, defer the work to the
2019 * currently executing one.
2021 collision
= find_worker_executing_work(pool
, work
);
2022 if (unlikely(collision
)) {
2023 move_linked_works(work
, &collision
->scheduled
, NULL
);
2027 /* claim and dequeue */
2028 debug_work_deactivate(work
);
2029 hash_add(pool
->busy_hash
, &worker
->hentry
, (unsigned long)work
);
2030 worker
->current_work
= work
;
2031 worker
->current_func
= work
->func
;
2032 worker
->current_pwq
= pwq
;
2033 work_color
= get_work_color(work
);
2035 list_del_init(&work
->entry
);
2038 * CPU intensive works don't participate in concurrency management.
2039 * They're the scheduler's responsibility. This takes @worker out
2040 * of concurrency management and the next code block will chain
2041 * execution of the pending work items.
2043 if (unlikely(cpu_intensive
))
2044 worker_set_flags(worker
, WORKER_CPU_INTENSIVE
);
2047 * Wake up another worker if necessary. The condition is always
2048 * false for normal per-cpu workers since nr_running would always
2049 * be >= 1 at this point. This is used to chain execution of the
2050 * pending work items for WORKER_NOT_RUNNING workers such as the
2051 * UNBOUND and CPU_INTENSIVE ones.
2053 if (need_more_worker(pool
))
2054 wake_up_worker(pool
);
2057 * Record the last pool and clear PENDING which should be the last
2058 * update to @work. Also, do this inside @pool->lock so that
2059 * PENDING and queued state changes happen together while IRQ is
2062 set_work_pool_and_clear_pending(work
, pool
->id
);
2064 spin_unlock_irq(&pool
->lock
);
2066 lock_map_acquire_read(&pwq
->wq
->lockdep_map
);
2067 lock_map_acquire(&lockdep_map
);
2068 trace_workqueue_execute_start(work
);
2069 worker
->current_func(work
);
2071 * While we must be careful to not use "work" after this, the trace
2072 * point will only record its address.
2074 trace_workqueue_execute_end(work
);
2075 lock_map_release(&lockdep_map
);
2076 lock_map_release(&pwq
->wq
->lockdep_map
);
2078 if (unlikely(in_atomic() || lockdep_depth(current
) > 0)) {
2079 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2080 " last function: %pf\n",
2081 current
->comm
, preempt_count(), task_pid_nr(current
),
2082 worker
->current_func
);
2083 debug_show_held_locks(current
);
2088 * The following prevents a kworker from hogging CPU on !PREEMPT
2089 * kernels, where a requeueing work item waiting for something to
2090 * happen could deadlock with stop_machine as such work item could
2091 * indefinitely requeue itself while all other CPUs are trapped in
2092 * stop_machine. At the same time, report a quiescent RCU state so
2093 * the same condition doesn't freeze RCU.
2095 cond_resched_rcu_qs();
2097 spin_lock_irq(&pool
->lock
);
2099 /* clear cpu intensive status */
2100 if (unlikely(cpu_intensive
))
2101 worker_clr_flags(worker
, WORKER_CPU_INTENSIVE
);
2103 /* we're done with it, release */
2104 hash_del(&worker
->hentry
);
2105 worker
->current_work
= NULL
;
2106 worker
->current_func
= NULL
;
2107 worker
->current_pwq
= NULL
;
2108 worker
->desc_valid
= false;
2109 pwq_dec_nr_in_flight(pwq
, work_color
);
2113 * process_scheduled_works - process scheduled works
2116 * Process all scheduled works. Please note that the scheduled list
2117 * may change while processing a work, so this function repeatedly
2118 * fetches a work from the top and executes it.
2121 * spin_lock_irq(pool->lock) which may be released and regrabbed
2124 static void process_scheduled_works(struct worker
*worker
)
2126 while (!list_empty(&worker
->scheduled
)) {
2127 struct work_struct
*work
= list_first_entry(&worker
->scheduled
,
2128 struct work_struct
, entry
);
2129 process_one_work(worker
, work
);
2134 * worker_thread - the worker thread function
2137 * The worker thread function. All workers belong to a worker_pool -
2138 * either a per-cpu one or dynamic unbound one. These workers process all
2139 * work items regardless of their specific target workqueue. The only
2140 * exception is work items which belong to workqueues with a rescuer which
2141 * will be explained in rescuer_thread().
2145 static int worker_thread(void *__worker
)
2147 struct worker
*worker
= __worker
;
2148 struct worker_pool
*pool
= worker
->pool
;
2150 /* tell the scheduler that this is a workqueue worker */
2151 worker
->task
->flags
|= PF_WQ_WORKER
;
2153 spin_lock_irq(&pool
->lock
);
2155 /* am I supposed to die? */
2156 if (unlikely(worker
->flags
& WORKER_DIE
)) {
2157 spin_unlock_irq(&pool
->lock
);
2158 WARN_ON_ONCE(!list_empty(&worker
->entry
));
2159 worker
->task
->flags
&= ~PF_WQ_WORKER
;
2161 set_task_comm(worker
->task
, "kworker/dying");
2162 ida_simple_remove(&pool
->worker_ida
, worker
->id
);
2163 worker_detach_from_pool(worker
, pool
);
2168 worker_leave_idle(worker
);
2170 /* no more worker necessary? */
2171 if (!need_more_worker(pool
))
2174 /* do we need to manage? */
2175 if (unlikely(!may_start_working(pool
)) && manage_workers(worker
))
2179 * ->scheduled list can only be filled while a worker is
2180 * preparing to process a work or actually processing it.
2181 * Make sure nobody diddled with it while I was sleeping.
2183 WARN_ON_ONCE(!list_empty(&worker
->scheduled
));
2186 * Finish PREP stage. We're guaranteed to have at least one idle
2187 * worker or that someone else has already assumed the manager
2188 * role. This is where @worker starts participating in concurrency
2189 * management if applicable and concurrency management is restored
2190 * after being rebound. See rebind_workers() for details.
2192 worker_clr_flags(worker
, WORKER_PREP
| WORKER_REBOUND
);
2195 struct work_struct
*work
=
2196 list_first_entry(&pool
->worklist
,
2197 struct work_struct
, entry
);
2199 if (likely(!(*work_data_bits(work
) & WORK_STRUCT_LINKED
))) {
2200 /* optimization path, not strictly necessary */
2201 process_one_work(worker
, work
);
2202 if (unlikely(!list_empty(&worker
->scheduled
)))
2203 process_scheduled_works(worker
);
2205 move_linked_works(work
, &worker
->scheduled
, NULL
);
2206 process_scheduled_works(worker
);
2208 } while (keep_working(pool
));
2210 worker_set_flags(worker
, WORKER_PREP
);
2213 * pool->lock is held and there's no work to process and no need to
2214 * manage, sleep. Workers are woken up only while holding
2215 * pool->lock or from local cpu, so setting the current state
2216 * before releasing pool->lock is enough to prevent losing any
2219 worker_enter_idle(worker
);
2220 __set_current_state(TASK_INTERRUPTIBLE
);
2221 spin_unlock_irq(&pool
->lock
);
2227 * rescuer_thread - the rescuer thread function
2230 * Workqueue rescuer thread function. There's one rescuer for each
2231 * workqueue which has WQ_MEM_RECLAIM set.
2233 * Regular work processing on a pool may block trying to create a new
2234 * worker which uses GFP_KERNEL allocation which has slight chance of
2235 * developing into deadlock if some works currently on the same queue
2236 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2237 * the problem rescuer solves.
2239 * When such condition is possible, the pool summons rescuers of all
2240 * workqueues which have works queued on the pool and let them process
2241 * those works so that forward progress can be guaranteed.
2243 * This should happen rarely.
2247 static int rescuer_thread(void *__rescuer
)
2249 struct worker
*rescuer
= __rescuer
;
2250 struct workqueue_struct
*wq
= rescuer
->rescue_wq
;
2251 struct list_head
*scheduled
= &rescuer
->scheduled
;
2254 set_user_nice(current
, RESCUER_NICE_LEVEL
);
2257 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2258 * doesn't participate in concurrency management.
2260 rescuer
->task
->flags
|= PF_WQ_WORKER
;
2262 set_current_state(TASK_INTERRUPTIBLE
);
2265 * By the time the rescuer is requested to stop, the workqueue
2266 * shouldn't have any work pending, but @wq->maydays may still have
2267 * pwq(s) queued. This can happen by non-rescuer workers consuming
2268 * all the work items before the rescuer got to them. Go through
2269 * @wq->maydays processing before acting on should_stop so that the
2270 * list is always empty on exit.
2272 should_stop
= kthread_should_stop();
2274 /* see whether any pwq is asking for help */
2275 spin_lock_irq(&wq_mayday_lock
);
2277 while (!list_empty(&wq
->maydays
)) {
2278 struct pool_workqueue
*pwq
= list_first_entry(&wq
->maydays
,
2279 struct pool_workqueue
, mayday_node
);
2280 struct worker_pool
*pool
= pwq
->pool
;
2281 struct work_struct
*work
, *n
;
2283 __set_current_state(TASK_RUNNING
);
2284 list_del_init(&pwq
->mayday_node
);
2286 spin_unlock_irq(&wq_mayday_lock
);
2288 worker_attach_to_pool(rescuer
, pool
);
2290 spin_lock_irq(&pool
->lock
);
2291 rescuer
->pool
= pool
;
2294 * Slurp in all works issued via this workqueue and
2297 WARN_ON_ONCE(!list_empty(scheduled
));
2298 list_for_each_entry_safe(work
, n
, &pool
->worklist
, entry
)
2299 if (get_work_pwq(work
) == pwq
)
2300 move_linked_works(work
, scheduled
, &n
);
2302 if (!list_empty(scheduled
)) {
2303 process_scheduled_works(rescuer
);
2306 * The above execution of rescued work items could
2307 * have created more to rescue through
2308 * pwq_activate_first_delayed() or chained
2309 * queueing. Let's put @pwq back on mayday list so
2310 * that such back-to-back work items, which may be
2311 * being used to relieve memory pressure, don't
2312 * incur MAYDAY_INTERVAL delay inbetween.
2314 if (need_to_create_worker(pool
)) {
2315 spin_lock(&wq_mayday_lock
);
2317 list_move_tail(&pwq
->mayday_node
, &wq
->maydays
);
2318 spin_unlock(&wq_mayday_lock
);
2323 * Put the reference grabbed by send_mayday(). @pool won't
2324 * go away while we're still attached to it.
2329 * Leave this pool. If need_more_worker() is %true, notify a
2330 * regular worker; otherwise, we end up with 0 concurrency
2331 * and stalling the execution.
2333 if (need_more_worker(pool
))
2334 wake_up_worker(pool
);
2336 rescuer
->pool
= NULL
;
2337 spin_unlock_irq(&pool
->lock
);
2339 worker_detach_from_pool(rescuer
, pool
);
2341 spin_lock_irq(&wq_mayday_lock
);
2344 spin_unlock_irq(&wq_mayday_lock
);
2347 __set_current_state(TASK_RUNNING
);
2348 rescuer
->task
->flags
&= ~PF_WQ_WORKER
;
2352 /* rescuers should never participate in concurrency management */
2353 WARN_ON_ONCE(!(rescuer
->flags
& WORKER_NOT_RUNNING
));
2359 struct work_struct work
;
2360 struct completion done
;
2361 struct task_struct
*task
; /* purely informational */
2364 static void wq_barrier_func(struct work_struct
*work
)
2366 struct wq_barrier
*barr
= container_of(work
, struct wq_barrier
, work
);
2367 complete(&barr
->done
);
2371 * insert_wq_barrier - insert a barrier work
2372 * @pwq: pwq to insert barrier into
2373 * @barr: wq_barrier to insert
2374 * @target: target work to attach @barr to
2375 * @worker: worker currently executing @target, NULL if @target is not executing
2377 * @barr is linked to @target such that @barr is completed only after
2378 * @target finishes execution. Please note that the ordering
2379 * guarantee is observed only with respect to @target and on the local
2382 * Currently, a queued barrier can't be canceled. This is because
2383 * try_to_grab_pending() can't determine whether the work to be
2384 * grabbed is at the head of the queue and thus can't clear LINKED
2385 * flag of the previous work while there must be a valid next work
2386 * after a work with LINKED flag set.
2388 * Note that when @worker is non-NULL, @target may be modified
2389 * underneath us, so we can't reliably determine pwq from @target.
2392 * spin_lock_irq(pool->lock).
2394 static void insert_wq_barrier(struct pool_workqueue
*pwq
,
2395 struct wq_barrier
*barr
,
2396 struct work_struct
*target
, struct worker
*worker
)
2398 struct list_head
*head
;
2399 unsigned int linked
= 0;
2402 * debugobject calls are safe here even with pool->lock locked
2403 * as we know for sure that this will not trigger any of the
2404 * checks and call back into the fixup functions where we
2407 INIT_WORK_ONSTACK(&barr
->work
, wq_barrier_func
);
2408 __set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(&barr
->work
));
2409 init_completion(&barr
->done
);
2410 barr
->task
= current
;
2413 * If @target is currently being executed, schedule the
2414 * barrier to the worker; otherwise, put it after @target.
2417 head
= worker
->scheduled
.next
;
2419 unsigned long *bits
= work_data_bits(target
);
2421 head
= target
->entry
.next
;
2422 /* there can already be other linked works, inherit and set */
2423 linked
= *bits
& WORK_STRUCT_LINKED
;
2424 __set_bit(WORK_STRUCT_LINKED_BIT
, bits
);
2427 debug_work_activate(&barr
->work
);
2428 insert_work(pwq
, &barr
->work
, head
,
2429 work_color_to_flags(WORK_NO_COLOR
) | linked
);
2433 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2434 * @wq: workqueue being flushed
2435 * @flush_color: new flush color, < 0 for no-op
2436 * @work_color: new work color, < 0 for no-op
2438 * Prepare pwqs for workqueue flushing.
2440 * If @flush_color is non-negative, flush_color on all pwqs should be
2441 * -1. If no pwq has in-flight commands at the specified color, all
2442 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2443 * has in flight commands, its pwq->flush_color is set to
2444 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2445 * wakeup logic is armed and %true is returned.
2447 * The caller should have initialized @wq->first_flusher prior to
2448 * calling this function with non-negative @flush_color. If
2449 * @flush_color is negative, no flush color update is done and %false
2452 * If @work_color is non-negative, all pwqs should have the same
2453 * work_color which is previous to @work_color and all will be
2454 * advanced to @work_color.
2457 * mutex_lock(wq->mutex).
2460 * %true if @flush_color >= 0 and there's something to flush. %false
2463 static bool flush_workqueue_prep_pwqs(struct workqueue_struct
*wq
,
2464 int flush_color
, int work_color
)
2467 struct pool_workqueue
*pwq
;
2469 if (flush_color
>= 0) {
2470 WARN_ON_ONCE(atomic_read(&wq
->nr_pwqs_to_flush
));
2471 atomic_set(&wq
->nr_pwqs_to_flush
, 1);
2474 for_each_pwq(pwq
, wq
) {
2475 struct worker_pool
*pool
= pwq
->pool
;
2477 spin_lock_irq(&pool
->lock
);
2479 if (flush_color
>= 0) {
2480 WARN_ON_ONCE(pwq
->flush_color
!= -1);
2482 if (pwq
->nr_in_flight
[flush_color
]) {
2483 pwq
->flush_color
= flush_color
;
2484 atomic_inc(&wq
->nr_pwqs_to_flush
);
2489 if (work_color
>= 0) {
2490 WARN_ON_ONCE(work_color
!= work_next_color(pwq
->work_color
));
2491 pwq
->work_color
= work_color
;
2494 spin_unlock_irq(&pool
->lock
);
2497 if (flush_color
>= 0 && atomic_dec_and_test(&wq
->nr_pwqs_to_flush
))
2498 complete(&wq
->first_flusher
->done
);
2504 * flush_workqueue - ensure that any scheduled work has run to completion.
2505 * @wq: workqueue to flush
2507 * This function sleeps until all work items which were queued on entry
2508 * have finished execution, but it is not livelocked by new incoming ones.
2510 void flush_workqueue(struct workqueue_struct
*wq
)
2512 struct wq_flusher this_flusher
= {
2513 .list
= LIST_HEAD_INIT(this_flusher
.list
),
2515 .done
= COMPLETION_INITIALIZER_ONSTACK(this_flusher
.done
),
2519 lock_map_acquire(&wq
->lockdep_map
);
2520 lock_map_release(&wq
->lockdep_map
);
2522 mutex_lock(&wq
->mutex
);
2525 * Start-to-wait phase
2527 next_color
= work_next_color(wq
->work_color
);
2529 if (next_color
!= wq
->flush_color
) {
2531 * Color space is not full. The current work_color
2532 * becomes our flush_color and work_color is advanced
2535 WARN_ON_ONCE(!list_empty(&wq
->flusher_overflow
));
2536 this_flusher
.flush_color
= wq
->work_color
;
2537 wq
->work_color
= next_color
;
2539 if (!wq
->first_flusher
) {
2540 /* no flush in progress, become the first flusher */
2541 WARN_ON_ONCE(wq
->flush_color
!= this_flusher
.flush_color
);
2543 wq
->first_flusher
= &this_flusher
;
2545 if (!flush_workqueue_prep_pwqs(wq
, wq
->flush_color
,
2547 /* nothing to flush, done */
2548 wq
->flush_color
= next_color
;
2549 wq
->first_flusher
= NULL
;
2554 WARN_ON_ONCE(wq
->flush_color
== this_flusher
.flush_color
);
2555 list_add_tail(&this_flusher
.list
, &wq
->flusher_queue
);
2556 flush_workqueue_prep_pwqs(wq
, -1, wq
->work_color
);
2560 * Oops, color space is full, wait on overflow queue.
2561 * The next flush completion will assign us
2562 * flush_color and transfer to flusher_queue.
2564 list_add_tail(&this_flusher
.list
, &wq
->flusher_overflow
);
2567 mutex_unlock(&wq
->mutex
);
2569 wait_for_completion(&this_flusher
.done
);
2572 * Wake-up-and-cascade phase
2574 * First flushers are responsible for cascading flushes and
2575 * handling overflow. Non-first flushers can simply return.
2577 if (wq
->first_flusher
!= &this_flusher
)
2580 mutex_lock(&wq
->mutex
);
2582 /* we might have raced, check again with mutex held */
2583 if (wq
->first_flusher
!= &this_flusher
)
2586 wq
->first_flusher
= NULL
;
2588 WARN_ON_ONCE(!list_empty(&this_flusher
.list
));
2589 WARN_ON_ONCE(wq
->flush_color
!= this_flusher
.flush_color
);
2592 struct wq_flusher
*next
, *tmp
;
2594 /* complete all the flushers sharing the current flush color */
2595 list_for_each_entry_safe(next
, tmp
, &wq
->flusher_queue
, list
) {
2596 if (next
->flush_color
!= wq
->flush_color
)
2598 list_del_init(&next
->list
);
2599 complete(&next
->done
);
2602 WARN_ON_ONCE(!list_empty(&wq
->flusher_overflow
) &&
2603 wq
->flush_color
!= work_next_color(wq
->work_color
));
2605 /* this flush_color is finished, advance by one */
2606 wq
->flush_color
= work_next_color(wq
->flush_color
);
2608 /* one color has been freed, handle overflow queue */
2609 if (!list_empty(&wq
->flusher_overflow
)) {
2611 * Assign the same color to all overflowed
2612 * flushers, advance work_color and append to
2613 * flusher_queue. This is the start-to-wait
2614 * phase for these overflowed flushers.
2616 list_for_each_entry(tmp
, &wq
->flusher_overflow
, list
)
2617 tmp
->flush_color
= wq
->work_color
;
2619 wq
->work_color
= work_next_color(wq
->work_color
);
2621 list_splice_tail_init(&wq
->flusher_overflow
,
2622 &wq
->flusher_queue
);
2623 flush_workqueue_prep_pwqs(wq
, -1, wq
->work_color
);
2626 if (list_empty(&wq
->flusher_queue
)) {
2627 WARN_ON_ONCE(wq
->flush_color
!= wq
->work_color
);
2632 * Need to flush more colors. Make the next flusher
2633 * the new first flusher and arm pwqs.
2635 WARN_ON_ONCE(wq
->flush_color
== wq
->work_color
);
2636 WARN_ON_ONCE(wq
->flush_color
!= next
->flush_color
);
2638 list_del_init(&next
->list
);
2639 wq
->first_flusher
= next
;
2641 if (flush_workqueue_prep_pwqs(wq
, wq
->flush_color
, -1))
2645 * Meh... this color is already done, clear first
2646 * flusher and repeat cascading.
2648 wq
->first_flusher
= NULL
;
2652 mutex_unlock(&wq
->mutex
);
2654 EXPORT_SYMBOL(flush_workqueue
);
2657 * drain_workqueue - drain a workqueue
2658 * @wq: workqueue to drain
2660 * Wait until the workqueue becomes empty. While draining is in progress,
2661 * only chain queueing is allowed. IOW, only currently pending or running
2662 * work items on @wq can queue further work items on it. @wq is flushed
2663 * repeatedly until it becomes empty. The number of flushing is determined
2664 * by the depth of chaining and should be relatively short. Whine if it
2667 void drain_workqueue(struct workqueue_struct
*wq
)
2669 unsigned int flush_cnt
= 0;
2670 struct pool_workqueue
*pwq
;
2673 * __queue_work() needs to test whether there are drainers, is much
2674 * hotter than drain_workqueue() and already looks at @wq->flags.
2675 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
2677 mutex_lock(&wq
->mutex
);
2678 if (!wq
->nr_drainers
++)
2679 wq
->flags
|= __WQ_DRAINING
;
2680 mutex_unlock(&wq
->mutex
);
2682 flush_workqueue(wq
);
2684 mutex_lock(&wq
->mutex
);
2686 for_each_pwq(pwq
, wq
) {
2689 spin_lock_irq(&pwq
->pool
->lock
);
2690 drained
= !pwq
->nr_active
&& list_empty(&pwq
->delayed_works
);
2691 spin_unlock_irq(&pwq
->pool
->lock
);
2696 if (++flush_cnt
== 10 ||
2697 (flush_cnt
% 100 == 0 && flush_cnt
<= 1000))
2698 pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
2699 wq
->name
, flush_cnt
);
2701 mutex_unlock(&wq
->mutex
);
2705 if (!--wq
->nr_drainers
)
2706 wq
->flags
&= ~__WQ_DRAINING
;
2707 mutex_unlock(&wq
->mutex
);
2709 EXPORT_SYMBOL_GPL(drain_workqueue
);
2711 static bool start_flush_work(struct work_struct
*work
, struct wq_barrier
*barr
)
2713 struct worker
*worker
= NULL
;
2714 struct worker_pool
*pool
;
2715 struct pool_workqueue
*pwq
;
2719 local_irq_disable();
2720 pool
= get_work_pool(work
);
2726 spin_lock(&pool
->lock
);
2727 /* see the comment in try_to_grab_pending() with the same code */
2728 pwq
= get_work_pwq(work
);
2730 if (unlikely(pwq
->pool
!= pool
))
2733 worker
= find_worker_executing_work(pool
, work
);
2736 pwq
= worker
->current_pwq
;
2739 insert_wq_barrier(pwq
, barr
, work
, worker
);
2740 spin_unlock_irq(&pool
->lock
);
2743 * If @max_active is 1 or rescuer is in use, flushing another work
2744 * item on the same workqueue may lead to deadlock. Make sure the
2745 * flusher is not running on the same workqueue by verifying write
2748 if (pwq
->wq
->saved_max_active
== 1 || pwq
->wq
->rescuer
)
2749 lock_map_acquire(&pwq
->wq
->lockdep_map
);
2751 lock_map_acquire_read(&pwq
->wq
->lockdep_map
);
2752 lock_map_release(&pwq
->wq
->lockdep_map
);
2756 spin_unlock_irq(&pool
->lock
);
2761 * flush_work - wait for a work to finish executing the last queueing instance
2762 * @work: the work to flush
2764 * Wait until @work has finished execution. @work is guaranteed to be idle
2765 * on return if it hasn't been requeued since flush started.
2768 * %true if flush_work() waited for the work to finish execution,
2769 * %false if it was already idle.
2771 bool flush_work(struct work_struct
*work
)
2773 struct wq_barrier barr
;
2775 lock_map_acquire(&work
->lockdep_map
);
2776 lock_map_release(&work
->lockdep_map
);
2778 if (start_flush_work(work
, &barr
)) {
2779 wait_for_completion(&barr
.done
);
2780 destroy_work_on_stack(&barr
.work
);
2786 EXPORT_SYMBOL_GPL(flush_work
);
2790 struct work_struct
*work
;
2793 static int cwt_wakefn(wait_queue_t
*wait
, unsigned mode
, int sync
, void *key
)
2795 struct cwt_wait
*cwait
= container_of(wait
, struct cwt_wait
, wait
);
2797 if (cwait
->work
!= key
)
2799 return autoremove_wake_function(wait
, mode
, sync
, key
);
2802 static bool __cancel_work_timer(struct work_struct
*work
, bool is_dwork
)
2804 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq
);
2805 unsigned long flags
;
2809 ret
= try_to_grab_pending(work
, is_dwork
, &flags
);
2811 * If someone else is already canceling, wait for it to
2812 * finish. flush_work() doesn't work for PREEMPT_NONE
2813 * because we may get scheduled between @work's completion
2814 * and the other canceling task resuming and clearing
2815 * CANCELING - flush_work() will return false immediately
2816 * as @work is no longer busy, try_to_grab_pending() will
2817 * return -ENOENT as @work is still being canceled and the
2818 * other canceling task won't be able to clear CANCELING as
2819 * we're hogging the CPU.
2821 * Let's wait for completion using a waitqueue. As this
2822 * may lead to the thundering herd problem, use a custom
2823 * wake function which matches @work along with exclusive
2826 if (unlikely(ret
== -ENOENT
)) {
2827 struct cwt_wait cwait
;
2829 init_wait(&cwait
.wait
);
2830 cwait
.wait
.func
= cwt_wakefn
;
2833 prepare_to_wait_exclusive(&cancel_waitq
, &cwait
.wait
,
2834 TASK_UNINTERRUPTIBLE
);
2835 if (work_is_canceling(work
))
2837 finish_wait(&cancel_waitq
, &cwait
.wait
);
2839 } while (unlikely(ret
< 0));
2841 /* tell other tasks trying to grab @work to back off */
2842 mark_work_canceling(work
);
2843 local_irq_restore(flags
);
2846 clear_work_data(work
);
2849 * Paired with prepare_to_wait() above so that either
2850 * waitqueue_active() is visible here or !work_is_canceling() is
2854 if (waitqueue_active(&cancel_waitq
))
2855 __wake_up(&cancel_waitq
, TASK_NORMAL
, 1, work
);
2861 * cancel_work_sync - cancel a work and wait for it to finish
2862 * @work: the work to cancel
2864 * Cancel @work and wait for its execution to finish. This function
2865 * can be used even if the work re-queues itself or migrates to
2866 * another workqueue. On return from this function, @work is
2867 * guaranteed to be not pending or executing on any CPU.
2869 * cancel_work_sync(&delayed_work->work) must not be used for
2870 * delayed_work's. Use cancel_delayed_work_sync() instead.
2872 * The caller must ensure that the workqueue on which @work was last
2873 * queued can't be destroyed before this function returns.
2876 * %true if @work was pending, %false otherwise.
2878 bool cancel_work_sync(struct work_struct
*work
)
2880 return __cancel_work_timer(work
, false);
2882 EXPORT_SYMBOL_GPL(cancel_work_sync
);
2885 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2886 * @dwork: the delayed work to flush
2888 * Delayed timer is cancelled and the pending work is queued for
2889 * immediate execution. Like flush_work(), this function only
2890 * considers the last queueing instance of @dwork.
2893 * %true if flush_work() waited for the work to finish execution,
2894 * %false if it was already idle.
2896 bool flush_delayed_work(struct delayed_work
*dwork
)
2898 local_irq_disable();
2899 if (del_timer_sync(&dwork
->timer
))
2900 __queue_work(dwork
->cpu
, dwork
->wq
, &dwork
->work
);
2902 return flush_work(&dwork
->work
);
2904 EXPORT_SYMBOL(flush_delayed_work
);
2907 * cancel_delayed_work - cancel a delayed work
2908 * @dwork: delayed_work to cancel
2910 * Kill off a pending delayed_work.
2912 * Return: %true if @dwork was pending and canceled; %false if it wasn't
2916 * The work callback function may still be running on return, unless
2917 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
2918 * use cancel_delayed_work_sync() to wait on it.
2920 * This function is safe to call from any context including IRQ handler.
2922 bool cancel_delayed_work(struct delayed_work
*dwork
)
2924 unsigned long flags
;
2928 ret
= try_to_grab_pending(&dwork
->work
, true, &flags
);
2929 } while (unlikely(ret
== -EAGAIN
));
2931 if (unlikely(ret
< 0))
2934 set_work_pool_and_clear_pending(&dwork
->work
,
2935 get_work_pool_id(&dwork
->work
));
2936 local_irq_restore(flags
);
2939 EXPORT_SYMBOL(cancel_delayed_work
);
2942 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2943 * @dwork: the delayed work cancel
2945 * This is cancel_work_sync() for delayed works.
2948 * %true if @dwork was pending, %false otherwise.
2950 bool cancel_delayed_work_sync(struct delayed_work
*dwork
)
2952 return __cancel_work_timer(&dwork
->work
, true);
2954 EXPORT_SYMBOL(cancel_delayed_work_sync
);
2957 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2958 * @func: the function to call
2960 * schedule_on_each_cpu() executes @func on each online CPU using the
2961 * system workqueue and blocks until all CPUs have completed.
2962 * schedule_on_each_cpu() is very slow.
2965 * 0 on success, -errno on failure.
2967 int schedule_on_each_cpu(work_func_t func
)
2970 struct work_struct __percpu
*works
;
2972 works
= alloc_percpu(struct work_struct
);
2978 for_each_online_cpu(cpu
) {
2979 struct work_struct
*work
= per_cpu_ptr(works
, cpu
);
2981 INIT_WORK(work
, func
);
2982 schedule_work_on(cpu
, work
);
2985 for_each_online_cpu(cpu
)
2986 flush_work(per_cpu_ptr(works
, cpu
));
2994 * execute_in_process_context - reliably execute the routine with user context
2995 * @fn: the function to execute
2996 * @ew: guaranteed storage for the execute work structure (must
2997 * be available when the work executes)
2999 * Executes the function immediately if process context is available,
3000 * otherwise schedules the function for delayed execution.
3002 * Return: 0 - function was executed
3003 * 1 - function was scheduled for execution
3005 int execute_in_process_context(work_func_t fn
, struct execute_work
*ew
)
3007 if (!in_interrupt()) {
3012 INIT_WORK(&ew
->work
, fn
);
3013 schedule_work(&ew
->work
);
3017 EXPORT_SYMBOL_GPL(execute_in_process_context
);
3020 * free_workqueue_attrs - free a workqueue_attrs
3021 * @attrs: workqueue_attrs to free
3023 * Undo alloc_workqueue_attrs().
3025 void free_workqueue_attrs(struct workqueue_attrs
*attrs
)
3028 free_cpumask_var(attrs
->cpumask
);
3034 * alloc_workqueue_attrs - allocate a workqueue_attrs
3035 * @gfp_mask: allocation mask to use
3037 * Allocate a new workqueue_attrs, initialize with default settings and
3040 * Return: The allocated new workqueue_attr on success. %NULL on failure.
3042 struct workqueue_attrs
*alloc_workqueue_attrs(gfp_t gfp_mask
)
3044 struct workqueue_attrs
*attrs
;
3046 attrs
= kzalloc(sizeof(*attrs
), gfp_mask
);
3049 if (!alloc_cpumask_var(&attrs
->cpumask
, gfp_mask
))
3052 cpumask_copy(attrs
->cpumask
, cpu_possible_mask
);
3055 free_workqueue_attrs(attrs
);
3059 static void copy_workqueue_attrs(struct workqueue_attrs
*to
,
3060 const struct workqueue_attrs
*from
)
3062 to
->nice
= from
->nice
;
3063 cpumask_copy(to
->cpumask
, from
->cpumask
);
3065 * Unlike hash and equality test, this function doesn't ignore
3066 * ->no_numa as it is used for both pool and wq attrs. Instead,
3067 * get_unbound_pool() explicitly clears ->no_numa after copying.
3069 to
->no_numa
= from
->no_numa
;
3072 /* hash value of the content of @attr */
3073 static u32
wqattrs_hash(const struct workqueue_attrs
*attrs
)
3077 hash
= jhash_1word(attrs
->nice
, hash
);
3078 hash
= jhash(cpumask_bits(attrs
->cpumask
),
3079 BITS_TO_LONGS(nr_cpumask_bits
) * sizeof(long), hash
);
3083 /* content equality test */
3084 static bool wqattrs_equal(const struct workqueue_attrs
*a
,
3085 const struct workqueue_attrs
*b
)
3087 if (a
->nice
!= b
->nice
)
3089 if (!cpumask_equal(a
->cpumask
, b
->cpumask
))
3095 * init_worker_pool - initialize a newly zalloc'd worker_pool
3096 * @pool: worker_pool to initialize
3098 * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
3100 * Return: 0 on success, -errno on failure. Even on failure, all fields
3101 * inside @pool proper are initialized and put_unbound_pool() can be called
3102 * on @pool safely to release it.
3104 static int init_worker_pool(struct worker_pool
*pool
)
3106 spin_lock_init(&pool
->lock
);
3109 pool
->node
= NUMA_NO_NODE
;
3110 pool
->flags
|= POOL_DISASSOCIATED
;
3111 INIT_LIST_HEAD(&pool
->worklist
);
3112 INIT_LIST_HEAD(&pool
->idle_list
);
3113 hash_init(pool
->busy_hash
);
3115 init_timer_deferrable(&pool
->idle_timer
);
3116 pool
->idle_timer
.function
= idle_worker_timeout
;
3117 pool
->idle_timer
.data
= (unsigned long)pool
;
3119 setup_timer(&pool
->mayday_timer
, pool_mayday_timeout
,
3120 (unsigned long)pool
);
3122 mutex_init(&pool
->manager_arb
);
3123 mutex_init(&pool
->attach_mutex
);
3124 INIT_LIST_HEAD(&pool
->workers
);
3126 ida_init(&pool
->worker_ida
);
3127 INIT_HLIST_NODE(&pool
->hash_node
);
3130 /* shouldn't fail above this point */
3131 pool
->attrs
= alloc_workqueue_attrs(GFP_KERNEL
);
3137 static void rcu_free_wq(struct rcu_head
*rcu
)
3139 struct workqueue_struct
*wq
=
3140 container_of(rcu
, struct workqueue_struct
, rcu
);
3142 if (!(wq
->flags
& WQ_UNBOUND
))
3143 free_percpu(wq
->cpu_pwqs
);
3145 free_workqueue_attrs(wq
->unbound_attrs
);
3151 static void rcu_free_pool(struct rcu_head
*rcu
)
3153 struct worker_pool
*pool
= container_of(rcu
, struct worker_pool
, rcu
);
3155 ida_destroy(&pool
->worker_ida
);
3156 free_workqueue_attrs(pool
->attrs
);
3161 * put_unbound_pool - put a worker_pool
3162 * @pool: worker_pool to put
3164 * Put @pool. If its refcnt reaches zero, it gets destroyed in sched-RCU
3165 * safe manner. get_unbound_pool() calls this function on its failure path
3166 * and this function should be able to release pools which went through,
3167 * successfully or not, init_worker_pool().
3169 * Should be called with wq_pool_mutex held.
3171 static void put_unbound_pool(struct worker_pool
*pool
)
3173 DECLARE_COMPLETION_ONSTACK(detach_completion
);
3174 struct worker
*worker
;
3176 lockdep_assert_held(&wq_pool_mutex
);
3182 if (WARN_ON(!(pool
->cpu
< 0)) ||
3183 WARN_ON(!list_empty(&pool
->worklist
)))
3186 /* release id and unhash */
3188 idr_remove(&worker_pool_idr
, pool
->id
);
3189 hash_del(&pool
->hash_node
);
3192 * Become the manager and destroy all workers. Grabbing
3193 * manager_arb prevents @pool's workers from blocking on
3196 mutex_lock(&pool
->manager_arb
);
3198 spin_lock_irq(&pool
->lock
);
3199 while ((worker
= first_idle_worker(pool
)))
3200 destroy_worker(worker
);
3201 WARN_ON(pool
->nr_workers
|| pool
->nr_idle
);
3202 spin_unlock_irq(&pool
->lock
);
3204 mutex_lock(&pool
->attach_mutex
);
3205 if (!list_empty(&pool
->workers
))
3206 pool
->detach_completion
= &detach_completion
;
3207 mutex_unlock(&pool
->attach_mutex
);
3209 if (pool
->detach_completion
)
3210 wait_for_completion(pool
->detach_completion
);
3212 mutex_unlock(&pool
->manager_arb
);
3214 /* shut down the timers */
3215 del_timer_sync(&pool
->idle_timer
);
3216 del_timer_sync(&pool
->mayday_timer
);
3218 /* sched-RCU protected to allow dereferences from get_work_pool() */
3219 call_rcu_sched(&pool
->rcu
, rcu_free_pool
);
3223 * get_unbound_pool - get a worker_pool with the specified attributes
3224 * @attrs: the attributes of the worker_pool to get
3226 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3227 * reference count and return it. If there already is a matching
3228 * worker_pool, it will be used; otherwise, this function attempts to
3231 * Should be called with wq_pool_mutex held.
3233 * Return: On success, a worker_pool with the same attributes as @attrs.
3234 * On failure, %NULL.
3236 static struct worker_pool
*get_unbound_pool(const struct workqueue_attrs
*attrs
)
3238 u32 hash
= wqattrs_hash(attrs
);
3239 struct worker_pool
*pool
;
3241 int target_node
= NUMA_NO_NODE
;
3243 lockdep_assert_held(&wq_pool_mutex
);
3245 /* do we already have a matching pool? */
3246 hash_for_each_possible(unbound_pool_hash
, pool
, hash_node
, hash
) {
3247 if (wqattrs_equal(pool
->attrs
, attrs
)) {
3253 /* if cpumask is contained inside a NUMA node, we belong to that node */
3254 if (wq_numa_enabled
) {
3255 for_each_node(node
) {
3256 if (cpumask_subset(attrs
->cpumask
,
3257 wq_numa_possible_cpumask
[node
])) {
3264 /* nope, create a new one */
3265 pool
= kzalloc_node(sizeof(*pool
), GFP_KERNEL
, target_node
);
3266 if (!pool
|| init_worker_pool(pool
) < 0)
3269 lockdep_set_subclass(&pool
->lock
, 1); /* see put_pwq() */
3270 copy_workqueue_attrs(pool
->attrs
, attrs
);
3271 pool
->node
= target_node
;
3274 * no_numa isn't a worker_pool attribute, always clear it. See
3275 * 'struct workqueue_attrs' comments for detail.
3277 pool
->attrs
->no_numa
= false;
3279 if (worker_pool_assign_id(pool
) < 0)
3282 /* create and start the initial worker */
3283 if (!create_worker(pool
))
3287 hash_add(unbound_pool_hash
, &pool
->hash_node
, hash
);
3292 put_unbound_pool(pool
);
3296 static void rcu_free_pwq(struct rcu_head
*rcu
)
3298 kmem_cache_free(pwq_cache
,
3299 container_of(rcu
, struct pool_workqueue
, rcu
));
3303 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
3304 * and needs to be destroyed.
3306 static void pwq_unbound_release_workfn(struct work_struct
*work
)
3308 struct pool_workqueue
*pwq
= container_of(work
, struct pool_workqueue
,
3309 unbound_release_work
);
3310 struct workqueue_struct
*wq
= pwq
->wq
;
3311 struct worker_pool
*pool
= pwq
->pool
;
3314 if (WARN_ON_ONCE(!(wq
->flags
& WQ_UNBOUND
)))
3317 mutex_lock(&wq
->mutex
);
3318 list_del_rcu(&pwq
->pwqs_node
);
3319 is_last
= list_empty(&wq
->pwqs
);
3320 mutex_unlock(&wq
->mutex
);
3322 mutex_lock(&wq_pool_mutex
);
3323 put_unbound_pool(pool
);
3324 mutex_unlock(&wq_pool_mutex
);
3326 call_rcu_sched(&pwq
->rcu
, rcu_free_pwq
);
3329 * If we're the last pwq going away, @wq is already dead and no one
3330 * is gonna access it anymore. Schedule RCU free.
3333 call_rcu_sched(&wq
->rcu
, rcu_free_wq
);
3337 * pwq_adjust_max_active - update a pwq's max_active to the current setting
3338 * @pwq: target pool_workqueue
3340 * If @pwq isn't freezing, set @pwq->max_active to the associated
3341 * workqueue's saved_max_active and activate delayed work items
3342 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
3344 static void pwq_adjust_max_active(struct pool_workqueue
*pwq
)
3346 struct workqueue_struct
*wq
= pwq
->wq
;
3347 bool freezable
= wq
->flags
& WQ_FREEZABLE
;
3349 /* for @wq->saved_max_active */
3350 lockdep_assert_held(&wq
->mutex
);
3352 /* fast exit for non-freezable wqs */
3353 if (!freezable
&& pwq
->max_active
== wq
->saved_max_active
)
3356 spin_lock_irq(&pwq
->pool
->lock
);
3359 * During [un]freezing, the caller is responsible for ensuring that
3360 * this function is called at least once after @workqueue_freezing
3361 * is updated and visible.
3363 if (!freezable
|| !workqueue_freezing
) {
3364 pwq
->max_active
= wq
->saved_max_active
;
3366 while (!list_empty(&pwq
->delayed_works
) &&
3367 pwq
->nr_active
< pwq
->max_active
)
3368 pwq_activate_first_delayed(pwq
);
3371 * Need to kick a worker after thawed or an unbound wq's
3372 * max_active is bumped. It's a slow path. Do it always.
3374 wake_up_worker(pwq
->pool
);
3376 pwq
->max_active
= 0;
3379 spin_unlock_irq(&pwq
->pool
->lock
);
3382 /* initialize newly alloced @pwq which is associated with @wq and @pool */
3383 static void init_pwq(struct pool_workqueue
*pwq
, struct workqueue_struct
*wq
,
3384 struct worker_pool
*pool
)
3386 BUG_ON((unsigned long)pwq
& WORK_STRUCT_FLAG_MASK
);
3388 memset(pwq
, 0, sizeof(*pwq
));
3392 pwq
->flush_color
= -1;
3394 INIT_LIST_HEAD(&pwq
->delayed_works
);
3395 INIT_LIST_HEAD(&pwq
->pwqs_node
);
3396 INIT_LIST_HEAD(&pwq
->mayday_node
);
3397 INIT_WORK(&pwq
->unbound_release_work
, pwq_unbound_release_workfn
);
3400 /* sync @pwq with the current state of its associated wq and link it */
3401 static void link_pwq(struct pool_workqueue
*pwq
)
3403 struct workqueue_struct
*wq
= pwq
->wq
;
3405 lockdep_assert_held(&wq
->mutex
);
3407 /* may be called multiple times, ignore if already linked */
3408 if (!list_empty(&pwq
->pwqs_node
))
3411 /* set the matching work_color */
3412 pwq
->work_color
= wq
->work_color
;
3414 /* sync max_active to the current setting */
3415 pwq_adjust_max_active(pwq
);
3418 list_add_rcu(&pwq
->pwqs_node
, &wq
->pwqs
);
3421 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3422 static struct pool_workqueue
*alloc_unbound_pwq(struct workqueue_struct
*wq
,
3423 const struct workqueue_attrs
*attrs
)
3425 struct worker_pool
*pool
;
3426 struct pool_workqueue
*pwq
;
3428 lockdep_assert_held(&wq_pool_mutex
);
3430 pool
= get_unbound_pool(attrs
);
3434 pwq
= kmem_cache_alloc_node(pwq_cache
, GFP_KERNEL
, pool
->node
);
3436 put_unbound_pool(pool
);
3440 init_pwq(pwq
, wq
, pool
);
3445 * wq_calc_node_cpumask - calculate a wq_attrs' cpumask for the specified node
3446 * @attrs: the wq_attrs of the default pwq of the target workqueue
3447 * @node: the target NUMA node
3448 * @cpu_going_down: if >= 0, the CPU to consider as offline
3449 * @cpumask: outarg, the resulting cpumask
3451 * Calculate the cpumask a workqueue with @attrs should use on @node. If
3452 * @cpu_going_down is >= 0, that cpu is considered offline during
3453 * calculation. The result is stored in @cpumask.
3455 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
3456 * enabled and @node has online CPUs requested by @attrs, the returned
3457 * cpumask is the intersection of the possible CPUs of @node and
3460 * The caller is responsible for ensuring that the cpumask of @node stays
3463 * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3466 static bool wq_calc_node_cpumask(const struct workqueue_attrs
*attrs
, int node
,
3467 int cpu_going_down
, cpumask_t
*cpumask
)
3469 if (!wq_numa_enabled
|| attrs
->no_numa
)
3472 /* does @node have any online CPUs @attrs wants? */
3473 cpumask_and(cpumask
, cpumask_of_node(node
), attrs
->cpumask
);
3474 if (cpu_going_down
>= 0)
3475 cpumask_clear_cpu(cpu_going_down
, cpumask
);
3477 if (cpumask_empty(cpumask
))
3480 /* yeap, return possible CPUs in @node that @attrs wants */
3481 cpumask_and(cpumask
, attrs
->cpumask
, wq_numa_possible_cpumask
[node
]);
3482 return !cpumask_equal(cpumask
, attrs
->cpumask
);
3485 cpumask_copy(cpumask
, attrs
->cpumask
);
3489 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
3490 static struct pool_workqueue
*numa_pwq_tbl_install(struct workqueue_struct
*wq
,
3492 struct pool_workqueue
*pwq
)
3494 struct pool_workqueue
*old_pwq
;
3496 lockdep_assert_held(&wq_pool_mutex
);
3497 lockdep_assert_held(&wq
->mutex
);
3499 /* link_pwq() can handle duplicate calls */
3502 old_pwq
= rcu_access_pointer(wq
->numa_pwq_tbl
[node
]);
3503 rcu_assign_pointer(wq
->numa_pwq_tbl
[node
], pwq
);
3507 /* context to store the prepared attrs & pwqs before applying */
3508 struct apply_wqattrs_ctx
{
3509 struct workqueue_struct
*wq
; /* target workqueue */
3510 struct workqueue_attrs
*attrs
; /* attrs to apply */
3511 struct list_head list
; /* queued for batching commit */
3512 struct pool_workqueue
*dfl_pwq
;
3513 struct pool_workqueue
*pwq_tbl
[];
3516 /* free the resources after success or abort */
3517 static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx
*ctx
)
3523 put_pwq_unlocked(ctx
->pwq_tbl
[node
]);
3524 put_pwq_unlocked(ctx
->dfl_pwq
);
3526 free_workqueue_attrs(ctx
->attrs
);
3532 /* allocate the attrs and pwqs for later installation */
3533 static struct apply_wqattrs_ctx
*
3534 apply_wqattrs_prepare(struct workqueue_struct
*wq
,
3535 const struct workqueue_attrs
*attrs
)
3537 struct apply_wqattrs_ctx
*ctx
;
3538 struct workqueue_attrs
*new_attrs
, *tmp_attrs
;
3541 lockdep_assert_held(&wq_pool_mutex
);
3543 ctx
= kzalloc(sizeof(*ctx
) + nr_node_ids
* sizeof(ctx
->pwq_tbl
[0]),
3546 new_attrs
= alloc_workqueue_attrs(GFP_KERNEL
);
3547 tmp_attrs
= alloc_workqueue_attrs(GFP_KERNEL
);
3548 if (!ctx
|| !new_attrs
|| !tmp_attrs
)
3552 * Calculate the attrs of the default pwq.
3553 * If the user configured cpumask doesn't overlap with the
3554 * wq_unbound_cpumask, we fallback to the wq_unbound_cpumask.
3556 copy_workqueue_attrs(new_attrs
, attrs
);
3557 cpumask_and(new_attrs
->cpumask
, new_attrs
->cpumask
, wq_unbound_cpumask
);
3558 if (unlikely(cpumask_empty(new_attrs
->cpumask
)))
3559 cpumask_copy(new_attrs
->cpumask
, wq_unbound_cpumask
);
3562 * We may create multiple pwqs with differing cpumasks. Make a
3563 * copy of @new_attrs which will be modified and used to obtain
3566 copy_workqueue_attrs(tmp_attrs
, new_attrs
);
3569 * If something goes wrong during CPU up/down, we'll fall back to
3570 * the default pwq covering whole @attrs->cpumask. Always create
3571 * it even if we don't use it immediately.
3573 ctx
->dfl_pwq
= alloc_unbound_pwq(wq
, new_attrs
);
3577 for_each_node(node
) {
3578 if (wq_calc_node_cpumask(new_attrs
, node
, -1, tmp_attrs
->cpumask
)) {
3579 ctx
->pwq_tbl
[node
] = alloc_unbound_pwq(wq
, tmp_attrs
);
3580 if (!ctx
->pwq_tbl
[node
])
3583 ctx
->dfl_pwq
->refcnt
++;
3584 ctx
->pwq_tbl
[node
] = ctx
->dfl_pwq
;
3588 /* save the user configured attrs and sanitize it. */
3589 copy_workqueue_attrs(new_attrs
, attrs
);
3590 cpumask_and(new_attrs
->cpumask
, new_attrs
->cpumask
, cpu_possible_mask
);
3591 ctx
->attrs
= new_attrs
;
3594 free_workqueue_attrs(tmp_attrs
);
3598 free_workqueue_attrs(tmp_attrs
);
3599 free_workqueue_attrs(new_attrs
);
3600 apply_wqattrs_cleanup(ctx
);
3604 /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
3605 static void apply_wqattrs_commit(struct apply_wqattrs_ctx
*ctx
)
3609 /* all pwqs have been created successfully, let's install'em */
3610 mutex_lock(&ctx
->wq
->mutex
);
3612 copy_workqueue_attrs(ctx
->wq
->unbound_attrs
, ctx
->attrs
);
3614 /* save the previous pwq and install the new one */
3616 ctx
->pwq_tbl
[node
] = numa_pwq_tbl_install(ctx
->wq
, node
,
3617 ctx
->pwq_tbl
[node
]);
3619 /* @dfl_pwq might not have been used, ensure it's linked */
3620 link_pwq(ctx
->dfl_pwq
);
3621 swap(ctx
->wq
->dfl_pwq
, ctx
->dfl_pwq
);
3623 mutex_unlock(&ctx
->wq
->mutex
);
3626 static void apply_wqattrs_lock(void)
3628 /* CPUs should stay stable across pwq creations and installations */
3630 mutex_lock(&wq_pool_mutex
);
3633 static void apply_wqattrs_unlock(void)
3635 mutex_unlock(&wq_pool_mutex
);
3639 static int apply_workqueue_attrs_locked(struct workqueue_struct
*wq
,
3640 const struct workqueue_attrs
*attrs
)
3642 struct apply_wqattrs_ctx
*ctx
;
3645 /* only unbound workqueues can change attributes */
3646 if (WARN_ON(!(wq
->flags
& WQ_UNBOUND
)))
3649 /* creating multiple pwqs breaks ordering guarantee */
3650 if (WARN_ON((wq
->flags
& __WQ_ORDERED
) && !list_empty(&wq
->pwqs
)))
3653 ctx
= apply_wqattrs_prepare(wq
, attrs
);
3655 /* the ctx has been prepared successfully, let's commit it */
3657 apply_wqattrs_commit(ctx
);
3661 apply_wqattrs_cleanup(ctx
);
3667 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
3668 * @wq: the target workqueue
3669 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
3671 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
3672 * machines, this function maps a separate pwq to each NUMA node with
3673 * possibles CPUs in @attrs->cpumask so that work items are affine to the
3674 * NUMA node it was issued on. Older pwqs are released as in-flight work
3675 * items finish. Note that a work item which repeatedly requeues itself
3676 * back-to-back will stay on its current pwq.
3678 * Performs GFP_KERNEL allocations.
3680 * Return: 0 on success and -errno on failure.
3682 int apply_workqueue_attrs(struct workqueue_struct
*wq
,
3683 const struct workqueue_attrs
*attrs
)
3687 apply_wqattrs_lock();
3688 ret
= apply_workqueue_attrs_locked(wq
, attrs
);
3689 apply_wqattrs_unlock();
3695 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
3696 * @wq: the target workqueue
3697 * @cpu: the CPU coming up or going down
3698 * @online: whether @cpu is coming up or going down
3700 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
3701 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
3704 * If NUMA affinity can't be adjusted due to memory allocation failure, it
3705 * falls back to @wq->dfl_pwq which may not be optimal but is always
3708 * Note that when the last allowed CPU of a NUMA node goes offline for a
3709 * workqueue with a cpumask spanning multiple nodes, the workers which were
3710 * already executing the work items for the workqueue will lose their CPU
3711 * affinity and may execute on any CPU. This is similar to how per-cpu
3712 * workqueues behave on CPU_DOWN. If a workqueue user wants strict
3713 * affinity, it's the user's responsibility to flush the work item from
3716 static void wq_update_unbound_numa(struct workqueue_struct
*wq
, int cpu
,
3719 int node
= cpu_to_node(cpu
);
3720 int cpu_off
= online
? -1 : cpu
;
3721 struct pool_workqueue
*old_pwq
= NULL
, *pwq
;
3722 struct workqueue_attrs
*target_attrs
;
3725 lockdep_assert_held(&wq_pool_mutex
);
3727 if (!wq_numa_enabled
|| !(wq
->flags
& WQ_UNBOUND
) ||
3728 wq
->unbound_attrs
->no_numa
)
3732 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
3733 * Let's use a preallocated one. The following buf is protected by
3734 * CPU hotplug exclusion.
3736 target_attrs
= wq_update_unbound_numa_attrs_buf
;
3737 cpumask
= target_attrs
->cpumask
;
3739 copy_workqueue_attrs(target_attrs
, wq
->unbound_attrs
);
3740 pwq
= unbound_pwq_by_node(wq
, node
);
3743 * Let's determine what needs to be done. If the target cpumask is
3744 * different from the default pwq's, we need to compare it to @pwq's
3745 * and create a new one if they don't match. If the target cpumask
3746 * equals the default pwq's, the default pwq should be used.
3748 if (wq_calc_node_cpumask(wq
->dfl_pwq
->pool
->attrs
, node
, cpu_off
, cpumask
)) {
3749 if (cpumask_equal(cpumask
, pwq
->pool
->attrs
->cpumask
))
3755 /* create a new pwq */
3756 pwq
= alloc_unbound_pwq(wq
, target_attrs
);
3758 pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
3763 /* Install the new pwq. */
3764 mutex_lock(&wq
->mutex
);
3765 old_pwq
= numa_pwq_tbl_install(wq
, node
, pwq
);
3769 mutex_lock(&wq
->mutex
);
3770 spin_lock_irq(&wq
->dfl_pwq
->pool
->lock
);
3771 get_pwq(wq
->dfl_pwq
);
3772 spin_unlock_irq(&wq
->dfl_pwq
->pool
->lock
);
3773 old_pwq
= numa_pwq_tbl_install(wq
, node
, wq
->dfl_pwq
);
3775 mutex_unlock(&wq
->mutex
);
3776 put_pwq_unlocked(old_pwq
);
3779 static int alloc_and_link_pwqs(struct workqueue_struct
*wq
)
3781 bool highpri
= wq
->flags
& WQ_HIGHPRI
;
3784 if (!(wq
->flags
& WQ_UNBOUND
)) {
3785 wq
->cpu_pwqs
= alloc_percpu(struct pool_workqueue
);
3789 for_each_possible_cpu(cpu
) {
3790 struct pool_workqueue
*pwq
=
3791 per_cpu_ptr(wq
->cpu_pwqs
, cpu
);
3792 struct worker_pool
*cpu_pools
=
3793 per_cpu(cpu_worker_pools
, cpu
);
3795 init_pwq(pwq
, wq
, &cpu_pools
[highpri
]);
3797 mutex_lock(&wq
->mutex
);
3799 mutex_unlock(&wq
->mutex
);
3802 } else if (wq
->flags
& __WQ_ORDERED
) {
3803 ret
= apply_workqueue_attrs(wq
, ordered_wq_attrs
[highpri
]);
3804 /* there should only be single pwq for ordering guarantee */
3805 WARN(!ret
&& (wq
->pwqs
.next
!= &wq
->dfl_pwq
->pwqs_node
||
3806 wq
->pwqs
.prev
!= &wq
->dfl_pwq
->pwqs_node
),
3807 "ordering guarantee broken for workqueue %s\n", wq
->name
);
3810 return apply_workqueue_attrs(wq
, unbound_std_wq_attrs
[highpri
]);
3814 static int wq_clamp_max_active(int max_active
, unsigned int flags
,
3817 int lim
= flags
& WQ_UNBOUND
? WQ_UNBOUND_MAX_ACTIVE
: WQ_MAX_ACTIVE
;
3819 if (max_active
< 1 || max_active
> lim
)
3820 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3821 max_active
, name
, 1, lim
);
3823 return clamp_val(max_active
, 1, lim
);
3826 struct workqueue_struct
*__alloc_workqueue_key(const char *fmt
,
3829 struct lock_class_key
*key
,
3830 const char *lock_name
, ...)
3832 size_t tbl_size
= 0;
3834 struct workqueue_struct
*wq
;
3835 struct pool_workqueue
*pwq
;
3837 /* see the comment above the definition of WQ_POWER_EFFICIENT */
3838 if ((flags
& WQ_POWER_EFFICIENT
) && wq_power_efficient
)
3839 flags
|= WQ_UNBOUND
;
3841 /* allocate wq and format name */
3842 if (flags
& WQ_UNBOUND
)
3843 tbl_size
= nr_node_ids
* sizeof(wq
->numa_pwq_tbl
[0]);
3845 wq
= kzalloc(sizeof(*wq
) + tbl_size
, GFP_KERNEL
);
3849 if (flags
& WQ_UNBOUND
) {
3850 wq
->unbound_attrs
= alloc_workqueue_attrs(GFP_KERNEL
);
3851 if (!wq
->unbound_attrs
)
3855 va_start(args
, lock_name
);
3856 vsnprintf(wq
->name
, sizeof(wq
->name
), fmt
, args
);
3859 max_active
= max_active
?: WQ_DFL_ACTIVE
;
3860 max_active
= wq_clamp_max_active(max_active
, flags
, wq
->name
);
3864 wq
->saved_max_active
= max_active
;
3865 mutex_init(&wq
->mutex
);
3866 atomic_set(&wq
->nr_pwqs_to_flush
, 0);
3867 INIT_LIST_HEAD(&wq
->pwqs
);
3868 INIT_LIST_HEAD(&wq
->flusher_queue
);
3869 INIT_LIST_HEAD(&wq
->flusher_overflow
);
3870 INIT_LIST_HEAD(&wq
->maydays
);
3872 lockdep_init_map(&wq
->lockdep_map
, lock_name
, key
, 0);
3873 INIT_LIST_HEAD(&wq
->list
);
3875 if (alloc_and_link_pwqs(wq
) < 0)
3879 * Workqueues which may be used during memory reclaim should
3880 * have a rescuer to guarantee forward progress.
3882 if (flags
& WQ_MEM_RECLAIM
) {
3883 struct worker
*rescuer
;
3885 rescuer
= alloc_worker(NUMA_NO_NODE
);
3889 rescuer
->rescue_wq
= wq
;
3890 rescuer
->task
= kthread_create(rescuer_thread
, rescuer
, "%s",
3892 if (IS_ERR(rescuer
->task
)) {
3897 wq
->rescuer
= rescuer
;
3898 kthread_bind_mask(rescuer
->task
, cpu_possible_mask
);
3899 wake_up_process(rescuer
->task
);
3902 if ((wq
->flags
& WQ_SYSFS
) && workqueue_sysfs_register(wq
))
3906 * wq_pool_mutex protects global freeze state and workqueues list.
3907 * Grab it, adjust max_active and add the new @wq to workqueues
3910 mutex_lock(&wq_pool_mutex
);
3912 mutex_lock(&wq
->mutex
);
3913 for_each_pwq(pwq
, wq
)
3914 pwq_adjust_max_active(pwq
);
3915 mutex_unlock(&wq
->mutex
);
3917 list_add_tail_rcu(&wq
->list
, &workqueues
);
3919 mutex_unlock(&wq_pool_mutex
);
3924 free_workqueue_attrs(wq
->unbound_attrs
);
3928 destroy_workqueue(wq
);
3931 EXPORT_SYMBOL_GPL(__alloc_workqueue_key
);
3934 * destroy_workqueue - safely terminate a workqueue
3935 * @wq: target workqueue
3937 * Safely destroy a workqueue. All work currently pending will be done first.
3939 void destroy_workqueue(struct workqueue_struct
*wq
)
3941 struct pool_workqueue
*pwq
;
3944 /* drain it before proceeding with destruction */
3945 drain_workqueue(wq
);
3948 mutex_lock(&wq
->mutex
);
3949 for_each_pwq(pwq
, wq
) {
3952 for (i
= 0; i
< WORK_NR_COLORS
; i
++) {
3953 if (WARN_ON(pwq
->nr_in_flight
[i
])) {
3954 mutex_unlock(&wq
->mutex
);
3959 if (WARN_ON((pwq
!= wq
->dfl_pwq
) && (pwq
->refcnt
> 1)) ||
3960 WARN_ON(pwq
->nr_active
) ||
3961 WARN_ON(!list_empty(&pwq
->delayed_works
))) {
3962 mutex_unlock(&wq
->mutex
);
3966 mutex_unlock(&wq
->mutex
);
3969 * wq list is used to freeze wq, remove from list after
3970 * flushing is complete in case freeze races us.
3972 mutex_lock(&wq_pool_mutex
);
3973 list_del_rcu(&wq
->list
);
3974 mutex_unlock(&wq_pool_mutex
);
3976 workqueue_sysfs_unregister(wq
);
3979 kthread_stop(wq
->rescuer
->task
);
3981 if (!(wq
->flags
& WQ_UNBOUND
)) {
3983 * The base ref is never dropped on per-cpu pwqs. Directly
3984 * schedule RCU free.
3986 call_rcu_sched(&wq
->rcu
, rcu_free_wq
);
3989 * We're the sole accessor of @wq at this point. Directly
3990 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
3991 * @wq will be freed when the last pwq is released.
3993 for_each_node(node
) {
3994 pwq
= rcu_access_pointer(wq
->numa_pwq_tbl
[node
]);
3995 RCU_INIT_POINTER(wq
->numa_pwq_tbl
[node
], NULL
);
3996 put_pwq_unlocked(pwq
);
4000 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
4001 * put. Don't access it afterwards.
4005 put_pwq_unlocked(pwq
);
4008 EXPORT_SYMBOL_GPL(destroy_workqueue
);
4011 * workqueue_set_max_active - adjust max_active of a workqueue
4012 * @wq: target workqueue
4013 * @max_active: new max_active value.
4015 * Set max_active of @wq to @max_active.
4018 * Don't call from IRQ context.
4020 void workqueue_set_max_active(struct workqueue_struct
*wq
, int max_active
)
4022 struct pool_workqueue
*pwq
;
4024 /* disallow meddling with max_active for ordered workqueues */
4025 if (WARN_ON(wq
->flags
& __WQ_ORDERED
))
4028 max_active
= wq_clamp_max_active(max_active
, wq
->flags
, wq
->name
);
4030 mutex_lock(&wq
->mutex
);
4032 wq
->saved_max_active
= max_active
;
4034 for_each_pwq(pwq
, wq
)
4035 pwq_adjust_max_active(pwq
);
4037 mutex_unlock(&wq
->mutex
);
4039 EXPORT_SYMBOL_GPL(workqueue_set_max_active
);
4042 * current_is_workqueue_rescuer - is %current workqueue rescuer?
4044 * Determine whether %current is a workqueue rescuer. Can be used from
4045 * work functions to determine whether it's being run off the rescuer task.
4047 * Return: %true if %current is a workqueue rescuer. %false otherwise.
4049 bool current_is_workqueue_rescuer(void)
4051 struct worker
*worker
= current_wq_worker();
4053 return worker
&& worker
->rescue_wq
;
4057 * workqueue_congested - test whether a workqueue is congested
4058 * @cpu: CPU in question
4059 * @wq: target workqueue
4061 * Test whether @wq's cpu workqueue for @cpu is congested. There is
4062 * no synchronization around this function and the test result is
4063 * unreliable and only useful as advisory hints or for debugging.
4065 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4066 * Note that both per-cpu and unbound workqueues may be associated with
4067 * multiple pool_workqueues which have separate congested states. A
4068 * workqueue being congested on one CPU doesn't mean the workqueue is also
4069 * contested on other CPUs / NUMA nodes.
4072 * %true if congested, %false otherwise.
4074 bool workqueue_congested(int cpu
, struct workqueue_struct
*wq
)
4076 struct pool_workqueue
*pwq
;
4079 rcu_read_lock_sched();
4081 if (cpu
== WORK_CPU_UNBOUND
)
4082 cpu
= smp_processor_id();
4084 if (!(wq
->flags
& WQ_UNBOUND
))
4085 pwq
= per_cpu_ptr(wq
->cpu_pwqs
, cpu
);
4087 pwq
= unbound_pwq_by_node(wq
, cpu_to_node(cpu
));
4089 ret
= !list_empty(&pwq
->delayed_works
);
4090 rcu_read_unlock_sched();
4094 EXPORT_SYMBOL_GPL(workqueue_congested
);
4097 * work_busy - test whether a work is currently pending or running
4098 * @work: the work to be tested
4100 * Test whether @work is currently pending or running. There is no
4101 * synchronization around this function and the test result is
4102 * unreliable and only useful as advisory hints or for debugging.
4105 * OR'd bitmask of WORK_BUSY_* bits.
4107 unsigned int work_busy(struct work_struct
*work
)
4109 struct worker_pool
*pool
;
4110 unsigned long flags
;
4111 unsigned int ret
= 0;
4113 if (work_pending(work
))
4114 ret
|= WORK_BUSY_PENDING
;
4116 local_irq_save(flags
);
4117 pool
= get_work_pool(work
);
4119 spin_lock(&pool
->lock
);
4120 if (find_worker_executing_work(pool
, work
))
4121 ret
|= WORK_BUSY_RUNNING
;
4122 spin_unlock(&pool
->lock
);
4124 local_irq_restore(flags
);
4128 EXPORT_SYMBOL_GPL(work_busy
);
4131 * set_worker_desc - set description for the current work item
4132 * @fmt: printf-style format string
4133 * @...: arguments for the format string
4135 * This function can be called by a running work function to describe what
4136 * the work item is about. If the worker task gets dumped, this
4137 * information will be printed out together to help debugging. The
4138 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
4140 void set_worker_desc(const char *fmt
, ...)
4142 struct worker
*worker
= current_wq_worker();
4146 va_start(args
, fmt
);
4147 vsnprintf(worker
->desc
, sizeof(worker
->desc
), fmt
, args
);
4149 worker
->desc_valid
= true;
4154 * print_worker_info - print out worker information and description
4155 * @log_lvl: the log level to use when printing
4156 * @task: target task
4158 * If @task is a worker and currently executing a work item, print out the
4159 * name of the workqueue being serviced and worker description set with
4160 * set_worker_desc() by the currently executing work item.
4162 * This function can be safely called on any task as long as the
4163 * task_struct itself is accessible. While safe, this function isn't
4164 * synchronized and may print out mixups or garbages of limited length.
4166 void print_worker_info(const char *log_lvl
, struct task_struct
*task
)
4168 work_func_t
*fn
= NULL
;
4169 char name
[WQ_NAME_LEN
] = { };
4170 char desc
[WORKER_DESC_LEN
] = { };
4171 struct pool_workqueue
*pwq
= NULL
;
4172 struct workqueue_struct
*wq
= NULL
;
4173 bool desc_valid
= false;
4174 struct worker
*worker
;
4176 if (!(task
->flags
& PF_WQ_WORKER
))
4180 * This function is called without any synchronization and @task
4181 * could be in any state. Be careful with dereferences.
4183 worker
= probe_kthread_data(task
);
4186 * Carefully copy the associated workqueue's workfn and name. Keep
4187 * the original last '\0' in case the original contains garbage.
4189 probe_kernel_read(&fn
, &worker
->current_func
, sizeof(fn
));
4190 probe_kernel_read(&pwq
, &worker
->current_pwq
, sizeof(pwq
));
4191 probe_kernel_read(&wq
, &pwq
->wq
, sizeof(wq
));
4192 probe_kernel_read(name
, wq
->name
, sizeof(name
) - 1);
4194 /* copy worker description */
4195 probe_kernel_read(&desc_valid
, &worker
->desc_valid
, sizeof(desc_valid
));
4197 probe_kernel_read(desc
, worker
->desc
, sizeof(desc
) - 1);
4199 if (fn
|| name
[0] || desc
[0]) {
4200 printk("%sWorkqueue: %s %pf", log_lvl
, name
, fn
);
4202 pr_cont(" (%s)", desc
);
4207 static void pr_cont_pool_info(struct worker_pool
*pool
)
4209 pr_cont(" cpus=%*pbl", nr_cpumask_bits
, pool
->attrs
->cpumask
);
4210 if (pool
->node
!= NUMA_NO_NODE
)
4211 pr_cont(" node=%d", pool
->node
);
4212 pr_cont(" flags=0x%x nice=%d", pool
->flags
, pool
->attrs
->nice
);
4215 static void pr_cont_work(bool comma
, struct work_struct
*work
)
4217 if (work
->func
== wq_barrier_func
) {
4218 struct wq_barrier
*barr
;
4220 barr
= container_of(work
, struct wq_barrier
, work
);
4222 pr_cont("%s BAR(%d)", comma
? "," : "",
4223 task_pid_nr(barr
->task
));
4225 pr_cont("%s %pf", comma
? "," : "", work
->func
);
4229 static void show_pwq(struct pool_workqueue
*pwq
)
4231 struct worker_pool
*pool
= pwq
->pool
;
4232 struct work_struct
*work
;
4233 struct worker
*worker
;
4234 bool has_in_flight
= false, has_pending
= false;
4237 pr_info(" pwq %d:", pool
->id
);
4238 pr_cont_pool_info(pool
);
4240 pr_cont(" active=%d/%d%s\n", pwq
->nr_active
, pwq
->max_active
,
4241 !list_empty(&pwq
->mayday_node
) ? " MAYDAY" : "");
4243 hash_for_each(pool
->busy_hash
, bkt
, worker
, hentry
) {
4244 if (worker
->current_pwq
== pwq
) {
4245 has_in_flight
= true;
4249 if (has_in_flight
) {
4252 pr_info(" in-flight:");
4253 hash_for_each(pool
->busy_hash
, bkt
, worker
, hentry
) {
4254 if (worker
->current_pwq
!= pwq
)
4257 pr_cont("%s %d%s:%pf", comma
? "," : "",
4258 task_pid_nr(worker
->task
),
4259 worker
== pwq
->wq
->rescuer
? "(RESCUER)" : "",
4260 worker
->current_func
);
4261 list_for_each_entry(work
, &worker
->scheduled
, entry
)
4262 pr_cont_work(false, work
);
4268 list_for_each_entry(work
, &pool
->worklist
, entry
) {
4269 if (get_work_pwq(work
) == pwq
) {
4277 pr_info(" pending:");
4278 list_for_each_entry(work
, &pool
->worklist
, entry
) {
4279 if (get_work_pwq(work
) != pwq
)
4282 pr_cont_work(comma
, work
);
4283 comma
= !(*work_data_bits(work
) & WORK_STRUCT_LINKED
);
4288 if (!list_empty(&pwq
->delayed_works
)) {
4291 pr_info(" delayed:");
4292 list_for_each_entry(work
, &pwq
->delayed_works
, entry
) {
4293 pr_cont_work(comma
, work
);
4294 comma
= !(*work_data_bits(work
) & WORK_STRUCT_LINKED
);
4301 * show_workqueue_state - dump workqueue state
4303 * Called from a sysrq handler and prints out all busy workqueues and
4306 void show_workqueue_state(void)
4308 struct workqueue_struct
*wq
;
4309 struct worker_pool
*pool
;
4310 unsigned long flags
;
4313 rcu_read_lock_sched();
4315 pr_info("Showing busy workqueues and worker pools:\n");
4317 list_for_each_entry_rcu(wq
, &workqueues
, list
) {
4318 struct pool_workqueue
*pwq
;
4321 for_each_pwq(pwq
, wq
) {
4322 if (pwq
->nr_active
|| !list_empty(&pwq
->delayed_works
)) {
4330 pr_info("workqueue %s: flags=0x%x\n", wq
->name
, wq
->flags
);
4332 for_each_pwq(pwq
, wq
) {
4333 spin_lock_irqsave(&pwq
->pool
->lock
, flags
);
4334 if (pwq
->nr_active
|| !list_empty(&pwq
->delayed_works
))
4336 spin_unlock_irqrestore(&pwq
->pool
->lock
, flags
);
4340 for_each_pool(pool
, pi
) {
4341 struct worker
*worker
;
4344 spin_lock_irqsave(&pool
->lock
, flags
);
4345 if (pool
->nr_workers
== pool
->nr_idle
)
4348 pr_info("pool %d:", pool
->id
);
4349 pr_cont_pool_info(pool
);
4350 pr_cont(" workers=%d", pool
->nr_workers
);
4352 pr_cont(" manager: %d",
4353 task_pid_nr(pool
->manager
->task
));
4354 list_for_each_entry(worker
, &pool
->idle_list
, entry
) {
4355 pr_cont(" %s%d", first
? "idle: " : "",
4356 task_pid_nr(worker
->task
));
4361 spin_unlock_irqrestore(&pool
->lock
, flags
);
4364 rcu_read_unlock_sched();
4370 * There are two challenges in supporting CPU hotplug. Firstly, there
4371 * are a lot of assumptions on strong associations among work, pwq and
4372 * pool which make migrating pending and scheduled works very
4373 * difficult to implement without impacting hot paths. Secondly,
4374 * worker pools serve mix of short, long and very long running works making
4375 * blocked draining impractical.
4377 * This is solved by allowing the pools to be disassociated from the CPU
4378 * running as an unbound one and allowing it to be reattached later if the
4379 * cpu comes back online.
4382 static void wq_unbind_fn(struct work_struct
*work
)
4384 int cpu
= smp_processor_id();
4385 struct worker_pool
*pool
;
4386 struct worker
*worker
;
4388 for_each_cpu_worker_pool(pool
, cpu
) {
4389 mutex_lock(&pool
->attach_mutex
);
4390 spin_lock_irq(&pool
->lock
);
4393 * We've blocked all attach/detach operations. Make all workers
4394 * unbound and set DISASSOCIATED. Before this, all workers
4395 * except for the ones which are still executing works from
4396 * before the last CPU down must be on the cpu. After
4397 * this, they may become diasporas.
4399 for_each_pool_worker(worker
, pool
)
4400 worker
->flags
|= WORKER_UNBOUND
;
4402 pool
->flags
|= POOL_DISASSOCIATED
;
4404 spin_unlock_irq(&pool
->lock
);
4405 mutex_unlock(&pool
->attach_mutex
);
4408 * Call schedule() so that we cross rq->lock and thus can
4409 * guarantee sched callbacks see the %WORKER_UNBOUND flag.
4410 * This is necessary as scheduler callbacks may be invoked
4416 * Sched callbacks are disabled now. Zap nr_running.
4417 * After this, nr_running stays zero and need_more_worker()
4418 * and keep_working() are always true as long as the
4419 * worklist is not empty. This pool now behaves as an
4420 * unbound (in terms of concurrency management) pool which
4421 * are served by workers tied to the pool.
4423 atomic_set(&pool
->nr_running
, 0);
4426 * With concurrency management just turned off, a busy
4427 * worker blocking could lead to lengthy stalls. Kick off
4428 * unbound chain execution of currently pending work items.
4430 spin_lock_irq(&pool
->lock
);
4431 wake_up_worker(pool
);
4432 spin_unlock_irq(&pool
->lock
);
4437 * rebind_workers - rebind all workers of a pool to the associated CPU
4438 * @pool: pool of interest
4440 * @pool->cpu is coming online. Rebind all workers to the CPU.
4442 static void rebind_workers(struct worker_pool
*pool
)
4444 struct worker
*worker
;
4446 lockdep_assert_held(&pool
->attach_mutex
);
4449 * Restore CPU affinity of all workers. As all idle workers should
4450 * be on the run-queue of the associated CPU before any local
4451 * wake-ups for concurrency management happen, restore CPU affinity
4452 * of all workers first and then clear UNBOUND. As we're called
4453 * from CPU_ONLINE, the following shouldn't fail.
4455 for_each_pool_worker(worker
, pool
)
4456 WARN_ON_ONCE(set_cpus_allowed_ptr(worker
->task
,
4457 pool
->attrs
->cpumask
) < 0);
4459 spin_lock_irq(&pool
->lock
);
4462 * XXX: CPU hotplug notifiers are weird and can call DOWN_FAILED
4463 * w/o preceding DOWN_PREPARE. Work around it. CPU hotplug is
4464 * being reworked and this can go away in time.
4466 if (!(pool
->flags
& POOL_DISASSOCIATED
)) {
4467 spin_unlock_irq(&pool
->lock
);
4471 pool
->flags
&= ~POOL_DISASSOCIATED
;
4473 for_each_pool_worker(worker
, pool
) {
4474 unsigned int worker_flags
= worker
->flags
;
4477 * A bound idle worker should actually be on the runqueue
4478 * of the associated CPU for local wake-ups targeting it to
4479 * work. Kick all idle workers so that they migrate to the
4480 * associated CPU. Doing this in the same loop as
4481 * replacing UNBOUND with REBOUND is safe as no worker will
4482 * be bound before @pool->lock is released.
4484 if (worker_flags
& WORKER_IDLE
)
4485 wake_up_process(worker
->task
);
4488 * We want to clear UNBOUND but can't directly call
4489 * worker_clr_flags() or adjust nr_running. Atomically
4490 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4491 * @worker will clear REBOUND using worker_clr_flags() when
4492 * it initiates the next execution cycle thus restoring
4493 * concurrency management. Note that when or whether
4494 * @worker clears REBOUND doesn't affect correctness.
4496 * ACCESS_ONCE() is necessary because @worker->flags may be
4497 * tested without holding any lock in
4498 * wq_worker_waking_up(). Without it, NOT_RUNNING test may
4499 * fail incorrectly leading to premature concurrency
4500 * management operations.
4502 WARN_ON_ONCE(!(worker_flags
& WORKER_UNBOUND
));
4503 worker_flags
|= WORKER_REBOUND
;
4504 worker_flags
&= ~WORKER_UNBOUND
;
4505 ACCESS_ONCE(worker
->flags
) = worker_flags
;
4508 spin_unlock_irq(&pool
->lock
);
4512 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
4513 * @pool: unbound pool of interest
4514 * @cpu: the CPU which is coming up
4516 * An unbound pool may end up with a cpumask which doesn't have any online
4517 * CPUs. When a worker of such pool get scheduled, the scheduler resets
4518 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
4519 * online CPU before, cpus_allowed of all its workers should be restored.
4521 static void restore_unbound_workers_cpumask(struct worker_pool
*pool
, int cpu
)
4523 static cpumask_t cpumask
;
4524 struct worker
*worker
;
4526 lockdep_assert_held(&pool
->attach_mutex
);
4528 /* is @cpu allowed for @pool? */
4529 if (!cpumask_test_cpu(cpu
, pool
->attrs
->cpumask
))
4532 /* is @cpu the only online CPU? */
4533 cpumask_and(&cpumask
, pool
->attrs
->cpumask
, cpu_online_mask
);
4534 if (cpumask_weight(&cpumask
) != 1)
4537 /* as we're called from CPU_ONLINE, the following shouldn't fail */
4538 for_each_pool_worker(worker
, pool
)
4539 WARN_ON_ONCE(set_cpus_allowed_ptr(worker
->task
,
4540 pool
->attrs
->cpumask
) < 0);
4544 * Workqueues should be brought up before normal priority CPU notifiers.
4545 * This will be registered high priority CPU notifier.
4547 static int workqueue_cpu_up_callback(struct notifier_block
*nfb
,
4548 unsigned long action
,
4551 int cpu
= (unsigned long)hcpu
;
4552 struct worker_pool
*pool
;
4553 struct workqueue_struct
*wq
;
4556 switch (action
& ~CPU_TASKS_FROZEN
) {
4557 case CPU_UP_PREPARE
:
4558 for_each_cpu_worker_pool(pool
, cpu
) {
4559 if (pool
->nr_workers
)
4561 if (!create_worker(pool
))
4566 case CPU_DOWN_FAILED
:
4568 mutex_lock(&wq_pool_mutex
);
4570 for_each_pool(pool
, pi
) {
4571 mutex_lock(&pool
->attach_mutex
);
4573 if (pool
->cpu
== cpu
)
4574 rebind_workers(pool
);
4575 else if (pool
->cpu
< 0)
4576 restore_unbound_workers_cpumask(pool
, cpu
);
4578 mutex_unlock(&pool
->attach_mutex
);
4581 /* update NUMA affinity of unbound workqueues */
4582 list_for_each_entry(wq
, &workqueues
, list
)
4583 wq_update_unbound_numa(wq
, cpu
, true);
4585 mutex_unlock(&wq_pool_mutex
);
4592 * Workqueues should be brought down after normal priority CPU notifiers.
4593 * This will be registered as low priority CPU notifier.
4595 static int workqueue_cpu_down_callback(struct notifier_block
*nfb
,
4596 unsigned long action
,
4599 int cpu
= (unsigned long)hcpu
;
4600 struct work_struct unbind_work
;
4601 struct workqueue_struct
*wq
;
4603 switch (action
& ~CPU_TASKS_FROZEN
) {
4604 case CPU_DOWN_PREPARE
:
4605 /* unbinding per-cpu workers should happen on the local CPU */
4606 INIT_WORK_ONSTACK(&unbind_work
, wq_unbind_fn
);
4607 queue_work_on(cpu
, system_highpri_wq
, &unbind_work
);
4609 /* update NUMA affinity of unbound workqueues */
4610 mutex_lock(&wq_pool_mutex
);
4611 list_for_each_entry(wq
, &workqueues
, list
)
4612 wq_update_unbound_numa(wq
, cpu
, false);
4613 mutex_unlock(&wq_pool_mutex
);
4615 /* wait for per-cpu unbinding to finish */
4616 flush_work(&unbind_work
);
4617 destroy_work_on_stack(&unbind_work
);
4625 struct work_for_cpu
{
4626 struct work_struct work
;
4632 static void work_for_cpu_fn(struct work_struct
*work
)
4634 struct work_for_cpu
*wfc
= container_of(work
, struct work_for_cpu
, work
);
4636 wfc
->ret
= wfc
->fn(wfc
->arg
);
4640 * work_on_cpu - run a function in user context on a particular cpu
4641 * @cpu: the cpu to run on
4642 * @fn: the function to run
4643 * @arg: the function arg
4645 * It is up to the caller to ensure that the cpu doesn't go offline.
4646 * The caller must not hold any locks which would prevent @fn from completing.
4648 * Return: The value @fn returns.
4650 long work_on_cpu(int cpu
, long (*fn
)(void *), void *arg
)
4652 struct work_for_cpu wfc
= { .fn
= fn
, .arg
= arg
};
4654 INIT_WORK_ONSTACK(&wfc
.work
, work_for_cpu_fn
);
4655 schedule_work_on(cpu
, &wfc
.work
);
4656 flush_work(&wfc
.work
);
4657 destroy_work_on_stack(&wfc
.work
);
4660 EXPORT_SYMBOL_GPL(work_on_cpu
);
4661 #endif /* CONFIG_SMP */
4663 #ifdef CONFIG_FREEZER
4666 * freeze_workqueues_begin - begin freezing workqueues
4668 * Start freezing workqueues. After this function returns, all freezable
4669 * workqueues will queue new works to their delayed_works list instead of
4673 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4675 void freeze_workqueues_begin(void)
4677 struct workqueue_struct
*wq
;
4678 struct pool_workqueue
*pwq
;
4680 mutex_lock(&wq_pool_mutex
);
4682 WARN_ON_ONCE(workqueue_freezing
);
4683 workqueue_freezing
= true;
4685 list_for_each_entry(wq
, &workqueues
, list
) {
4686 mutex_lock(&wq
->mutex
);
4687 for_each_pwq(pwq
, wq
)
4688 pwq_adjust_max_active(pwq
);
4689 mutex_unlock(&wq
->mutex
);
4692 mutex_unlock(&wq_pool_mutex
);
4696 * freeze_workqueues_busy - are freezable workqueues still busy?
4698 * Check whether freezing is complete. This function must be called
4699 * between freeze_workqueues_begin() and thaw_workqueues().
4702 * Grabs and releases wq_pool_mutex.
4705 * %true if some freezable workqueues are still busy. %false if freezing
4708 bool freeze_workqueues_busy(void)
4711 struct workqueue_struct
*wq
;
4712 struct pool_workqueue
*pwq
;
4714 mutex_lock(&wq_pool_mutex
);
4716 WARN_ON_ONCE(!workqueue_freezing
);
4718 list_for_each_entry(wq
, &workqueues
, list
) {
4719 if (!(wq
->flags
& WQ_FREEZABLE
))
4722 * nr_active is monotonically decreasing. It's safe
4723 * to peek without lock.
4725 rcu_read_lock_sched();
4726 for_each_pwq(pwq
, wq
) {
4727 WARN_ON_ONCE(pwq
->nr_active
< 0);
4728 if (pwq
->nr_active
) {
4730 rcu_read_unlock_sched();
4734 rcu_read_unlock_sched();
4737 mutex_unlock(&wq_pool_mutex
);
4742 * thaw_workqueues - thaw workqueues
4744 * Thaw workqueues. Normal queueing is restored and all collected
4745 * frozen works are transferred to their respective pool worklists.
4748 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4750 void thaw_workqueues(void)
4752 struct workqueue_struct
*wq
;
4753 struct pool_workqueue
*pwq
;
4755 mutex_lock(&wq_pool_mutex
);
4757 if (!workqueue_freezing
)
4760 workqueue_freezing
= false;
4762 /* restore max_active and repopulate worklist */
4763 list_for_each_entry(wq
, &workqueues
, list
) {
4764 mutex_lock(&wq
->mutex
);
4765 for_each_pwq(pwq
, wq
)
4766 pwq_adjust_max_active(pwq
);
4767 mutex_unlock(&wq
->mutex
);
4771 mutex_unlock(&wq_pool_mutex
);
4773 #endif /* CONFIG_FREEZER */
4775 static int workqueue_apply_unbound_cpumask(void)
4779 struct workqueue_struct
*wq
;
4780 struct apply_wqattrs_ctx
*ctx
, *n
;
4782 lockdep_assert_held(&wq_pool_mutex
);
4784 list_for_each_entry(wq
, &workqueues
, list
) {
4785 if (!(wq
->flags
& WQ_UNBOUND
))
4787 /* creating multiple pwqs breaks ordering guarantee */
4788 if (wq
->flags
& __WQ_ORDERED
)
4791 ctx
= apply_wqattrs_prepare(wq
, wq
->unbound_attrs
);
4797 list_add_tail(&ctx
->list
, &ctxs
);
4800 list_for_each_entry_safe(ctx
, n
, &ctxs
, list
) {
4802 apply_wqattrs_commit(ctx
);
4803 apply_wqattrs_cleanup(ctx
);
4810 * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
4811 * @cpumask: the cpumask to set
4813 * The low-level workqueues cpumask is a global cpumask that limits
4814 * the affinity of all unbound workqueues. This function check the @cpumask
4815 * and apply it to all unbound workqueues and updates all pwqs of them.
4817 * Retun: 0 - Success
4818 * -EINVAL - Invalid @cpumask
4819 * -ENOMEM - Failed to allocate memory for attrs or pwqs.
4821 int workqueue_set_unbound_cpumask(cpumask_var_t cpumask
)
4824 cpumask_var_t saved_cpumask
;
4826 if (!zalloc_cpumask_var(&saved_cpumask
, GFP_KERNEL
))
4829 cpumask_and(cpumask
, cpumask
, cpu_possible_mask
);
4830 if (!cpumask_empty(cpumask
)) {
4831 apply_wqattrs_lock();
4833 /* save the old wq_unbound_cpumask. */
4834 cpumask_copy(saved_cpumask
, wq_unbound_cpumask
);
4836 /* update wq_unbound_cpumask at first and apply it to wqs. */
4837 cpumask_copy(wq_unbound_cpumask
, cpumask
);
4838 ret
= workqueue_apply_unbound_cpumask();
4840 /* restore the wq_unbound_cpumask when failed. */
4842 cpumask_copy(wq_unbound_cpumask
, saved_cpumask
);
4844 apply_wqattrs_unlock();
4847 free_cpumask_var(saved_cpumask
);
4853 * Workqueues with WQ_SYSFS flag set is visible to userland via
4854 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
4855 * following attributes.
4857 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
4858 * max_active RW int : maximum number of in-flight work items
4860 * Unbound workqueues have the following extra attributes.
4862 * id RO int : the associated pool ID
4863 * nice RW int : nice value of the workers
4864 * cpumask RW mask : bitmask of allowed CPUs for the workers
4867 struct workqueue_struct
*wq
;
4871 static struct workqueue_struct
*dev_to_wq(struct device
*dev
)
4873 struct wq_device
*wq_dev
= container_of(dev
, struct wq_device
, dev
);
4878 static ssize_t
per_cpu_show(struct device
*dev
, struct device_attribute
*attr
,
4881 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4883 return scnprintf(buf
, PAGE_SIZE
, "%d\n", (bool)!(wq
->flags
& WQ_UNBOUND
));
4885 static DEVICE_ATTR_RO(per_cpu
);
4887 static ssize_t
max_active_show(struct device
*dev
,
4888 struct device_attribute
*attr
, char *buf
)
4890 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4892 return scnprintf(buf
, PAGE_SIZE
, "%d\n", wq
->saved_max_active
);
4895 static ssize_t
max_active_store(struct device
*dev
,
4896 struct device_attribute
*attr
, const char *buf
,
4899 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4902 if (sscanf(buf
, "%d", &val
) != 1 || val
<= 0)
4905 workqueue_set_max_active(wq
, val
);
4908 static DEVICE_ATTR_RW(max_active
);
4910 static struct attribute
*wq_sysfs_attrs
[] = {
4911 &dev_attr_per_cpu
.attr
,
4912 &dev_attr_max_active
.attr
,
4915 ATTRIBUTE_GROUPS(wq_sysfs
);
4917 static ssize_t
wq_pool_ids_show(struct device
*dev
,
4918 struct device_attribute
*attr
, char *buf
)
4920 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4921 const char *delim
= "";
4922 int node
, written
= 0;
4924 rcu_read_lock_sched();
4925 for_each_node(node
) {
4926 written
+= scnprintf(buf
+ written
, PAGE_SIZE
- written
,
4927 "%s%d:%d", delim
, node
,
4928 unbound_pwq_by_node(wq
, node
)->pool
->id
);
4931 written
+= scnprintf(buf
+ written
, PAGE_SIZE
- written
, "\n");
4932 rcu_read_unlock_sched();
4937 static ssize_t
wq_nice_show(struct device
*dev
, struct device_attribute
*attr
,
4940 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4943 mutex_lock(&wq
->mutex
);
4944 written
= scnprintf(buf
, PAGE_SIZE
, "%d\n", wq
->unbound_attrs
->nice
);
4945 mutex_unlock(&wq
->mutex
);
4950 /* prepare workqueue_attrs for sysfs store operations */
4951 static struct workqueue_attrs
*wq_sysfs_prep_attrs(struct workqueue_struct
*wq
)
4953 struct workqueue_attrs
*attrs
;
4955 lockdep_assert_held(&wq_pool_mutex
);
4957 attrs
= alloc_workqueue_attrs(GFP_KERNEL
);
4961 copy_workqueue_attrs(attrs
, wq
->unbound_attrs
);
4965 static ssize_t
wq_nice_store(struct device
*dev
, struct device_attribute
*attr
,
4966 const char *buf
, size_t count
)
4968 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4969 struct workqueue_attrs
*attrs
;
4972 apply_wqattrs_lock();
4974 attrs
= wq_sysfs_prep_attrs(wq
);
4978 if (sscanf(buf
, "%d", &attrs
->nice
) == 1 &&
4979 attrs
->nice
>= MIN_NICE
&& attrs
->nice
<= MAX_NICE
)
4980 ret
= apply_workqueue_attrs_locked(wq
, attrs
);
4985 apply_wqattrs_unlock();
4986 free_workqueue_attrs(attrs
);
4987 return ret
?: count
;
4990 static ssize_t
wq_cpumask_show(struct device
*dev
,
4991 struct device_attribute
*attr
, char *buf
)
4993 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4996 mutex_lock(&wq
->mutex
);
4997 written
= scnprintf(buf
, PAGE_SIZE
, "%*pb\n",
4998 cpumask_pr_args(wq
->unbound_attrs
->cpumask
));
4999 mutex_unlock(&wq
->mutex
);
5003 static ssize_t
wq_cpumask_store(struct device
*dev
,
5004 struct device_attribute
*attr
,
5005 const char *buf
, size_t count
)
5007 struct workqueue_struct
*wq
= dev_to_wq(dev
);
5008 struct workqueue_attrs
*attrs
;
5011 apply_wqattrs_lock();
5013 attrs
= wq_sysfs_prep_attrs(wq
);
5017 ret
= cpumask_parse(buf
, attrs
->cpumask
);
5019 ret
= apply_workqueue_attrs_locked(wq
, attrs
);
5022 apply_wqattrs_unlock();
5023 free_workqueue_attrs(attrs
);
5024 return ret
?: count
;
5027 static ssize_t
wq_numa_show(struct device
*dev
, struct device_attribute
*attr
,
5030 struct workqueue_struct
*wq
= dev_to_wq(dev
);
5033 mutex_lock(&wq
->mutex
);
5034 written
= scnprintf(buf
, PAGE_SIZE
, "%d\n",
5035 !wq
->unbound_attrs
->no_numa
);
5036 mutex_unlock(&wq
->mutex
);
5041 static ssize_t
wq_numa_store(struct device
*dev
, struct device_attribute
*attr
,
5042 const char *buf
, size_t count
)
5044 struct workqueue_struct
*wq
= dev_to_wq(dev
);
5045 struct workqueue_attrs
*attrs
;
5046 int v
, ret
= -ENOMEM
;
5048 apply_wqattrs_lock();
5050 attrs
= wq_sysfs_prep_attrs(wq
);
5055 if (sscanf(buf
, "%d", &v
) == 1) {
5056 attrs
->no_numa
= !v
;
5057 ret
= apply_workqueue_attrs_locked(wq
, attrs
);
5061 apply_wqattrs_unlock();
5062 free_workqueue_attrs(attrs
);
5063 return ret
?: count
;
5066 static struct device_attribute wq_sysfs_unbound_attrs
[] = {
5067 __ATTR(pool_ids
, 0444, wq_pool_ids_show
, NULL
),
5068 __ATTR(nice
, 0644, wq_nice_show
, wq_nice_store
),
5069 __ATTR(cpumask
, 0644, wq_cpumask_show
, wq_cpumask_store
),
5070 __ATTR(numa
, 0644, wq_numa_show
, wq_numa_store
),
5074 static struct bus_type wq_subsys
= {
5075 .name
= "workqueue",
5076 .dev_groups
= wq_sysfs_groups
,
5079 static ssize_t
wq_unbound_cpumask_show(struct device
*dev
,
5080 struct device_attribute
*attr
, char *buf
)
5084 mutex_lock(&wq_pool_mutex
);
5085 written
= scnprintf(buf
, PAGE_SIZE
, "%*pb\n",
5086 cpumask_pr_args(wq_unbound_cpumask
));
5087 mutex_unlock(&wq_pool_mutex
);
5092 static ssize_t
wq_unbound_cpumask_store(struct device
*dev
,
5093 struct device_attribute
*attr
, const char *buf
, size_t count
)
5095 cpumask_var_t cpumask
;
5098 if (!zalloc_cpumask_var(&cpumask
, GFP_KERNEL
))
5101 ret
= cpumask_parse(buf
, cpumask
);
5103 ret
= workqueue_set_unbound_cpumask(cpumask
);
5105 free_cpumask_var(cpumask
);
5106 return ret
? ret
: count
;
5109 static struct device_attribute wq_sysfs_cpumask_attr
=
5110 __ATTR(cpumask
, 0644, wq_unbound_cpumask_show
,
5111 wq_unbound_cpumask_store
);
5113 static int __init
wq_sysfs_init(void)
5117 err
= subsys_virtual_register(&wq_subsys
, NULL
);
5121 return device_create_file(wq_subsys
.dev_root
, &wq_sysfs_cpumask_attr
);
5123 core_initcall(wq_sysfs_init
);
5125 static void wq_device_release(struct device
*dev
)
5127 struct wq_device
*wq_dev
= container_of(dev
, struct wq_device
, dev
);
5133 * workqueue_sysfs_register - make a workqueue visible in sysfs
5134 * @wq: the workqueue to register
5136 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
5137 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
5138 * which is the preferred method.
5140 * Workqueue user should use this function directly iff it wants to apply
5141 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
5142 * apply_workqueue_attrs() may race against userland updating the
5145 * Return: 0 on success, -errno on failure.
5147 int workqueue_sysfs_register(struct workqueue_struct
*wq
)
5149 struct wq_device
*wq_dev
;
5153 * Adjusting max_active or creating new pwqs by applying
5154 * attributes breaks ordering guarantee. Disallow exposing ordered
5157 if (WARN_ON(wq
->flags
& __WQ_ORDERED
))
5160 wq
->wq_dev
= wq_dev
= kzalloc(sizeof(*wq_dev
), GFP_KERNEL
);
5165 wq_dev
->dev
.bus
= &wq_subsys
;
5166 wq_dev
->dev
.init_name
= wq
->name
;
5167 wq_dev
->dev
.release
= wq_device_release
;
5170 * unbound_attrs are created separately. Suppress uevent until
5171 * everything is ready.
5173 dev_set_uevent_suppress(&wq_dev
->dev
, true);
5175 ret
= device_register(&wq_dev
->dev
);
5182 if (wq
->flags
& WQ_UNBOUND
) {
5183 struct device_attribute
*attr
;
5185 for (attr
= wq_sysfs_unbound_attrs
; attr
->attr
.name
; attr
++) {
5186 ret
= device_create_file(&wq_dev
->dev
, attr
);
5188 device_unregister(&wq_dev
->dev
);
5195 dev_set_uevent_suppress(&wq_dev
->dev
, false);
5196 kobject_uevent(&wq_dev
->dev
.kobj
, KOBJ_ADD
);
5201 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
5202 * @wq: the workqueue to unregister
5204 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
5206 static void workqueue_sysfs_unregister(struct workqueue_struct
*wq
)
5208 struct wq_device
*wq_dev
= wq
->wq_dev
;
5214 device_unregister(&wq_dev
->dev
);
5216 #else /* CONFIG_SYSFS */
5217 static void workqueue_sysfs_unregister(struct workqueue_struct
*wq
) { }
5218 #endif /* CONFIG_SYSFS */
5220 static void __init
wq_numa_init(void)
5225 if (num_possible_nodes() <= 1)
5228 if (wq_disable_numa
) {
5229 pr_info("workqueue: NUMA affinity support disabled\n");
5233 wq_update_unbound_numa_attrs_buf
= alloc_workqueue_attrs(GFP_KERNEL
);
5234 BUG_ON(!wq_update_unbound_numa_attrs_buf
);
5237 * We want masks of possible CPUs of each node which isn't readily
5238 * available. Build one from cpu_to_node() which should have been
5239 * fully initialized by now.
5241 tbl
= kzalloc(nr_node_ids
* sizeof(tbl
[0]), GFP_KERNEL
);
5245 BUG_ON(!zalloc_cpumask_var_node(&tbl
[node
], GFP_KERNEL
,
5246 node_online(node
) ? node
: NUMA_NO_NODE
));
5248 for_each_possible_cpu(cpu
) {
5249 node
= cpu_to_node(cpu
);
5250 if (WARN_ON(node
== NUMA_NO_NODE
)) {
5251 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu
);
5252 /* happens iff arch is bonkers, let's just proceed */
5255 cpumask_set_cpu(cpu
, tbl
[node
]);
5258 wq_numa_possible_cpumask
= tbl
;
5259 wq_numa_enabled
= true;
5262 static int __init
init_workqueues(void)
5264 int std_nice
[NR_STD_WORKER_POOLS
] = { 0, HIGHPRI_NICE_LEVEL
};
5267 WARN_ON(__alignof__(struct pool_workqueue
) < __alignof__(long long));
5269 BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask
, GFP_KERNEL
));
5270 cpumask_copy(wq_unbound_cpumask
, cpu_possible_mask
);
5272 pwq_cache
= KMEM_CACHE(pool_workqueue
, SLAB_PANIC
);
5274 cpu_notifier(workqueue_cpu_up_callback
, CPU_PRI_WORKQUEUE_UP
);
5275 hotcpu_notifier(workqueue_cpu_down_callback
, CPU_PRI_WORKQUEUE_DOWN
);
5279 /* initialize CPU pools */
5280 for_each_possible_cpu(cpu
) {
5281 struct worker_pool
*pool
;
5284 for_each_cpu_worker_pool(pool
, cpu
) {
5285 BUG_ON(init_worker_pool(pool
));
5287 cpumask_copy(pool
->attrs
->cpumask
, cpumask_of(cpu
));
5288 pool
->attrs
->nice
= std_nice
[i
++];
5289 pool
->node
= cpu_to_node(cpu
);
5292 mutex_lock(&wq_pool_mutex
);
5293 BUG_ON(worker_pool_assign_id(pool
));
5294 mutex_unlock(&wq_pool_mutex
);
5298 /* create the initial worker */
5299 for_each_online_cpu(cpu
) {
5300 struct worker_pool
*pool
;
5302 for_each_cpu_worker_pool(pool
, cpu
) {
5303 pool
->flags
&= ~POOL_DISASSOCIATED
;
5304 BUG_ON(!create_worker(pool
));
5308 /* create default unbound and ordered wq attrs */
5309 for (i
= 0; i
< NR_STD_WORKER_POOLS
; i
++) {
5310 struct workqueue_attrs
*attrs
;
5312 BUG_ON(!(attrs
= alloc_workqueue_attrs(GFP_KERNEL
)));
5313 attrs
->nice
= std_nice
[i
];
5314 unbound_std_wq_attrs
[i
] = attrs
;
5317 * An ordered wq should have only one pwq as ordering is
5318 * guaranteed by max_active which is enforced by pwqs.
5319 * Turn off NUMA so that dfl_pwq is used for all nodes.
5321 BUG_ON(!(attrs
= alloc_workqueue_attrs(GFP_KERNEL
)));
5322 attrs
->nice
= std_nice
[i
];
5323 attrs
->no_numa
= true;
5324 ordered_wq_attrs
[i
] = attrs
;
5327 system_wq
= alloc_workqueue("events", 0, 0);
5328 system_highpri_wq
= alloc_workqueue("events_highpri", WQ_HIGHPRI
, 0);
5329 system_long_wq
= alloc_workqueue("events_long", 0, 0);
5330 system_unbound_wq
= alloc_workqueue("events_unbound", WQ_UNBOUND
,
5331 WQ_UNBOUND_MAX_ACTIVE
);
5332 system_freezable_wq
= alloc_workqueue("events_freezable",
5334 system_power_efficient_wq
= alloc_workqueue("events_power_efficient",
5335 WQ_POWER_EFFICIENT
, 0);
5336 system_freezable_power_efficient_wq
= alloc_workqueue("events_freezable_power_efficient",
5337 WQ_FREEZABLE
| WQ_POWER_EFFICIENT
,
5339 BUG_ON(!system_wq
|| !system_highpri_wq
|| !system_long_wq
||
5340 !system_unbound_wq
|| !system_freezable_wq
||
5341 !system_power_efficient_wq
||
5342 !system_freezable_power_efficient_wq
);
5345 early_initcall(init_workqueues
);