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 * WQ: wq->mutex protected.
132 * WR: wq->mutex protected for writes. Sched-RCU protected for reads.
134 * MD: wq_mayday_lock protected.
137 /* struct worker is defined in workqueue_internal.h */
140 spinlock_t lock
; /* the pool lock */
141 int cpu
; /* I: the associated cpu */
142 int node
; /* I: the associated node ID */
143 int id
; /* I: pool ID */
144 unsigned int flags
; /* X: flags */
146 struct list_head worklist
; /* L: list of pending works */
147 int nr_workers
; /* L: total number of workers */
149 /* nr_idle includes the ones off idle_list for rebinding */
150 int nr_idle
; /* L: currently idle ones */
152 struct list_head idle_list
; /* X: list of idle workers */
153 struct timer_list idle_timer
; /* L: worker idle timeout */
154 struct timer_list mayday_timer
; /* L: SOS timer for workers */
156 /* a workers is either on busy_hash or idle_list, or the manager */
157 DECLARE_HASHTABLE(busy_hash
, BUSY_WORKER_HASH_ORDER
);
158 /* L: hash of busy workers */
160 /* see manage_workers() for details on the two manager mutexes */
161 struct mutex manager_arb
; /* manager arbitration */
162 struct worker
*manager
; /* L: purely informational */
163 struct mutex attach_mutex
; /* attach/detach exclusion */
164 struct list_head workers
; /* A: attached workers */
165 struct completion
*detach_completion
; /* all workers detached */
167 struct ida worker_ida
; /* worker IDs for task name */
169 struct workqueue_attrs
*attrs
; /* I: worker attributes */
170 struct hlist_node hash_node
; /* PL: unbound_pool_hash node */
171 int refcnt
; /* PL: refcnt for unbound pools */
174 * The current concurrency level. As it's likely to be accessed
175 * from other CPUs during try_to_wake_up(), put it in a separate
178 atomic_t nr_running ____cacheline_aligned_in_smp
;
181 * Destruction of pool is sched-RCU protected to allow dereferences
182 * from get_work_pool().
185 } ____cacheline_aligned_in_smp
;
188 * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
189 * of work_struct->data are used for flags and the remaining high bits
190 * point to the pwq; thus, pwqs need to be aligned at two's power of the
191 * number of flag bits.
193 struct pool_workqueue
{
194 struct worker_pool
*pool
; /* I: the associated pool */
195 struct workqueue_struct
*wq
; /* I: the owning workqueue */
196 int work_color
; /* L: current color */
197 int flush_color
; /* L: flushing color */
198 int refcnt
; /* L: reference count */
199 int nr_in_flight
[WORK_NR_COLORS
];
200 /* L: nr of in_flight works */
201 int nr_active
; /* L: nr of active works */
202 int max_active
; /* L: max active works */
203 struct list_head delayed_works
; /* L: delayed works */
204 struct list_head pwqs_node
; /* WR: node on wq->pwqs */
205 struct list_head mayday_node
; /* MD: node on wq->maydays */
208 * Release of unbound pwq is punted to system_wq. See put_pwq()
209 * and pwq_unbound_release_workfn() for details. pool_workqueue
210 * itself is also sched-RCU protected so that the first pwq can be
211 * determined without grabbing wq->mutex.
213 struct work_struct unbound_release_work
;
215 } __aligned(1 << WORK_STRUCT_FLAG_BITS
);
218 * Structure used to wait for workqueue flush.
221 struct list_head list
; /* WQ: list of flushers */
222 int flush_color
; /* WQ: flush color waiting for */
223 struct completion done
; /* flush completion */
229 * The externally visible workqueue. It relays the issued work items to
230 * the appropriate worker_pool through its pool_workqueues.
232 struct workqueue_struct
{
233 struct list_head pwqs
; /* WR: all pwqs of this wq */
234 struct list_head list
; /* PR: list of all workqueues */
236 struct mutex mutex
; /* protects this wq */
237 int work_color
; /* WQ: current work color */
238 int flush_color
; /* WQ: current flush color */
239 atomic_t nr_pwqs_to_flush
; /* flush in progress */
240 struct wq_flusher
*first_flusher
; /* WQ: first flusher */
241 struct list_head flusher_queue
; /* WQ: flush waiters */
242 struct list_head flusher_overflow
; /* WQ: flush overflow list */
244 struct list_head maydays
; /* MD: pwqs requesting rescue */
245 struct worker
*rescuer
; /* I: rescue worker */
247 int nr_drainers
; /* WQ: drain in progress */
248 int saved_max_active
; /* WQ: saved pwq max_active */
250 struct workqueue_attrs
*unbound_attrs
; /* WQ: only for unbound wqs */
251 struct pool_workqueue
*dfl_pwq
; /* WQ: only for unbound wqs */
254 struct wq_device
*wq_dev
; /* I: for sysfs interface */
256 #ifdef CONFIG_LOCKDEP
257 struct lockdep_map lockdep_map
;
259 char name
[WQ_NAME_LEN
]; /* I: workqueue name */
262 * Destruction of workqueue_struct is sched-RCU protected to allow
263 * walking the workqueues list without grabbing wq_pool_mutex.
264 * This is used to dump all workqueues from sysrq.
268 /* hot fields used during command issue, aligned to cacheline */
269 unsigned int flags ____cacheline_aligned
; /* WQ: WQ_* flags */
270 struct pool_workqueue __percpu
*cpu_pwqs
; /* I: per-cpu pwqs */
271 struct pool_workqueue __rcu
*numa_pwq_tbl
[]; /* FR: unbound pwqs indexed by node */
274 static struct kmem_cache
*pwq_cache
;
276 static cpumask_var_t
*wq_numa_possible_cpumask
;
277 /* possible CPUs of each node */
279 static bool wq_disable_numa
;
280 module_param_named(disable_numa
, wq_disable_numa
, bool, 0444);
282 /* see the comment above the definition of WQ_POWER_EFFICIENT */
283 static bool wq_power_efficient
= IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT
);
284 module_param_named(power_efficient
, wq_power_efficient
, bool, 0444);
286 static bool wq_numa_enabled
; /* unbound NUMA affinity enabled */
288 /* buf for wq_update_unbound_numa_attrs(), protected by CPU hotplug exclusion */
289 static struct workqueue_attrs
*wq_update_unbound_numa_attrs_buf
;
291 static DEFINE_MUTEX(wq_pool_mutex
); /* protects pools and workqueues list */
292 static DEFINE_SPINLOCK(wq_mayday_lock
); /* protects wq->maydays list */
294 static LIST_HEAD(workqueues
); /* PR: list of all workqueues */
295 static bool workqueue_freezing
; /* PL: have wqs started freezing? */
297 /* the per-cpu worker pools */
298 static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool
[NR_STD_WORKER_POOLS
],
301 static DEFINE_IDR(worker_pool_idr
); /* PR: idr of all pools */
303 /* PL: hash of all unbound pools keyed by pool->attrs */
304 static DEFINE_HASHTABLE(unbound_pool_hash
, UNBOUND_POOL_HASH_ORDER
);
306 /* I: attributes used when instantiating standard unbound pools on demand */
307 static struct workqueue_attrs
*unbound_std_wq_attrs
[NR_STD_WORKER_POOLS
];
309 /* I: attributes used when instantiating ordered pools on demand */
310 static struct workqueue_attrs
*ordered_wq_attrs
[NR_STD_WORKER_POOLS
];
312 struct workqueue_struct
*system_wq __read_mostly
;
313 EXPORT_SYMBOL(system_wq
);
314 struct workqueue_struct
*system_highpri_wq __read_mostly
;
315 EXPORT_SYMBOL_GPL(system_highpri_wq
);
316 struct workqueue_struct
*system_long_wq __read_mostly
;
317 EXPORT_SYMBOL_GPL(system_long_wq
);
318 struct workqueue_struct
*system_unbound_wq __read_mostly
;
319 EXPORT_SYMBOL_GPL(system_unbound_wq
);
320 struct workqueue_struct
*system_freezable_wq __read_mostly
;
321 EXPORT_SYMBOL_GPL(system_freezable_wq
);
322 struct workqueue_struct
*system_power_efficient_wq __read_mostly
;
323 EXPORT_SYMBOL_GPL(system_power_efficient_wq
);
324 struct workqueue_struct
*system_freezable_power_efficient_wq __read_mostly
;
325 EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq
);
327 static int worker_thread(void *__worker
);
328 static void copy_workqueue_attrs(struct workqueue_attrs
*to
,
329 const struct workqueue_attrs
*from
);
330 static void workqueue_sysfs_unregister(struct workqueue_struct
*wq
);
332 #define CREATE_TRACE_POINTS
333 #include <trace/events/workqueue.h>
335 #define assert_rcu_or_pool_mutex() \
336 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
337 lockdep_is_held(&wq_pool_mutex), \
338 "sched RCU or wq_pool_mutex should be held")
340 #define assert_rcu_or_wq_mutex(wq) \
341 rcu_lockdep_assert(rcu_read_lock_sched_held() || \
342 lockdep_is_held(&wq->mutex), \
343 "sched RCU or wq->mutex should be held")
345 #define for_each_cpu_worker_pool(pool, cpu) \
346 for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
347 (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
351 * for_each_pool - iterate through all worker_pools in the system
352 * @pool: iteration cursor
353 * @pi: integer used for iteration
355 * This must be called either with wq_pool_mutex held or sched RCU read
356 * locked. If the pool needs to be used beyond the locking in effect, the
357 * caller is responsible for guaranteeing that the pool stays online.
359 * The if/else clause exists only for the lockdep assertion and can be
362 #define for_each_pool(pool, pi) \
363 idr_for_each_entry(&worker_pool_idr, pool, pi) \
364 if (({ assert_rcu_or_pool_mutex(); false; })) { } \
368 * for_each_pool_worker - iterate through all workers of a worker_pool
369 * @worker: iteration cursor
370 * @pool: worker_pool to iterate workers of
372 * This must be called with @pool->attach_mutex.
374 * The if/else clause exists only for the lockdep assertion and can be
377 #define for_each_pool_worker(worker, pool) \
378 list_for_each_entry((worker), &(pool)->workers, node) \
379 if (({ lockdep_assert_held(&pool->attach_mutex); false; })) { } \
383 * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
384 * @pwq: iteration cursor
385 * @wq: the target workqueue
387 * This must be called either with wq->mutex held or sched RCU read locked.
388 * If the pwq needs to be used beyond the locking in effect, the caller is
389 * responsible for guaranteeing that the pwq stays online.
391 * The if/else clause exists only for the lockdep assertion and can be
394 #define for_each_pwq(pwq, wq) \
395 list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node) \
396 if (({ assert_rcu_or_wq_mutex(wq); false; })) { } \
399 #ifdef CONFIG_DEBUG_OBJECTS_WORK
401 static struct debug_obj_descr work_debug_descr
;
403 static void *work_debug_hint(void *addr
)
405 return ((struct work_struct
*) addr
)->func
;
409 * fixup_init is called when:
410 * - an active object is initialized
412 static int work_fixup_init(void *addr
, enum debug_obj_state state
)
414 struct work_struct
*work
= addr
;
417 case ODEBUG_STATE_ACTIVE
:
418 cancel_work_sync(work
);
419 debug_object_init(work
, &work_debug_descr
);
427 * fixup_activate is called when:
428 * - an active object is activated
429 * - an unknown object is activated (might be a statically initialized object)
431 static int work_fixup_activate(void *addr
, enum debug_obj_state state
)
433 struct work_struct
*work
= addr
;
437 case ODEBUG_STATE_NOTAVAILABLE
:
439 * This is not really a fixup. The work struct was
440 * statically initialized. We just make sure that it
441 * is tracked in the object tracker.
443 if (test_bit(WORK_STRUCT_STATIC_BIT
, work_data_bits(work
))) {
444 debug_object_init(work
, &work_debug_descr
);
445 debug_object_activate(work
, &work_debug_descr
);
451 case ODEBUG_STATE_ACTIVE
:
460 * fixup_free is called when:
461 * - an active object is freed
463 static int work_fixup_free(void *addr
, enum debug_obj_state state
)
465 struct work_struct
*work
= addr
;
468 case ODEBUG_STATE_ACTIVE
:
469 cancel_work_sync(work
);
470 debug_object_free(work
, &work_debug_descr
);
477 static struct debug_obj_descr work_debug_descr
= {
478 .name
= "work_struct",
479 .debug_hint
= work_debug_hint
,
480 .fixup_init
= work_fixup_init
,
481 .fixup_activate
= work_fixup_activate
,
482 .fixup_free
= work_fixup_free
,
485 static inline void debug_work_activate(struct work_struct
*work
)
487 debug_object_activate(work
, &work_debug_descr
);
490 static inline void debug_work_deactivate(struct work_struct
*work
)
492 debug_object_deactivate(work
, &work_debug_descr
);
495 void __init_work(struct work_struct
*work
, int onstack
)
498 debug_object_init_on_stack(work
, &work_debug_descr
);
500 debug_object_init(work
, &work_debug_descr
);
502 EXPORT_SYMBOL_GPL(__init_work
);
504 void destroy_work_on_stack(struct work_struct
*work
)
506 debug_object_free(work
, &work_debug_descr
);
508 EXPORT_SYMBOL_GPL(destroy_work_on_stack
);
510 void destroy_delayed_work_on_stack(struct delayed_work
*work
)
512 destroy_timer_on_stack(&work
->timer
);
513 debug_object_free(&work
->work
, &work_debug_descr
);
515 EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack
);
518 static inline void debug_work_activate(struct work_struct
*work
) { }
519 static inline void debug_work_deactivate(struct work_struct
*work
) { }
523 * worker_pool_assign_id - allocate ID and assing it to @pool
524 * @pool: the pool pointer of interest
526 * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
527 * successfully, -errno on failure.
529 static int worker_pool_assign_id(struct worker_pool
*pool
)
533 lockdep_assert_held(&wq_pool_mutex
);
535 ret
= idr_alloc(&worker_pool_idr
, pool
, 0, WORK_OFFQ_POOL_NONE
,
545 * unbound_pwq_by_node - return the unbound pool_workqueue for the given node
546 * @wq: the target workqueue
549 * This must be called either with pwq_lock held or sched RCU read locked.
550 * If the pwq needs to be used beyond the locking in effect, the caller is
551 * responsible for guaranteeing that the pwq stays online.
553 * Return: The unbound pool_workqueue for @node.
555 static struct pool_workqueue
*unbound_pwq_by_node(struct workqueue_struct
*wq
,
558 assert_rcu_or_wq_mutex(wq
);
559 return rcu_dereference_raw(wq
->numa_pwq_tbl
[node
]);
562 static unsigned int work_color_to_flags(int color
)
564 return color
<< WORK_STRUCT_COLOR_SHIFT
;
567 static int get_work_color(struct work_struct
*work
)
569 return (*work_data_bits(work
) >> WORK_STRUCT_COLOR_SHIFT
) &
570 ((1 << WORK_STRUCT_COLOR_BITS
) - 1);
573 static int work_next_color(int color
)
575 return (color
+ 1) % WORK_NR_COLORS
;
579 * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
580 * contain the pointer to the queued pwq. Once execution starts, the flag
581 * is cleared and the high bits contain OFFQ flags and pool ID.
583 * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
584 * and clear_work_data() can be used to set the pwq, pool or clear
585 * work->data. These functions should only be called while the work is
586 * owned - ie. while the PENDING bit is set.
588 * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
589 * corresponding to a work. Pool is available once the work has been
590 * queued anywhere after initialization until it is sync canceled. pwq is
591 * available only while the work item is queued.
593 * %WORK_OFFQ_CANCELING is used to mark a work item which is being
594 * canceled. While being canceled, a work item may have its PENDING set
595 * but stay off timer and worklist for arbitrarily long and nobody should
596 * try to steal the PENDING bit.
598 static inline void set_work_data(struct work_struct
*work
, unsigned long data
,
601 WARN_ON_ONCE(!work_pending(work
));
602 atomic_long_set(&work
->data
, data
| flags
| work_static(work
));
605 static void set_work_pwq(struct work_struct
*work
, struct pool_workqueue
*pwq
,
606 unsigned long extra_flags
)
608 set_work_data(work
, (unsigned long)pwq
,
609 WORK_STRUCT_PENDING
| WORK_STRUCT_PWQ
| extra_flags
);
612 static void set_work_pool_and_keep_pending(struct work_struct
*work
,
615 set_work_data(work
, (unsigned long)pool_id
<< WORK_OFFQ_POOL_SHIFT
,
616 WORK_STRUCT_PENDING
);
619 static void set_work_pool_and_clear_pending(struct work_struct
*work
,
623 * The following wmb is paired with the implied mb in
624 * test_and_set_bit(PENDING) and ensures all updates to @work made
625 * here are visible to and precede any updates by the next PENDING
629 set_work_data(work
, (unsigned long)pool_id
<< WORK_OFFQ_POOL_SHIFT
, 0);
632 static void clear_work_data(struct work_struct
*work
)
634 smp_wmb(); /* see set_work_pool_and_clear_pending() */
635 set_work_data(work
, WORK_STRUCT_NO_POOL
, 0);
638 static struct pool_workqueue
*get_work_pwq(struct work_struct
*work
)
640 unsigned long data
= atomic_long_read(&work
->data
);
642 if (data
& WORK_STRUCT_PWQ
)
643 return (void *)(data
& WORK_STRUCT_WQ_DATA_MASK
);
649 * get_work_pool - return the worker_pool a given work was associated with
650 * @work: the work item of interest
652 * Pools are created and destroyed under wq_pool_mutex, and allows read
653 * access under sched-RCU read lock. As such, this function should be
654 * called under wq_pool_mutex or with preemption disabled.
656 * All fields of the returned pool are accessible as long as the above
657 * mentioned locking is in effect. If the returned pool needs to be used
658 * beyond the critical section, the caller is responsible for ensuring the
659 * returned pool is and stays online.
661 * Return: The worker_pool @work was last associated with. %NULL if none.
663 static struct worker_pool
*get_work_pool(struct work_struct
*work
)
665 unsigned long data
= atomic_long_read(&work
->data
);
668 assert_rcu_or_pool_mutex();
670 if (data
& WORK_STRUCT_PWQ
)
671 return ((struct pool_workqueue
*)
672 (data
& WORK_STRUCT_WQ_DATA_MASK
))->pool
;
674 pool_id
= data
>> WORK_OFFQ_POOL_SHIFT
;
675 if (pool_id
== WORK_OFFQ_POOL_NONE
)
678 return idr_find(&worker_pool_idr
, pool_id
);
682 * get_work_pool_id - return the worker pool ID a given work is associated with
683 * @work: the work item of interest
685 * Return: The worker_pool ID @work was last associated with.
686 * %WORK_OFFQ_POOL_NONE if none.
688 static int get_work_pool_id(struct work_struct
*work
)
690 unsigned long data
= atomic_long_read(&work
->data
);
692 if (data
& WORK_STRUCT_PWQ
)
693 return ((struct pool_workqueue
*)
694 (data
& WORK_STRUCT_WQ_DATA_MASK
))->pool
->id
;
696 return data
>> WORK_OFFQ_POOL_SHIFT
;
699 static void mark_work_canceling(struct work_struct
*work
)
701 unsigned long pool_id
= get_work_pool_id(work
);
703 pool_id
<<= WORK_OFFQ_POOL_SHIFT
;
704 set_work_data(work
, pool_id
| WORK_OFFQ_CANCELING
, WORK_STRUCT_PENDING
);
707 static bool work_is_canceling(struct work_struct
*work
)
709 unsigned long data
= atomic_long_read(&work
->data
);
711 return !(data
& WORK_STRUCT_PWQ
) && (data
& WORK_OFFQ_CANCELING
);
715 * Policy functions. These define the policies on how the global worker
716 * pools are managed. Unless noted otherwise, these functions assume that
717 * they're being called with pool->lock held.
720 static bool __need_more_worker(struct worker_pool
*pool
)
722 return !atomic_read(&pool
->nr_running
);
726 * Need to wake up a worker? Called from anything but currently
729 * Note that, because unbound workers never contribute to nr_running, this
730 * function will always return %true for unbound pools as long as the
731 * worklist isn't empty.
733 static bool need_more_worker(struct worker_pool
*pool
)
735 return !list_empty(&pool
->worklist
) && __need_more_worker(pool
);
738 /* Can I start working? Called from busy but !running workers. */
739 static bool may_start_working(struct worker_pool
*pool
)
741 return pool
->nr_idle
;
744 /* Do I need to keep working? Called from currently running workers. */
745 static bool keep_working(struct worker_pool
*pool
)
747 return !list_empty(&pool
->worklist
) &&
748 atomic_read(&pool
->nr_running
) <= 1;
751 /* Do we need a new worker? Called from manager. */
752 static bool need_to_create_worker(struct worker_pool
*pool
)
754 return need_more_worker(pool
) && !may_start_working(pool
);
757 /* Do we have too many workers and should some go away? */
758 static bool too_many_workers(struct worker_pool
*pool
)
760 bool managing
= mutex_is_locked(&pool
->manager_arb
);
761 int nr_idle
= pool
->nr_idle
+ managing
; /* manager is considered idle */
762 int nr_busy
= pool
->nr_workers
- nr_idle
;
764 return nr_idle
> 2 && (nr_idle
- 2) * MAX_IDLE_WORKERS_RATIO
>= nr_busy
;
771 /* Return the first idle worker. Safe with preemption disabled */
772 static struct worker
*first_idle_worker(struct worker_pool
*pool
)
774 if (unlikely(list_empty(&pool
->idle_list
)))
777 return list_first_entry(&pool
->idle_list
, struct worker
, entry
);
781 * wake_up_worker - wake up an idle worker
782 * @pool: worker pool to wake worker from
784 * Wake up the first idle worker of @pool.
787 * spin_lock_irq(pool->lock).
789 static void wake_up_worker(struct worker_pool
*pool
)
791 struct worker
*worker
= first_idle_worker(pool
);
794 wake_up_process(worker
->task
);
798 * wq_worker_waking_up - a worker is waking up
799 * @task: task waking up
800 * @cpu: CPU @task is waking up to
802 * This function is called during try_to_wake_up() when a worker is
806 * spin_lock_irq(rq->lock)
808 void wq_worker_waking_up(struct task_struct
*task
, int cpu
)
810 struct worker
*worker
= kthread_data(task
);
812 if (!(worker
->flags
& WORKER_NOT_RUNNING
)) {
813 WARN_ON_ONCE(worker
->pool
->cpu
!= cpu
);
814 atomic_inc(&worker
->pool
->nr_running
);
819 * wq_worker_sleeping - a worker is going to sleep
820 * @task: task going to sleep
821 * @cpu: CPU in question, must be the current CPU number
823 * This function is called during schedule() when a busy worker is
824 * going to sleep. Worker on the same cpu can be woken up by
825 * returning pointer to its task.
828 * spin_lock_irq(rq->lock)
831 * Worker task on @cpu to wake up, %NULL if none.
833 struct task_struct
*wq_worker_sleeping(struct task_struct
*task
, int cpu
)
835 struct worker
*worker
= kthread_data(task
), *to_wakeup
= NULL
;
836 struct worker_pool
*pool
;
839 * Rescuers, which may not have all the fields set up like normal
840 * workers, also reach here, let's not access anything before
841 * checking NOT_RUNNING.
843 if (worker
->flags
& WORKER_NOT_RUNNING
)
848 /* this can only happen on the local cpu */
849 if (WARN_ON_ONCE(cpu
!= raw_smp_processor_id() || pool
->cpu
!= cpu
))
853 * The counterpart of the following dec_and_test, implied mb,
854 * worklist not empty test sequence is in insert_work().
855 * Please read comment there.
857 * NOT_RUNNING is clear. This means that we're bound to and
858 * running on the local cpu w/ rq lock held and preemption
859 * disabled, which in turn means that none else could be
860 * manipulating idle_list, so dereferencing idle_list without pool
863 if (atomic_dec_and_test(&pool
->nr_running
) &&
864 !list_empty(&pool
->worklist
))
865 to_wakeup
= first_idle_worker(pool
);
866 return to_wakeup
? to_wakeup
->task
: NULL
;
870 * worker_set_flags - set worker flags and adjust nr_running accordingly
872 * @flags: flags to set
874 * Set @flags in @worker->flags and adjust nr_running accordingly.
877 * spin_lock_irq(pool->lock)
879 static inline void worker_set_flags(struct worker
*worker
, unsigned int flags
)
881 struct worker_pool
*pool
= worker
->pool
;
883 WARN_ON_ONCE(worker
->task
!= current
);
885 /* If transitioning into NOT_RUNNING, adjust nr_running. */
886 if ((flags
& WORKER_NOT_RUNNING
) &&
887 !(worker
->flags
& WORKER_NOT_RUNNING
)) {
888 atomic_dec(&pool
->nr_running
);
891 worker
->flags
|= flags
;
895 * worker_clr_flags - clear worker flags and adjust nr_running accordingly
897 * @flags: flags to clear
899 * Clear @flags in @worker->flags and adjust nr_running accordingly.
902 * spin_lock_irq(pool->lock)
904 static inline void worker_clr_flags(struct worker
*worker
, unsigned int flags
)
906 struct worker_pool
*pool
= worker
->pool
;
907 unsigned int oflags
= worker
->flags
;
909 WARN_ON_ONCE(worker
->task
!= current
);
911 worker
->flags
&= ~flags
;
914 * If transitioning out of NOT_RUNNING, increment nr_running. Note
915 * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
916 * of multiple flags, not a single flag.
918 if ((flags
& WORKER_NOT_RUNNING
) && (oflags
& WORKER_NOT_RUNNING
))
919 if (!(worker
->flags
& WORKER_NOT_RUNNING
))
920 atomic_inc(&pool
->nr_running
);
924 * find_worker_executing_work - find worker which is executing a work
925 * @pool: pool of interest
926 * @work: work to find worker for
928 * Find a worker which is executing @work on @pool by searching
929 * @pool->busy_hash which is keyed by the address of @work. For a worker
930 * to match, its current execution should match the address of @work and
931 * its work function. This is to avoid unwanted dependency between
932 * unrelated work executions through a work item being recycled while still
935 * This is a bit tricky. A work item may be freed once its execution
936 * starts and nothing prevents the freed area from being recycled for
937 * another work item. If the same work item address ends up being reused
938 * before the original execution finishes, workqueue will identify the
939 * recycled work item as currently executing and make it wait until the
940 * current execution finishes, introducing an unwanted dependency.
942 * This function checks the work item address and work function to avoid
943 * false positives. Note that this isn't complete as one may construct a
944 * work function which can introduce dependency onto itself through a
945 * recycled work item. Well, if somebody wants to shoot oneself in the
946 * foot that badly, there's only so much we can do, and if such deadlock
947 * actually occurs, it should be easy to locate the culprit work function.
950 * spin_lock_irq(pool->lock).
953 * Pointer to worker which is executing @work if found, %NULL
956 static struct worker
*find_worker_executing_work(struct worker_pool
*pool
,
957 struct work_struct
*work
)
959 struct worker
*worker
;
961 hash_for_each_possible(pool
->busy_hash
, worker
, hentry
,
963 if (worker
->current_work
== work
&&
964 worker
->current_func
== work
->func
)
971 * move_linked_works - move linked works to a list
972 * @work: start of series of works to be scheduled
973 * @head: target list to append @work to
974 * @nextp: out paramter for nested worklist walking
976 * Schedule linked works starting from @work to @head. Work series to
977 * be scheduled starts at @work and includes any consecutive work with
978 * WORK_STRUCT_LINKED set in its predecessor.
980 * If @nextp is not NULL, it's updated to point to the next work of
981 * the last scheduled work. This allows move_linked_works() to be
982 * nested inside outer list_for_each_entry_safe().
985 * spin_lock_irq(pool->lock).
987 static void move_linked_works(struct work_struct
*work
, struct list_head
*head
,
988 struct work_struct
**nextp
)
990 struct work_struct
*n
;
993 * Linked worklist will always end before the end of the list,
994 * use NULL for list head.
996 list_for_each_entry_safe_from(work
, n
, NULL
, entry
) {
997 list_move_tail(&work
->entry
, head
);
998 if (!(*work_data_bits(work
) & WORK_STRUCT_LINKED
))
1003 * If we're already inside safe list traversal and have moved
1004 * multiple works to the scheduled queue, the next position
1005 * needs to be updated.
1012 * get_pwq - get an extra reference on the specified pool_workqueue
1013 * @pwq: pool_workqueue to get
1015 * Obtain an extra reference on @pwq. The caller should guarantee that
1016 * @pwq has positive refcnt and be holding the matching pool->lock.
1018 static void get_pwq(struct pool_workqueue
*pwq
)
1020 lockdep_assert_held(&pwq
->pool
->lock
);
1021 WARN_ON_ONCE(pwq
->refcnt
<= 0);
1026 * put_pwq - put a pool_workqueue reference
1027 * @pwq: pool_workqueue to put
1029 * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
1030 * destruction. The caller should be holding the matching pool->lock.
1032 static void put_pwq(struct pool_workqueue
*pwq
)
1034 lockdep_assert_held(&pwq
->pool
->lock
);
1035 if (likely(--pwq
->refcnt
))
1037 if (WARN_ON_ONCE(!(pwq
->wq
->flags
& WQ_UNBOUND
)))
1040 * @pwq can't be released under pool->lock, bounce to
1041 * pwq_unbound_release_workfn(). This never recurses on the same
1042 * pool->lock as this path is taken only for unbound workqueues and
1043 * the release work item is scheduled on a per-cpu workqueue. To
1044 * avoid lockdep warning, unbound pool->locks are given lockdep
1045 * subclass of 1 in get_unbound_pool().
1047 schedule_work(&pwq
->unbound_release_work
);
1051 * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1052 * @pwq: pool_workqueue to put (can be %NULL)
1054 * put_pwq() with locking. This function also allows %NULL @pwq.
1056 static void put_pwq_unlocked(struct pool_workqueue
*pwq
)
1060 * As both pwqs and pools are sched-RCU protected, the
1061 * following lock operations are safe.
1063 spin_lock_irq(&pwq
->pool
->lock
);
1065 spin_unlock_irq(&pwq
->pool
->lock
);
1069 static void pwq_activate_delayed_work(struct work_struct
*work
)
1071 struct pool_workqueue
*pwq
= get_work_pwq(work
);
1073 trace_workqueue_activate_work(work
);
1074 move_linked_works(work
, &pwq
->pool
->worklist
, NULL
);
1075 __clear_bit(WORK_STRUCT_DELAYED_BIT
, work_data_bits(work
));
1079 static void pwq_activate_first_delayed(struct pool_workqueue
*pwq
)
1081 struct work_struct
*work
= list_first_entry(&pwq
->delayed_works
,
1082 struct work_struct
, entry
);
1084 pwq_activate_delayed_work(work
);
1088 * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1089 * @pwq: pwq of interest
1090 * @color: color of work which left the queue
1092 * A work either has completed or is removed from pending queue,
1093 * decrement nr_in_flight of its pwq and handle workqueue flushing.
1096 * spin_lock_irq(pool->lock).
1098 static void pwq_dec_nr_in_flight(struct pool_workqueue
*pwq
, int color
)
1100 /* uncolored work items don't participate in flushing or nr_active */
1101 if (color
== WORK_NO_COLOR
)
1104 pwq
->nr_in_flight
[color
]--;
1107 if (!list_empty(&pwq
->delayed_works
)) {
1108 /* one down, submit a delayed one */
1109 if (pwq
->nr_active
< pwq
->max_active
)
1110 pwq_activate_first_delayed(pwq
);
1113 /* is flush in progress and are we at the flushing tip? */
1114 if (likely(pwq
->flush_color
!= color
))
1117 /* are there still in-flight works? */
1118 if (pwq
->nr_in_flight
[color
])
1121 /* this pwq is done, clear flush_color */
1122 pwq
->flush_color
= -1;
1125 * If this was the last pwq, wake up the first flusher. It
1126 * will handle the rest.
1128 if (atomic_dec_and_test(&pwq
->wq
->nr_pwqs_to_flush
))
1129 complete(&pwq
->wq
->first_flusher
->done
);
1135 * try_to_grab_pending - steal work item from worklist and disable irq
1136 * @work: work item to steal
1137 * @is_dwork: @work is a delayed_work
1138 * @flags: place to store irq state
1140 * Try to grab PENDING bit of @work. This function can handle @work in any
1141 * stable state - idle, on timer or on worklist.
1144 * 1 if @work was pending and we successfully stole PENDING
1145 * 0 if @work was idle and we claimed PENDING
1146 * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1147 * -ENOENT if someone else is canceling @work, this state may persist
1148 * for arbitrarily long
1151 * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1152 * interrupted while holding PENDING and @work off queue, irq must be
1153 * disabled on entry. This, combined with delayed_work->timer being
1154 * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1156 * On successful return, >= 0, irq is disabled and the caller is
1157 * responsible for releasing it using local_irq_restore(*@flags).
1159 * This function is safe to call from any context including IRQ handler.
1161 static int try_to_grab_pending(struct work_struct
*work
, bool is_dwork
,
1162 unsigned long *flags
)
1164 struct worker_pool
*pool
;
1165 struct pool_workqueue
*pwq
;
1167 local_irq_save(*flags
);
1169 /* try to steal the timer if it exists */
1171 struct delayed_work
*dwork
= to_delayed_work(work
);
1174 * dwork->timer is irqsafe. If del_timer() fails, it's
1175 * guaranteed that the timer is not queued anywhere and not
1176 * running on the local CPU.
1178 if (likely(del_timer(&dwork
->timer
)))
1182 /* try to claim PENDING the normal way */
1183 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
)))
1187 * The queueing is in progress, or it is already queued. Try to
1188 * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1190 pool
= get_work_pool(work
);
1194 spin_lock(&pool
->lock
);
1196 * work->data is guaranteed to point to pwq only while the work
1197 * item is queued on pwq->wq, and both updating work->data to point
1198 * to pwq on queueing and to pool on dequeueing are done under
1199 * pwq->pool->lock. This in turn guarantees that, if work->data
1200 * points to pwq which is associated with a locked pool, the work
1201 * item is currently queued on that pool.
1203 pwq
= get_work_pwq(work
);
1204 if (pwq
&& pwq
->pool
== pool
) {
1205 debug_work_deactivate(work
);
1208 * A delayed work item cannot be grabbed directly because
1209 * it might have linked NO_COLOR work items which, if left
1210 * on the delayed_list, will confuse pwq->nr_active
1211 * management later on and cause stall. Make sure the work
1212 * item is activated before grabbing.
1214 if (*work_data_bits(work
) & WORK_STRUCT_DELAYED
)
1215 pwq_activate_delayed_work(work
);
1217 list_del_init(&work
->entry
);
1218 pwq_dec_nr_in_flight(pwq
, get_work_color(work
));
1220 /* work->data points to pwq iff queued, point to pool */
1221 set_work_pool_and_keep_pending(work
, pool
->id
);
1223 spin_unlock(&pool
->lock
);
1226 spin_unlock(&pool
->lock
);
1228 local_irq_restore(*flags
);
1229 if (work_is_canceling(work
))
1236 * insert_work - insert a work into a pool
1237 * @pwq: pwq @work belongs to
1238 * @work: work to insert
1239 * @head: insertion point
1240 * @extra_flags: extra WORK_STRUCT_* flags to set
1242 * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1243 * work_struct flags.
1246 * spin_lock_irq(pool->lock).
1248 static void insert_work(struct pool_workqueue
*pwq
, struct work_struct
*work
,
1249 struct list_head
*head
, unsigned int extra_flags
)
1251 struct worker_pool
*pool
= pwq
->pool
;
1253 /* we own @work, set data and link */
1254 set_work_pwq(work
, pwq
, extra_flags
);
1255 list_add_tail(&work
->entry
, head
);
1259 * Ensure either wq_worker_sleeping() sees the above
1260 * list_add_tail() or we see zero nr_running to avoid workers lying
1261 * around lazily while there are works to be processed.
1265 if (__need_more_worker(pool
))
1266 wake_up_worker(pool
);
1270 * Test whether @work is being queued from another work executing on the
1273 static bool is_chained_work(struct workqueue_struct
*wq
)
1275 struct worker
*worker
;
1277 worker
= current_wq_worker();
1279 * Return %true iff I'm a worker execuing a work item on @wq. If
1280 * I'm @worker, it's safe to dereference it without locking.
1282 return worker
&& worker
->current_pwq
->wq
== wq
;
1285 static void __queue_work(int cpu
, struct workqueue_struct
*wq
,
1286 struct work_struct
*work
)
1288 struct pool_workqueue
*pwq
;
1289 struct worker_pool
*last_pool
;
1290 struct list_head
*worklist
;
1291 unsigned int work_flags
;
1292 unsigned int req_cpu
= cpu
;
1295 * While a work item is PENDING && off queue, a task trying to
1296 * steal the PENDING will busy-loop waiting for it to either get
1297 * queued or lose PENDING. Grabbing PENDING and queueing should
1298 * happen with IRQ disabled.
1300 WARN_ON_ONCE(!irqs_disabled());
1302 debug_work_activate(work
);
1304 /* if draining, only works from the same workqueue are allowed */
1305 if (unlikely(wq
->flags
& __WQ_DRAINING
) &&
1306 WARN_ON_ONCE(!is_chained_work(wq
)))
1309 if (req_cpu
== WORK_CPU_UNBOUND
)
1310 cpu
= raw_smp_processor_id();
1312 /* pwq which will be used unless @work is executing elsewhere */
1313 if (!(wq
->flags
& WQ_UNBOUND
))
1314 pwq
= per_cpu_ptr(wq
->cpu_pwqs
, cpu
);
1316 pwq
= unbound_pwq_by_node(wq
, cpu_to_node(cpu
));
1319 * If @work was previously on a different pool, it might still be
1320 * running there, in which case the work needs to be queued on that
1321 * pool to guarantee non-reentrancy.
1323 last_pool
= get_work_pool(work
);
1324 if (last_pool
&& last_pool
!= pwq
->pool
) {
1325 struct worker
*worker
;
1327 spin_lock(&last_pool
->lock
);
1329 worker
= find_worker_executing_work(last_pool
, work
);
1331 if (worker
&& worker
->current_pwq
->wq
== wq
) {
1332 pwq
= worker
->current_pwq
;
1334 /* meh... not running there, queue here */
1335 spin_unlock(&last_pool
->lock
);
1336 spin_lock(&pwq
->pool
->lock
);
1339 spin_lock(&pwq
->pool
->lock
);
1343 * pwq is determined and locked. For unbound pools, we could have
1344 * raced with pwq release and it could already be dead. If its
1345 * refcnt is zero, repeat pwq selection. Note that pwqs never die
1346 * without another pwq replacing it in the numa_pwq_tbl or while
1347 * work items are executing on it, so the retrying is guaranteed to
1348 * make forward-progress.
1350 if (unlikely(!pwq
->refcnt
)) {
1351 if (wq
->flags
& WQ_UNBOUND
) {
1352 spin_unlock(&pwq
->pool
->lock
);
1357 WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
1361 /* pwq determined, queue */
1362 trace_workqueue_queue_work(req_cpu
, pwq
, work
);
1364 if (WARN_ON(!list_empty(&work
->entry
))) {
1365 spin_unlock(&pwq
->pool
->lock
);
1369 pwq
->nr_in_flight
[pwq
->work_color
]++;
1370 work_flags
= work_color_to_flags(pwq
->work_color
);
1372 if (likely(pwq
->nr_active
< pwq
->max_active
)) {
1373 trace_workqueue_activate_work(work
);
1375 worklist
= &pwq
->pool
->worklist
;
1377 work_flags
|= WORK_STRUCT_DELAYED
;
1378 worklist
= &pwq
->delayed_works
;
1381 insert_work(pwq
, work
, worklist
, work_flags
);
1383 spin_unlock(&pwq
->pool
->lock
);
1387 * queue_work_on - queue work on specific cpu
1388 * @cpu: CPU number to execute work on
1389 * @wq: workqueue to use
1390 * @work: work to queue
1392 * We queue the work to a specific CPU, the caller must ensure it
1395 * Return: %false if @work was already on a queue, %true otherwise.
1397 bool queue_work_on(int cpu
, struct workqueue_struct
*wq
,
1398 struct work_struct
*work
)
1401 unsigned long flags
;
1403 local_irq_save(flags
);
1405 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
))) {
1406 __queue_work(cpu
, wq
, work
);
1410 local_irq_restore(flags
);
1413 EXPORT_SYMBOL(queue_work_on
);
1415 void delayed_work_timer_fn(unsigned long __data
)
1417 struct delayed_work
*dwork
= (struct delayed_work
*)__data
;
1419 /* should have been called from irqsafe timer with irq already off */
1420 __queue_work(dwork
->cpu
, dwork
->wq
, &dwork
->work
);
1422 EXPORT_SYMBOL(delayed_work_timer_fn
);
1424 static void __queue_delayed_work(int cpu
, struct workqueue_struct
*wq
,
1425 struct delayed_work
*dwork
, unsigned long delay
)
1427 struct timer_list
*timer
= &dwork
->timer
;
1428 struct work_struct
*work
= &dwork
->work
;
1430 WARN_ON_ONCE(timer
->function
!= delayed_work_timer_fn
||
1431 timer
->data
!= (unsigned long)dwork
);
1432 WARN_ON_ONCE(timer_pending(timer
));
1433 WARN_ON_ONCE(!list_empty(&work
->entry
));
1436 * If @delay is 0, queue @dwork->work immediately. This is for
1437 * both optimization and correctness. The earliest @timer can
1438 * expire is on the closest next tick and delayed_work users depend
1439 * on that there's no such delay when @delay is 0.
1442 __queue_work(cpu
, wq
, &dwork
->work
);
1446 timer_stats_timer_set_start_info(&dwork
->timer
);
1450 timer
->expires
= jiffies
+ delay
;
1452 if (unlikely(cpu
!= WORK_CPU_UNBOUND
))
1453 add_timer_on(timer
, cpu
);
1459 * queue_delayed_work_on - queue work on specific CPU after delay
1460 * @cpu: CPU number to execute work on
1461 * @wq: workqueue to use
1462 * @dwork: work to queue
1463 * @delay: number of jiffies to wait before queueing
1465 * Return: %false if @work was already on a queue, %true otherwise. If
1466 * @delay is zero and @dwork is idle, it will be scheduled for immediate
1469 bool queue_delayed_work_on(int cpu
, struct workqueue_struct
*wq
,
1470 struct delayed_work
*dwork
, unsigned long delay
)
1472 struct work_struct
*work
= &dwork
->work
;
1474 unsigned long flags
;
1476 /* read the comment in __queue_work() */
1477 local_irq_save(flags
);
1479 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(work
))) {
1480 __queue_delayed_work(cpu
, wq
, dwork
, delay
);
1484 local_irq_restore(flags
);
1487 EXPORT_SYMBOL(queue_delayed_work_on
);
1490 * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
1491 * @cpu: CPU number to execute work on
1492 * @wq: workqueue to use
1493 * @dwork: work to queue
1494 * @delay: number of jiffies to wait before queueing
1496 * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
1497 * modify @dwork's timer so that it expires after @delay. If @delay is
1498 * zero, @work is guaranteed to be scheduled immediately regardless of its
1501 * Return: %false if @dwork was idle and queued, %true if @dwork was
1502 * pending and its timer was modified.
1504 * This function is safe to call from any context including IRQ handler.
1505 * See try_to_grab_pending() for details.
1507 bool mod_delayed_work_on(int cpu
, struct workqueue_struct
*wq
,
1508 struct delayed_work
*dwork
, unsigned long delay
)
1510 unsigned long flags
;
1514 ret
= try_to_grab_pending(&dwork
->work
, true, &flags
);
1515 } while (unlikely(ret
== -EAGAIN
));
1517 if (likely(ret
>= 0)) {
1518 __queue_delayed_work(cpu
, wq
, dwork
, delay
);
1519 local_irq_restore(flags
);
1522 /* -ENOENT from try_to_grab_pending() becomes %true */
1525 EXPORT_SYMBOL_GPL(mod_delayed_work_on
);
1528 * worker_enter_idle - enter idle state
1529 * @worker: worker which is entering idle state
1531 * @worker is entering idle state. Update stats and idle timer if
1535 * spin_lock_irq(pool->lock).
1537 static void worker_enter_idle(struct worker
*worker
)
1539 struct worker_pool
*pool
= worker
->pool
;
1541 if (WARN_ON_ONCE(worker
->flags
& WORKER_IDLE
) ||
1542 WARN_ON_ONCE(!list_empty(&worker
->entry
) &&
1543 (worker
->hentry
.next
|| worker
->hentry
.pprev
)))
1546 /* can't use worker_set_flags(), also called from create_worker() */
1547 worker
->flags
|= WORKER_IDLE
;
1549 worker
->last_active
= jiffies
;
1551 /* idle_list is LIFO */
1552 list_add(&worker
->entry
, &pool
->idle_list
);
1554 if (too_many_workers(pool
) && !timer_pending(&pool
->idle_timer
))
1555 mod_timer(&pool
->idle_timer
, jiffies
+ IDLE_WORKER_TIMEOUT
);
1558 * Sanity check nr_running. Because wq_unbind_fn() releases
1559 * pool->lock between setting %WORKER_UNBOUND and zapping
1560 * nr_running, the warning may trigger spuriously. Check iff
1561 * unbind is not in progress.
1563 WARN_ON_ONCE(!(pool
->flags
& POOL_DISASSOCIATED
) &&
1564 pool
->nr_workers
== pool
->nr_idle
&&
1565 atomic_read(&pool
->nr_running
));
1569 * worker_leave_idle - leave idle state
1570 * @worker: worker which is leaving idle state
1572 * @worker is leaving idle state. Update stats.
1575 * spin_lock_irq(pool->lock).
1577 static void worker_leave_idle(struct worker
*worker
)
1579 struct worker_pool
*pool
= worker
->pool
;
1581 if (WARN_ON_ONCE(!(worker
->flags
& WORKER_IDLE
)))
1583 worker_clr_flags(worker
, WORKER_IDLE
);
1585 list_del_init(&worker
->entry
);
1588 static struct worker
*alloc_worker(int node
)
1590 struct worker
*worker
;
1592 worker
= kzalloc_node(sizeof(*worker
), GFP_KERNEL
, node
);
1594 INIT_LIST_HEAD(&worker
->entry
);
1595 INIT_LIST_HEAD(&worker
->scheduled
);
1596 INIT_LIST_HEAD(&worker
->node
);
1597 /* on creation a worker is in !idle && prep state */
1598 worker
->flags
= WORKER_PREP
;
1604 * worker_attach_to_pool() - attach a worker to a pool
1605 * @worker: worker to be attached
1606 * @pool: the target pool
1608 * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
1609 * cpu-binding of @worker are kept coordinated with the pool across
1612 static void worker_attach_to_pool(struct worker
*worker
,
1613 struct worker_pool
*pool
)
1615 mutex_lock(&pool
->attach_mutex
);
1618 * set_cpus_allowed_ptr() will fail if the cpumask doesn't have any
1619 * online CPUs. It'll be re-applied when any of the CPUs come up.
1621 set_cpus_allowed_ptr(worker
->task
, pool
->attrs
->cpumask
);
1624 * The pool->attach_mutex ensures %POOL_DISASSOCIATED remains
1625 * stable across this function. See the comments above the
1626 * flag definition for details.
1628 if (pool
->flags
& POOL_DISASSOCIATED
)
1629 worker
->flags
|= WORKER_UNBOUND
;
1631 list_add_tail(&worker
->node
, &pool
->workers
);
1633 mutex_unlock(&pool
->attach_mutex
);
1637 * worker_detach_from_pool() - detach a worker from its pool
1638 * @worker: worker which is attached to its pool
1639 * @pool: the pool @worker is attached to
1641 * Undo the attaching which had been done in worker_attach_to_pool(). The
1642 * caller worker shouldn't access to the pool after detached except it has
1643 * other reference to the pool.
1645 static void worker_detach_from_pool(struct worker
*worker
,
1646 struct worker_pool
*pool
)
1648 struct completion
*detach_completion
= NULL
;
1650 mutex_lock(&pool
->attach_mutex
);
1651 list_del(&worker
->node
);
1652 if (list_empty(&pool
->workers
))
1653 detach_completion
= pool
->detach_completion
;
1654 mutex_unlock(&pool
->attach_mutex
);
1656 /* clear leftover flags without pool->lock after it is detached */
1657 worker
->flags
&= ~(WORKER_UNBOUND
| WORKER_REBOUND
);
1659 if (detach_completion
)
1660 complete(detach_completion
);
1664 * create_worker - create a new workqueue worker
1665 * @pool: pool the new worker will belong to
1667 * Create and start a new worker which is attached to @pool.
1670 * Might sleep. Does GFP_KERNEL allocations.
1673 * Pointer to the newly created worker.
1675 static struct worker
*create_worker(struct worker_pool
*pool
)
1677 struct worker
*worker
= NULL
;
1681 /* ID is needed to determine kthread name */
1682 id
= ida_simple_get(&pool
->worker_ida
, 0, 0, GFP_KERNEL
);
1686 worker
= alloc_worker(pool
->node
);
1690 worker
->pool
= pool
;
1694 snprintf(id_buf
, sizeof(id_buf
), "%d:%d%s", pool
->cpu
, id
,
1695 pool
->attrs
->nice
< 0 ? "H" : "");
1697 snprintf(id_buf
, sizeof(id_buf
), "u%d:%d", pool
->id
, id
);
1699 worker
->task
= kthread_create_on_node(worker_thread
, worker
, pool
->node
,
1700 "kworker/%s", id_buf
);
1701 if (IS_ERR(worker
->task
))
1704 set_user_nice(worker
->task
, pool
->attrs
->nice
);
1706 /* prevent userland from meddling with cpumask of workqueue workers */
1707 worker
->task
->flags
|= PF_NO_SETAFFINITY
;
1709 /* successful, attach the worker to the pool */
1710 worker_attach_to_pool(worker
, pool
);
1712 /* start the newly created worker */
1713 spin_lock_irq(&pool
->lock
);
1714 worker
->pool
->nr_workers
++;
1715 worker_enter_idle(worker
);
1716 wake_up_process(worker
->task
);
1717 spin_unlock_irq(&pool
->lock
);
1723 ida_simple_remove(&pool
->worker_ida
, id
);
1729 * destroy_worker - destroy a workqueue worker
1730 * @worker: worker to be destroyed
1732 * Destroy @worker and adjust @pool stats accordingly. The worker should
1736 * spin_lock_irq(pool->lock).
1738 static void destroy_worker(struct worker
*worker
)
1740 struct worker_pool
*pool
= worker
->pool
;
1742 lockdep_assert_held(&pool
->lock
);
1744 /* sanity check frenzy */
1745 if (WARN_ON(worker
->current_work
) ||
1746 WARN_ON(!list_empty(&worker
->scheduled
)) ||
1747 WARN_ON(!(worker
->flags
& WORKER_IDLE
)))
1753 list_del_init(&worker
->entry
);
1754 worker
->flags
|= WORKER_DIE
;
1755 wake_up_process(worker
->task
);
1758 static void idle_worker_timeout(unsigned long __pool
)
1760 struct worker_pool
*pool
= (void *)__pool
;
1762 spin_lock_irq(&pool
->lock
);
1764 while (too_many_workers(pool
)) {
1765 struct worker
*worker
;
1766 unsigned long expires
;
1768 /* idle_list is kept in LIFO order, check the last one */
1769 worker
= list_entry(pool
->idle_list
.prev
, struct worker
, entry
);
1770 expires
= worker
->last_active
+ IDLE_WORKER_TIMEOUT
;
1772 if (time_before(jiffies
, expires
)) {
1773 mod_timer(&pool
->idle_timer
, expires
);
1777 destroy_worker(worker
);
1780 spin_unlock_irq(&pool
->lock
);
1783 static void send_mayday(struct work_struct
*work
)
1785 struct pool_workqueue
*pwq
= get_work_pwq(work
);
1786 struct workqueue_struct
*wq
= pwq
->wq
;
1788 lockdep_assert_held(&wq_mayday_lock
);
1793 /* mayday mayday mayday */
1794 if (list_empty(&pwq
->mayday_node
)) {
1796 * If @pwq is for an unbound wq, its base ref may be put at
1797 * any time due to an attribute change. Pin @pwq until the
1798 * rescuer is done with it.
1801 list_add_tail(&pwq
->mayday_node
, &wq
->maydays
);
1802 wake_up_process(wq
->rescuer
->task
);
1806 static void pool_mayday_timeout(unsigned long __pool
)
1808 struct worker_pool
*pool
= (void *)__pool
;
1809 struct work_struct
*work
;
1811 spin_lock_irq(&pool
->lock
);
1812 spin_lock(&wq_mayday_lock
); /* for wq->maydays */
1814 if (need_to_create_worker(pool
)) {
1816 * We've been trying to create a new worker but
1817 * haven't been successful. We might be hitting an
1818 * allocation deadlock. Send distress signals to
1821 list_for_each_entry(work
, &pool
->worklist
, entry
)
1825 spin_unlock(&wq_mayday_lock
);
1826 spin_unlock_irq(&pool
->lock
);
1828 mod_timer(&pool
->mayday_timer
, jiffies
+ MAYDAY_INTERVAL
);
1832 * maybe_create_worker - create a new worker if necessary
1833 * @pool: pool to create a new worker for
1835 * Create a new worker for @pool if necessary. @pool is guaranteed to
1836 * have at least one idle worker on return from this function. If
1837 * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
1838 * sent to all rescuers with works scheduled on @pool to resolve
1839 * possible allocation deadlock.
1841 * On return, need_to_create_worker() is guaranteed to be %false and
1842 * may_start_working() %true.
1845 * spin_lock_irq(pool->lock) which may be released and regrabbed
1846 * multiple times. Does GFP_KERNEL allocations. Called only from
1849 static void maybe_create_worker(struct worker_pool
*pool
)
1850 __releases(&pool
->lock
)
1851 __acquires(&pool
->lock
)
1854 spin_unlock_irq(&pool
->lock
);
1856 /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
1857 mod_timer(&pool
->mayday_timer
, jiffies
+ MAYDAY_INITIAL_TIMEOUT
);
1860 if (create_worker(pool
) || !need_to_create_worker(pool
))
1863 schedule_timeout_interruptible(CREATE_COOLDOWN
);
1865 if (!need_to_create_worker(pool
))
1869 del_timer_sync(&pool
->mayday_timer
);
1870 spin_lock_irq(&pool
->lock
);
1872 * This is necessary even after a new worker was just successfully
1873 * created as @pool->lock was dropped and the new worker might have
1874 * already become busy.
1876 if (need_to_create_worker(pool
))
1881 * manage_workers - manage worker pool
1884 * Assume the manager role and manage the worker pool @worker belongs
1885 * to. At any given time, there can be only zero or one manager per
1886 * pool. The exclusion is handled automatically by this function.
1888 * The caller can safely start processing works on false return. On
1889 * true return, it's guaranteed that need_to_create_worker() is false
1890 * and may_start_working() is true.
1893 * spin_lock_irq(pool->lock) which may be released and regrabbed
1894 * multiple times. Does GFP_KERNEL allocations.
1897 * %false if the pool doesn't need management and the caller can safely
1898 * start processing works, %true if management function was performed and
1899 * the conditions that the caller verified before calling the function may
1900 * no longer be true.
1902 static bool manage_workers(struct worker
*worker
)
1904 struct worker_pool
*pool
= worker
->pool
;
1907 * Anyone who successfully grabs manager_arb wins the arbitration
1908 * and becomes the manager. mutex_trylock() on pool->manager_arb
1909 * failure while holding pool->lock reliably indicates that someone
1910 * else is managing the pool and the worker which failed trylock
1911 * can proceed to executing work items. This means that anyone
1912 * grabbing manager_arb is responsible for actually performing
1913 * manager duties. If manager_arb is grabbed and released without
1914 * actual management, the pool may stall indefinitely.
1916 if (!mutex_trylock(&pool
->manager_arb
))
1918 pool
->manager
= worker
;
1920 maybe_create_worker(pool
);
1922 pool
->manager
= NULL
;
1923 mutex_unlock(&pool
->manager_arb
);
1928 * process_one_work - process single work
1930 * @work: work to process
1932 * Process @work. This function contains all the logics necessary to
1933 * process a single work including synchronization against and
1934 * interaction with other workers on the same cpu, queueing and
1935 * flushing. As long as context requirement is met, any worker can
1936 * call this function to process a work.
1939 * spin_lock_irq(pool->lock) which is released and regrabbed.
1941 static void process_one_work(struct worker
*worker
, struct work_struct
*work
)
1942 __releases(&pool
->lock
)
1943 __acquires(&pool
->lock
)
1945 struct pool_workqueue
*pwq
= get_work_pwq(work
);
1946 struct worker_pool
*pool
= worker
->pool
;
1947 bool cpu_intensive
= pwq
->wq
->flags
& WQ_CPU_INTENSIVE
;
1949 struct worker
*collision
;
1950 #ifdef CONFIG_LOCKDEP
1952 * It is permissible to free the struct work_struct from
1953 * inside the function that is called from it, this we need to
1954 * take into account for lockdep too. To avoid bogus "held
1955 * lock freed" warnings as well as problems when looking into
1956 * work->lockdep_map, make a copy and use that here.
1958 struct lockdep_map lockdep_map
;
1960 lockdep_copy_map(&lockdep_map
, &work
->lockdep_map
);
1962 /* ensure we're on the correct CPU */
1963 WARN_ON_ONCE(!(pool
->flags
& POOL_DISASSOCIATED
) &&
1964 raw_smp_processor_id() != pool
->cpu
);
1967 * A single work shouldn't be executed concurrently by
1968 * multiple workers on a single cpu. Check whether anyone is
1969 * already processing the work. If so, defer the work to the
1970 * currently executing one.
1972 collision
= find_worker_executing_work(pool
, work
);
1973 if (unlikely(collision
)) {
1974 move_linked_works(work
, &collision
->scheduled
, NULL
);
1978 /* claim and dequeue */
1979 debug_work_deactivate(work
);
1980 hash_add(pool
->busy_hash
, &worker
->hentry
, (unsigned long)work
);
1981 worker
->current_work
= work
;
1982 worker
->current_func
= work
->func
;
1983 worker
->current_pwq
= pwq
;
1984 work_color
= get_work_color(work
);
1986 list_del_init(&work
->entry
);
1989 * CPU intensive works don't participate in concurrency management.
1990 * They're the scheduler's responsibility. This takes @worker out
1991 * of concurrency management and the next code block will chain
1992 * execution of the pending work items.
1994 if (unlikely(cpu_intensive
))
1995 worker_set_flags(worker
, WORKER_CPU_INTENSIVE
);
1998 * Wake up another worker if necessary. The condition is always
1999 * false for normal per-cpu workers since nr_running would always
2000 * be >= 1 at this point. This is used to chain execution of the
2001 * pending work items for WORKER_NOT_RUNNING workers such as the
2002 * UNBOUND and CPU_INTENSIVE ones.
2004 if (need_more_worker(pool
))
2005 wake_up_worker(pool
);
2008 * Record the last pool and clear PENDING which should be the last
2009 * update to @work. Also, do this inside @pool->lock so that
2010 * PENDING and queued state changes happen together while IRQ is
2013 set_work_pool_and_clear_pending(work
, pool
->id
);
2015 spin_unlock_irq(&pool
->lock
);
2017 lock_map_acquire_read(&pwq
->wq
->lockdep_map
);
2018 lock_map_acquire(&lockdep_map
);
2019 trace_workqueue_execute_start(work
);
2020 worker
->current_func(work
);
2022 * While we must be careful to not use "work" after this, the trace
2023 * point will only record its address.
2025 trace_workqueue_execute_end(work
);
2026 lock_map_release(&lockdep_map
);
2027 lock_map_release(&pwq
->wq
->lockdep_map
);
2029 if (unlikely(in_atomic() || lockdep_depth(current
) > 0)) {
2030 pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2031 " last function: %pf\n",
2032 current
->comm
, preempt_count(), task_pid_nr(current
),
2033 worker
->current_func
);
2034 debug_show_held_locks(current
);
2039 * The following prevents a kworker from hogging CPU on !PREEMPT
2040 * kernels, where a requeueing work item waiting for something to
2041 * happen could deadlock with stop_machine as such work item could
2042 * indefinitely requeue itself while all other CPUs are trapped in
2043 * stop_machine. At the same time, report a quiescent RCU state so
2044 * the same condition doesn't freeze RCU.
2046 cond_resched_rcu_qs();
2048 spin_lock_irq(&pool
->lock
);
2050 /* clear cpu intensive status */
2051 if (unlikely(cpu_intensive
))
2052 worker_clr_flags(worker
, WORKER_CPU_INTENSIVE
);
2054 /* we're done with it, release */
2055 hash_del(&worker
->hentry
);
2056 worker
->current_work
= NULL
;
2057 worker
->current_func
= NULL
;
2058 worker
->current_pwq
= NULL
;
2059 worker
->desc_valid
= false;
2060 pwq_dec_nr_in_flight(pwq
, work_color
);
2064 * process_scheduled_works - process scheduled works
2067 * Process all scheduled works. Please note that the scheduled list
2068 * may change while processing a work, so this function repeatedly
2069 * fetches a work from the top and executes it.
2072 * spin_lock_irq(pool->lock) which may be released and regrabbed
2075 static void process_scheduled_works(struct worker
*worker
)
2077 while (!list_empty(&worker
->scheduled
)) {
2078 struct work_struct
*work
= list_first_entry(&worker
->scheduled
,
2079 struct work_struct
, entry
);
2080 process_one_work(worker
, work
);
2085 * worker_thread - the worker thread function
2088 * The worker thread function. All workers belong to a worker_pool -
2089 * either a per-cpu one or dynamic unbound one. These workers process all
2090 * work items regardless of their specific target workqueue. The only
2091 * exception is work items which belong to workqueues with a rescuer which
2092 * will be explained in rescuer_thread().
2096 static int worker_thread(void *__worker
)
2098 struct worker
*worker
= __worker
;
2099 struct worker_pool
*pool
= worker
->pool
;
2101 /* tell the scheduler that this is a workqueue worker */
2102 worker
->task
->flags
|= PF_WQ_WORKER
;
2104 spin_lock_irq(&pool
->lock
);
2106 /* am I supposed to die? */
2107 if (unlikely(worker
->flags
& WORKER_DIE
)) {
2108 spin_unlock_irq(&pool
->lock
);
2109 WARN_ON_ONCE(!list_empty(&worker
->entry
));
2110 worker
->task
->flags
&= ~PF_WQ_WORKER
;
2112 set_task_comm(worker
->task
, "kworker/dying");
2113 ida_simple_remove(&pool
->worker_ida
, worker
->id
);
2114 worker_detach_from_pool(worker
, pool
);
2119 worker_leave_idle(worker
);
2121 /* no more worker necessary? */
2122 if (!need_more_worker(pool
))
2125 /* do we need to manage? */
2126 if (unlikely(!may_start_working(pool
)) && manage_workers(worker
))
2130 * ->scheduled list can only be filled while a worker is
2131 * preparing to process a work or actually processing it.
2132 * Make sure nobody diddled with it while I was sleeping.
2134 WARN_ON_ONCE(!list_empty(&worker
->scheduled
));
2137 * Finish PREP stage. We're guaranteed to have at least one idle
2138 * worker or that someone else has already assumed the manager
2139 * role. This is where @worker starts participating in concurrency
2140 * management if applicable and concurrency management is restored
2141 * after being rebound. See rebind_workers() for details.
2143 worker_clr_flags(worker
, WORKER_PREP
| WORKER_REBOUND
);
2146 struct work_struct
*work
=
2147 list_first_entry(&pool
->worklist
,
2148 struct work_struct
, entry
);
2150 if (likely(!(*work_data_bits(work
) & WORK_STRUCT_LINKED
))) {
2151 /* optimization path, not strictly necessary */
2152 process_one_work(worker
, work
);
2153 if (unlikely(!list_empty(&worker
->scheduled
)))
2154 process_scheduled_works(worker
);
2156 move_linked_works(work
, &worker
->scheduled
, NULL
);
2157 process_scheduled_works(worker
);
2159 } while (keep_working(pool
));
2161 worker_set_flags(worker
, WORKER_PREP
);
2164 * pool->lock is held and there's no work to process and no need to
2165 * manage, sleep. Workers are woken up only while holding
2166 * pool->lock or from local cpu, so setting the current state
2167 * before releasing pool->lock is enough to prevent losing any
2170 worker_enter_idle(worker
);
2171 __set_current_state(TASK_INTERRUPTIBLE
);
2172 spin_unlock_irq(&pool
->lock
);
2178 * rescuer_thread - the rescuer thread function
2181 * Workqueue rescuer thread function. There's one rescuer for each
2182 * workqueue which has WQ_MEM_RECLAIM set.
2184 * Regular work processing on a pool may block trying to create a new
2185 * worker which uses GFP_KERNEL allocation which has slight chance of
2186 * developing into deadlock if some works currently on the same queue
2187 * need to be processed to satisfy the GFP_KERNEL allocation. This is
2188 * the problem rescuer solves.
2190 * When such condition is possible, the pool summons rescuers of all
2191 * workqueues which have works queued on the pool and let them process
2192 * those works so that forward progress can be guaranteed.
2194 * This should happen rarely.
2198 static int rescuer_thread(void *__rescuer
)
2200 struct worker
*rescuer
= __rescuer
;
2201 struct workqueue_struct
*wq
= rescuer
->rescue_wq
;
2202 struct list_head
*scheduled
= &rescuer
->scheduled
;
2205 set_user_nice(current
, RESCUER_NICE_LEVEL
);
2208 * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2209 * doesn't participate in concurrency management.
2211 rescuer
->task
->flags
|= PF_WQ_WORKER
;
2213 set_current_state(TASK_INTERRUPTIBLE
);
2216 * By the time the rescuer is requested to stop, the workqueue
2217 * shouldn't have any work pending, but @wq->maydays may still have
2218 * pwq(s) queued. This can happen by non-rescuer workers consuming
2219 * all the work items before the rescuer got to them. Go through
2220 * @wq->maydays processing before acting on should_stop so that the
2221 * list is always empty on exit.
2223 should_stop
= kthread_should_stop();
2225 /* see whether any pwq is asking for help */
2226 spin_lock_irq(&wq_mayday_lock
);
2228 while (!list_empty(&wq
->maydays
)) {
2229 struct pool_workqueue
*pwq
= list_first_entry(&wq
->maydays
,
2230 struct pool_workqueue
, mayday_node
);
2231 struct worker_pool
*pool
= pwq
->pool
;
2232 struct work_struct
*work
, *n
;
2234 __set_current_state(TASK_RUNNING
);
2235 list_del_init(&pwq
->mayday_node
);
2237 spin_unlock_irq(&wq_mayday_lock
);
2239 worker_attach_to_pool(rescuer
, pool
);
2241 spin_lock_irq(&pool
->lock
);
2242 rescuer
->pool
= pool
;
2245 * Slurp in all works issued via this workqueue and
2248 WARN_ON_ONCE(!list_empty(scheduled
));
2249 list_for_each_entry_safe(work
, n
, &pool
->worklist
, entry
)
2250 if (get_work_pwq(work
) == pwq
)
2251 move_linked_works(work
, scheduled
, &n
);
2253 if (!list_empty(scheduled
)) {
2254 process_scheduled_works(rescuer
);
2257 * The above execution of rescued work items could
2258 * have created more to rescue through
2259 * pwq_activate_first_delayed() or chained
2260 * queueing. Let's put @pwq back on mayday list so
2261 * that such back-to-back work items, which may be
2262 * being used to relieve memory pressure, don't
2263 * incur MAYDAY_INTERVAL delay inbetween.
2265 if (need_to_create_worker(pool
)) {
2266 spin_lock(&wq_mayday_lock
);
2268 list_move_tail(&pwq
->mayday_node
, &wq
->maydays
);
2269 spin_unlock(&wq_mayday_lock
);
2274 * Put the reference grabbed by send_mayday(). @pool won't
2275 * go away while we're still attached to it.
2280 * Leave this pool. If need_more_worker() is %true, notify a
2281 * regular worker; otherwise, we end up with 0 concurrency
2282 * and stalling the execution.
2284 if (need_more_worker(pool
))
2285 wake_up_worker(pool
);
2287 rescuer
->pool
= NULL
;
2288 spin_unlock_irq(&pool
->lock
);
2290 worker_detach_from_pool(rescuer
, pool
);
2292 spin_lock_irq(&wq_mayday_lock
);
2295 spin_unlock_irq(&wq_mayday_lock
);
2298 __set_current_state(TASK_RUNNING
);
2299 rescuer
->task
->flags
&= ~PF_WQ_WORKER
;
2303 /* rescuers should never participate in concurrency management */
2304 WARN_ON_ONCE(!(rescuer
->flags
& WORKER_NOT_RUNNING
));
2310 struct work_struct work
;
2311 struct completion done
;
2312 struct task_struct
*task
; /* purely informational */
2315 static void wq_barrier_func(struct work_struct
*work
)
2317 struct wq_barrier
*barr
= container_of(work
, struct wq_barrier
, work
);
2318 complete(&barr
->done
);
2322 * insert_wq_barrier - insert a barrier work
2323 * @pwq: pwq to insert barrier into
2324 * @barr: wq_barrier to insert
2325 * @target: target work to attach @barr to
2326 * @worker: worker currently executing @target, NULL if @target is not executing
2328 * @barr is linked to @target such that @barr is completed only after
2329 * @target finishes execution. Please note that the ordering
2330 * guarantee is observed only with respect to @target and on the local
2333 * Currently, a queued barrier can't be canceled. This is because
2334 * try_to_grab_pending() can't determine whether the work to be
2335 * grabbed is at the head of the queue and thus can't clear LINKED
2336 * flag of the previous work while there must be a valid next work
2337 * after a work with LINKED flag set.
2339 * Note that when @worker is non-NULL, @target may be modified
2340 * underneath us, so we can't reliably determine pwq from @target.
2343 * spin_lock_irq(pool->lock).
2345 static void insert_wq_barrier(struct pool_workqueue
*pwq
,
2346 struct wq_barrier
*barr
,
2347 struct work_struct
*target
, struct worker
*worker
)
2349 struct list_head
*head
;
2350 unsigned int linked
= 0;
2353 * debugobject calls are safe here even with pool->lock locked
2354 * as we know for sure that this will not trigger any of the
2355 * checks and call back into the fixup functions where we
2358 INIT_WORK_ONSTACK(&barr
->work
, wq_barrier_func
);
2359 __set_bit(WORK_STRUCT_PENDING_BIT
, work_data_bits(&barr
->work
));
2360 init_completion(&barr
->done
);
2361 barr
->task
= current
;
2364 * If @target is currently being executed, schedule the
2365 * barrier to the worker; otherwise, put it after @target.
2368 head
= worker
->scheduled
.next
;
2370 unsigned long *bits
= work_data_bits(target
);
2372 head
= target
->entry
.next
;
2373 /* there can already be other linked works, inherit and set */
2374 linked
= *bits
& WORK_STRUCT_LINKED
;
2375 __set_bit(WORK_STRUCT_LINKED_BIT
, bits
);
2378 debug_work_activate(&barr
->work
);
2379 insert_work(pwq
, &barr
->work
, head
,
2380 work_color_to_flags(WORK_NO_COLOR
) | linked
);
2384 * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
2385 * @wq: workqueue being flushed
2386 * @flush_color: new flush color, < 0 for no-op
2387 * @work_color: new work color, < 0 for no-op
2389 * Prepare pwqs for workqueue flushing.
2391 * If @flush_color is non-negative, flush_color on all pwqs should be
2392 * -1. If no pwq has in-flight commands at the specified color, all
2393 * pwq->flush_color's stay at -1 and %false is returned. If any pwq
2394 * has in flight commands, its pwq->flush_color is set to
2395 * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
2396 * wakeup logic is armed and %true is returned.
2398 * The caller should have initialized @wq->first_flusher prior to
2399 * calling this function with non-negative @flush_color. If
2400 * @flush_color is negative, no flush color update is done and %false
2403 * If @work_color is non-negative, all pwqs should have the same
2404 * work_color which is previous to @work_color and all will be
2405 * advanced to @work_color.
2408 * mutex_lock(wq->mutex).
2411 * %true if @flush_color >= 0 and there's something to flush. %false
2414 static bool flush_workqueue_prep_pwqs(struct workqueue_struct
*wq
,
2415 int flush_color
, int work_color
)
2418 struct pool_workqueue
*pwq
;
2420 if (flush_color
>= 0) {
2421 WARN_ON_ONCE(atomic_read(&wq
->nr_pwqs_to_flush
));
2422 atomic_set(&wq
->nr_pwqs_to_flush
, 1);
2425 for_each_pwq(pwq
, wq
) {
2426 struct worker_pool
*pool
= pwq
->pool
;
2428 spin_lock_irq(&pool
->lock
);
2430 if (flush_color
>= 0) {
2431 WARN_ON_ONCE(pwq
->flush_color
!= -1);
2433 if (pwq
->nr_in_flight
[flush_color
]) {
2434 pwq
->flush_color
= flush_color
;
2435 atomic_inc(&wq
->nr_pwqs_to_flush
);
2440 if (work_color
>= 0) {
2441 WARN_ON_ONCE(work_color
!= work_next_color(pwq
->work_color
));
2442 pwq
->work_color
= work_color
;
2445 spin_unlock_irq(&pool
->lock
);
2448 if (flush_color
>= 0 && atomic_dec_and_test(&wq
->nr_pwqs_to_flush
))
2449 complete(&wq
->first_flusher
->done
);
2455 * flush_workqueue - ensure that any scheduled work has run to completion.
2456 * @wq: workqueue to flush
2458 * This function sleeps until all work items which were queued on entry
2459 * have finished execution, but it is not livelocked by new incoming ones.
2461 void flush_workqueue(struct workqueue_struct
*wq
)
2463 struct wq_flusher this_flusher
= {
2464 .list
= LIST_HEAD_INIT(this_flusher
.list
),
2466 .done
= COMPLETION_INITIALIZER_ONSTACK(this_flusher
.done
),
2470 lock_map_acquire(&wq
->lockdep_map
);
2471 lock_map_release(&wq
->lockdep_map
);
2473 mutex_lock(&wq
->mutex
);
2476 * Start-to-wait phase
2478 next_color
= work_next_color(wq
->work_color
);
2480 if (next_color
!= wq
->flush_color
) {
2482 * Color space is not full. The current work_color
2483 * becomes our flush_color and work_color is advanced
2486 WARN_ON_ONCE(!list_empty(&wq
->flusher_overflow
));
2487 this_flusher
.flush_color
= wq
->work_color
;
2488 wq
->work_color
= next_color
;
2490 if (!wq
->first_flusher
) {
2491 /* no flush in progress, become the first flusher */
2492 WARN_ON_ONCE(wq
->flush_color
!= this_flusher
.flush_color
);
2494 wq
->first_flusher
= &this_flusher
;
2496 if (!flush_workqueue_prep_pwqs(wq
, wq
->flush_color
,
2498 /* nothing to flush, done */
2499 wq
->flush_color
= next_color
;
2500 wq
->first_flusher
= NULL
;
2505 WARN_ON_ONCE(wq
->flush_color
== this_flusher
.flush_color
);
2506 list_add_tail(&this_flusher
.list
, &wq
->flusher_queue
);
2507 flush_workqueue_prep_pwqs(wq
, -1, wq
->work_color
);
2511 * Oops, color space is full, wait on overflow queue.
2512 * The next flush completion will assign us
2513 * flush_color and transfer to flusher_queue.
2515 list_add_tail(&this_flusher
.list
, &wq
->flusher_overflow
);
2518 mutex_unlock(&wq
->mutex
);
2520 wait_for_completion(&this_flusher
.done
);
2523 * Wake-up-and-cascade phase
2525 * First flushers are responsible for cascading flushes and
2526 * handling overflow. Non-first flushers can simply return.
2528 if (wq
->first_flusher
!= &this_flusher
)
2531 mutex_lock(&wq
->mutex
);
2533 /* we might have raced, check again with mutex held */
2534 if (wq
->first_flusher
!= &this_flusher
)
2537 wq
->first_flusher
= NULL
;
2539 WARN_ON_ONCE(!list_empty(&this_flusher
.list
));
2540 WARN_ON_ONCE(wq
->flush_color
!= this_flusher
.flush_color
);
2543 struct wq_flusher
*next
, *tmp
;
2545 /* complete all the flushers sharing the current flush color */
2546 list_for_each_entry_safe(next
, tmp
, &wq
->flusher_queue
, list
) {
2547 if (next
->flush_color
!= wq
->flush_color
)
2549 list_del_init(&next
->list
);
2550 complete(&next
->done
);
2553 WARN_ON_ONCE(!list_empty(&wq
->flusher_overflow
) &&
2554 wq
->flush_color
!= work_next_color(wq
->work_color
));
2556 /* this flush_color is finished, advance by one */
2557 wq
->flush_color
= work_next_color(wq
->flush_color
);
2559 /* one color has been freed, handle overflow queue */
2560 if (!list_empty(&wq
->flusher_overflow
)) {
2562 * Assign the same color to all overflowed
2563 * flushers, advance work_color and append to
2564 * flusher_queue. This is the start-to-wait
2565 * phase for these overflowed flushers.
2567 list_for_each_entry(tmp
, &wq
->flusher_overflow
, list
)
2568 tmp
->flush_color
= wq
->work_color
;
2570 wq
->work_color
= work_next_color(wq
->work_color
);
2572 list_splice_tail_init(&wq
->flusher_overflow
,
2573 &wq
->flusher_queue
);
2574 flush_workqueue_prep_pwqs(wq
, -1, wq
->work_color
);
2577 if (list_empty(&wq
->flusher_queue
)) {
2578 WARN_ON_ONCE(wq
->flush_color
!= wq
->work_color
);
2583 * Need to flush more colors. Make the next flusher
2584 * the new first flusher and arm pwqs.
2586 WARN_ON_ONCE(wq
->flush_color
== wq
->work_color
);
2587 WARN_ON_ONCE(wq
->flush_color
!= next
->flush_color
);
2589 list_del_init(&next
->list
);
2590 wq
->first_flusher
= next
;
2592 if (flush_workqueue_prep_pwqs(wq
, wq
->flush_color
, -1))
2596 * Meh... this color is already done, clear first
2597 * flusher and repeat cascading.
2599 wq
->first_flusher
= NULL
;
2603 mutex_unlock(&wq
->mutex
);
2605 EXPORT_SYMBOL_GPL(flush_workqueue
);
2608 * drain_workqueue - drain a workqueue
2609 * @wq: workqueue to drain
2611 * Wait until the workqueue becomes empty. While draining is in progress,
2612 * only chain queueing is allowed. IOW, only currently pending or running
2613 * work items on @wq can queue further work items on it. @wq is flushed
2614 * repeatedly until it becomes empty. The number of flushing is detemined
2615 * by the depth of chaining and should be relatively short. Whine if it
2618 void drain_workqueue(struct workqueue_struct
*wq
)
2620 unsigned int flush_cnt
= 0;
2621 struct pool_workqueue
*pwq
;
2624 * __queue_work() needs to test whether there are drainers, is much
2625 * hotter than drain_workqueue() and already looks at @wq->flags.
2626 * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
2628 mutex_lock(&wq
->mutex
);
2629 if (!wq
->nr_drainers
++)
2630 wq
->flags
|= __WQ_DRAINING
;
2631 mutex_unlock(&wq
->mutex
);
2633 flush_workqueue(wq
);
2635 mutex_lock(&wq
->mutex
);
2637 for_each_pwq(pwq
, wq
) {
2640 spin_lock_irq(&pwq
->pool
->lock
);
2641 drained
= !pwq
->nr_active
&& list_empty(&pwq
->delayed_works
);
2642 spin_unlock_irq(&pwq
->pool
->lock
);
2647 if (++flush_cnt
== 10 ||
2648 (flush_cnt
% 100 == 0 && flush_cnt
<= 1000))
2649 pr_warn("workqueue %s: drain_workqueue() isn't complete after %u tries\n",
2650 wq
->name
, flush_cnt
);
2652 mutex_unlock(&wq
->mutex
);
2656 if (!--wq
->nr_drainers
)
2657 wq
->flags
&= ~__WQ_DRAINING
;
2658 mutex_unlock(&wq
->mutex
);
2660 EXPORT_SYMBOL_GPL(drain_workqueue
);
2662 static bool start_flush_work(struct work_struct
*work
, struct wq_barrier
*barr
)
2664 struct worker
*worker
= NULL
;
2665 struct worker_pool
*pool
;
2666 struct pool_workqueue
*pwq
;
2670 local_irq_disable();
2671 pool
= get_work_pool(work
);
2677 spin_lock(&pool
->lock
);
2678 /* see the comment in try_to_grab_pending() with the same code */
2679 pwq
= get_work_pwq(work
);
2681 if (unlikely(pwq
->pool
!= pool
))
2684 worker
= find_worker_executing_work(pool
, work
);
2687 pwq
= worker
->current_pwq
;
2690 insert_wq_barrier(pwq
, barr
, work
, worker
);
2691 spin_unlock_irq(&pool
->lock
);
2694 * If @max_active is 1 or rescuer is in use, flushing another work
2695 * item on the same workqueue may lead to deadlock. Make sure the
2696 * flusher is not running on the same workqueue by verifying write
2699 if (pwq
->wq
->saved_max_active
== 1 || pwq
->wq
->rescuer
)
2700 lock_map_acquire(&pwq
->wq
->lockdep_map
);
2702 lock_map_acquire_read(&pwq
->wq
->lockdep_map
);
2703 lock_map_release(&pwq
->wq
->lockdep_map
);
2707 spin_unlock_irq(&pool
->lock
);
2712 * flush_work - wait for a work to finish executing the last queueing instance
2713 * @work: the work to flush
2715 * Wait until @work has finished execution. @work is guaranteed to be idle
2716 * on return if it hasn't been requeued since flush started.
2719 * %true if flush_work() waited for the work to finish execution,
2720 * %false if it was already idle.
2722 bool flush_work(struct work_struct
*work
)
2724 struct wq_barrier barr
;
2726 lock_map_acquire(&work
->lockdep_map
);
2727 lock_map_release(&work
->lockdep_map
);
2729 if (start_flush_work(work
, &barr
)) {
2730 wait_for_completion(&barr
.done
);
2731 destroy_work_on_stack(&barr
.work
);
2737 EXPORT_SYMBOL_GPL(flush_work
);
2741 struct work_struct
*work
;
2744 static int cwt_wakefn(wait_queue_t
*wait
, unsigned mode
, int sync
, void *key
)
2746 struct cwt_wait
*cwait
= container_of(wait
, struct cwt_wait
, wait
);
2748 if (cwait
->work
!= key
)
2750 return autoremove_wake_function(wait
, mode
, sync
, key
);
2753 static bool __cancel_work_timer(struct work_struct
*work
, bool is_dwork
)
2755 static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq
);
2756 unsigned long flags
;
2760 ret
= try_to_grab_pending(work
, is_dwork
, &flags
);
2762 * If someone else is already canceling, wait for it to
2763 * finish. flush_work() doesn't work for PREEMPT_NONE
2764 * because we may get scheduled between @work's completion
2765 * and the other canceling task resuming and clearing
2766 * CANCELING - flush_work() will return false immediately
2767 * as @work is no longer busy, try_to_grab_pending() will
2768 * return -ENOENT as @work is still being canceled and the
2769 * other canceling task won't be able to clear CANCELING as
2770 * we're hogging the CPU.
2772 * Let's wait for completion using a waitqueue. As this
2773 * may lead to the thundering herd problem, use a custom
2774 * wake function which matches @work along with exclusive
2777 if (unlikely(ret
== -ENOENT
)) {
2778 struct cwt_wait cwait
;
2780 init_wait(&cwait
.wait
);
2781 cwait
.wait
.func
= cwt_wakefn
;
2784 prepare_to_wait_exclusive(&cancel_waitq
, &cwait
.wait
,
2785 TASK_UNINTERRUPTIBLE
);
2786 if (work_is_canceling(work
))
2788 finish_wait(&cancel_waitq
, &cwait
.wait
);
2790 } while (unlikely(ret
< 0));
2792 /* tell other tasks trying to grab @work to back off */
2793 mark_work_canceling(work
);
2794 local_irq_restore(flags
);
2797 clear_work_data(work
);
2800 * Paired with prepare_to_wait() above so that either
2801 * waitqueue_active() is visible here or !work_is_canceling() is
2805 if (waitqueue_active(&cancel_waitq
))
2806 __wake_up(&cancel_waitq
, TASK_NORMAL
, 1, work
);
2812 * cancel_work_sync - cancel a work and wait for it to finish
2813 * @work: the work to cancel
2815 * Cancel @work and wait for its execution to finish. This function
2816 * can be used even if the work re-queues itself or migrates to
2817 * another workqueue. On return from this function, @work is
2818 * guaranteed to be not pending or executing on any CPU.
2820 * cancel_work_sync(&delayed_work->work) must not be used for
2821 * delayed_work's. Use cancel_delayed_work_sync() instead.
2823 * The caller must ensure that the workqueue on which @work was last
2824 * queued can't be destroyed before this function returns.
2827 * %true if @work was pending, %false otherwise.
2829 bool cancel_work_sync(struct work_struct
*work
)
2831 return __cancel_work_timer(work
, false);
2833 EXPORT_SYMBOL_GPL(cancel_work_sync
);
2836 * flush_delayed_work - wait for a dwork to finish executing the last queueing
2837 * @dwork: the delayed work to flush
2839 * Delayed timer is cancelled and the pending work is queued for
2840 * immediate execution. Like flush_work(), this function only
2841 * considers the last queueing instance of @dwork.
2844 * %true if flush_work() waited for the work to finish execution,
2845 * %false if it was already idle.
2847 bool flush_delayed_work(struct delayed_work
*dwork
)
2849 local_irq_disable();
2850 if (del_timer_sync(&dwork
->timer
))
2851 __queue_work(dwork
->cpu
, dwork
->wq
, &dwork
->work
);
2853 return flush_work(&dwork
->work
);
2855 EXPORT_SYMBOL(flush_delayed_work
);
2858 * cancel_delayed_work - cancel a delayed work
2859 * @dwork: delayed_work to cancel
2861 * Kill off a pending delayed_work.
2863 * Return: %true if @dwork was pending and canceled; %false if it wasn't
2867 * The work callback function may still be running on return, unless
2868 * it returns %true and the work doesn't re-arm itself. Explicitly flush or
2869 * use cancel_delayed_work_sync() to wait on it.
2871 * This function is safe to call from any context including IRQ handler.
2873 bool cancel_delayed_work(struct delayed_work
*dwork
)
2875 unsigned long flags
;
2879 ret
= try_to_grab_pending(&dwork
->work
, true, &flags
);
2880 } while (unlikely(ret
== -EAGAIN
));
2882 if (unlikely(ret
< 0))
2885 set_work_pool_and_clear_pending(&dwork
->work
,
2886 get_work_pool_id(&dwork
->work
));
2887 local_irq_restore(flags
);
2890 EXPORT_SYMBOL(cancel_delayed_work
);
2893 * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
2894 * @dwork: the delayed work cancel
2896 * This is cancel_work_sync() for delayed works.
2899 * %true if @dwork was pending, %false otherwise.
2901 bool cancel_delayed_work_sync(struct delayed_work
*dwork
)
2903 return __cancel_work_timer(&dwork
->work
, true);
2905 EXPORT_SYMBOL(cancel_delayed_work_sync
);
2908 * schedule_on_each_cpu - execute a function synchronously on each online CPU
2909 * @func: the function to call
2911 * schedule_on_each_cpu() executes @func on each online CPU using the
2912 * system workqueue and blocks until all CPUs have completed.
2913 * schedule_on_each_cpu() is very slow.
2916 * 0 on success, -errno on failure.
2918 int schedule_on_each_cpu(work_func_t func
)
2921 struct work_struct __percpu
*works
;
2923 works
= alloc_percpu(struct work_struct
);
2929 for_each_online_cpu(cpu
) {
2930 struct work_struct
*work
= per_cpu_ptr(works
, cpu
);
2932 INIT_WORK(work
, func
);
2933 schedule_work_on(cpu
, work
);
2936 for_each_online_cpu(cpu
)
2937 flush_work(per_cpu_ptr(works
, cpu
));
2945 * flush_scheduled_work - ensure that any scheduled work has run to completion.
2947 * Forces execution of the kernel-global workqueue and blocks until its
2950 * Think twice before calling this function! It's very easy to get into
2951 * trouble if you don't take great care. Either of the following situations
2952 * will lead to deadlock:
2954 * One of the work items currently on the workqueue needs to acquire
2955 * a lock held by your code or its caller.
2957 * Your code is running in the context of a work routine.
2959 * They will be detected by lockdep when they occur, but the first might not
2960 * occur very often. It depends on what work items are on the workqueue and
2961 * what locks they need, which you have no control over.
2963 * In most situations flushing the entire workqueue is overkill; you merely
2964 * need to know that a particular work item isn't queued and isn't running.
2965 * In such cases you should use cancel_delayed_work_sync() or
2966 * cancel_work_sync() instead.
2968 void flush_scheduled_work(void)
2970 flush_workqueue(system_wq
);
2972 EXPORT_SYMBOL(flush_scheduled_work
);
2975 * execute_in_process_context - reliably execute the routine with user context
2976 * @fn: the function to execute
2977 * @ew: guaranteed storage for the execute work structure (must
2978 * be available when the work executes)
2980 * Executes the function immediately if process context is available,
2981 * otherwise schedules the function for delayed execution.
2983 * Return: 0 - function was executed
2984 * 1 - function was scheduled for execution
2986 int execute_in_process_context(work_func_t fn
, struct execute_work
*ew
)
2988 if (!in_interrupt()) {
2993 INIT_WORK(&ew
->work
, fn
);
2994 schedule_work(&ew
->work
);
2998 EXPORT_SYMBOL_GPL(execute_in_process_context
);
3001 * free_workqueue_attrs - free a workqueue_attrs
3002 * @attrs: workqueue_attrs to free
3004 * Undo alloc_workqueue_attrs().
3006 void free_workqueue_attrs(struct workqueue_attrs
*attrs
)
3009 free_cpumask_var(attrs
->cpumask
);
3015 * alloc_workqueue_attrs - allocate a workqueue_attrs
3016 * @gfp_mask: allocation mask to use
3018 * Allocate a new workqueue_attrs, initialize with default settings and
3021 * Return: The allocated new workqueue_attr on success. %NULL on failure.
3023 struct workqueue_attrs
*alloc_workqueue_attrs(gfp_t gfp_mask
)
3025 struct workqueue_attrs
*attrs
;
3027 attrs
= kzalloc(sizeof(*attrs
), gfp_mask
);
3030 if (!alloc_cpumask_var(&attrs
->cpumask
, gfp_mask
))
3033 cpumask_copy(attrs
->cpumask
, cpu_possible_mask
);
3036 free_workqueue_attrs(attrs
);
3040 static void copy_workqueue_attrs(struct workqueue_attrs
*to
,
3041 const struct workqueue_attrs
*from
)
3043 to
->nice
= from
->nice
;
3044 cpumask_copy(to
->cpumask
, from
->cpumask
);
3046 * Unlike hash and equality test, this function doesn't ignore
3047 * ->no_numa as it is used for both pool and wq attrs. Instead,
3048 * get_unbound_pool() explicitly clears ->no_numa after copying.
3050 to
->no_numa
= from
->no_numa
;
3053 /* hash value of the content of @attr */
3054 static u32
wqattrs_hash(const struct workqueue_attrs
*attrs
)
3058 hash
= jhash_1word(attrs
->nice
, hash
);
3059 hash
= jhash(cpumask_bits(attrs
->cpumask
),
3060 BITS_TO_LONGS(nr_cpumask_bits
) * sizeof(long), hash
);
3064 /* content equality test */
3065 static bool wqattrs_equal(const struct workqueue_attrs
*a
,
3066 const struct workqueue_attrs
*b
)
3068 if (a
->nice
!= b
->nice
)
3070 if (!cpumask_equal(a
->cpumask
, b
->cpumask
))
3076 * init_worker_pool - initialize a newly zalloc'd worker_pool
3077 * @pool: worker_pool to initialize
3079 * Initiailize a newly zalloc'd @pool. It also allocates @pool->attrs.
3081 * Return: 0 on success, -errno on failure. Even on failure, all fields
3082 * inside @pool proper are initialized and put_unbound_pool() can be called
3083 * on @pool safely to release it.
3085 static int init_worker_pool(struct worker_pool
*pool
)
3087 spin_lock_init(&pool
->lock
);
3090 pool
->node
= NUMA_NO_NODE
;
3091 pool
->flags
|= POOL_DISASSOCIATED
;
3092 INIT_LIST_HEAD(&pool
->worklist
);
3093 INIT_LIST_HEAD(&pool
->idle_list
);
3094 hash_init(pool
->busy_hash
);
3096 init_timer_deferrable(&pool
->idle_timer
);
3097 pool
->idle_timer
.function
= idle_worker_timeout
;
3098 pool
->idle_timer
.data
= (unsigned long)pool
;
3100 setup_timer(&pool
->mayday_timer
, pool_mayday_timeout
,
3101 (unsigned long)pool
);
3103 mutex_init(&pool
->manager_arb
);
3104 mutex_init(&pool
->attach_mutex
);
3105 INIT_LIST_HEAD(&pool
->workers
);
3107 ida_init(&pool
->worker_ida
);
3108 INIT_HLIST_NODE(&pool
->hash_node
);
3111 /* shouldn't fail above this point */
3112 pool
->attrs
= alloc_workqueue_attrs(GFP_KERNEL
);
3118 static void rcu_free_wq(struct rcu_head
*rcu
)
3120 struct workqueue_struct
*wq
=
3121 container_of(rcu
, struct workqueue_struct
, rcu
);
3123 if (!(wq
->flags
& WQ_UNBOUND
))
3124 free_percpu(wq
->cpu_pwqs
);
3126 free_workqueue_attrs(wq
->unbound_attrs
);
3132 static void rcu_free_pool(struct rcu_head
*rcu
)
3134 struct worker_pool
*pool
= container_of(rcu
, struct worker_pool
, rcu
);
3136 ida_destroy(&pool
->worker_ida
);
3137 free_workqueue_attrs(pool
->attrs
);
3142 * put_unbound_pool - put a worker_pool
3143 * @pool: worker_pool to put
3145 * Put @pool. If its refcnt reaches zero, it gets destroyed in sched-RCU
3146 * safe manner. get_unbound_pool() calls this function on its failure path
3147 * and this function should be able to release pools which went through,
3148 * successfully or not, init_worker_pool().
3150 * Should be called with wq_pool_mutex held.
3152 static void put_unbound_pool(struct worker_pool
*pool
)
3154 DECLARE_COMPLETION_ONSTACK(detach_completion
);
3155 struct worker
*worker
;
3157 lockdep_assert_held(&wq_pool_mutex
);
3163 if (WARN_ON(!(pool
->cpu
< 0)) ||
3164 WARN_ON(!list_empty(&pool
->worklist
)))
3167 /* release id and unhash */
3169 idr_remove(&worker_pool_idr
, pool
->id
);
3170 hash_del(&pool
->hash_node
);
3173 * Become the manager and destroy all workers. Grabbing
3174 * manager_arb prevents @pool's workers from blocking on
3177 mutex_lock(&pool
->manager_arb
);
3179 spin_lock_irq(&pool
->lock
);
3180 while ((worker
= first_idle_worker(pool
)))
3181 destroy_worker(worker
);
3182 WARN_ON(pool
->nr_workers
|| pool
->nr_idle
);
3183 spin_unlock_irq(&pool
->lock
);
3185 mutex_lock(&pool
->attach_mutex
);
3186 if (!list_empty(&pool
->workers
))
3187 pool
->detach_completion
= &detach_completion
;
3188 mutex_unlock(&pool
->attach_mutex
);
3190 if (pool
->detach_completion
)
3191 wait_for_completion(pool
->detach_completion
);
3193 mutex_unlock(&pool
->manager_arb
);
3195 /* shut down the timers */
3196 del_timer_sync(&pool
->idle_timer
);
3197 del_timer_sync(&pool
->mayday_timer
);
3199 /* sched-RCU protected to allow dereferences from get_work_pool() */
3200 call_rcu_sched(&pool
->rcu
, rcu_free_pool
);
3204 * get_unbound_pool - get a worker_pool with the specified attributes
3205 * @attrs: the attributes of the worker_pool to get
3207 * Obtain a worker_pool which has the same attributes as @attrs, bump the
3208 * reference count and return it. If there already is a matching
3209 * worker_pool, it will be used; otherwise, this function attempts to
3212 * Should be called with wq_pool_mutex held.
3214 * Return: On success, a worker_pool with the same attributes as @attrs.
3215 * On failure, %NULL.
3217 static struct worker_pool
*get_unbound_pool(const struct workqueue_attrs
*attrs
)
3219 u32 hash
= wqattrs_hash(attrs
);
3220 struct worker_pool
*pool
;
3223 lockdep_assert_held(&wq_pool_mutex
);
3225 /* do we already have a matching pool? */
3226 hash_for_each_possible(unbound_pool_hash
, pool
, hash_node
, hash
) {
3227 if (wqattrs_equal(pool
->attrs
, attrs
)) {
3233 /* nope, create a new one */
3234 pool
= kzalloc(sizeof(*pool
), GFP_KERNEL
);
3235 if (!pool
|| init_worker_pool(pool
) < 0)
3238 lockdep_set_subclass(&pool
->lock
, 1); /* see put_pwq() */
3239 copy_workqueue_attrs(pool
->attrs
, attrs
);
3242 * no_numa isn't a worker_pool attribute, always clear it. See
3243 * 'struct workqueue_attrs' comments for detail.
3245 pool
->attrs
->no_numa
= false;
3247 /* if cpumask is contained inside a NUMA node, we belong to that node */
3248 if (wq_numa_enabled
) {
3249 for_each_node(node
) {
3250 if (cpumask_subset(pool
->attrs
->cpumask
,
3251 wq_numa_possible_cpumask
[node
])) {
3258 if (worker_pool_assign_id(pool
) < 0)
3261 /* create and start the initial worker */
3262 if (!create_worker(pool
))
3266 hash_add(unbound_pool_hash
, &pool
->hash_node
, hash
);
3271 put_unbound_pool(pool
);
3275 static void rcu_free_pwq(struct rcu_head
*rcu
)
3277 kmem_cache_free(pwq_cache
,
3278 container_of(rcu
, struct pool_workqueue
, rcu
));
3282 * Scheduled on system_wq by put_pwq() when an unbound pwq hits zero refcnt
3283 * and needs to be destroyed.
3285 static void pwq_unbound_release_workfn(struct work_struct
*work
)
3287 struct pool_workqueue
*pwq
= container_of(work
, struct pool_workqueue
,
3288 unbound_release_work
);
3289 struct workqueue_struct
*wq
= pwq
->wq
;
3290 struct worker_pool
*pool
= pwq
->pool
;
3293 if (WARN_ON_ONCE(!(wq
->flags
& WQ_UNBOUND
)))
3296 mutex_lock(&wq
->mutex
);
3297 list_del_rcu(&pwq
->pwqs_node
);
3298 is_last
= list_empty(&wq
->pwqs
);
3299 mutex_unlock(&wq
->mutex
);
3301 mutex_lock(&wq_pool_mutex
);
3302 put_unbound_pool(pool
);
3303 mutex_unlock(&wq_pool_mutex
);
3305 call_rcu_sched(&pwq
->rcu
, rcu_free_pwq
);
3308 * If we're the last pwq going away, @wq is already dead and no one
3309 * is gonna access it anymore. Schedule RCU free.
3312 call_rcu_sched(&wq
->rcu
, rcu_free_wq
);
3316 * pwq_adjust_max_active - update a pwq's max_active to the current setting
3317 * @pwq: target pool_workqueue
3319 * If @pwq isn't freezing, set @pwq->max_active to the associated
3320 * workqueue's saved_max_active and activate delayed work items
3321 * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
3323 static void pwq_adjust_max_active(struct pool_workqueue
*pwq
)
3325 struct workqueue_struct
*wq
= pwq
->wq
;
3326 bool freezable
= wq
->flags
& WQ_FREEZABLE
;
3328 /* for @wq->saved_max_active */
3329 lockdep_assert_held(&wq
->mutex
);
3331 /* fast exit for non-freezable wqs */
3332 if (!freezable
&& pwq
->max_active
== wq
->saved_max_active
)
3335 spin_lock_irq(&pwq
->pool
->lock
);
3338 * During [un]freezing, the caller is responsible for ensuring that
3339 * this function is called at least once after @workqueue_freezing
3340 * is updated and visible.
3342 if (!freezable
|| !workqueue_freezing
) {
3343 pwq
->max_active
= wq
->saved_max_active
;
3345 while (!list_empty(&pwq
->delayed_works
) &&
3346 pwq
->nr_active
< pwq
->max_active
)
3347 pwq_activate_first_delayed(pwq
);
3350 * Need to kick a worker after thawed or an unbound wq's
3351 * max_active is bumped. It's a slow path. Do it always.
3353 wake_up_worker(pwq
->pool
);
3355 pwq
->max_active
= 0;
3358 spin_unlock_irq(&pwq
->pool
->lock
);
3361 /* initialize newly alloced @pwq which is associated with @wq and @pool */
3362 static void init_pwq(struct pool_workqueue
*pwq
, struct workqueue_struct
*wq
,
3363 struct worker_pool
*pool
)
3365 BUG_ON((unsigned long)pwq
& WORK_STRUCT_FLAG_MASK
);
3367 memset(pwq
, 0, sizeof(*pwq
));
3371 pwq
->flush_color
= -1;
3373 INIT_LIST_HEAD(&pwq
->delayed_works
);
3374 INIT_LIST_HEAD(&pwq
->pwqs_node
);
3375 INIT_LIST_HEAD(&pwq
->mayday_node
);
3376 INIT_WORK(&pwq
->unbound_release_work
, pwq_unbound_release_workfn
);
3379 /* sync @pwq with the current state of its associated wq and link it */
3380 static void link_pwq(struct pool_workqueue
*pwq
)
3382 struct workqueue_struct
*wq
= pwq
->wq
;
3384 lockdep_assert_held(&wq
->mutex
);
3386 /* may be called multiple times, ignore if already linked */
3387 if (!list_empty(&pwq
->pwqs_node
))
3390 /* set the matching work_color */
3391 pwq
->work_color
= wq
->work_color
;
3393 /* sync max_active to the current setting */
3394 pwq_adjust_max_active(pwq
);
3397 list_add_rcu(&pwq
->pwqs_node
, &wq
->pwqs
);
3400 /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
3401 static struct pool_workqueue
*alloc_unbound_pwq(struct workqueue_struct
*wq
,
3402 const struct workqueue_attrs
*attrs
)
3404 struct worker_pool
*pool
;
3405 struct pool_workqueue
*pwq
;
3407 lockdep_assert_held(&wq_pool_mutex
);
3409 pool
= get_unbound_pool(attrs
);
3413 pwq
= kmem_cache_alloc_node(pwq_cache
, GFP_KERNEL
, pool
->node
);
3415 put_unbound_pool(pool
);
3419 init_pwq(pwq
, wq
, pool
);
3423 /* undo alloc_unbound_pwq(), used only in the error path */
3424 static void free_unbound_pwq(struct pool_workqueue
*pwq
)
3426 lockdep_assert_held(&wq_pool_mutex
);
3429 put_unbound_pool(pwq
->pool
);
3430 kmem_cache_free(pwq_cache
, pwq
);
3435 * wq_calc_node_mask - calculate a wq_attrs' cpumask for the specified node
3436 * @attrs: the wq_attrs of interest
3437 * @node: the target NUMA node
3438 * @cpu_going_down: if >= 0, the CPU to consider as offline
3439 * @cpumask: outarg, the resulting cpumask
3441 * Calculate the cpumask a workqueue with @attrs should use on @node. If
3442 * @cpu_going_down is >= 0, that cpu is considered offline during
3443 * calculation. The result is stored in @cpumask.
3445 * If NUMA affinity is not enabled, @attrs->cpumask is always used. If
3446 * enabled and @node has online CPUs requested by @attrs, the returned
3447 * cpumask is the intersection of the possible CPUs of @node and
3450 * The caller is responsible for ensuring that the cpumask of @node stays
3453 * Return: %true if the resulting @cpumask is different from @attrs->cpumask,
3456 static bool wq_calc_node_cpumask(const struct workqueue_attrs
*attrs
, int node
,
3457 int cpu_going_down
, cpumask_t
*cpumask
)
3459 if (!wq_numa_enabled
|| attrs
->no_numa
)
3462 /* does @node have any online CPUs @attrs wants? */
3463 cpumask_and(cpumask
, cpumask_of_node(node
), attrs
->cpumask
);
3464 if (cpu_going_down
>= 0)
3465 cpumask_clear_cpu(cpu_going_down
, cpumask
);
3467 if (cpumask_empty(cpumask
))
3470 /* yeap, return possible CPUs in @node that @attrs wants */
3471 cpumask_and(cpumask
, attrs
->cpumask
, wq_numa_possible_cpumask
[node
]);
3472 return !cpumask_equal(cpumask
, attrs
->cpumask
);
3475 cpumask_copy(cpumask
, attrs
->cpumask
);
3479 /* install @pwq into @wq's numa_pwq_tbl[] for @node and return the old pwq */
3480 static struct pool_workqueue
*numa_pwq_tbl_install(struct workqueue_struct
*wq
,
3482 struct pool_workqueue
*pwq
)
3484 struct pool_workqueue
*old_pwq
;
3486 lockdep_assert_held(&wq
->mutex
);
3488 /* link_pwq() can handle duplicate calls */
3491 old_pwq
= rcu_access_pointer(wq
->numa_pwq_tbl
[node
]);
3492 rcu_assign_pointer(wq
->numa_pwq_tbl
[node
], pwq
);
3497 * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
3498 * @wq: the target workqueue
3499 * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
3501 * Apply @attrs to an unbound workqueue @wq. Unless disabled, on NUMA
3502 * machines, this function maps a separate pwq to each NUMA node with
3503 * possibles CPUs in @attrs->cpumask so that work items are affine to the
3504 * NUMA node it was issued on. Older pwqs are released as in-flight work
3505 * items finish. Note that a work item which repeatedly requeues itself
3506 * back-to-back will stay on its current pwq.
3508 * Performs GFP_KERNEL allocations.
3510 * Return: 0 on success and -errno on failure.
3512 int apply_workqueue_attrs(struct workqueue_struct
*wq
,
3513 const struct workqueue_attrs
*attrs
)
3515 struct workqueue_attrs
*new_attrs
, *tmp_attrs
;
3516 struct pool_workqueue
**pwq_tbl
, *dfl_pwq
;
3519 /* only unbound workqueues can change attributes */
3520 if (WARN_ON(!(wq
->flags
& WQ_UNBOUND
)))
3523 /* creating multiple pwqs breaks ordering guarantee */
3524 if (WARN_ON((wq
->flags
& __WQ_ORDERED
) && !list_empty(&wq
->pwqs
)))
3527 pwq_tbl
= kzalloc(nr_node_ids
* sizeof(pwq_tbl
[0]), GFP_KERNEL
);
3528 new_attrs
= alloc_workqueue_attrs(GFP_KERNEL
);
3529 tmp_attrs
= alloc_workqueue_attrs(GFP_KERNEL
);
3530 if (!pwq_tbl
|| !new_attrs
|| !tmp_attrs
)
3533 /* make a copy of @attrs and sanitize it */
3534 copy_workqueue_attrs(new_attrs
, attrs
);
3535 cpumask_and(new_attrs
->cpumask
, new_attrs
->cpumask
, cpu_possible_mask
);
3538 * We may create multiple pwqs with differing cpumasks. Make a
3539 * copy of @new_attrs which will be modified and used to obtain
3542 copy_workqueue_attrs(tmp_attrs
, new_attrs
);
3545 * CPUs should stay stable across pwq creations and installations.
3546 * Pin CPUs, determine the target cpumask for each node and create
3551 mutex_lock(&wq_pool_mutex
);
3554 * If something goes wrong during CPU up/down, we'll fall back to
3555 * the default pwq covering whole @attrs->cpumask. Always create
3556 * it even if we don't use it immediately.
3558 dfl_pwq
= alloc_unbound_pwq(wq
, new_attrs
);
3562 for_each_node(node
) {
3563 if (wq_calc_node_cpumask(attrs
, node
, -1, tmp_attrs
->cpumask
)) {
3564 pwq_tbl
[node
] = alloc_unbound_pwq(wq
, tmp_attrs
);
3569 pwq_tbl
[node
] = dfl_pwq
;
3573 mutex_unlock(&wq_pool_mutex
);
3575 /* all pwqs have been created successfully, let's install'em */
3576 mutex_lock(&wq
->mutex
);
3578 copy_workqueue_attrs(wq
->unbound_attrs
, new_attrs
);
3580 /* save the previous pwq and install the new one */
3582 pwq_tbl
[node
] = numa_pwq_tbl_install(wq
, node
, pwq_tbl
[node
]);
3584 /* @dfl_pwq might not have been used, ensure it's linked */
3586 swap(wq
->dfl_pwq
, dfl_pwq
);
3588 mutex_unlock(&wq
->mutex
);
3590 /* put the old pwqs */
3592 put_pwq_unlocked(pwq_tbl
[node
]);
3593 put_pwq_unlocked(dfl_pwq
);
3599 free_workqueue_attrs(tmp_attrs
);
3600 free_workqueue_attrs(new_attrs
);
3605 free_unbound_pwq(dfl_pwq
);
3607 if (pwq_tbl
&& pwq_tbl
[node
] != dfl_pwq
)
3608 free_unbound_pwq(pwq_tbl
[node
]);
3609 mutex_unlock(&wq_pool_mutex
);
3617 * wq_update_unbound_numa - update NUMA affinity of a wq for CPU hot[un]plug
3618 * @wq: the target workqueue
3619 * @cpu: the CPU coming up or going down
3620 * @online: whether @cpu is coming up or going down
3622 * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
3623 * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update NUMA affinity of
3626 * If NUMA affinity can't be adjusted due to memory allocation failure, it
3627 * falls back to @wq->dfl_pwq which may not be optimal but is always
3630 * Note that when the last allowed CPU of a NUMA node goes offline for a
3631 * workqueue with a cpumask spanning multiple nodes, the workers which were
3632 * already executing the work items for the workqueue will lose their CPU
3633 * affinity and may execute on any CPU. This is similar to how per-cpu
3634 * workqueues behave on CPU_DOWN. If a workqueue user wants strict
3635 * affinity, it's the user's responsibility to flush the work item from
3638 static void wq_update_unbound_numa(struct workqueue_struct
*wq
, int cpu
,
3641 int node
= cpu_to_node(cpu
);
3642 int cpu_off
= online
? -1 : cpu
;
3643 struct pool_workqueue
*old_pwq
= NULL
, *pwq
;
3644 struct workqueue_attrs
*target_attrs
;
3647 lockdep_assert_held(&wq_pool_mutex
);
3649 if (!wq_numa_enabled
|| !(wq
->flags
& WQ_UNBOUND
))
3653 * We don't wanna alloc/free wq_attrs for each wq for each CPU.
3654 * Let's use a preallocated one. The following buf is protected by
3655 * CPU hotplug exclusion.
3657 target_attrs
= wq_update_unbound_numa_attrs_buf
;
3658 cpumask
= target_attrs
->cpumask
;
3660 mutex_lock(&wq
->mutex
);
3661 if (wq
->unbound_attrs
->no_numa
)
3664 copy_workqueue_attrs(target_attrs
, wq
->unbound_attrs
);
3665 pwq
= unbound_pwq_by_node(wq
, node
);
3668 * Let's determine what needs to be done. If the target cpumask is
3669 * different from wq's, we need to compare it to @pwq's and create
3670 * a new one if they don't match. If the target cpumask equals
3671 * wq's, the default pwq should be used.
3673 if (wq_calc_node_cpumask(wq
->unbound_attrs
, node
, cpu_off
, cpumask
)) {
3674 if (cpumask_equal(cpumask
, pwq
->pool
->attrs
->cpumask
))
3680 mutex_unlock(&wq
->mutex
);
3682 /* create a new pwq */
3683 pwq
= alloc_unbound_pwq(wq
, target_attrs
);
3685 pr_warn("workqueue: allocation failed while updating NUMA affinity of \"%s\"\n",
3687 mutex_lock(&wq
->mutex
);
3692 * Install the new pwq. As this function is called only from CPU
3693 * hotplug callbacks and applying a new attrs is wrapped with
3694 * get/put_online_cpus(), @wq->unbound_attrs couldn't have changed
3697 mutex_lock(&wq
->mutex
);
3698 old_pwq
= numa_pwq_tbl_install(wq
, node
, pwq
);
3702 spin_lock_irq(&wq
->dfl_pwq
->pool
->lock
);
3703 get_pwq(wq
->dfl_pwq
);
3704 spin_unlock_irq(&wq
->dfl_pwq
->pool
->lock
);
3705 old_pwq
= numa_pwq_tbl_install(wq
, node
, wq
->dfl_pwq
);
3707 mutex_unlock(&wq
->mutex
);
3708 put_pwq_unlocked(old_pwq
);
3711 static int alloc_and_link_pwqs(struct workqueue_struct
*wq
)
3713 bool highpri
= wq
->flags
& WQ_HIGHPRI
;
3716 if (!(wq
->flags
& WQ_UNBOUND
)) {
3717 wq
->cpu_pwqs
= alloc_percpu(struct pool_workqueue
);
3721 for_each_possible_cpu(cpu
) {
3722 struct pool_workqueue
*pwq
=
3723 per_cpu_ptr(wq
->cpu_pwqs
, cpu
);
3724 struct worker_pool
*cpu_pools
=
3725 per_cpu(cpu_worker_pools
, cpu
);
3727 init_pwq(pwq
, wq
, &cpu_pools
[highpri
]);
3729 mutex_lock(&wq
->mutex
);
3731 mutex_unlock(&wq
->mutex
);
3734 } else if (wq
->flags
& __WQ_ORDERED
) {
3735 ret
= apply_workqueue_attrs(wq
, ordered_wq_attrs
[highpri
]);
3736 /* there should only be single pwq for ordering guarantee */
3737 WARN(!ret
&& (wq
->pwqs
.next
!= &wq
->dfl_pwq
->pwqs_node
||
3738 wq
->pwqs
.prev
!= &wq
->dfl_pwq
->pwqs_node
),
3739 "ordering guarantee broken for workqueue %s\n", wq
->name
);
3742 return apply_workqueue_attrs(wq
, unbound_std_wq_attrs
[highpri
]);
3746 static int wq_clamp_max_active(int max_active
, unsigned int flags
,
3749 int lim
= flags
& WQ_UNBOUND
? WQ_UNBOUND_MAX_ACTIVE
: WQ_MAX_ACTIVE
;
3751 if (max_active
< 1 || max_active
> lim
)
3752 pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
3753 max_active
, name
, 1, lim
);
3755 return clamp_val(max_active
, 1, lim
);
3758 struct workqueue_struct
*__alloc_workqueue_key(const char *fmt
,
3761 struct lock_class_key
*key
,
3762 const char *lock_name
, ...)
3764 size_t tbl_size
= 0;
3766 struct workqueue_struct
*wq
;
3767 struct pool_workqueue
*pwq
;
3769 /* see the comment above the definition of WQ_POWER_EFFICIENT */
3770 if ((flags
& WQ_POWER_EFFICIENT
) && wq_power_efficient
)
3771 flags
|= WQ_UNBOUND
;
3773 /* allocate wq and format name */
3774 if (flags
& WQ_UNBOUND
)
3775 tbl_size
= nr_node_ids
* sizeof(wq
->numa_pwq_tbl
[0]);
3777 wq
= kzalloc(sizeof(*wq
) + tbl_size
, GFP_KERNEL
);
3781 if (flags
& WQ_UNBOUND
) {
3782 wq
->unbound_attrs
= alloc_workqueue_attrs(GFP_KERNEL
);
3783 if (!wq
->unbound_attrs
)
3787 va_start(args
, lock_name
);
3788 vsnprintf(wq
->name
, sizeof(wq
->name
), fmt
, args
);
3791 max_active
= max_active
?: WQ_DFL_ACTIVE
;
3792 max_active
= wq_clamp_max_active(max_active
, flags
, wq
->name
);
3796 wq
->saved_max_active
= max_active
;
3797 mutex_init(&wq
->mutex
);
3798 atomic_set(&wq
->nr_pwqs_to_flush
, 0);
3799 INIT_LIST_HEAD(&wq
->pwqs
);
3800 INIT_LIST_HEAD(&wq
->flusher_queue
);
3801 INIT_LIST_HEAD(&wq
->flusher_overflow
);
3802 INIT_LIST_HEAD(&wq
->maydays
);
3804 lockdep_init_map(&wq
->lockdep_map
, lock_name
, key
, 0);
3805 INIT_LIST_HEAD(&wq
->list
);
3807 if (alloc_and_link_pwqs(wq
) < 0)
3811 * Workqueues which may be used during memory reclaim should
3812 * have a rescuer to guarantee forward progress.
3814 if (flags
& WQ_MEM_RECLAIM
) {
3815 struct worker
*rescuer
;
3817 rescuer
= alloc_worker(NUMA_NO_NODE
);
3821 rescuer
->rescue_wq
= wq
;
3822 rescuer
->task
= kthread_create(rescuer_thread
, rescuer
, "%s",
3824 if (IS_ERR(rescuer
->task
)) {
3829 wq
->rescuer
= rescuer
;
3830 rescuer
->task
->flags
|= PF_NO_SETAFFINITY
;
3831 wake_up_process(rescuer
->task
);
3834 if ((wq
->flags
& WQ_SYSFS
) && workqueue_sysfs_register(wq
))
3838 * wq_pool_mutex protects global freeze state and workqueues list.
3839 * Grab it, adjust max_active and add the new @wq to workqueues
3842 mutex_lock(&wq_pool_mutex
);
3844 mutex_lock(&wq
->mutex
);
3845 for_each_pwq(pwq
, wq
)
3846 pwq_adjust_max_active(pwq
);
3847 mutex_unlock(&wq
->mutex
);
3849 list_add_tail_rcu(&wq
->list
, &workqueues
);
3851 mutex_unlock(&wq_pool_mutex
);
3856 free_workqueue_attrs(wq
->unbound_attrs
);
3860 destroy_workqueue(wq
);
3863 EXPORT_SYMBOL_GPL(__alloc_workqueue_key
);
3866 * destroy_workqueue - safely terminate a workqueue
3867 * @wq: target workqueue
3869 * Safely destroy a workqueue. All work currently pending will be done first.
3871 void destroy_workqueue(struct workqueue_struct
*wq
)
3873 struct pool_workqueue
*pwq
;
3876 /* drain it before proceeding with destruction */
3877 drain_workqueue(wq
);
3880 mutex_lock(&wq
->mutex
);
3881 for_each_pwq(pwq
, wq
) {
3884 for (i
= 0; i
< WORK_NR_COLORS
; i
++) {
3885 if (WARN_ON(pwq
->nr_in_flight
[i
])) {
3886 mutex_unlock(&wq
->mutex
);
3891 if (WARN_ON((pwq
!= wq
->dfl_pwq
) && (pwq
->refcnt
> 1)) ||
3892 WARN_ON(pwq
->nr_active
) ||
3893 WARN_ON(!list_empty(&pwq
->delayed_works
))) {
3894 mutex_unlock(&wq
->mutex
);
3898 mutex_unlock(&wq
->mutex
);
3901 * wq list is used to freeze wq, remove from list after
3902 * flushing is complete in case freeze races us.
3904 mutex_lock(&wq_pool_mutex
);
3905 list_del_rcu(&wq
->list
);
3906 mutex_unlock(&wq_pool_mutex
);
3908 workqueue_sysfs_unregister(wq
);
3911 kthread_stop(wq
->rescuer
->task
);
3913 if (!(wq
->flags
& WQ_UNBOUND
)) {
3915 * The base ref is never dropped on per-cpu pwqs. Directly
3916 * schedule RCU free.
3918 call_rcu_sched(&wq
->rcu
, rcu_free_wq
);
3921 * We're the sole accessor of @wq at this point. Directly
3922 * access numa_pwq_tbl[] and dfl_pwq to put the base refs.
3923 * @wq will be freed when the last pwq is released.
3925 for_each_node(node
) {
3926 pwq
= rcu_access_pointer(wq
->numa_pwq_tbl
[node
]);
3927 RCU_INIT_POINTER(wq
->numa_pwq_tbl
[node
], NULL
);
3928 put_pwq_unlocked(pwq
);
3932 * Put dfl_pwq. @wq may be freed any time after dfl_pwq is
3933 * put. Don't access it afterwards.
3937 put_pwq_unlocked(pwq
);
3940 EXPORT_SYMBOL_GPL(destroy_workqueue
);
3943 * workqueue_set_max_active - adjust max_active of a workqueue
3944 * @wq: target workqueue
3945 * @max_active: new max_active value.
3947 * Set max_active of @wq to @max_active.
3950 * Don't call from IRQ context.
3952 void workqueue_set_max_active(struct workqueue_struct
*wq
, int max_active
)
3954 struct pool_workqueue
*pwq
;
3956 /* disallow meddling with max_active for ordered workqueues */
3957 if (WARN_ON(wq
->flags
& __WQ_ORDERED
))
3960 max_active
= wq_clamp_max_active(max_active
, wq
->flags
, wq
->name
);
3962 mutex_lock(&wq
->mutex
);
3964 wq
->saved_max_active
= max_active
;
3966 for_each_pwq(pwq
, wq
)
3967 pwq_adjust_max_active(pwq
);
3969 mutex_unlock(&wq
->mutex
);
3971 EXPORT_SYMBOL_GPL(workqueue_set_max_active
);
3974 * current_is_workqueue_rescuer - is %current workqueue rescuer?
3976 * Determine whether %current is a workqueue rescuer. Can be used from
3977 * work functions to determine whether it's being run off the rescuer task.
3979 * Return: %true if %current is a workqueue rescuer. %false otherwise.
3981 bool current_is_workqueue_rescuer(void)
3983 struct worker
*worker
= current_wq_worker();
3985 return worker
&& worker
->rescue_wq
;
3989 * workqueue_congested - test whether a workqueue is congested
3990 * @cpu: CPU in question
3991 * @wq: target workqueue
3993 * Test whether @wq's cpu workqueue for @cpu is congested. There is
3994 * no synchronization around this function and the test result is
3995 * unreliable and only useful as advisory hints or for debugging.
3997 * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
3998 * Note that both per-cpu and unbound workqueues may be associated with
3999 * multiple pool_workqueues which have separate congested states. A
4000 * workqueue being congested on one CPU doesn't mean the workqueue is also
4001 * contested on other CPUs / NUMA nodes.
4004 * %true if congested, %false otherwise.
4006 bool workqueue_congested(int cpu
, struct workqueue_struct
*wq
)
4008 struct pool_workqueue
*pwq
;
4011 rcu_read_lock_sched();
4013 if (cpu
== WORK_CPU_UNBOUND
)
4014 cpu
= smp_processor_id();
4016 if (!(wq
->flags
& WQ_UNBOUND
))
4017 pwq
= per_cpu_ptr(wq
->cpu_pwqs
, cpu
);
4019 pwq
= unbound_pwq_by_node(wq
, cpu_to_node(cpu
));
4021 ret
= !list_empty(&pwq
->delayed_works
);
4022 rcu_read_unlock_sched();
4026 EXPORT_SYMBOL_GPL(workqueue_congested
);
4029 * work_busy - test whether a work is currently pending or running
4030 * @work: the work to be tested
4032 * Test whether @work is currently pending or running. There is no
4033 * synchronization around this function and the test result is
4034 * unreliable and only useful as advisory hints or for debugging.
4037 * OR'd bitmask of WORK_BUSY_* bits.
4039 unsigned int work_busy(struct work_struct
*work
)
4041 struct worker_pool
*pool
;
4042 unsigned long flags
;
4043 unsigned int ret
= 0;
4045 if (work_pending(work
))
4046 ret
|= WORK_BUSY_PENDING
;
4048 local_irq_save(flags
);
4049 pool
= get_work_pool(work
);
4051 spin_lock(&pool
->lock
);
4052 if (find_worker_executing_work(pool
, work
))
4053 ret
|= WORK_BUSY_RUNNING
;
4054 spin_unlock(&pool
->lock
);
4056 local_irq_restore(flags
);
4060 EXPORT_SYMBOL_GPL(work_busy
);
4063 * set_worker_desc - set description for the current work item
4064 * @fmt: printf-style format string
4065 * @...: arguments for the format string
4067 * This function can be called by a running work function to describe what
4068 * the work item is about. If the worker task gets dumped, this
4069 * information will be printed out together to help debugging. The
4070 * description can be at most WORKER_DESC_LEN including the trailing '\0'.
4072 void set_worker_desc(const char *fmt
, ...)
4074 struct worker
*worker
= current_wq_worker();
4078 va_start(args
, fmt
);
4079 vsnprintf(worker
->desc
, sizeof(worker
->desc
), fmt
, args
);
4081 worker
->desc_valid
= true;
4086 * print_worker_info - print out worker information and description
4087 * @log_lvl: the log level to use when printing
4088 * @task: target task
4090 * If @task is a worker and currently executing a work item, print out the
4091 * name of the workqueue being serviced and worker description set with
4092 * set_worker_desc() by the currently executing work item.
4094 * This function can be safely called on any task as long as the
4095 * task_struct itself is accessible. While safe, this function isn't
4096 * synchronized and may print out mixups or garbages of limited length.
4098 void print_worker_info(const char *log_lvl
, struct task_struct
*task
)
4100 work_func_t
*fn
= NULL
;
4101 char name
[WQ_NAME_LEN
] = { };
4102 char desc
[WORKER_DESC_LEN
] = { };
4103 struct pool_workqueue
*pwq
= NULL
;
4104 struct workqueue_struct
*wq
= NULL
;
4105 bool desc_valid
= false;
4106 struct worker
*worker
;
4108 if (!(task
->flags
& PF_WQ_WORKER
))
4112 * This function is called without any synchronization and @task
4113 * could be in any state. Be careful with dereferences.
4115 worker
= probe_kthread_data(task
);
4118 * Carefully copy the associated workqueue's workfn and name. Keep
4119 * the original last '\0' in case the original contains garbage.
4121 probe_kernel_read(&fn
, &worker
->current_func
, sizeof(fn
));
4122 probe_kernel_read(&pwq
, &worker
->current_pwq
, sizeof(pwq
));
4123 probe_kernel_read(&wq
, &pwq
->wq
, sizeof(wq
));
4124 probe_kernel_read(name
, wq
->name
, sizeof(name
) - 1);
4126 /* copy worker description */
4127 probe_kernel_read(&desc_valid
, &worker
->desc_valid
, sizeof(desc_valid
));
4129 probe_kernel_read(desc
, worker
->desc
, sizeof(desc
) - 1);
4131 if (fn
|| name
[0] || desc
[0]) {
4132 printk("%sWorkqueue: %s %pf", log_lvl
, name
, fn
);
4134 pr_cont(" (%s)", desc
);
4139 static void pr_cont_pool_info(struct worker_pool
*pool
)
4141 pr_cont(" cpus=%*pbl", nr_cpumask_bits
, pool
->attrs
->cpumask
);
4142 if (pool
->node
!= NUMA_NO_NODE
)
4143 pr_cont(" node=%d", pool
->node
);
4144 pr_cont(" flags=0x%x nice=%d", pool
->flags
, pool
->attrs
->nice
);
4147 static void pr_cont_work(bool comma
, struct work_struct
*work
)
4149 if (work
->func
== wq_barrier_func
) {
4150 struct wq_barrier
*barr
;
4152 barr
= container_of(work
, struct wq_barrier
, work
);
4154 pr_cont("%s BAR(%d)", comma
? "," : "",
4155 task_pid_nr(barr
->task
));
4157 pr_cont("%s %pf", comma
? "," : "", work
->func
);
4161 static void show_pwq(struct pool_workqueue
*pwq
)
4163 struct worker_pool
*pool
= pwq
->pool
;
4164 struct work_struct
*work
;
4165 struct worker
*worker
;
4166 bool has_in_flight
= false, has_pending
= false;
4169 pr_info(" pwq %d:", pool
->id
);
4170 pr_cont_pool_info(pool
);
4172 pr_cont(" active=%d/%d%s\n", pwq
->nr_active
, pwq
->max_active
,
4173 !list_empty(&pwq
->mayday_node
) ? " MAYDAY" : "");
4175 hash_for_each(pool
->busy_hash
, bkt
, worker
, hentry
) {
4176 if (worker
->current_pwq
== pwq
) {
4177 has_in_flight
= true;
4181 if (has_in_flight
) {
4184 pr_info(" in-flight:");
4185 hash_for_each(pool
->busy_hash
, bkt
, worker
, hentry
) {
4186 if (worker
->current_pwq
!= pwq
)
4189 pr_cont("%s %d%s:%pf", comma
? "," : "",
4190 task_pid_nr(worker
->task
),
4191 worker
== pwq
->wq
->rescuer
? "(RESCUER)" : "",
4192 worker
->current_func
);
4193 list_for_each_entry(work
, &worker
->scheduled
, entry
)
4194 pr_cont_work(false, work
);
4200 list_for_each_entry(work
, &pool
->worklist
, entry
) {
4201 if (get_work_pwq(work
) == pwq
) {
4209 pr_info(" pending:");
4210 list_for_each_entry(work
, &pool
->worklist
, entry
) {
4211 if (get_work_pwq(work
) != pwq
)
4214 pr_cont_work(comma
, work
);
4215 comma
= !(*work_data_bits(work
) & WORK_STRUCT_LINKED
);
4220 if (!list_empty(&pwq
->delayed_works
)) {
4223 pr_info(" delayed:");
4224 list_for_each_entry(work
, &pwq
->delayed_works
, entry
) {
4225 pr_cont_work(comma
, work
);
4226 comma
= !(*work_data_bits(work
) & WORK_STRUCT_LINKED
);
4233 * show_workqueue_state - dump workqueue state
4235 * Called from a sysrq handler and prints out all busy workqueues and
4238 void show_workqueue_state(void)
4240 struct workqueue_struct
*wq
;
4241 struct worker_pool
*pool
;
4242 unsigned long flags
;
4245 rcu_read_lock_sched();
4247 pr_info("Showing busy workqueues and worker pools:\n");
4249 list_for_each_entry_rcu(wq
, &workqueues
, list
) {
4250 struct pool_workqueue
*pwq
;
4253 for_each_pwq(pwq
, wq
) {
4254 if (pwq
->nr_active
|| !list_empty(&pwq
->delayed_works
)) {
4262 pr_info("workqueue %s: flags=0x%x\n", wq
->name
, wq
->flags
);
4264 for_each_pwq(pwq
, wq
) {
4265 spin_lock_irqsave(&pwq
->pool
->lock
, flags
);
4266 if (pwq
->nr_active
|| !list_empty(&pwq
->delayed_works
))
4268 spin_unlock_irqrestore(&pwq
->pool
->lock
, flags
);
4272 for_each_pool(pool
, pi
) {
4273 struct worker
*worker
;
4276 spin_lock_irqsave(&pool
->lock
, flags
);
4277 if (pool
->nr_workers
== pool
->nr_idle
)
4280 pr_info("pool %d:", pool
->id
);
4281 pr_cont_pool_info(pool
);
4282 pr_cont(" workers=%d", pool
->nr_workers
);
4284 pr_cont(" manager: %d",
4285 task_pid_nr(pool
->manager
->task
));
4286 list_for_each_entry(worker
, &pool
->idle_list
, entry
) {
4287 pr_cont(" %s%d", first
? "idle: " : "",
4288 task_pid_nr(worker
->task
));
4293 spin_unlock_irqrestore(&pool
->lock
, flags
);
4296 rcu_read_unlock_sched();
4302 * There are two challenges in supporting CPU hotplug. Firstly, there
4303 * are a lot of assumptions on strong associations among work, pwq and
4304 * pool which make migrating pending and scheduled works very
4305 * difficult to implement without impacting hot paths. Secondly,
4306 * worker pools serve mix of short, long and very long running works making
4307 * blocked draining impractical.
4309 * This is solved by allowing the pools to be disassociated from the CPU
4310 * running as an unbound one and allowing it to be reattached later if the
4311 * cpu comes back online.
4314 static void wq_unbind_fn(struct work_struct
*work
)
4316 int cpu
= smp_processor_id();
4317 struct worker_pool
*pool
;
4318 struct worker
*worker
;
4320 for_each_cpu_worker_pool(pool
, cpu
) {
4321 mutex_lock(&pool
->attach_mutex
);
4322 spin_lock_irq(&pool
->lock
);
4325 * We've blocked all attach/detach operations. Make all workers
4326 * unbound and set DISASSOCIATED. Before this, all workers
4327 * except for the ones which are still executing works from
4328 * before the last CPU down must be on the cpu. After
4329 * this, they may become diasporas.
4331 for_each_pool_worker(worker
, pool
)
4332 worker
->flags
|= WORKER_UNBOUND
;
4334 pool
->flags
|= POOL_DISASSOCIATED
;
4336 spin_unlock_irq(&pool
->lock
);
4337 mutex_unlock(&pool
->attach_mutex
);
4340 * Call schedule() so that we cross rq->lock and thus can
4341 * guarantee sched callbacks see the %WORKER_UNBOUND flag.
4342 * This is necessary as scheduler callbacks may be invoked
4348 * Sched callbacks are disabled now. Zap nr_running.
4349 * After this, nr_running stays zero and need_more_worker()
4350 * and keep_working() are always true as long as the
4351 * worklist is not empty. This pool now behaves as an
4352 * unbound (in terms of concurrency management) pool which
4353 * are served by workers tied to the pool.
4355 atomic_set(&pool
->nr_running
, 0);
4358 * With concurrency management just turned off, a busy
4359 * worker blocking could lead to lengthy stalls. Kick off
4360 * unbound chain execution of currently pending work items.
4362 spin_lock_irq(&pool
->lock
);
4363 wake_up_worker(pool
);
4364 spin_unlock_irq(&pool
->lock
);
4369 * rebind_workers - rebind all workers of a pool to the associated CPU
4370 * @pool: pool of interest
4372 * @pool->cpu is coming online. Rebind all workers to the CPU.
4374 static void rebind_workers(struct worker_pool
*pool
)
4376 struct worker
*worker
;
4378 lockdep_assert_held(&pool
->attach_mutex
);
4381 * Restore CPU affinity of all workers. As all idle workers should
4382 * be on the run-queue of the associated CPU before any local
4383 * wake-ups for concurrency management happen, restore CPU affinty
4384 * of all workers first and then clear UNBOUND. As we're called
4385 * from CPU_ONLINE, the following shouldn't fail.
4387 for_each_pool_worker(worker
, pool
)
4388 WARN_ON_ONCE(set_cpus_allowed_ptr(worker
->task
,
4389 pool
->attrs
->cpumask
) < 0);
4391 spin_lock_irq(&pool
->lock
);
4392 pool
->flags
&= ~POOL_DISASSOCIATED
;
4394 for_each_pool_worker(worker
, pool
) {
4395 unsigned int worker_flags
= worker
->flags
;
4398 * A bound idle worker should actually be on the runqueue
4399 * of the associated CPU for local wake-ups targeting it to
4400 * work. Kick all idle workers so that they migrate to the
4401 * associated CPU. Doing this in the same loop as
4402 * replacing UNBOUND with REBOUND is safe as no worker will
4403 * be bound before @pool->lock is released.
4405 if (worker_flags
& WORKER_IDLE
)
4406 wake_up_process(worker
->task
);
4409 * We want to clear UNBOUND but can't directly call
4410 * worker_clr_flags() or adjust nr_running. Atomically
4411 * replace UNBOUND with another NOT_RUNNING flag REBOUND.
4412 * @worker will clear REBOUND using worker_clr_flags() when
4413 * it initiates the next execution cycle thus restoring
4414 * concurrency management. Note that when or whether
4415 * @worker clears REBOUND doesn't affect correctness.
4417 * ACCESS_ONCE() is necessary because @worker->flags may be
4418 * tested without holding any lock in
4419 * wq_worker_waking_up(). Without it, NOT_RUNNING test may
4420 * fail incorrectly leading to premature concurrency
4421 * management operations.
4423 WARN_ON_ONCE(!(worker_flags
& WORKER_UNBOUND
));
4424 worker_flags
|= WORKER_REBOUND
;
4425 worker_flags
&= ~WORKER_UNBOUND
;
4426 ACCESS_ONCE(worker
->flags
) = worker_flags
;
4429 spin_unlock_irq(&pool
->lock
);
4433 * restore_unbound_workers_cpumask - restore cpumask of unbound workers
4434 * @pool: unbound pool of interest
4435 * @cpu: the CPU which is coming up
4437 * An unbound pool may end up with a cpumask which doesn't have any online
4438 * CPUs. When a worker of such pool get scheduled, the scheduler resets
4439 * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
4440 * online CPU before, cpus_allowed of all its workers should be restored.
4442 static void restore_unbound_workers_cpumask(struct worker_pool
*pool
, int cpu
)
4444 static cpumask_t cpumask
;
4445 struct worker
*worker
;
4447 lockdep_assert_held(&pool
->attach_mutex
);
4449 /* is @cpu allowed for @pool? */
4450 if (!cpumask_test_cpu(cpu
, pool
->attrs
->cpumask
))
4453 /* is @cpu the only online CPU? */
4454 cpumask_and(&cpumask
, pool
->attrs
->cpumask
, cpu_online_mask
);
4455 if (cpumask_weight(&cpumask
) != 1)
4458 /* as we're called from CPU_ONLINE, the following shouldn't fail */
4459 for_each_pool_worker(worker
, pool
)
4460 WARN_ON_ONCE(set_cpus_allowed_ptr(worker
->task
,
4461 pool
->attrs
->cpumask
) < 0);
4465 * Workqueues should be brought up before normal priority CPU notifiers.
4466 * This will be registered high priority CPU notifier.
4468 static int workqueue_cpu_up_callback(struct notifier_block
*nfb
,
4469 unsigned long action
,
4472 int cpu
= (unsigned long)hcpu
;
4473 struct worker_pool
*pool
;
4474 struct workqueue_struct
*wq
;
4477 switch (action
& ~CPU_TASKS_FROZEN
) {
4478 case CPU_UP_PREPARE
:
4479 for_each_cpu_worker_pool(pool
, cpu
) {
4480 if (pool
->nr_workers
)
4482 if (!create_worker(pool
))
4487 case CPU_DOWN_FAILED
:
4489 mutex_lock(&wq_pool_mutex
);
4491 for_each_pool(pool
, pi
) {
4492 mutex_lock(&pool
->attach_mutex
);
4494 if (pool
->cpu
== cpu
)
4495 rebind_workers(pool
);
4496 else if (pool
->cpu
< 0)
4497 restore_unbound_workers_cpumask(pool
, cpu
);
4499 mutex_unlock(&pool
->attach_mutex
);
4502 /* update NUMA affinity of unbound workqueues */
4503 list_for_each_entry(wq
, &workqueues
, list
)
4504 wq_update_unbound_numa(wq
, cpu
, true);
4506 mutex_unlock(&wq_pool_mutex
);
4513 * Workqueues should be brought down after normal priority CPU notifiers.
4514 * This will be registered as low priority CPU notifier.
4516 static int workqueue_cpu_down_callback(struct notifier_block
*nfb
,
4517 unsigned long action
,
4520 int cpu
= (unsigned long)hcpu
;
4521 struct work_struct unbind_work
;
4522 struct workqueue_struct
*wq
;
4524 switch (action
& ~CPU_TASKS_FROZEN
) {
4525 case CPU_DOWN_PREPARE
:
4526 /* unbinding per-cpu workers should happen on the local CPU */
4527 INIT_WORK_ONSTACK(&unbind_work
, wq_unbind_fn
);
4528 queue_work_on(cpu
, system_highpri_wq
, &unbind_work
);
4530 /* update NUMA affinity of unbound workqueues */
4531 mutex_lock(&wq_pool_mutex
);
4532 list_for_each_entry(wq
, &workqueues
, list
)
4533 wq_update_unbound_numa(wq
, cpu
, false);
4534 mutex_unlock(&wq_pool_mutex
);
4536 /* wait for per-cpu unbinding to finish */
4537 flush_work(&unbind_work
);
4538 destroy_work_on_stack(&unbind_work
);
4546 struct work_for_cpu
{
4547 struct work_struct work
;
4553 static void work_for_cpu_fn(struct work_struct
*work
)
4555 struct work_for_cpu
*wfc
= container_of(work
, struct work_for_cpu
, work
);
4557 wfc
->ret
= wfc
->fn(wfc
->arg
);
4561 * work_on_cpu - run a function in user context on a particular cpu
4562 * @cpu: the cpu to run on
4563 * @fn: the function to run
4564 * @arg: the function arg
4566 * It is up to the caller to ensure that the cpu doesn't go offline.
4567 * The caller must not hold any locks which would prevent @fn from completing.
4569 * Return: The value @fn returns.
4571 long work_on_cpu(int cpu
, long (*fn
)(void *), void *arg
)
4573 struct work_for_cpu wfc
= { .fn
= fn
, .arg
= arg
};
4575 INIT_WORK_ONSTACK(&wfc
.work
, work_for_cpu_fn
);
4576 schedule_work_on(cpu
, &wfc
.work
);
4577 flush_work(&wfc
.work
);
4578 destroy_work_on_stack(&wfc
.work
);
4581 EXPORT_SYMBOL_GPL(work_on_cpu
);
4582 #endif /* CONFIG_SMP */
4584 #ifdef CONFIG_FREEZER
4587 * freeze_workqueues_begin - begin freezing workqueues
4589 * Start freezing workqueues. After this function returns, all freezable
4590 * workqueues will queue new works to their delayed_works list instead of
4594 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4596 void freeze_workqueues_begin(void)
4598 struct workqueue_struct
*wq
;
4599 struct pool_workqueue
*pwq
;
4601 mutex_lock(&wq_pool_mutex
);
4603 WARN_ON_ONCE(workqueue_freezing
);
4604 workqueue_freezing
= true;
4606 list_for_each_entry(wq
, &workqueues
, list
) {
4607 mutex_lock(&wq
->mutex
);
4608 for_each_pwq(pwq
, wq
)
4609 pwq_adjust_max_active(pwq
);
4610 mutex_unlock(&wq
->mutex
);
4613 mutex_unlock(&wq_pool_mutex
);
4617 * freeze_workqueues_busy - are freezable workqueues still busy?
4619 * Check whether freezing is complete. This function must be called
4620 * between freeze_workqueues_begin() and thaw_workqueues().
4623 * Grabs and releases wq_pool_mutex.
4626 * %true if some freezable workqueues are still busy. %false if freezing
4629 bool freeze_workqueues_busy(void)
4632 struct workqueue_struct
*wq
;
4633 struct pool_workqueue
*pwq
;
4635 mutex_lock(&wq_pool_mutex
);
4637 WARN_ON_ONCE(!workqueue_freezing
);
4639 list_for_each_entry(wq
, &workqueues
, list
) {
4640 if (!(wq
->flags
& WQ_FREEZABLE
))
4643 * nr_active is monotonically decreasing. It's safe
4644 * to peek without lock.
4646 rcu_read_lock_sched();
4647 for_each_pwq(pwq
, wq
) {
4648 WARN_ON_ONCE(pwq
->nr_active
< 0);
4649 if (pwq
->nr_active
) {
4651 rcu_read_unlock_sched();
4655 rcu_read_unlock_sched();
4658 mutex_unlock(&wq_pool_mutex
);
4663 * thaw_workqueues - thaw workqueues
4665 * Thaw workqueues. Normal queueing is restored and all collected
4666 * frozen works are transferred to their respective pool worklists.
4669 * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
4671 void thaw_workqueues(void)
4673 struct workqueue_struct
*wq
;
4674 struct pool_workqueue
*pwq
;
4676 mutex_lock(&wq_pool_mutex
);
4678 if (!workqueue_freezing
)
4681 workqueue_freezing
= false;
4683 /* restore max_active and repopulate worklist */
4684 list_for_each_entry(wq
, &workqueues
, list
) {
4685 mutex_lock(&wq
->mutex
);
4686 for_each_pwq(pwq
, wq
)
4687 pwq_adjust_max_active(pwq
);
4688 mutex_unlock(&wq
->mutex
);
4692 mutex_unlock(&wq_pool_mutex
);
4694 #endif /* CONFIG_FREEZER */
4698 * Workqueues with WQ_SYSFS flag set is visible to userland via
4699 * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
4700 * following attributes.
4702 * per_cpu RO bool : whether the workqueue is per-cpu or unbound
4703 * max_active RW int : maximum number of in-flight work items
4705 * Unbound workqueues have the following extra attributes.
4707 * id RO int : the associated pool ID
4708 * nice RW int : nice value of the workers
4709 * cpumask RW mask : bitmask of allowed CPUs for the workers
4712 struct workqueue_struct
*wq
;
4716 static struct workqueue_struct
*dev_to_wq(struct device
*dev
)
4718 struct wq_device
*wq_dev
= container_of(dev
, struct wq_device
, dev
);
4723 static ssize_t
per_cpu_show(struct device
*dev
, struct device_attribute
*attr
,
4726 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4728 return scnprintf(buf
, PAGE_SIZE
, "%d\n", (bool)!(wq
->flags
& WQ_UNBOUND
));
4730 static DEVICE_ATTR_RO(per_cpu
);
4732 static ssize_t
max_active_show(struct device
*dev
,
4733 struct device_attribute
*attr
, char *buf
)
4735 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4737 return scnprintf(buf
, PAGE_SIZE
, "%d\n", wq
->saved_max_active
);
4740 static ssize_t
max_active_store(struct device
*dev
,
4741 struct device_attribute
*attr
, const char *buf
,
4744 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4747 if (sscanf(buf
, "%d", &val
) != 1 || val
<= 0)
4750 workqueue_set_max_active(wq
, val
);
4753 static DEVICE_ATTR_RW(max_active
);
4755 static struct attribute
*wq_sysfs_attrs
[] = {
4756 &dev_attr_per_cpu
.attr
,
4757 &dev_attr_max_active
.attr
,
4760 ATTRIBUTE_GROUPS(wq_sysfs
);
4762 static ssize_t
wq_pool_ids_show(struct device
*dev
,
4763 struct device_attribute
*attr
, char *buf
)
4765 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4766 const char *delim
= "";
4767 int node
, written
= 0;
4769 rcu_read_lock_sched();
4770 for_each_node(node
) {
4771 written
+= scnprintf(buf
+ written
, PAGE_SIZE
- written
,
4772 "%s%d:%d", delim
, node
,
4773 unbound_pwq_by_node(wq
, node
)->pool
->id
);
4776 written
+= scnprintf(buf
+ written
, PAGE_SIZE
- written
, "\n");
4777 rcu_read_unlock_sched();
4782 static ssize_t
wq_nice_show(struct device
*dev
, struct device_attribute
*attr
,
4785 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4788 mutex_lock(&wq
->mutex
);
4789 written
= scnprintf(buf
, PAGE_SIZE
, "%d\n", wq
->unbound_attrs
->nice
);
4790 mutex_unlock(&wq
->mutex
);
4795 /* prepare workqueue_attrs for sysfs store operations */
4796 static struct workqueue_attrs
*wq_sysfs_prep_attrs(struct workqueue_struct
*wq
)
4798 struct workqueue_attrs
*attrs
;
4800 attrs
= alloc_workqueue_attrs(GFP_KERNEL
);
4804 mutex_lock(&wq
->mutex
);
4805 copy_workqueue_attrs(attrs
, wq
->unbound_attrs
);
4806 mutex_unlock(&wq
->mutex
);
4810 static ssize_t
wq_nice_store(struct device
*dev
, struct device_attribute
*attr
,
4811 const char *buf
, size_t count
)
4813 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4814 struct workqueue_attrs
*attrs
;
4817 attrs
= wq_sysfs_prep_attrs(wq
);
4821 if (sscanf(buf
, "%d", &attrs
->nice
) == 1 &&
4822 attrs
->nice
>= MIN_NICE
&& attrs
->nice
<= MAX_NICE
)
4823 ret
= apply_workqueue_attrs(wq
, attrs
);
4827 free_workqueue_attrs(attrs
);
4828 return ret
?: count
;
4831 static ssize_t
wq_cpumask_show(struct device
*dev
,
4832 struct device_attribute
*attr
, char *buf
)
4834 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4837 mutex_lock(&wq
->mutex
);
4838 written
= scnprintf(buf
, PAGE_SIZE
, "%*pb\n",
4839 cpumask_pr_args(wq
->unbound_attrs
->cpumask
));
4840 mutex_unlock(&wq
->mutex
);
4844 static ssize_t
wq_cpumask_store(struct device
*dev
,
4845 struct device_attribute
*attr
,
4846 const char *buf
, size_t count
)
4848 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4849 struct workqueue_attrs
*attrs
;
4852 attrs
= wq_sysfs_prep_attrs(wq
);
4856 ret
= cpumask_parse(buf
, attrs
->cpumask
);
4858 ret
= apply_workqueue_attrs(wq
, attrs
);
4860 free_workqueue_attrs(attrs
);
4861 return ret
?: count
;
4864 static ssize_t
wq_numa_show(struct device
*dev
, struct device_attribute
*attr
,
4867 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4870 mutex_lock(&wq
->mutex
);
4871 written
= scnprintf(buf
, PAGE_SIZE
, "%d\n",
4872 !wq
->unbound_attrs
->no_numa
);
4873 mutex_unlock(&wq
->mutex
);
4878 static ssize_t
wq_numa_store(struct device
*dev
, struct device_attribute
*attr
,
4879 const char *buf
, size_t count
)
4881 struct workqueue_struct
*wq
= dev_to_wq(dev
);
4882 struct workqueue_attrs
*attrs
;
4885 attrs
= wq_sysfs_prep_attrs(wq
);
4890 if (sscanf(buf
, "%d", &v
) == 1) {
4891 attrs
->no_numa
= !v
;
4892 ret
= apply_workqueue_attrs(wq
, attrs
);
4895 free_workqueue_attrs(attrs
);
4896 return ret
?: count
;
4899 static struct device_attribute wq_sysfs_unbound_attrs
[] = {
4900 __ATTR(pool_ids
, 0444, wq_pool_ids_show
, NULL
),
4901 __ATTR(nice
, 0644, wq_nice_show
, wq_nice_store
),
4902 __ATTR(cpumask
, 0644, wq_cpumask_show
, wq_cpumask_store
),
4903 __ATTR(numa
, 0644, wq_numa_show
, wq_numa_store
),
4907 static struct bus_type wq_subsys
= {
4908 .name
= "workqueue",
4909 .dev_groups
= wq_sysfs_groups
,
4912 static int __init
wq_sysfs_init(void)
4914 return subsys_virtual_register(&wq_subsys
, NULL
);
4916 core_initcall(wq_sysfs_init
);
4918 static void wq_device_release(struct device
*dev
)
4920 struct wq_device
*wq_dev
= container_of(dev
, struct wq_device
, dev
);
4926 * workqueue_sysfs_register - make a workqueue visible in sysfs
4927 * @wq: the workqueue to register
4929 * Expose @wq in sysfs under /sys/bus/workqueue/devices.
4930 * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
4931 * which is the preferred method.
4933 * Workqueue user should use this function directly iff it wants to apply
4934 * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
4935 * apply_workqueue_attrs() may race against userland updating the
4938 * Return: 0 on success, -errno on failure.
4940 int workqueue_sysfs_register(struct workqueue_struct
*wq
)
4942 struct wq_device
*wq_dev
;
4946 * Adjusting max_active or creating new pwqs by applyting
4947 * attributes breaks ordering guarantee. Disallow exposing ordered
4950 if (WARN_ON(wq
->flags
& __WQ_ORDERED
))
4953 wq
->wq_dev
= wq_dev
= kzalloc(sizeof(*wq_dev
), GFP_KERNEL
);
4958 wq_dev
->dev
.bus
= &wq_subsys
;
4959 wq_dev
->dev
.init_name
= wq
->name
;
4960 wq_dev
->dev
.release
= wq_device_release
;
4963 * unbound_attrs are created separately. Suppress uevent until
4964 * everything is ready.
4966 dev_set_uevent_suppress(&wq_dev
->dev
, true);
4968 ret
= device_register(&wq_dev
->dev
);
4975 if (wq
->flags
& WQ_UNBOUND
) {
4976 struct device_attribute
*attr
;
4978 for (attr
= wq_sysfs_unbound_attrs
; attr
->attr
.name
; attr
++) {
4979 ret
= device_create_file(&wq_dev
->dev
, attr
);
4981 device_unregister(&wq_dev
->dev
);
4988 dev_set_uevent_suppress(&wq_dev
->dev
, false);
4989 kobject_uevent(&wq_dev
->dev
.kobj
, KOBJ_ADD
);
4994 * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
4995 * @wq: the workqueue to unregister
4997 * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
4999 static void workqueue_sysfs_unregister(struct workqueue_struct
*wq
)
5001 struct wq_device
*wq_dev
= wq
->wq_dev
;
5007 device_unregister(&wq_dev
->dev
);
5009 #else /* CONFIG_SYSFS */
5010 static void workqueue_sysfs_unregister(struct workqueue_struct
*wq
) { }
5011 #endif /* CONFIG_SYSFS */
5013 static void __init
wq_numa_init(void)
5018 if (num_possible_nodes() <= 1)
5021 if (wq_disable_numa
) {
5022 pr_info("workqueue: NUMA affinity support disabled\n");
5026 wq_update_unbound_numa_attrs_buf
= alloc_workqueue_attrs(GFP_KERNEL
);
5027 BUG_ON(!wq_update_unbound_numa_attrs_buf
);
5030 * We want masks of possible CPUs of each node which isn't readily
5031 * available. Build one from cpu_to_node() which should have been
5032 * fully initialized by now.
5034 tbl
= kzalloc(nr_node_ids
* sizeof(tbl
[0]), GFP_KERNEL
);
5038 BUG_ON(!zalloc_cpumask_var_node(&tbl
[node
], GFP_KERNEL
,
5039 node_online(node
) ? node
: NUMA_NO_NODE
));
5041 for_each_possible_cpu(cpu
) {
5042 node
= cpu_to_node(cpu
);
5043 if (WARN_ON(node
== NUMA_NO_NODE
)) {
5044 pr_warn("workqueue: NUMA node mapping not available for cpu%d, disabling NUMA support\n", cpu
);
5045 /* happens iff arch is bonkers, let's just proceed */
5048 cpumask_set_cpu(cpu
, tbl
[node
]);
5051 wq_numa_possible_cpumask
= tbl
;
5052 wq_numa_enabled
= true;
5055 static int __init
init_workqueues(void)
5057 int std_nice
[NR_STD_WORKER_POOLS
] = { 0, HIGHPRI_NICE_LEVEL
};
5060 WARN_ON(__alignof__(struct pool_workqueue
) < __alignof__(long long));
5062 pwq_cache
= KMEM_CACHE(pool_workqueue
, SLAB_PANIC
);
5064 cpu_notifier(workqueue_cpu_up_callback
, CPU_PRI_WORKQUEUE_UP
);
5065 hotcpu_notifier(workqueue_cpu_down_callback
, CPU_PRI_WORKQUEUE_DOWN
);
5069 /* initialize CPU pools */
5070 for_each_possible_cpu(cpu
) {
5071 struct worker_pool
*pool
;
5074 for_each_cpu_worker_pool(pool
, cpu
) {
5075 BUG_ON(init_worker_pool(pool
));
5077 cpumask_copy(pool
->attrs
->cpumask
, cpumask_of(cpu
));
5078 pool
->attrs
->nice
= std_nice
[i
++];
5079 pool
->node
= cpu_to_node(cpu
);
5082 mutex_lock(&wq_pool_mutex
);
5083 BUG_ON(worker_pool_assign_id(pool
));
5084 mutex_unlock(&wq_pool_mutex
);
5088 /* create the initial worker */
5089 for_each_online_cpu(cpu
) {
5090 struct worker_pool
*pool
;
5092 for_each_cpu_worker_pool(pool
, cpu
) {
5093 pool
->flags
&= ~POOL_DISASSOCIATED
;
5094 BUG_ON(!create_worker(pool
));
5098 /* create default unbound and ordered wq attrs */
5099 for (i
= 0; i
< NR_STD_WORKER_POOLS
; i
++) {
5100 struct workqueue_attrs
*attrs
;
5102 BUG_ON(!(attrs
= alloc_workqueue_attrs(GFP_KERNEL
)));
5103 attrs
->nice
= std_nice
[i
];
5104 unbound_std_wq_attrs
[i
] = attrs
;
5107 * An ordered wq should have only one pwq as ordering is
5108 * guaranteed by max_active which is enforced by pwqs.
5109 * Turn off NUMA so that dfl_pwq is used for all nodes.
5111 BUG_ON(!(attrs
= alloc_workqueue_attrs(GFP_KERNEL
)));
5112 attrs
->nice
= std_nice
[i
];
5113 attrs
->no_numa
= true;
5114 ordered_wq_attrs
[i
] = attrs
;
5117 system_wq
= alloc_workqueue("events", 0, 0);
5118 system_highpri_wq
= alloc_workqueue("events_highpri", WQ_HIGHPRI
, 0);
5119 system_long_wq
= alloc_workqueue("events_long", 0, 0);
5120 system_unbound_wq
= alloc_workqueue("events_unbound", WQ_UNBOUND
,
5121 WQ_UNBOUND_MAX_ACTIVE
);
5122 system_freezable_wq
= alloc_workqueue("events_freezable",
5124 system_power_efficient_wq
= alloc_workqueue("events_power_efficient",
5125 WQ_POWER_EFFICIENT
, 0);
5126 system_freezable_power_efficient_wq
= alloc_workqueue("events_freezable_power_efficient",
5127 WQ_FREEZABLE
| WQ_POWER_EFFICIENT
,
5129 BUG_ON(!system_wq
|| !system_highpri_wq
|| !system_long_wq
||
5130 !system_unbound_wq
|| !system_freezable_wq
||
5131 !system_power_efficient_wq
||
5132 !system_freezable_power_efficient_wq
);
5135 early_initcall(init_workqueues
);