1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
3c54fce6eSTejun Heo * kernel/workqueue.c - generic async execution with shared worker pool
41da177e4SLinus Torvalds *
5c54fce6eSTejun Heo * Copyright (C) 2002 Ingo Molnar
61da177e4SLinus Torvalds *
71da177e4SLinus Torvalds * Derived from the taskqueue/keventd code by:
81da177e4SLinus Torvalds * David Woodhouse <dwmw2@infradead.org>
9e1f8e874SFrancois Cami * Andrew Morton
101da177e4SLinus Torvalds * Kai Petzke <wpp@marie.physik.tu-berlin.de>
111da177e4SLinus Torvalds * Theodore Ts'o <tytso@mit.edu>
1289ada679SChristoph Lameter *
13cde53535SChristoph Lameter * Made to use alloc_percpu by Christoph Lameter.
14c54fce6eSTejun Heo *
15c54fce6eSTejun Heo * Copyright (C) 2010 SUSE Linux Products GmbH
16c54fce6eSTejun Heo * Copyright (C) 2010 Tejun Heo <tj@kernel.org>
17c54fce6eSTejun Heo *
18c54fce6eSTejun Heo * This is the generic async execution mechanism. Work items as are
19c54fce6eSTejun Heo * executed in process context. The worker pool is shared and
20b11895c4SLibin * automatically managed. There are two worker pools for each CPU (one for
21b11895c4SLibin * normal work items and the other for high priority ones) and some extra
22b11895c4SLibin * pools for workqueues which are not bound to any specific CPU - the
23b11895c4SLibin * number of these backing pools is dynamic.
24c54fce6eSTejun Heo *
259a261491SBenjamin Peterson * Please read Documentation/core-api/workqueue.rst for details.
261da177e4SLinus Torvalds */
271da177e4SLinus Torvalds
289984de1aSPaul Gortmaker #include <linux/export.h>
291da177e4SLinus Torvalds #include <linux/kernel.h>
301da177e4SLinus Torvalds #include <linux/sched.h>
311da177e4SLinus Torvalds #include <linux/init.h>
321da177e4SLinus Torvalds #include <linux/signal.h>
331da177e4SLinus Torvalds #include <linux/completion.h>
341da177e4SLinus Torvalds #include <linux/workqueue.h>
351da177e4SLinus Torvalds #include <linux/slab.h>
361da177e4SLinus Torvalds #include <linux/cpu.h>
371da177e4SLinus Torvalds #include <linux/notifier.h>
381da177e4SLinus Torvalds #include <linux/kthread.h>
391fa44ecaSJames Bottomley #include <linux/hardirq.h>
4046934023SChristoph Lameter #include <linux/mempolicy.h>
41341a5958SRafael J. Wysocki #include <linux/freezer.h>
42d5abe669SPeter Zijlstra #include <linux/debug_locks.h>
434e6045f1SJohannes Berg #include <linux/lockdep.h>
44c34056a3STejun Heo #include <linux/idr.h>
4529c91e99STejun Heo #include <linux/jhash.h>
4642f8570fSSasha Levin #include <linux/hashtable.h>
4776af4d93STejun Heo #include <linux/rculist.h>
48bce90380STejun Heo #include <linux/nodemask.h>
494c16bd32STejun Heo #include <linux/moduleparam.h>
503d1cb205STejun Heo #include <linux/uaccess.h>
51c98a9805STal Shorer #include <linux/sched/isolation.h>
52cd2440d6SPetr Mladek #include <linux/sched/debug.h>
5362635ea8SSergey Senozhatsky #include <linux/nmi.h>
54940d71c6SSergey Senozhatsky #include <linux/kvm_para.h>
55aa6fde93STejun Heo #include <linux/delay.h>
56e22bee78STejun Heo
57ea138446STejun Heo #include "workqueue_internal.h"
581da177e4SLinus Torvalds
59c8e55f36STejun Heo enum {
60bc2ae0f5STejun Heo /*
6124647570STejun Heo * worker_pool flags
62bc2ae0f5STejun Heo *
6324647570STejun Heo * A bound pool is either associated or disassociated with its CPU.
64bc2ae0f5STejun Heo * While associated (!DISASSOCIATED), all workers are bound to the
65bc2ae0f5STejun Heo * CPU and none has %WORKER_UNBOUND set and concurrency management
66bc2ae0f5STejun Heo * is in effect.
67bc2ae0f5STejun Heo *
68bc2ae0f5STejun Heo * While DISASSOCIATED, the cpu may be offline and all workers have
69bc2ae0f5STejun Heo * %WORKER_UNBOUND set and concurrency management disabled, and may
7024647570STejun Heo * be executing on any CPU. The pool behaves as an unbound one.
71bc2ae0f5STejun Heo *
72bc3a1afcSTejun Heo * Note that DISASSOCIATED should be flipped only while holding
731258fae7STejun Heo * wq_pool_attach_mutex to avoid changing binding state while
744736cbf7SLai Jiangshan * worker_attach_to_pool() is in progress.
75bc2ae0f5STejun Heo */
76692b4825STejun Heo POOL_MANAGER_ACTIVE = 1 << 0, /* being managed */
7724647570STejun Heo POOL_DISASSOCIATED = 1 << 2, /* cpu can't serve workers */
78db7bccf4STejun Heo
79c8e55f36STejun Heo /* worker flags */
80c8e55f36STejun Heo WORKER_DIE = 1 << 1, /* die die die */
81c8e55f36STejun Heo WORKER_IDLE = 1 << 2, /* is idle */
82e22bee78STejun Heo WORKER_PREP = 1 << 3, /* preparing to run works */
83fb0e7bebSTejun Heo WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
84f3421797STejun Heo WORKER_UNBOUND = 1 << 7, /* worker is unbound */
85a9ab775bSTejun Heo WORKER_REBOUND = 1 << 8, /* worker was rebound */
86e22bee78STejun Heo
87a9ab775bSTejun Heo WORKER_NOT_RUNNING = WORKER_PREP | WORKER_CPU_INTENSIVE |
88a9ab775bSTejun Heo WORKER_UNBOUND | WORKER_REBOUND,
89db7bccf4STejun Heo
90e34cdddbSTejun Heo NR_STD_WORKER_POOLS = 2, /* # standard pools per cpu */
914ce62e9eSTejun Heo
9229c91e99STejun Heo UNBOUND_POOL_HASH_ORDER = 6, /* hashed by pool->attrs */
93c8e55f36STejun Heo BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
94db7bccf4STejun Heo
95e22bee78STejun Heo MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
96e22bee78STejun Heo IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
97e22bee78STejun Heo
983233cdbdSTejun Heo MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
993233cdbdSTejun Heo /* call for help after 10ms
1003233cdbdSTejun Heo (min two ticks) */
101e22bee78STejun Heo MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
102e22bee78STejun Heo CREATE_COOLDOWN = HZ, /* time to breath after fail */
1031da177e4SLinus Torvalds
1041da177e4SLinus Torvalds /*
105e22bee78STejun Heo * Rescue workers are used only on emergencies and shared by
1068698a745SDongsheng Yang * all cpus. Give MIN_NICE.
107e22bee78STejun Heo */
1088698a745SDongsheng Yang RESCUER_NICE_LEVEL = MIN_NICE,
1098698a745SDongsheng Yang HIGHPRI_NICE_LEVEL = MIN_NICE,
110ecf6881fSTejun Heo
111a99d7274SGreg Kroah-Hartman WQ_NAME_LEN = 24,
112c8e55f36STejun Heo };
113c8e55f36STejun Heo
1141da177e4SLinus Torvalds /*
1154690c4abSTejun Heo * Structure fields follow one of the following exclusion rules.
1164690c4abSTejun Heo *
117e41e704bSTejun Heo * I: Modifiable by initialization/destruction paths and read-only for
118e41e704bSTejun Heo * everyone else.
1194690c4abSTejun Heo *
120e22bee78STejun Heo * P: Preemption protected. Disabling preemption is enough and should
121e22bee78STejun Heo * only be modified and accessed from the local cpu.
122e22bee78STejun Heo *
123d565ed63STejun Heo * L: pool->lock protected. Access with pool->lock held.
1244690c4abSTejun Heo *
125bdf8b9bfSTejun Heo * K: Only modified by worker while holding pool->lock. Can be safely read by
126bdf8b9bfSTejun Heo * self, while holding pool->lock or from IRQ context if %current is the
127bdf8b9bfSTejun Heo * kworker.
128bdf8b9bfSTejun Heo *
129bdf8b9bfSTejun Heo * S: Only modified by worker self.
130bdf8b9bfSTejun Heo *
1311258fae7STejun Heo * A: wq_pool_attach_mutex protected.
132822d8405STejun Heo *
13368e13a67SLai Jiangshan * PL: wq_pool_mutex protected.
13476af4d93STejun Heo *
13524acfb71SThomas Gleixner * PR: wq_pool_mutex protected for writes. RCU protected for reads.
1365bcab335STejun Heo *
1375b95e1afSLai Jiangshan * PW: wq_pool_mutex and wq->mutex protected for writes. Either for reads.
1385b95e1afSLai Jiangshan *
1395b95e1afSLai Jiangshan * PWR: wq_pool_mutex and wq->mutex protected for writes. Either or
14024acfb71SThomas Gleixner * RCU for reads.
1415b95e1afSLai Jiangshan *
1423c25a55dSLai Jiangshan * WQ: wq->mutex protected.
1433c25a55dSLai Jiangshan *
14424acfb71SThomas Gleixner * WR: wq->mutex protected for writes. RCU protected for reads.
1452e109a28STejun Heo *
1462e109a28STejun Heo * MD: wq_mayday_lock protected.
147cd2440d6SPetr Mladek *
148cd2440d6SPetr Mladek * WD: Used internally by the watchdog.
1494690c4abSTejun Heo */
1504690c4abSTejun Heo
1512eaebdb3STejun Heo /* struct worker is defined in workqueue_internal.h */
152c34056a3STejun Heo
153bd7bdd43STejun Heo struct worker_pool {
154a9b8a985SSebastian Andrzej Siewior raw_spinlock_t lock; /* the pool lock */
155d84ff051STejun Heo int cpu; /* I: the associated cpu */
156f3f90ad4STejun Heo int node; /* I: the associated node ID */
1579daf9e67STejun Heo int id; /* I: pool ID */
158bc8b50c2STejun Heo unsigned int flags; /* L: flags */
159bd7bdd43STejun Heo
16082607adcSTejun Heo unsigned long watchdog_ts; /* L: watchdog timestamp */
161cd2440d6SPetr Mladek bool cpu_stall; /* WD: stalled cpu bound pool */
16282607adcSTejun Heo
163bc35f7efSLai Jiangshan /*
164bc35f7efSLai Jiangshan * The counter is incremented in a process context on the associated CPU
165bc35f7efSLai Jiangshan * w/ preemption disabled, and decremented or reset in the same context
166bc35f7efSLai Jiangshan * but w/ pool->lock held. The readers grab pool->lock and are
167bc35f7efSLai Jiangshan * guaranteed to see if the counter reached zero.
168bc35f7efSLai Jiangshan */
169bc35f7efSLai Jiangshan int nr_running;
17084f91c62SLai Jiangshan
171bd7bdd43STejun Heo struct list_head worklist; /* L: list of pending works */
172ea1abd61SLai Jiangshan
1735826cc8fSLai Jiangshan int nr_workers; /* L: total number of workers */
1745826cc8fSLai Jiangshan int nr_idle; /* L: currently idle workers */
175bd7bdd43STejun Heo
1762c1f1a91SLai Jiangshan struct list_head idle_list; /* L: list of idle workers */
177bd7bdd43STejun Heo struct timer_list idle_timer; /* L: worker idle timeout */
1783f959aa3SValentin Schneider struct work_struct idle_cull_work; /* L: worker idle cleanup */
1793f959aa3SValentin Schneider
180bd7bdd43STejun Heo struct timer_list mayday_timer; /* L: SOS timer for workers */
181bd7bdd43STejun Heo
182c5aa87bbSTejun Heo /* a workers is either on busy_hash or idle_list, or the manager */
183c9e7cf27STejun Heo DECLARE_HASHTABLE(busy_hash, BUSY_WORKER_HASH_ORDER);
184c9e7cf27STejun Heo /* L: hash of busy workers */
185c9e7cf27STejun Heo
1862607d7a6STejun Heo struct worker *manager; /* L: purely informational */
18792f9c5c4SLai Jiangshan struct list_head workers; /* A: attached workers */
188e02b9312SValentin Schneider struct list_head dying_workers; /* A: workers about to die */
18960f5a4bcSLai Jiangshan struct completion *detach_completion; /* all workers detached */
190e19e397aSTejun Heo
1917cda9aaeSLai Jiangshan struct ida worker_ida; /* worker IDs for task name */
192e19e397aSTejun Heo
1937a4e344cSTejun Heo struct workqueue_attrs *attrs; /* I: worker attributes */
19468e13a67SLai Jiangshan struct hlist_node hash_node; /* PL: unbound_pool_hash node */
19568e13a67SLai Jiangshan int refcnt; /* PL: refcnt for unbound pools */
1967a4e344cSTejun Heo
197e19e397aSTejun Heo /*
19824acfb71SThomas Gleixner * Destruction of pool is RCU protected to allow dereferences
19929c91e99STejun Heo * from get_work_pool().
20029c91e99STejun Heo */
20129c91e99STejun Heo struct rcu_head rcu;
20284f91c62SLai Jiangshan };
2038b03ae3cSTejun Heo
2048b03ae3cSTejun Heo /*
205725e8ec5STejun Heo * Per-pool_workqueue statistics. These can be monitored using
206725e8ec5STejun Heo * tools/workqueue/wq_monitor.py.
207725e8ec5STejun Heo */
208725e8ec5STejun Heo enum pool_workqueue_stats {
209725e8ec5STejun Heo PWQ_STAT_STARTED, /* work items started execution */
210725e8ec5STejun Heo PWQ_STAT_COMPLETED, /* work items completed execution */
2118a1dd1e5STejun Heo PWQ_STAT_CPU_TIME, /* total CPU time consumed */
212616db877STejun Heo PWQ_STAT_CPU_INTENSIVE, /* wq_cpu_intensive_thresh_us violations */
213725e8ec5STejun Heo PWQ_STAT_CM_WAKEUP, /* concurrency-management worker wakeups */
2148639ecebSTejun Heo PWQ_STAT_REPATRIATED, /* unbound workers brought back into scope */
215725e8ec5STejun Heo PWQ_STAT_MAYDAY, /* maydays to rescuer */
216725e8ec5STejun Heo PWQ_STAT_RESCUED, /* linked work items executed by rescuer */
217725e8ec5STejun Heo
218725e8ec5STejun Heo PWQ_NR_STATS,
219725e8ec5STejun Heo };
220725e8ec5STejun Heo
221725e8ec5STejun Heo /*
222112202d9STejun Heo * The per-pool workqueue. While queued, the lower WORK_STRUCT_FLAG_BITS
223112202d9STejun Heo * of work_struct->data are used for flags and the remaining high bits
224112202d9STejun Heo * point to the pwq; thus, pwqs need to be aligned at two's power of the
225112202d9STejun Heo * number of flag bits.
2261da177e4SLinus Torvalds */
227112202d9STejun Heo struct pool_workqueue {
228bd7bdd43STejun Heo struct worker_pool *pool; /* I: the associated pool */
2294690c4abSTejun Heo struct workqueue_struct *wq; /* I: the owning workqueue */
23073f53c4aSTejun Heo int work_color; /* L: current color */
23173f53c4aSTejun Heo int flush_color; /* L: flushing color */
2328864b4e5STejun Heo int refcnt; /* L: reference count */
23373f53c4aSTejun Heo int nr_in_flight[WORK_NR_COLORS];
23473f53c4aSTejun Heo /* L: nr of in_flight works */
235018f3a13SLai Jiangshan
236018f3a13SLai Jiangshan /*
237018f3a13SLai Jiangshan * nr_active management and WORK_STRUCT_INACTIVE:
238018f3a13SLai Jiangshan *
239018f3a13SLai Jiangshan * When pwq->nr_active >= max_active, new work item is queued to
240018f3a13SLai Jiangshan * pwq->inactive_works instead of pool->worklist and marked with
241018f3a13SLai Jiangshan * WORK_STRUCT_INACTIVE.
242018f3a13SLai Jiangshan *
2436741dd3fSGreg Kroah-Hartman * All work items marked with WORK_STRUCT_INACTIVE do not participate
2446741dd3fSGreg Kroah-Hartman * in pwq->nr_active and all work items in pwq->inactive_works are
2456741dd3fSGreg Kroah-Hartman * marked with WORK_STRUCT_INACTIVE. But not all WORK_STRUCT_INACTIVE
2466741dd3fSGreg Kroah-Hartman * work items are in pwq->inactive_works. Some of them are ready to
2476741dd3fSGreg Kroah-Hartman * run in pool->worklist or worker->scheduled. Those work itmes are
2486741dd3fSGreg Kroah-Hartman * only struct wq_barrier which is used for flush_work() and should
2496741dd3fSGreg Kroah-Hartman * not participate in pwq->nr_active. For non-barrier work item, it
2506741dd3fSGreg Kroah-Hartman * is marked with WORK_STRUCT_INACTIVE iff it is in pwq->inactive_works.
251018f3a13SLai Jiangshan */
2521e19ffc6STejun Heo int nr_active; /* L: nr of active works */
253d8354f26SGreg Kroah-Hartman int max_active; /* L: max active works */
254f97a4a1aSLai Jiangshan struct list_head inactive_works; /* L: inactive works */
2553c25a55dSLai Jiangshan struct list_head pwqs_node; /* WR: node on wq->pwqs */
2562e109a28STejun Heo struct list_head mayday_node; /* MD: node on wq->maydays */
2578864b4e5STejun Heo
258725e8ec5STejun Heo u64 stats[PWQ_NR_STATS];
259725e8ec5STejun Heo
2608864b4e5STejun Heo /*
261967b494eSTejun Heo * Release of unbound pwq is punted to a kthread_worker. See put_pwq()
262687a9aa5STejun Heo * and pwq_release_workfn() for details. pool_workqueue itself is also
263687a9aa5STejun Heo * RCU protected so that the first pwq can be determined without
264967b494eSTejun Heo * grabbing wq->mutex.
2658864b4e5STejun Heo */
266687a9aa5STejun Heo struct kthread_work release_work;
2678864b4e5STejun Heo struct rcu_head rcu;
268e904e6c2STejun Heo } __aligned(1 << WORK_STRUCT_FLAG_BITS);
2691da177e4SLinus Torvalds
2701da177e4SLinus Torvalds /*
27173f53c4aSTejun Heo * Structure used to wait for workqueue flush.
27273f53c4aSTejun Heo */
27373f53c4aSTejun Heo struct wq_flusher {
2743c25a55dSLai Jiangshan struct list_head list; /* WQ: list of flushers */
2753c25a55dSLai Jiangshan int flush_color; /* WQ: flush color waiting for */
27673f53c4aSTejun Heo struct completion done; /* flush completion */
27773f53c4aSTejun Heo };
2781da177e4SLinus Torvalds
279226223abSTejun Heo struct wq_device;
280226223abSTejun Heo
28173f53c4aSTejun Heo /*
282c5aa87bbSTejun Heo * The externally visible workqueue. It relays the issued work items to
283c5aa87bbSTejun Heo * the appropriate worker_pool through its pool_workqueues.
2841da177e4SLinus Torvalds */
2851da177e4SLinus Torvalds struct workqueue_struct {
2863c25a55dSLai Jiangshan struct list_head pwqs; /* WR: all pwqs of this wq */
287e2dca7adSTejun Heo struct list_head list; /* PR: list of all workqueues */
28873f53c4aSTejun Heo
2893c25a55dSLai Jiangshan struct mutex mutex; /* protects this wq */
2903c25a55dSLai Jiangshan int work_color; /* WQ: current work color */
2913c25a55dSLai Jiangshan int flush_color; /* WQ: current flush color */
292112202d9STejun Heo atomic_t nr_pwqs_to_flush; /* flush in progress */
2933c25a55dSLai Jiangshan struct wq_flusher *first_flusher; /* WQ: first flusher */
2943c25a55dSLai Jiangshan struct list_head flusher_queue; /* WQ: flush waiters */
2953c25a55dSLai Jiangshan struct list_head flusher_overflow; /* WQ: flush overflow list */
29673f53c4aSTejun Heo
2972e109a28STejun Heo struct list_head maydays; /* MD: pwqs requesting rescue */
29830ae2fc0STejun Heo struct worker *rescuer; /* MD: rescue worker */
299e22bee78STejun Heo
30087fc741eSLai Jiangshan int nr_drainers; /* WQ: drain in progress */
301d8354f26SGreg Kroah-Hartman int saved_max_active; /* WQ: saved pwq max_active */
302226223abSTejun Heo
3035b95e1afSLai Jiangshan struct workqueue_attrs *unbound_attrs; /* PW: only for unbound wqs */
304f3c11cb2SGreg Kroah-Hartman struct pool_workqueue *dfl_pwq; /* PW: only for unbound wqs */
3056029a918STejun Heo
306226223abSTejun Heo #ifdef CONFIG_SYSFS
307226223abSTejun Heo struct wq_device *wq_dev; /* I: for sysfs interface */
308226223abSTejun Heo #endif
3094e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
310669de8bdSBart Van Assche char *lock_name;
311669de8bdSBart Van Assche struct lock_class_key key;
3124e6045f1SJohannes Berg struct lockdep_map lockdep_map;
3134e6045f1SJohannes Berg #endif
314ecf6881fSTejun Heo char name[WQ_NAME_LEN]; /* I: workqueue name */
3152728fd2fSTejun Heo
316e2dca7adSTejun Heo /*
31724acfb71SThomas Gleixner * Destruction of workqueue_struct is RCU protected to allow walking
31824acfb71SThomas Gleixner * the workqueues list without grabbing wq_pool_mutex.
319e2dca7adSTejun Heo * This is used to dump all workqueues from sysrq.
320e2dca7adSTejun Heo */
321e2dca7adSTejun Heo struct rcu_head rcu;
322e2dca7adSTejun Heo
3232728fd2fSTejun Heo /* hot fields used during command issue, aligned to cacheline */
3242728fd2fSTejun Heo unsigned int flags ____cacheline_aligned; /* WQ: WQ_* flags */
325636b927eSTejun Heo struct pool_workqueue __percpu __rcu **cpu_pwq; /* I: per-cpu pwqs */
3261da177e4SLinus Torvalds };
3271da177e4SLinus Torvalds
328e904e6c2STejun Heo static struct kmem_cache *pwq_cache;
329e904e6c2STejun Heo
33084193c07STejun Heo /*
33184193c07STejun Heo * Each pod type describes how CPUs should be grouped for unbound workqueues.
33284193c07STejun Heo * See the comment above workqueue_attrs->affn_scope.
33384193c07STejun Heo */
33484193c07STejun Heo struct wq_pod_type {
33584193c07STejun Heo int nr_pods; /* number of pods */
33684193c07STejun Heo cpumask_var_t *pod_cpus; /* pod -> cpus */
33784193c07STejun Heo int *pod_node; /* pod -> node */
33884193c07STejun Heo int *cpu_pod; /* cpu -> pod */
33984193c07STejun Heo };
34084193c07STejun Heo
34184193c07STejun Heo static struct wq_pod_type wq_pod_types[WQ_AFFN_NR_TYPES];
342523a301eSTejun Heo static enum wq_affn_scope wq_affn_dfl = WQ_AFFN_CACHE;
34363c5484eSTejun Heo
34463c5484eSTejun Heo static const char *wq_affn_names[WQ_AFFN_NR_TYPES] = {
345523a301eSTejun Heo [WQ_AFFN_DFL] = "default",
34663c5484eSTejun Heo [WQ_AFFN_CPU] = "cpu",
34763c5484eSTejun Heo [WQ_AFFN_SMT] = "smt",
34863c5484eSTejun Heo [WQ_AFFN_CACHE] = "cache",
34963c5484eSTejun Heo [WQ_AFFN_NUMA] = "numa",
35063c5484eSTejun Heo [WQ_AFFN_SYSTEM] = "system",
35163c5484eSTejun Heo };
352bce90380STejun Heo
353616db877STejun Heo /*
354616db877STejun Heo * Per-cpu work items which run for longer than the following threshold are
355616db877STejun Heo * automatically considered CPU intensive and excluded from concurrency
356616db877STejun Heo * management to prevent them from noticeably delaying other per-cpu work items.
357aa6fde93STejun Heo * ULONG_MAX indicates that the user hasn't overridden it with a boot parameter.
358aa6fde93STejun Heo * The actual value is initialized in wq_cpu_intensive_thresh_init().
359616db877STejun Heo */
360aa6fde93STejun Heo static unsigned long wq_cpu_intensive_thresh_us = ULONG_MAX;
361616db877STejun Heo module_param_named(cpu_intensive_thresh_us, wq_cpu_intensive_thresh_us, ulong, 0644);
362616db877STejun Heo
363cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
364552f530cSLuis R. Rodriguez static bool wq_power_efficient = IS_ENABLED(CONFIG_WQ_POWER_EFFICIENT_DEFAULT);
365cee22a15SViresh Kumar module_param_named(power_efficient, wq_power_efficient, bool, 0444);
366cee22a15SViresh Kumar
367863b710bSTejun Heo static bool wq_online; /* can kworkers be created yet? */
3683347fa09STejun Heo
369fef59c9cSTejun Heo /* buf for wq_update_unbound_pod_attrs(), protected by CPU hotplug exclusion */
370fef59c9cSTejun Heo static struct workqueue_attrs *wq_update_pod_attrs_buf;
3714c16bd32STejun Heo
37268e13a67SLai Jiangshan static DEFINE_MUTEX(wq_pool_mutex); /* protects pools and workqueues list */
3731258fae7STejun Heo static DEFINE_MUTEX(wq_pool_attach_mutex); /* protects worker attach/detach */
374a9b8a985SSebastian Andrzej Siewior static DEFINE_RAW_SPINLOCK(wq_mayday_lock); /* protects wq->maydays list */
375d8bb65abSSebastian Andrzej Siewior /* wait for manager to go away */
376d8bb65abSSebastian Andrzej Siewior static struct rcuwait manager_wait = __RCUWAIT_INITIALIZER(manager_wait);
3775bcab335STejun Heo
378e2dca7adSTejun Heo static LIST_HEAD(workqueues); /* PR: list of all workqueues */
37968e13a67SLai Jiangshan static bool workqueue_freezing; /* PL: have wqs started freezing? */
3807d19c5ceSTejun Heo
38199c621efSLai Jiangshan /* PL&A: allowable cpus for unbound wqs and work items */
382ef557180SMike Galbraith static cpumask_var_t wq_unbound_cpumask;
383ef557180SMike Galbraith
384ace3c549Stiozhang /* for further constrain wq_unbound_cpumask by cmdline parameter*/
385ace3c549Stiozhang static struct cpumask wq_cmdline_cpumask __initdata;
386ace3c549Stiozhang
387ef557180SMike Galbraith /* CPU where unbound work was last round robin scheduled from this CPU */
388ef557180SMike Galbraith static DEFINE_PER_CPU(int, wq_rr_cpu_last);
389b05a7928SFrederic Weisbecker
390f303fccbSTejun Heo /*
391f303fccbSTejun Heo * Local execution of unbound work items is no longer guaranteed. The
392f303fccbSTejun Heo * following always forces round-robin CPU selection on unbound work items
393f303fccbSTejun Heo * to uncover usages which depend on it.
394f303fccbSTejun Heo */
395f303fccbSTejun Heo #ifdef CONFIG_DEBUG_WQ_FORCE_RR_CPU
396f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = true;
397f303fccbSTejun Heo #else
398f303fccbSTejun Heo static bool wq_debug_force_rr_cpu = false;
399f303fccbSTejun Heo #endif
400f303fccbSTejun Heo module_param_named(debug_force_rr_cpu, wq_debug_force_rr_cpu, bool, 0644);
401f303fccbSTejun Heo
4027d19c5ceSTejun Heo /* the per-cpu worker pools */
40325528213SPeter Zijlstra static DEFINE_PER_CPU_SHARED_ALIGNED(struct worker_pool [NR_STD_WORKER_POOLS], cpu_worker_pools);
4047d19c5ceSTejun Heo
40568e13a67SLai Jiangshan static DEFINE_IDR(worker_pool_idr); /* PR: idr of all pools */
4067d19c5ceSTejun Heo
40768e13a67SLai Jiangshan /* PL: hash of all unbound pools keyed by pool->attrs */
40829c91e99STejun Heo static DEFINE_HASHTABLE(unbound_pool_hash, UNBOUND_POOL_HASH_ORDER);
40929c91e99STejun Heo
410c5aa87bbSTejun Heo /* I: attributes used when instantiating standard unbound pools on demand */
41129c91e99STejun Heo static struct workqueue_attrs *unbound_std_wq_attrs[NR_STD_WORKER_POOLS];
41229c91e99STejun Heo
4138a2b7538STejun Heo /* I: attributes used when instantiating ordered pools on demand */
4148a2b7538STejun Heo static struct workqueue_attrs *ordered_wq_attrs[NR_STD_WORKER_POOLS];
4158a2b7538STejun Heo
416967b494eSTejun Heo /*
417967b494eSTejun Heo * I: kthread_worker to release pwq's. pwq release needs to be bounced to a
418967b494eSTejun Heo * process context while holding a pool lock. Bounce to a dedicated kthread
419967b494eSTejun Heo * worker to avoid A-A deadlocks.
420967b494eSTejun Heo */
421967b494eSTejun Heo static struct kthread_worker *pwq_release_worker;
422967b494eSTejun Heo
423d320c038STejun Heo struct workqueue_struct *system_wq __read_mostly;
424ad7b1f84SMarc Dionne EXPORT_SYMBOL(system_wq);
425044c782cSValentin Ilie struct workqueue_struct *system_highpri_wq __read_mostly;
4261aabe902SJoonsoo Kim EXPORT_SYMBOL_GPL(system_highpri_wq);
427044c782cSValentin Ilie struct workqueue_struct *system_long_wq __read_mostly;
428d320c038STejun Heo EXPORT_SYMBOL_GPL(system_long_wq);
429044c782cSValentin Ilie struct workqueue_struct *system_unbound_wq __read_mostly;
430f3421797STejun Heo EXPORT_SYMBOL_GPL(system_unbound_wq);
431044c782cSValentin Ilie struct workqueue_struct *system_freezable_wq __read_mostly;
43224d51addSTejun Heo EXPORT_SYMBOL_GPL(system_freezable_wq);
4330668106cSViresh Kumar struct workqueue_struct *system_power_efficient_wq __read_mostly;
4340668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_power_efficient_wq);
4350668106cSViresh Kumar struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
4360668106cSViresh Kumar EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
437d320c038STejun Heo
4387d19c5ceSTejun Heo static int worker_thread(void *__worker);
4396ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq);
440c29eb853STejun Heo static void show_pwq(struct pool_workqueue *pwq);
44155df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool);
4427d19c5ceSTejun Heo
44397bd2347STejun Heo #define CREATE_TRACE_POINTS
44497bd2347STejun Heo #include <trace/events/workqueue.h>
44597bd2347STejun Heo
44668e13a67SLai Jiangshan #define assert_rcu_or_pool_mutex() \
44724acfb71SThomas Gleixner RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
448f78f5b90SPaul E. McKenney !lockdep_is_held(&wq_pool_mutex), \
44924acfb71SThomas Gleixner "RCU or wq_pool_mutex should be held")
4505bcab335STejun Heo
4515b95e1afSLai Jiangshan #define assert_rcu_or_wq_mutex_or_pool_mutex(wq) \
45224acfb71SThomas Gleixner RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
453f78f5b90SPaul E. McKenney !lockdep_is_held(&wq->mutex) && \
454f78f5b90SPaul E. McKenney !lockdep_is_held(&wq_pool_mutex), \
45524acfb71SThomas Gleixner "RCU, wq->mutex or wq_pool_mutex should be held")
4565b95e1afSLai Jiangshan
457f02ae73aSTejun Heo #define for_each_cpu_worker_pool(pool, cpu) \
458f02ae73aSTejun Heo for ((pool) = &per_cpu(cpu_worker_pools, cpu)[0]; \
459f02ae73aSTejun Heo (pool) < &per_cpu(cpu_worker_pools, cpu)[NR_STD_WORKER_POOLS]; \
4607a62c2c8STejun Heo (pool)++)
4614ce62e9eSTejun Heo
46249e3cf44STejun Heo /**
46317116969STejun Heo * for_each_pool - iterate through all worker_pools in the system
46417116969STejun Heo * @pool: iteration cursor
465611c92a0STejun Heo * @pi: integer used for iteration
466fa1b54e6STejun Heo *
46724acfb71SThomas Gleixner * This must be called either with wq_pool_mutex held or RCU read
46868e13a67SLai Jiangshan * locked. If the pool needs to be used beyond the locking in effect, the
46968e13a67SLai Jiangshan * caller is responsible for guaranteeing that the pool stays online.
470fa1b54e6STejun Heo *
471fa1b54e6STejun Heo * The if/else clause exists only for the lockdep assertion and can be
472fa1b54e6STejun Heo * ignored.
47317116969STejun Heo */
474611c92a0STejun Heo #define for_each_pool(pool, pi) \
475611c92a0STejun Heo idr_for_each_entry(&worker_pool_idr, pool, pi) \
47668e13a67SLai Jiangshan if (({ assert_rcu_or_pool_mutex(); false; })) { } \
477fa1b54e6STejun Heo else
47817116969STejun Heo
47917116969STejun Heo /**
480822d8405STejun Heo * for_each_pool_worker - iterate through all workers of a worker_pool
481822d8405STejun Heo * @worker: iteration cursor
482822d8405STejun Heo * @pool: worker_pool to iterate workers of
483822d8405STejun Heo *
4841258fae7STejun Heo * This must be called with wq_pool_attach_mutex.
485822d8405STejun Heo *
486822d8405STejun Heo * The if/else clause exists only for the lockdep assertion and can be
487822d8405STejun Heo * ignored.
488822d8405STejun Heo */
489da028469SLai Jiangshan #define for_each_pool_worker(worker, pool) \
490da028469SLai Jiangshan list_for_each_entry((worker), &(pool)->workers, node) \
4911258fae7STejun Heo if (({ lockdep_assert_held(&wq_pool_attach_mutex); false; })) { } \
492822d8405STejun Heo else
493822d8405STejun Heo
494822d8405STejun Heo /**
49549e3cf44STejun Heo * for_each_pwq - iterate through all pool_workqueues of the specified workqueue
49649e3cf44STejun Heo * @pwq: iteration cursor
49749e3cf44STejun Heo * @wq: the target workqueue
49876af4d93STejun Heo *
49924acfb71SThomas Gleixner * This must be called either with wq->mutex held or RCU read locked.
500794b18bcSTejun Heo * If the pwq needs to be used beyond the locking in effect, the caller is
501794b18bcSTejun Heo * responsible for guaranteeing that the pwq stays online.
50276af4d93STejun Heo *
50376af4d93STejun Heo * The if/else clause exists only for the lockdep assertion and can be
50476af4d93STejun Heo * ignored.
50549e3cf44STejun Heo */
50649e3cf44STejun Heo #define for_each_pwq(pwq, wq) \
50749e9d1a9SSebastian Andrzej Siewior list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node, \
5085a644662SJoel Fernandes (Google) lockdep_is_held(&(wq->mutex)))
509f3421797STejun Heo
510dc186ad7SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_WORK
511dc186ad7SThomas Gleixner
512f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr;
513dc186ad7SThomas Gleixner
work_debug_hint(void * addr)51499777288SStanislaw Gruszka static void *work_debug_hint(void *addr)
51599777288SStanislaw Gruszka {
51699777288SStanislaw Gruszka return ((struct work_struct *) addr)->func;
51799777288SStanislaw Gruszka }
51899777288SStanislaw Gruszka
work_is_static_object(void * addr)519b9fdac7fSDu, Changbin static bool work_is_static_object(void *addr)
520b9fdac7fSDu, Changbin {
521b9fdac7fSDu, Changbin struct work_struct *work = addr;
522b9fdac7fSDu, Changbin
523b9fdac7fSDu, Changbin return test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work));
524b9fdac7fSDu, Changbin }
525b9fdac7fSDu, Changbin
526dc186ad7SThomas Gleixner /*
527dc186ad7SThomas Gleixner * fixup_init is called when:
528dc186ad7SThomas Gleixner * - an active object is initialized
529dc186ad7SThomas Gleixner */
work_fixup_init(void * addr,enum debug_obj_state state)53002a982a6SDu, Changbin static bool work_fixup_init(void *addr, enum debug_obj_state state)
531dc186ad7SThomas Gleixner {
532dc186ad7SThomas Gleixner struct work_struct *work = addr;
533dc186ad7SThomas Gleixner
534dc186ad7SThomas Gleixner switch (state) {
535dc186ad7SThomas Gleixner case ODEBUG_STATE_ACTIVE:
536dc186ad7SThomas Gleixner cancel_work_sync(work);
537dc186ad7SThomas Gleixner debug_object_init(work, &work_debug_descr);
53802a982a6SDu, Changbin return true;
539dc186ad7SThomas Gleixner default:
54002a982a6SDu, Changbin return false;
541dc186ad7SThomas Gleixner }
542dc186ad7SThomas Gleixner }
543dc186ad7SThomas Gleixner
544dc186ad7SThomas Gleixner /*
545dc186ad7SThomas Gleixner * fixup_free is called when:
546dc186ad7SThomas Gleixner * - an active object is freed
547dc186ad7SThomas Gleixner */
work_fixup_free(void * addr,enum debug_obj_state state)54802a982a6SDu, Changbin static bool work_fixup_free(void *addr, enum debug_obj_state state)
549dc186ad7SThomas Gleixner {
550dc186ad7SThomas Gleixner struct work_struct *work = addr;
551dc186ad7SThomas Gleixner
552dc186ad7SThomas Gleixner switch (state) {
553dc186ad7SThomas Gleixner case ODEBUG_STATE_ACTIVE:
554dc186ad7SThomas Gleixner cancel_work_sync(work);
555dc186ad7SThomas Gleixner debug_object_free(work, &work_debug_descr);
55602a982a6SDu, Changbin return true;
557dc186ad7SThomas Gleixner default:
55802a982a6SDu, Changbin return false;
559dc186ad7SThomas Gleixner }
560dc186ad7SThomas Gleixner }
561dc186ad7SThomas Gleixner
562f9e62f31SStephen Boyd static const struct debug_obj_descr work_debug_descr = {
563dc186ad7SThomas Gleixner .name = "work_struct",
56499777288SStanislaw Gruszka .debug_hint = work_debug_hint,
565b9fdac7fSDu, Changbin .is_static_object = work_is_static_object,
566dc186ad7SThomas Gleixner .fixup_init = work_fixup_init,
567dc186ad7SThomas Gleixner .fixup_free = work_fixup_free,
568dc186ad7SThomas Gleixner };
569dc186ad7SThomas Gleixner
debug_work_activate(struct work_struct * work)570dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work)
571dc186ad7SThomas Gleixner {
572dc186ad7SThomas Gleixner debug_object_activate(work, &work_debug_descr);
573dc186ad7SThomas Gleixner }
574dc186ad7SThomas Gleixner
debug_work_deactivate(struct work_struct * work)575dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work)
576dc186ad7SThomas Gleixner {
577dc186ad7SThomas Gleixner debug_object_deactivate(work, &work_debug_descr);
578dc186ad7SThomas Gleixner }
579dc186ad7SThomas Gleixner
__init_work(struct work_struct * work,int onstack)580dc186ad7SThomas Gleixner void __init_work(struct work_struct *work, int onstack)
581dc186ad7SThomas Gleixner {
582dc186ad7SThomas Gleixner if (onstack)
583dc186ad7SThomas Gleixner debug_object_init_on_stack(work, &work_debug_descr);
584dc186ad7SThomas Gleixner else
585dc186ad7SThomas Gleixner debug_object_init(work, &work_debug_descr);
586dc186ad7SThomas Gleixner }
587dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(__init_work);
588dc186ad7SThomas Gleixner
destroy_work_on_stack(struct work_struct * work)589dc186ad7SThomas Gleixner void destroy_work_on_stack(struct work_struct *work)
590dc186ad7SThomas Gleixner {
591dc186ad7SThomas Gleixner debug_object_free(work, &work_debug_descr);
592dc186ad7SThomas Gleixner }
593dc186ad7SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_work_on_stack);
594dc186ad7SThomas Gleixner
destroy_delayed_work_on_stack(struct delayed_work * work)595ea2e64f2SThomas Gleixner void destroy_delayed_work_on_stack(struct delayed_work *work)
596ea2e64f2SThomas Gleixner {
597ea2e64f2SThomas Gleixner destroy_timer_on_stack(&work->timer);
598ea2e64f2SThomas Gleixner debug_object_free(&work->work, &work_debug_descr);
599ea2e64f2SThomas Gleixner }
600ea2e64f2SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_delayed_work_on_stack);
601ea2e64f2SThomas Gleixner
602dc186ad7SThomas Gleixner #else
debug_work_activate(struct work_struct * work)603dc186ad7SThomas Gleixner static inline void debug_work_activate(struct work_struct *work) { }
debug_work_deactivate(struct work_struct * work)604dc186ad7SThomas Gleixner static inline void debug_work_deactivate(struct work_struct *work) { }
605dc186ad7SThomas Gleixner #endif
606dc186ad7SThomas Gleixner
6074e8b22bdSLi Bin /**
60867dc8325SCai Huoqing * worker_pool_assign_id - allocate ID and assign it to @pool
6094e8b22bdSLi Bin * @pool: the pool pointer of interest
6104e8b22bdSLi Bin *
6114e8b22bdSLi Bin * Returns 0 if ID in [0, WORK_OFFQ_POOL_NONE) is allocated and assigned
6124e8b22bdSLi Bin * successfully, -errno on failure.
6134e8b22bdSLi Bin */
worker_pool_assign_id(struct worker_pool * pool)6149daf9e67STejun Heo static int worker_pool_assign_id(struct worker_pool *pool)
6159daf9e67STejun Heo {
6169daf9e67STejun Heo int ret;
6179daf9e67STejun Heo
61868e13a67SLai Jiangshan lockdep_assert_held(&wq_pool_mutex);
6195bcab335STejun Heo
6204e8b22bdSLi Bin ret = idr_alloc(&worker_pool_idr, pool, 0, WORK_OFFQ_POOL_NONE,
6214e8b22bdSLi Bin GFP_KERNEL);
622229641a6STejun Heo if (ret >= 0) {
623e68035fbSTejun Heo pool->id = ret;
624229641a6STejun Heo return 0;
625229641a6STejun Heo }
6269daf9e67STejun Heo return ret;
6279daf9e67STejun Heo }
6289daf9e67STejun Heo
work_color_to_flags(int color)62973f53c4aSTejun Heo static unsigned int work_color_to_flags(int color)
63073f53c4aSTejun Heo {
63173f53c4aSTejun Heo return color << WORK_STRUCT_COLOR_SHIFT;
63273f53c4aSTejun Heo }
63373f53c4aSTejun Heo
get_work_color(unsigned long work_data)634c4560c2cSLai Jiangshan static int get_work_color(unsigned long work_data)
63573f53c4aSTejun Heo {
636c4560c2cSLai Jiangshan return (work_data >> WORK_STRUCT_COLOR_SHIFT) &
63773f53c4aSTejun Heo ((1 << WORK_STRUCT_COLOR_BITS) - 1);
63873f53c4aSTejun Heo }
63973f53c4aSTejun Heo
work_next_color(int color)64073f53c4aSTejun Heo static int work_next_color(int color)
64173f53c4aSTejun Heo {
64273f53c4aSTejun Heo return (color + 1) % WORK_NR_COLORS;
643a848e3b6SOleg Nesterov }
644a848e3b6SOleg Nesterov
6454594bf15SDavid Howells /*
646112202d9STejun Heo * While queued, %WORK_STRUCT_PWQ is set and non flag bits of a work's data
647112202d9STejun Heo * contain the pointer to the queued pwq. Once execution starts, the flag
6487c3eed5cSTejun Heo * is cleared and the high bits contain OFFQ flags and pool ID.
6497a22ad75STejun Heo *
650112202d9STejun Heo * set_work_pwq(), set_work_pool_and_clear_pending(), mark_work_canceling()
651112202d9STejun Heo * and clear_work_data() can be used to set the pwq, pool or clear
652bbb68dfaSTejun Heo * work->data. These functions should only be called while the work is
653bbb68dfaSTejun Heo * owned - ie. while the PENDING bit is set.
6547a22ad75STejun Heo *
655112202d9STejun Heo * get_work_pool() and get_work_pwq() can be used to obtain the pool or pwq
6567c3eed5cSTejun Heo * corresponding to a work. Pool is available once the work has been
657112202d9STejun Heo * queued anywhere after initialization until it is sync canceled. pwq is
6587c3eed5cSTejun Heo * available only while the work item is queued.
659bbb68dfaSTejun Heo *
660bbb68dfaSTejun Heo * %WORK_OFFQ_CANCELING is used to mark a work item which is being
661bbb68dfaSTejun Heo * canceled. While being canceled, a work item may have its PENDING set
662bbb68dfaSTejun Heo * but stay off timer and worklist for arbitrarily long and nobody should
663bbb68dfaSTejun Heo * try to steal the PENDING bit.
6644594bf15SDavid Howells */
set_work_data(struct work_struct * work,unsigned long data,unsigned long flags)6657a22ad75STejun Heo static inline void set_work_data(struct work_struct *work, unsigned long data,
6667a22ad75STejun Heo unsigned long flags)
6677a22ad75STejun Heo {
6686183c009STejun Heo WARN_ON_ONCE(!work_pending(work));
6697a22ad75STejun Heo atomic_long_set(&work->data, data | flags | work_static(work));
6707a22ad75STejun Heo }
6717a22ad75STejun Heo
set_work_pwq(struct work_struct * work,struct pool_workqueue * pwq,unsigned long extra_flags)672112202d9STejun Heo static void set_work_pwq(struct work_struct *work, struct pool_workqueue *pwq,
6734690c4abSTejun Heo unsigned long extra_flags)
674365970a1SDavid Howells {
675112202d9STejun Heo set_work_data(work, (unsigned long)pwq,
676112202d9STejun Heo WORK_STRUCT_PENDING | WORK_STRUCT_PWQ | extra_flags);
677365970a1SDavid Howells }
678365970a1SDavid Howells
set_work_pool_and_keep_pending(struct work_struct * work,int pool_id)6794468a00fSLai Jiangshan static void set_work_pool_and_keep_pending(struct work_struct *work,
6804468a00fSLai Jiangshan int pool_id)
6814468a00fSLai Jiangshan {
6824468a00fSLai Jiangshan set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT,
6834468a00fSLai Jiangshan WORK_STRUCT_PENDING);
6844468a00fSLai Jiangshan }
6854468a00fSLai Jiangshan
set_work_pool_and_clear_pending(struct work_struct * work,int pool_id)6867c3eed5cSTejun Heo static void set_work_pool_and_clear_pending(struct work_struct *work,
6877c3eed5cSTejun Heo int pool_id)
6884d707b9fSOleg Nesterov {
68923657bb1STejun Heo /*
69023657bb1STejun Heo * The following wmb is paired with the implied mb in
69123657bb1STejun Heo * test_and_set_bit(PENDING) and ensures all updates to @work made
69223657bb1STejun Heo * here are visible to and precede any updates by the next PENDING
69323657bb1STejun Heo * owner.
69423657bb1STejun Heo */
69523657bb1STejun Heo smp_wmb();
6967c3eed5cSTejun Heo set_work_data(work, (unsigned long)pool_id << WORK_OFFQ_POOL_SHIFT, 0);
697346c09f8SRoman Pen /*
698346c09f8SRoman Pen * The following mb guarantees that previous clear of a PENDING bit
699346c09f8SRoman Pen * will not be reordered with any speculative LOADS or STORES from
700346c09f8SRoman Pen * work->current_func, which is executed afterwards. This possible
7018bdc6201SLiu Song * reordering can lead to a missed execution on attempt to queue
702346c09f8SRoman Pen * the same @work. E.g. consider this case:
703346c09f8SRoman Pen *
704346c09f8SRoman Pen * CPU#0 CPU#1
705346c09f8SRoman Pen * ---------------------------- --------------------------------
706346c09f8SRoman Pen *
707346c09f8SRoman Pen * 1 STORE event_indicated
708346c09f8SRoman Pen * 2 queue_work_on() {
709346c09f8SRoman Pen * 3 test_and_set_bit(PENDING)
710346c09f8SRoman Pen * 4 } set_..._and_clear_pending() {
711346c09f8SRoman Pen * 5 set_work_data() # clear bit
712346c09f8SRoman Pen * 6 smp_mb()
713346c09f8SRoman Pen * 7 work->current_func() {
714346c09f8SRoman Pen * 8 LOAD event_indicated
715346c09f8SRoman Pen * }
716346c09f8SRoman Pen *
717346c09f8SRoman Pen * Without an explicit full barrier speculative LOAD on line 8 can
718346c09f8SRoman Pen * be executed before CPU#0 does STORE on line 1. If that happens,
719346c09f8SRoman Pen * CPU#0 observes the PENDING bit is still set and new execution of
720346c09f8SRoman Pen * a @work is not queued in a hope, that CPU#1 will eventually
721346c09f8SRoman Pen * finish the queued @work. Meanwhile CPU#1 does not see
722346c09f8SRoman Pen * event_indicated is set, because speculative LOAD was executed
723346c09f8SRoman Pen * before actual STORE.
724346c09f8SRoman Pen */
725346c09f8SRoman Pen smp_mb();
7264d707b9fSOleg Nesterov }
7274d707b9fSOleg Nesterov
clear_work_data(struct work_struct * work)7287a22ad75STejun Heo static void clear_work_data(struct work_struct *work)
729365970a1SDavid Howells {
7307c3eed5cSTejun Heo smp_wmb(); /* see set_work_pool_and_clear_pending() */
7317c3eed5cSTejun Heo set_work_data(work, WORK_STRUCT_NO_POOL, 0);
7327a22ad75STejun Heo }
7337a22ad75STejun Heo
work_struct_pwq(unsigned long data)734afa4bb77SLinus Torvalds static inline struct pool_workqueue *work_struct_pwq(unsigned long data)
735afa4bb77SLinus Torvalds {
736afa4bb77SLinus Torvalds return (struct pool_workqueue *)(data & WORK_STRUCT_WQ_DATA_MASK);
737afa4bb77SLinus Torvalds }
738afa4bb77SLinus Torvalds
get_work_pwq(struct work_struct * work)739112202d9STejun Heo static struct pool_workqueue *get_work_pwq(struct work_struct *work)
7407a22ad75STejun Heo {
741e120153dSTejun Heo unsigned long data = atomic_long_read(&work->data);
7427a22ad75STejun Heo
743112202d9STejun Heo if (data & WORK_STRUCT_PWQ)
744afa4bb77SLinus Torvalds return work_struct_pwq(data);
745e120153dSTejun Heo else
746e120153dSTejun Heo return NULL;
7477a22ad75STejun Heo }
7487a22ad75STejun Heo
7497c3eed5cSTejun Heo /**
7507c3eed5cSTejun Heo * get_work_pool - return the worker_pool a given work was associated with
7517c3eed5cSTejun Heo * @work: the work item of interest
7527c3eed5cSTejun Heo *
75368e13a67SLai Jiangshan * Pools are created and destroyed under wq_pool_mutex, and allows read
75424acfb71SThomas Gleixner * access under RCU read lock. As such, this function should be
75524acfb71SThomas Gleixner * called under wq_pool_mutex or inside of a rcu_read_lock() region.
756fa1b54e6STejun Heo *
757fa1b54e6STejun Heo * All fields of the returned pool are accessible as long as the above
758fa1b54e6STejun Heo * mentioned locking is in effect. If the returned pool needs to be used
759fa1b54e6STejun Heo * beyond the critical section, the caller is responsible for ensuring the
760fa1b54e6STejun Heo * returned pool is and stays online.
761d185af30SYacine Belkadi *
762d185af30SYacine Belkadi * Return: The worker_pool @work was last associated with. %NULL if none.
7637c3eed5cSTejun Heo */
get_work_pool(struct work_struct * work)7647c3eed5cSTejun Heo static struct worker_pool *get_work_pool(struct work_struct *work)
7657a22ad75STejun Heo {
766e120153dSTejun Heo unsigned long data = atomic_long_read(&work->data);
7677c3eed5cSTejun Heo int pool_id;
7687a22ad75STejun Heo
76968e13a67SLai Jiangshan assert_rcu_or_pool_mutex();
770fa1b54e6STejun Heo
771112202d9STejun Heo if (data & WORK_STRUCT_PWQ)
772afa4bb77SLinus Torvalds return work_struct_pwq(data)->pool;
7737a22ad75STejun Heo
7747c3eed5cSTejun Heo pool_id = data >> WORK_OFFQ_POOL_SHIFT;
7757c3eed5cSTejun Heo if (pool_id == WORK_OFFQ_POOL_NONE)
7767a22ad75STejun Heo return NULL;
7777a22ad75STejun Heo
778fa1b54e6STejun Heo return idr_find(&worker_pool_idr, pool_id);
7797c3eed5cSTejun Heo }
7807c3eed5cSTejun Heo
7817c3eed5cSTejun Heo /**
7827c3eed5cSTejun Heo * get_work_pool_id - return the worker pool ID a given work is associated with
7837c3eed5cSTejun Heo * @work: the work item of interest
7847c3eed5cSTejun Heo *
785d185af30SYacine Belkadi * Return: The worker_pool ID @work was last associated with.
7867c3eed5cSTejun Heo * %WORK_OFFQ_POOL_NONE if none.
7877c3eed5cSTejun Heo */
get_work_pool_id(struct work_struct * work)7887c3eed5cSTejun Heo static int get_work_pool_id(struct work_struct *work)
7897c3eed5cSTejun Heo {
79054d5b7d0SLai Jiangshan unsigned long data = atomic_long_read(&work->data);
7917c3eed5cSTejun Heo
792112202d9STejun Heo if (data & WORK_STRUCT_PWQ)
793afa4bb77SLinus Torvalds return work_struct_pwq(data)->pool->id;
79454d5b7d0SLai Jiangshan
79554d5b7d0SLai Jiangshan return data >> WORK_OFFQ_POOL_SHIFT;
7967c3eed5cSTejun Heo }
7977c3eed5cSTejun Heo
mark_work_canceling(struct work_struct * work)798bbb68dfaSTejun Heo static void mark_work_canceling(struct work_struct *work)
799bbb68dfaSTejun Heo {
8007c3eed5cSTejun Heo unsigned long pool_id = get_work_pool_id(work);
801bbb68dfaSTejun Heo
8027c3eed5cSTejun Heo pool_id <<= WORK_OFFQ_POOL_SHIFT;
8037c3eed5cSTejun Heo set_work_data(work, pool_id | WORK_OFFQ_CANCELING, WORK_STRUCT_PENDING);
804bbb68dfaSTejun Heo }
805bbb68dfaSTejun Heo
work_is_canceling(struct work_struct * work)806bbb68dfaSTejun Heo static bool work_is_canceling(struct work_struct *work)
807bbb68dfaSTejun Heo {
808bbb68dfaSTejun Heo unsigned long data = atomic_long_read(&work->data);
809bbb68dfaSTejun Heo
810112202d9STejun Heo return !(data & WORK_STRUCT_PWQ) && (data & WORK_OFFQ_CANCELING);
811bbb68dfaSTejun Heo }
812bbb68dfaSTejun Heo
813e22bee78STejun Heo /*
8143270476aSTejun Heo * Policy functions. These define the policies on how the global worker
8153270476aSTejun Heo * pools are managed. Unless noted otherwise, these functions assume that
816d565ed63STejun Heo * they're being called with pool->lock held.
817e22bee78STejun Heo */
818e22bee78STejun Heo
819e22bee78STejun Heo /*
820e22bee78STejun Heo * Need to wake up a worker? Called from anything but currently
821e22bee78STejun Heo * running workers.
822974271c4STejun Heo *
823974271c4STejun Heo * Note that, because unbound workers never contribute to nr_running, this
824706026c2STejun Heo * function will always return %true for unbound pools as long as the
825974271c4STejun Heo * worklist isn't empty.
826e22bee78STejun Heo */
need_more_worker(struct worker_pool * pool)82763d95a91STejun Heo static bool need_more_worker(struct worker_pool *pool)
828e22bee78STejun Heo {
8290219a352STejun Heo return !list_empty(&pool->worklist) && !pool->nr_running;
830e22bee78STejun Heo }
831e22bee78STejun Heo
832e22bee78STejun Heo /* Can I start working? Called from busy but !running workers. */
may_start_working(struct worker_pool * pool)83363d95a91STejun Heo static bool may_start_working(struct worker_pool *pool)
834e22bee78STejun Heo {
83563d95a91STejun Heo return pool->nr_idle;
836e22bee78STejun Heo }
837e22bee78STejun Heo
838e22bee78STejun Heo /* Do I need to keep working? Called from currently running workers. */
keep_working(struct worker_pool * pool)83963d95a91STejun Heo static bool keep_working(struct worker_pool *pool)
840e22bee78STejun Heo {
841bc35f7efSLai Jiangshan return !list_empty(&pool->worklist) && (pool->nr_running <= 1);
842e22bee78STejun Heo }
843e22bee78STejun Heo
844e22bee78STejun Heo /* Do we need a new worker? Called from manager. */
need_to_create_worker(struct worker_pool * pool)84563d95a91STejun Heo static bool need_to_create_worker(struct worker_pool *pool)
846e22bee78STejun Heo {
84763d95a91STejun Heo return need_more_worker(pool) && !may_start_working(pool);
848e22bee78STejun Heo }
849e22bee78STejun Heo
850e22bee78STejun Heo /* Do we have too many workers and should some go away? */
too_many_workers(struct worker_pool * pool)85163d95a91STejun Heo static bool too_many_workers(struct worker_pool *pool)
852e22bee78STejun Heo {
853692b4825STejun Heo bool managing = pool->flags & POOL_MANAGER_ACTIVE;
85463d95a91STejun Heo int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
85563d95a91STejun Heo int nr_busy = pool->nr_workers - nr_idle;
856e22bee78STejun Heo
857e22bee78STejun Heo return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
858e22bee78STejun Heo }
859e22bee78STejun Heo
8604690c4abSTejun Heo /**
861e22bee78STejun Heo * worker_set_flags - set worker flags and adjust nr_running accordingly
862cb444766STejun Heo * @worker: self
863d302f017STejun Heo * @flags: flags to set
864d302f017STejun Heo *
865228f1d00SLai Jiangshan * Set @flags in @worker->flags and adjust nr_running accordingly.
866d302f017STejun Heo */
worker_set_flags(struct worker * worker,unsigned int flags)867228f1d00SLai Jiangshan static inline void worker_set_flags(struct worker *worker, unsigned int flags)
868d302f017STejun Heo {
869bd7bdd43STejun Heo struct worker_pool *pool = worker->pool;
870e22bee78STejun Heo
871bc8b50c2STejun Heo lockdep_assert_held(&pool->lock);
872cb444766STejun Heo
873228f1d00SLai Jiangshan /* If transitioning into NOT_RUNNING, adjust nr_running. */
874e22bee78STejun Heo if ((flags & WORKER_NOT_RUNNING) &&
875e22bee78STejun Heo !(worker->flags & WORKER_NOT_RUNNING)) {
876bc35f7efSLai Jiangshan pool->nr_running--;
877e22bee78STejun Heo }
878e22bee78STejun Heo
879d302f017STejun Heo worker->flags |= flags;
880d302f017STejun Heo }
881d302f017STejun Heo
882d302f017STejun Heo /**
883e22bee78STejun Heo * worker_clr_flags - clear worker flags and adjust nr_running accordingly
884cb444766STejun Heo * @worker: self
885d302f017STejun Heo * @flags: flags to clear
886d302f017STejun Heo *
887e22bee78STejun Heo * Clear @flags in @worker->flags and adjust nr_running accordingly.
888d302f017STejun Heo */
worker_clr_flags(struct worker * worker,unsigned int flags)889d302f017STejun Heo static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
890d302f017STejun Heo {
89163d95a91STejun Heo struct worker_pool *pool = worker->pool;
892e22bee78STejun Heo unsigned int oflags = worker->flags;
893e22bee78STejun Heo
894bc8b50c2STejun Heo lockdep_assert_held(&pool->lock);
895cb444766STejun Heo
896d302f017STejun Heo worker->flags &= ~flags;
897e22bee78STejun Heo
89842c025f3STejun Heo /*
89942c025f3STejun Heo * If transitioning out of NOT_RUNNING, increment nr_running. Note
90042c025f3STejun Heo * that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
90142c025f3STejun Heo * of multiple flags, not a single flag.
90242c025f3STejun Heo */
903e22bee78STejun Heo if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
904e22bee78STejun Heo if (!(worker->flags & WORKER_NOT_RUNNING))
905bc35f7efSLai Jiangshan pool->nr_running++;
906d302f017STejun Heo }
907d302f017STejun Heo
908797e8345STejun Heo /* Return the first idle worker. Called with pool->lock held. */
first_idle_worker(struct worker_pool * pool)909797e8345STejun Heo static struct worker *first_idle_worker(struct worker_pool *pool)
910797e8345STejun Heo {
911797e8345STejun Heo if (unlikely(list_empty(&pool->idle_list)))
912797e8345STejun Heo return NULL;
913797e8345STejun Heo
914797e8345STejun Heo return list_first_entry(&pool->idle_list, struct worker, entry);
915797e8345STejun Heo }
916797e8345STejun Heo
917797e8345STejun Heo /**
918797e8345STejun Heo * worker_enter_idle - enter idle state
919797e8345STejun Heo * @worker: worker which is entering idle state
920797e8345STejun Heo *
921797e8345STejun Heo * @worker is entering idle state. Update stats and idle timer if
922797e8345STejun Heo * necessary.
923797e8345STejun Heo *
924797e8345STejun Heo * LOCKING:
925797e8345STejun Heo * raw_spin_lock_irq(pool->lock).
926797e8345STejun Heo */
worker_enter_idle(struct worker * worker)927797e8345STejun Heo static void worker_enter_idle(struct worker *worker)
928797e8345STejun Heo {
929797e8345STejun Heo struct worker_pool *pool = worker->pool;
930797e8345STejun Heo
931797e8345STejun Heo if (WARN_ON_ONCE(worker->flags & WORKER_IDLE) ||
932797e8345STejun Heo WARN_ON_ONCE(!list_empty(&worker->entry) &&
933797e8345STejun Heo (worker->hentry.next || worker->hentry.pprev)))
934797e8345STejun Heo return;
935797e8345STejun Heo
936797e8345STejun Heo /* can't use worker_set_flags(), also called from create_worker() */
937797e8345STejun Heo worker->flags |= WORKER_IDLE;
938797e8345STejun Heo pool->nr_idle++;
939797e8345STejun Heo worker->last_active = jiffies;
940797e8345STejun Heo
941797e8345STejun Heo /* idle_list is LIFO */
942797e8345STejun Heo list_add(&worker->entry, &pool->idle_list);
943797e8345STejun Heo
944797e8345STejun Heo if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
945797e8345STejun Heo mod_timer(&pool->idle_timer, jiffies + IDLE_WORKER_TIMEOUT);
946797e8345STejun Heo
947797e8345STejun Heo /* Sanity check nr_running. */
948797e8345STejun Heo WARN_ON_ONCE(pool->nr_workers == pool->nr_idle && pool->nr_running);
949797e8345STejun Heo }
950797e8345STejun Heo
951797e8345STejun Heo /**
952797e8345STejun Heo * worker_leave_idle - leave idle state
953797e8345STejun Heo * @worker: worker which is leaving idle state
954797e8345STejun Heo *
955797e8345STejun Heo * @worker is leaving idle state. Update stats.
956797e8345STejun Heo *
957797e8345STejun Heo * LOCKING:
958797e8345STejun Heo * raw_spin_lock_irq(pool->lock).
959797e8345STejun Heo */
worker_leave_idle(struct worker * worker)960797e8345STejun Heo static void worker_leave_idle(struct worker *worker)
961797e8345STejun Heo {
962797e8345STejun Heo struct worker_pool *pool = worker->pool;
963797e8345STejun Heo
964797e8345STejun Heo if (WARN_ON_ONCE(!(worker->flags & WORKER_IDLE)))
965797e8345STejun Heo return;
966797e8345STejun Heo worker_clr_flags(worker, WORKER_IDLE);
967797e8345STejun Heo pool->nr_idle--;
968797e8345STejun Heo list_del_init(&worker->entry);
969797e8345STejun Heo }
970797e8345STejun Heo
971797e8345STejun Heo /**
972797e8345STejun Heo * find_worker_executing_work - find worker which is executing a work
973797e8345STejun Heo * @pool: pool of interest
974797e8345STejun Heo * @work: work to find worker for
975797e8345STejun Heo *
976797e8345STejun Heo * Find a worker which is executing @work on @pool by searching
977797e8345STejun Heo * @pool->busy_hash which is keyed by the address of @work. For a worker
978797e8345STejun Heo * to match, its current execution should match the address of @work and
979797e8345STejun Heo * its work function. This is to avoid unwanted dependency between
980797e8345STejun Heo * unrelated work executions through a work item being recycled while still
981797e8345STejun Heo * being executed.
982797e8345STejun Heo *
983797e8345STejun Heo * This is a bit tricky. A work item may be freed once its execution
984797e8345STejun Heo * starts and nothing prevents the freed area from being recycled for
985797e8345STejun Heo * another work item. If the same work item address ends up being reused
986797e8345STejun Heo * before the original execution finishes, workqueue will identify the
987797e8345STejun Heo * recycled work item as currently executing and make it wait until the
988797e8345STejun Heo * current execution finishes, introducing an unwanted dependency.
989797e8345STejun Heo *
990797e8345STejun Heo * This function checks the work item address and work function to avoid
991797e8345STejun Heo * false positives. Note that this isn't complete as one may construct a
992797e8345STejun Heo * work function which can introduce dependency onto itself through a
993797e8345STejun Heo * recycled work item. Well, if somebody wants to shoot oneself in the
994797e8345STejun Heo * foot that badly, there's only so much we can do, and if such deadlock
995797e8345STejun Heo * actually occurs, it should be easy to locate the culprit work function.
996797e8345STejun Heo *
997797e8345STejun Heo * CONTEXT:
998797e8345STejun Heo * raw_spin_lock_irq(pool->lock).
999797e8345STejun Heo *
1000797e8345STejun Heo * Return:
1001797e8345STejun Heo * Pointer to worker which is executing @work if found, %NULL
1002797e8345STejun Heo * otherwise.
1003797e8345STejun Heo */
find_worker_executing_work(struct worker_pool * pool,struct work_struct * work)1004797e8345STejun Heo static struct worker *find_worker_executing_work(struct worker_pool *pool,
1005797e8345STejun Heo struct work_struct *work)
1006797e8345STejun Heo {
1007797e8345STejun Heo struct worker *worker;
1008797e8345STejun Heo
1009797e8345STejun Heo hash_for_each_possible(pool->busy_hash, worker, hentry,
1010797e8345STejun Heo (unsigned long)work)
1011797e8345STejun Heo if (worker->current_work == work &&
1012797e8345STejun Heo worker->current_func == work->func)
1013797e8345STejun Heo return worker;
1014797e8345STejun Heo
1015797e8345STejun Heo return NULL;
1016797e8345STejun Heo }
1017797e8345STejun Heo
1018797e8345STejun Heo /**
1019797e8345STejun Heo * move_linked_works - move linked works to a list
1020797e8345STejun Heo * @work: start of series of works to be scheduled
1021797e8345STejun Heo * @head: target list to append @work to
1022797e8345STejun Heo * @nextp: out parameter for nested worklist walking
1023797e8345STejun Heo *
1024873eaca6STejun Heo * Schedule linked works starting from @work to @head. Work series to be
1025873eaca6STejun Heo * scheduled starts at @work and includes any consecutive work with
1026873eaca6STejun Heo * WORK_STRUCT_LINKED set in its predecessor. See assign_work() for details on
1027873eaca6STejun Heo * @nextp.
1028797e8345STejun Heo *
1029797e8345STejun Heo * CONTEXT:
1030797e8345STejun Heo * raw_spin_lock_irq(pool->lock).
1031797e8345STejun Heo */
move_linked_works(struct work_struct * work,struct list_head * head,struct work_struct ** nextp)1032797e8345STejun Heo static void move_linked_works(struct work_struct *work, struct list_head *head,
1033797e8345STejun Heo struct work_struct **nextp)
1034797e8345STejun Heo {
1035797e8345STejun Heo struct work_struct *n;
1036797e8345STejun Heo
1037797e8345STejun Heo /*
1038797e8345STejun Heo * Linked worklist will always end before the end of the list,
1039797e8345STejun Heo * use NULL for list head.
1040797e8345STejun Heo */
1041797e8345STejun Heo list_for_each_entry_safe_from(work, n, NULL, entry) {
1042797e8345STejun Heo list_move_tail(&work->entry, head);
1043797e8345STejun Heo if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
1044797e8345STejun Heo break;
1045797e8345STejun Heo }
1046797e8345STejun Heo
1047797e8345STejun Heo /*
1048797e8345STejun Heo * If we're already inside safe list traversal and have moved
1049797e8345STejun Heo * multiple works to the scheduled queue, the next position
1050797e8345STejun Heo * needs to be updated.
1051797e8345STejun Heo */
1052797e8345STejun Heo if (nextp)
1053797e8345STejun Heo *nextp = n;
1054797e8345STejun Heo }
1055797e8345STejun Heo
1056797e8345STejun Heo /**
1057873eaca6STejun Heo * assign_work - assign a work item and its linked work items to a worker
1058873eaca6STejun Heo * @work: work to assign
1059873eaca6STejun Heo * @worker: worker to assign to
1060873eaca6STejun Heo * @nextp: out parameter for nested worklist walking
1061873eaca6STejun Heo *
1062873eaca6STejun Heo * Assign @work and its linked work items to @worker. If @work is already being
1063873eaca6STejun Heo * executed by another worker in the same pool, it'll be punted there.
1064873eaca6STejun Heo *
1065873eaca6STejun Heo * If @nextp is not NULL, it's updated to point to the next work of the last
1066873eaca6STejun Heo * scheduled work. This allows assign_work() to be nested inside
1067873eaca6STejun Heo * list_for_each_entry_safe().
1068873eaca6STejun Heo *
1069873eaca6STejun Heo * Returns %true if @work was successfully assigned to @worker. %false if @work
1070873eaca6STejun Heo * was punted to another worker already executing it.
1071873eaca6STejun Heo */
assign_work(struct work_struct * work,struct worker * worker,struct work_struct ** nextp)1072873eaca6STejun Heo static bool assign_work(struct work_struct *work, struct worker *worker,
1073873eaca6STejun Heo struct work_struct **nextp)
1074873eaca6STejun Heo {
1075873eaca6STejun Heo struct worker_pool *pool = worker->pool;
1076873eaca6STejun Heo struct worker *collision;
1077873eaca6STejun Heo
1078873eaca6STejun Heo lockdep_assert_held(&pool->lock);
1079873eaca6STejun Heo
1080873eaca6STejun Heo /*
1081873eaca6STejun Heo * A single work shouldn't be executed concurrently by multiple workers.
1082873eaca6STejun Heo * __queue_work() ensures that @work doesn't jump to a different pool
1083873eaca6STejun Heo * while still running in the previous pool. Here, we should ensure that
1084873eaca6STejun Heo * @work is not executed concurrently by multiple workers from the same
1085873eaca6STejun Heo * pool. Check whether anyone is already processing the work. If so,
1086873eaca6STejun Heo * defer the work to the currently executing one.
1087873eaca6STejun Heo */
1088873eaca6STejun Heo collision = find_worker_executing_work(pool, work);
1089873eaca6STejun Heo if (unlikely(collision)) {
1090873eaca6STejun Heo move_linked_works(work, &collision->scheduled, nextp);
1091873eaca6STejun Heo return false;
1092873eaca6STejun Heo }
1093873eaca6STejun Heo
1094873eaca6STejun Heo move_linked_works(work, &worker->scheduled, nextp);
1095873eaca6STejun Heo return true;
1096873eaca6STejun Heo }
1097873eaca6STejun Heo
1098873eaca6STejun Heo /**
10990219a352STejun Heo * kick_pool - wake up an idle worker if necessary
11000219a352STejun Heo * @pool: pool to kick
1101797e8345STejun Heo *
11020219a352STejun Heo * @pool may have pending work items. Wake up worker if necessary. Returns
11030219a352STejun Heo * whether a worker was woken up.
1104797e8345STejun Heo */
kick_pool(struct worker_pool * pool)11050219a352STejun Heo static bool kick_pool(struct worker_pool *pool)
1106797e8345STejun Heo {
1107797e8345STejun Heo struct worker *worker = first_idle_worker(pool);
11088639ecebSTejun Heo struct task_struct *p;
1109797e8345STejun Heo
11100219a352STejun Heo lockdep_assert_held(&pool->lock);
11110219a352STejun Heo
11120219a352STejun Heo if (!need_more_worker(pool) || !worker)
11130219a352STejun Heo return false;
11140219a352STejun Heo
11158639ecebSTejun Heo p = worker->task;
11168639ecebSTejun Heo
11178639ecebSTejun Heo #ifdef CONFIG_SMP
11188639ecebSTejun Heo /*
11198639ecebSTejun Heo * Idle @worker is about to execute @work and waking up provides an
11208639ecebSTejun Heo * opportunity to migrate @worker at a lower cost by setting the task's
11218639ecebSTejun Heo * wake_cpu field. Let's see if we want to move @worker to improve
11228639ecebSTejun Heo * execution locality.
11238639ecebSTejun Heo *
11248639ecebSTejun Heo * We're waking the worker that went idle the latest and there's some
11258639ecebSTejun Heo * chance that @worker is marked idle but hasn't gone off CPU yet. If
11268639ecebSTejun Heo * so, setting the wake_cpu won't do anything. As this is a best-effort
11278639ecebSTejun Heo * optimization and the race window is narrow, let's leave as-is for
11288639ecebSTejun Heo * now. If this becomes pronounced, we can skip over workers which are
11298639ecebSTejun Heo * still on cpu when picking an idle worker.
11308639ecebSTejun Heo *
11318639ecebSTejun Heo * If @pool has non-strict affinity, @worker might have ended up outside
11328639ecebSTejun Heo * its affinity scope. Repatriate.
11338639ecebSTejun Heo */
11348639ecebSTejun Heo if (!pool->attrs->affn_strict &&
11358639ecebSTejun Heo !cpumask_test_cpu(p->wake_cpu, pool->attrs->__pod_cpumask)) {
11368639ecebSTejun Heo struct work_struct *work = list_first_entry(&pool->worklist,
11378639ecebSTejun Heo struct work_struct, entry);
11388639ecebSTejun Heo p->wake_cpu = cpumask_any_distribute(pool->attrs->__pod_cpumask);
11398639ecebSTejun Heo get_work_pwq(work)->stats[PWQ_STAT_REPATRIATED]++;
11408639ecebSTejun Heo }
11418639ecebSTejun Heo #endif
11428639ecebSTejun Heo wake_up_process(p);
11430219a352STejun Heo return true;
1144797e8345STejun Heo }
1145797e8345STejun Heo
114663638450STejun Heo #ifdef CONFIG_WQ_CPU_INTENSIVE_REPORT
114763638450STejun Heo
114863638450STejun Heo /*
114963638450STejun Heo * Concurrency-managed per-cpu work items that hog CPU for longer than
115063638450STejun Heo * wq_cpu_intensive_thresh_us trigger the automatic CPU_INTENSIVE mechanism,
115163638450STejun Heo * which prevents them from stalling other concurrency-managed work items. If a
115263638450STejun Heo * work function keeps triggering this mechanism, it's likely that the work item
115363638450STejun Heo * should be using an unbound workqueue instead.
115463638450STejun Heo *
115563638450STejun Heo * wq_cpu_intensive_report() tracks work functions which trigger such conditions
115663638450STejun Heo * and report them so that they can be examined and converted to use unbound
115763638450STejun Heo * workqueues as appropriate. To avoid flooding the console, each violating work
115863638450STejun Heo * function is tracked and reported with exponential backoff.
115963638450STejun Heo */
116063638450STejun Heo #define WCI_MAX_ENTS 128
116163638450STejun Heo
116263638450STejun Heo struct wci_ent {
116363638450STejun Heo work_func_t func;
116463638450STejun Heo atomic64_t cnt;
116563638450STejun Heo struct hlist_node hash_node;
116663638450STejun Heo };
116763638450STejun Heo
116863638450STejun Heo static struct wci_ent wci_ents[WCI_MAX_ENTS];
116963638450STejun Heo static int wci_nr_ents;
117063638450STejun Heo static DEFINE_RAW_SPINLOCK(wci_lock);
117163638450STejun Heo static DEFINE_HASHTABLE(wci_hash, ilog2(WCI_MAX_ENTS));
117263638450STejun Heo
wci_find_ent(work_func_t func)117363638450STejun Heo static struct wci_ent *wci_find_ent(work_func_t func)
117463638450STejun Heo {
117563638450STejun Heo struct wci_ent *ent;
117663638450STejun Heo
117763638450STejun Heo hash_for_each_possible_rcu(wci_hash, ent, hash_node,
117863638450STejun Heo (unsigned long)func) {
117963638450STejun Heo if (ent->func == func)
118063638450STejun Heo return ent;
118163638450STejun Heo }
118263638450STejun Heo return NULL;
118363638450STejun Heo }
118463638450STejun Heo
wq_cpu_intensive_report(work_func_t func)118563638450STejun Heo static void wq_cpu_intensive_report(work_func_t func)
118663638450STejun Heo {
118763638450STejun Heo struct wci_ent *ent;
118863638450STejun Heo
118963638450STejun Heo restart:
119063638450STejun Heo ent = wci_find_ent(func);
119163638450STejun Heo if (ent) {
119263638450STejun Heo u64 cnt;
119363638450STejun Heo
119463638450STejun Heo /*
119563638450STejun Heo * Start reporting from the fourth time and back off
119663638450STejun Heo * exponentially.
119763638450STejun Heo */
119863638450STejun Heo cnt = atomic64_inc_return_relaxed(&ent->cnt);
119963638450STejun Heo if (cnt >= 4 && is_power_of_2(cnt))
120063638450STejun Heo printk_deferred(KERN_WARNING "workqueue: %ps hogged CPU for >%luus %llu times, consider switching to WQ_UNBOUND\n",
120163638450STejun Heo ent->func, wq_cpu_intensive_thresh_us,
120263638450STejun Heo atomic64_read(&ent->cnt));
120363638450STejun Heo return;
120463638450STejun Heo }
120563638450STejun Heo
120663638450STejun Heo /*
120763638450STejun Heo * @func is a new violation. Allocate a new entry for it. If wcn_ents[]
120863638450STejun Heo * is exhausted, something went really wrong and we probably made enough
120963638450STejun Heo * noise already.
121063638450STejun Heo */
121163638450STejun Heo if (wci_nr_ents >= WCI_MAX_ENTS)
121263638450STejun Heo return;
121363638450STejun Heo
121463638450STejun Heo raw_spin_lock(&wci_lock);
121563638450STejun Heo
121663638450STejun Heo if (wci_nr_ents >= WCI_MAX_ENTS) {
121763638450STejun Heo raw_spin_unlock(&wci_lock);
121863638450STejun Heo return;
121963638450STejun Heo }
122063638450STejun Heo
122163638450STejun Heo if (wci_find_ent(func)) {
122263638450STejun Heo raw_spin_unlock(&wci_lock);
122363638450STejun Heo goto restart;
122463638450STejun Heo }
122563638450STejun Heo
122663638450STejun Heo ent = &wci_ents[wci_nr_ents++];
122763638450STejun Heo ent->func = func;
122863638450STejun Heo atomic64_set(&ent->cnt, 1);
122963638450STejun Heo hash_add_rcu(wci_hash, &ent->hash_node, (unsigned long)func);
123063638450STejun Heo
123163638450STejun Heo raw_spin_unlock(&wci_lock);
123263638450STejun Heo }
123363638450STejun Heo
123463638450STejun Heo #else /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
wq_cpu_intensive_report(work_func_t func)123563638450STejun Heo static void wq_cpu_intensive_report(work_func_t func) {}
123663638450STejun Heo #endif /* CONFIG_WQ_CPU_INTENSIVE_REPORT */
123763638450STejun Heo
1238c54d5046STejun Heo /**
12391da177e4SLinus Torvalds * wq_worker_running - a worker is running again
12401da177e4SLinus Torvalds * @task: task waking up
12411da177e4SLinus Torvalds *
12421da177e4SLinus Torvalds * This function is called when a worker returns from schedule()
12431da177e4SLinus Torvalds */
wq_worker_running(struct task_struct * task)12441da177e4SLinus Torvalds void wq_worker_running(struct task_struct *task)
12451da177e4SLinus Torvalds {
12461da177e4SLinus Torvalds struct worker *worker = kthread_data(task);
12471da177e4SLinus Torvalds
1248c8f6219bSZqiang if (!READ_ONCE(worker->sleeping))
12491da177e4SLinus Torvalds return;
12501da177e4SLinus Torvalds
12511da177e4SLinus Torvalds /*
12521da177e4SLinus Torvalds * If preempted by unbind_workers() between the WORKER_NOT_RUNNING check
12531da177e4SLinus Torvalds * and the nr_running increment below, we may ruin the nr_running reset
12541da177e4SLinus Torvalds * and leave with an unexpected pool->nr_running == 1 on the newly unbound
12551da177e4SLinus Torvalds * pool. Protect against such race.
12561da177e4SLinus Torvalds */
12571da177e4SLinus Torvalds preempt_disable();
12581da177e4SLinus Torvalds if (!(worker->flags & WORKER_NOT_RUNNING))
12591da177e4SLinus Torvalds worker->pool->nr_running++;
12601da177e4SLinus Torvalds preempt_enable();
1261616db877STejun Heo
1262616db877STejun Heo /*
1263616db877STejun Heo * CPU intensive auto-detection cares about how long a work item hogged
1264616db877STejun Heo * CPU without sleeping. Reset the starting timestamp on wakeup.
1265616db877STejun Heo */
1266616db877STejun Heo worker->current_at = worker->task->se.sum_exec_runtime;
1267616db877STejun Heo
1268c8f6219bSZqiang WRITE_ONCE(worker->sleeping, 0);
12691da177e4SLinus Torvalds }
12701da177e4SLinus Torvalds
12711da177e4SLinus Torvalds /**
12721da177e4SLinus Torvalds * wq_worker_sleeping - a worker is going to sleep
12731da177e4SLinus Torvalds * @task: task going to sleep
12741da177e4SLinus Torvalds *
12751da177e4SLinus Torvalds * This function is called from schedule() when a busy worker is
12761da177e4SLinus Torvalds * going to sleep.
12771da177e4SLinus Torvalds */
wq_worker_sleeping(struct task_struct * task)12781da177e4SLinus Torvalds void wq_worker_sleeping(struct task_struct *task)
12791da177e4SLinus Torvalds {
12801da177e4SLinus Torvalds struct worker *worker = kthread_data(task);
12811da177e4SLinus Torvalds struct worker_pool *pool;
12821da177e4SLinus Torvalds
12831da177e4SLinus Torvalds /*
12841da177e4SLinus Torvalds * Rescuers, which may not have all the fields set up like normal
12851da177e4SLinus Torvalds * workers, also reach here, let's not access anything before
12861da177e4SLinus Torvalds * checking NOT_RUNNING.
12871da177e4SLinus Torvalds */
12881da177e4SLinus Torvalds if (worker->flags & WORKER_NOT_RUNNING)
12891da177e4SLinus Torvalds return;
12901da177e4SLinus Torvalds
12911da177e4SLinus Torvalds pool = worker->pool;
12921da177e4SLinus Torvalds
12931da177e4SLinus Torvalds /* Return if preempted before wq_worker_running() was reached */
1294c8f6219bSZqiang if (READ_ONCE(worker->sleeping))
12951da177e4SLinus Torvalds return;
12961da177e4SLinus Torvalds
1297c8f6219bSZqiang WRITE_ONCE(worker->sleeping, 1);
12981da177e4SLinus Torvalds raw_spin_lock_irq(&pool->lock);
12991da177e4SLinus Torvalds
13001da177e4SLinus Torvalds /*
13011da177e4SLinus Torvalds * Recheck in case unbind_workers() preempted us. We don't
13021da177e4SLinus Torvalds * want to decrement nr_running after the worker is unbound
13031da177e4SLinus Torvalds * and nr_running has been reset.
13041da177e4SLinus Torvalds */
13051da177e4SLinus Torvalds if (worker->flags & WORKER_NOT_RUNNING) {
13061da177e4SLinus Torvalds raw_spin_unlock_irq(&pool->lock);
13071da177e4SLinus Torvalds return;
13081da177e4SLinus Torvalds }
13091da177e4SLinus Torvalds
13101da177e4SLinus Torvalds pool->nr_running--;
13110219a352STejun Heo if (kick_pool(pool))
1312725e8ec5STejun Heo worker->current_pwq->stats[PWQ_STAT_CM_WAKEUP]++;
13130219a352STejun Heo
13141da177e4SLinus Torvalds raw_spin_unlock_irq(&pool->lock);
13151da177e4SLinus Torvalds }
13161da177e4SLinus Torvalds
13171da177e4SLinus Torvalds /**
1318616db877STejun Heo * wq_worker_tick - a scheduler tick occurred while a kworker is running
1319616db877STejun Heo * @task: task currently running
1320616db877STejun Heo *
1321616db877STejun Heo * Called from scheduler_tick(). We're in the IRQ context and the current
1322616db877STejun Heo * worker's fields which follow the 'K' locking rule can be accessed safely.
1323616db877STejun Heo */
wq_worker_tick(struct task_struct * task)1324616db877STejun Heo void wq_worker_tick(struct task_struct *task)
1325616db877STejun Heo {
1326616db877STejun Heo struct worker *worker = kthread_data(task);
1327616db877STejun Heo struct pool_workqueue *pwq = worker->current_pwq;
1328616db877STejun Heo struct worker_pool *pool = worker->pool;
1329616db877STejun Heo
1330616db877STejun Heo if (!pwq)
1331616db877STejun Heo return;
1332616db877STejun Heo
13338a1dd1e5STejun Heo pwq->stats[PWQ_STAT_CPU_TIME] += TICK_USEC;
13348a1dd1e5STejun Heo
133518c8ae81SZqiang if (!wq_cpu_intensive_thresh_us)
133618c8ae81SZqiang return;
133718c8ae81SZqiang
1338616db877STejun Heo /*
1339616db877STejun Heo * If the current worker is concurrency managed and hogged the CPU for
1340616db877STejun Heo * longer than wq_cpu_intensive_thresh_us, it's automatically marked
1341616db877STejun Heo * CPU_INTENSIVE to avoid stalling other concurrency-managed work items.
1342c8f6219bSZqiang *
1343c8f6219bSZqiang * Set @worker->sleeping means that @worker is in the process of
1344c8f6219bSZqiang * switching out voluntarily and won't be contributing to
1345c8f6219bSZqiang * @pool->nr_running until it wakes up. As wq_worker_sleeping() also
1346c8f6219bSZqiang * decrements ->nr_running, setting CPU_INTENSIVE here can lead to
1347c8f6219bSZqiang * double decrements. The task is releasing the CPU anyway. Let's skip.
1348c8f6219bSZqiang * We probably want to make this prettier in the future.
1349616db877STejun Heo */
1350c8f6219bSZqiang if ((worker->flags & WORKER_NOT_RUNNING) || READ_ONCE(worker->sleeping) ||
1351616db877STejun Heo worker->task->se.sum_exec_runtime - worker->current_at <
1352616db877STejun Heo wq_cpu_intensive_thresh_us * NSEC_PER_USEC)
1353616db877STejun Heo return;
1354616db877STejun Heo
1355616db877STejun Heo raw_spin_lock(&pool->lock);
1356616db877STejun Heo
1357616db877STejun Heo worker_set_flags(worker, WORKER_CPU_INTENSIVE);
135863638450STejun Heo wq_cpu_intensive_report(worker->current_func);
1359616db877STejun Heo pwq->stats[PWQ_STAT_CPU_INTENSIVE]++;
1360616db877STejun Heo
13610219a352STejun Heo if (kick_pool(pool))
1362616db877STejun Heo pwq->stats[PWQ_STAT_CM_WAKEUP]++;
1363616db877STejun Heo
1364616db877STejun Heo raw_spin_unlock(&pool->lock);
1365616db877STejun Heo }
1366616db877STejun Heo
1367616db877STejun Heo /**
13681da177e4SLinus Torvalds * wq_worker_last_func - retrieve worker's last work function
13691da177e4SLinus Torvalds * @task: Task to retrieve last work function of.
13701da177e4SLinus Torvalds *
13711da177e4SLinus Torvalds * Determine the last function a worker executed. This is called from
13721da177e4SLinus Torvalds * the scheduler to get a worker's last known identity.
13731da177e4SLinus Torvalds *
13741da177e4SLinus Torvalds * CONTEXT:
13759b41ea72SAndrew Morton * raw_spin_lock_irq(rq->lock)
13761da177e4SLinus Torvalds *
13771da177e4SLinus Torvalds * This function is called during schedule() when a kworker is going
1378f756d5e2SNathan Lynch * to sleep. It's used by psi to identify aggregation workers during
1379f756d5e2SNathan Lynch * dequeuing, to allow periodic aggregation to shut-off when that
13801da177e4SLinus Torvalds * worker is the last task in the system or cgroup to go to sleep.
13811da177e4SLinus Torvalds *
13821da177e4SLinus Torvalds * As this function doesn't involve any workqueue-related locking, it
13831da177e4SLinus Torvalds * only returns stable values when called from inside the scheduler's
13841da177e4SLinus Torvalds * queuing and dequeuing paths, when @task, which must be a kworker,
13851da177e4SLinus Torvalds * is guaranteed to not be processing any works.
1386365970a1SDavid Howells *
1387365970a1SDavid Howells * Return:
1388365970a1SDavid Howells * The last work function %current executed as a worker, NULL if it
1389365970a1SDavid Howells * hasn't executed any work yet.
1390365970a1SDavid Howells */
wq_worker_last_func(struct task_struct * task)1391365970a1SDavid Howells work_func_t wq_worker_last_func(struct task_struct *task)
1392365970a1SDavid Howells {
1393365970a1SDavid Howells struct worker *worker = kthread_data(task);
1394365970a1SDavid Howells
1395365970a1SDavid Howells return worker->last_func;
1396365970a1SDavid Howells }
1397365970a1SDavid Howells
1398d302f017STejun Heo /**
13998864b4e5STejun Heo * get_pwq - get an extra reference on the specified pool_workqueue
14008864b4e5STejun Heo * @pwq: pool_workqueue to get
14018864b4e5STejun Heo *
14028864b4e5STejun Heo * Obtain an extra reference on @pwq. The caller should guarantee that
14038864b4e5STejun Heo * @pwq has positive refcnt and be holding the matching pool->lock.
14048864b4e5STejun Heo */
get_pwq(struct pool_workqueue * pwq)14058864b4e5STejun Heo static void get_pwq(struct pool_workqueue *pwq)
14068864b4e5STejun Heo {
14078864b4e5STejun Heo lockdep_assert_held(&pwq->pool->lock);
14088864b4e5STejun Heo WARN_ON_ONCE(pwq->refcnt <= 0);
14098864b4e5STejun Heo pwq->refcnt++;
14108864b4e5STejun Heo }
14118864b4e5STejun Heo
14128864b4e5STejun Heo /**
14138864b4e5STejun Heo * put_pwq - put a pool_workqueue reference
14148864b4e5STejun Heo * @pwq: pool_workqueue to put
14158864b4e5STejun Heo *
14168864b4e5STejun Heo * Drop a reference of @pwq. If its refcnt reaches zero, schedule its
14178864b4e5STejun Heo * destruction. The caller should be holding the matching pool->lock.
14188864b4e5STejun Heo */
put_pwq(struct pool_workqueue * pwq)14198864b4e5STejun Heo static void put_pwq(struct pool_workqueue *pwq)
14208864b4e5STejun Heo {
14218864b4e5STejun Heo lockdep_assert_held(&pwq->pool->lock);
14228864b4e5STejun Heo if (likely(--pwq->refcnt))
14238864b4e5STejun Heo return;
14248864b4e5STejun Heo /*
1425967b494eSTejun Heo * @pwq can't be released under pool->lock, bounce to a dedicated
1426967b494eSTejun Heo * kthread_worker to avoid A-A deadlocks.
14278864b4e5STejun Heo */
1428687a9aa5STejun Heo kthread_queue_work(pwq_release_worker, &pwq->release_work);
14298864b4e5STejun Heo }
14308864b4e5STejun Heo
1431dce90d47STejun Heo /**
1432dce90d47STejun Heo * put_pwq_unlocked - put_pwq() with surrounding pool lock/unlock
1433dce90d47STejun Heo * @pwq: pool_workqueue to put (can be %NULL)
1434dce90d47STejun Heo *
1435dce90d47STejun Heo * put_pwq() with locking. This function also allows %NULL @pwq.
1436dce90d47STejun Heo */
put_pwq_unlocked(struct pool_workqueue * pwq)1437dce90d47STejun Heo static void put_pwq_unlocked(struct pool_workqueue *pwq)
1438dce90d47STejun Heo {
1439dce90d47STejun Heo if (pwq) {
1440dce90d47STejun Heo /*
144124acfb71SThomas Gleixner * As both pwqs and pools are RCU protected, the
1442dce90d47STejun Heo * following lock operations are safe.
1443dce90d47STejun Heo */
1444a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pwq->pool->lock);
1445dce90d47STejun Heo put_pwq(pwq);
1446a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pwq->pool->lock);
1447dce90d47STejun Heo }
1448dce90d47STejun Heo }
1449dce90d47STejun Heo
pwq_activate_inactive_work(struct work_struct * work)1450957578ecSGreg Kroah-Hartman static void pwq_activate_inactive_work(struct work_struct *work)
1451bf4ede01STejun Heo {
1452957578ecSGreg Kroah-Hartman struct pool_workqueue *pwq = get_work_pwq(work);
1453957578ecSGreg Kroah-Hartman
1454bf4ede01STejun Heo trace_workqueue_activate_work(work);
145582607adcSTejun Heo if (list_empty(&pwq->pool->worklist))
145682607adcSTejun Heo pwq->pool->watchdog_ts = jiffies;
1457112202d9STejun Heo move_linked_works(work, &pwq->pool->worklist, NULL);
14585debbff9SGreg Kroah-Hartman __clear_bit(WORK_STRUCT_INACTIVE_BIT, work_data_bits(work));
1459112202d9STejun Heo pwq->nr_active++;
1460bf4ede01STejun Heo }
1461bf4ede01STejun Heo
pwq_activate_first_inactive(struct pool_workqueue * pwq)14625debbff9SGreg Kroah-Hartman static void pwq_activate_first_inactive(struct pool_workqueue *pwq)
14633aa62497SLai Jiangshan {
14645debbff9SGreg Kroah-Hartman struct work_struct *work = list_first_entry(&pwq->inactive_works,
14653aa62497SLai Jiangshan struct work_struct, entry);
14663aa62497SLai Jiangshan
1467957578ecSGreg Kroah-Hartman pwq_activate_inactive_work(work);
14683aa62497SLai Jiangshan }
14693aa62497SLai Jiangshan
1470bf4ede01STejun Heo /**
1471112202d9STejun Heo * pwq_dec_nr_in_flight - decrement pwq's nr_in_flight
1472112202d9STejun Heo * @pwq: pwq of interest
1473c4560c2cSLai Jiangshan * @work_data: work_data of work which left the queue
1474bf4ede01STejun Heo *
1475bf4ede01STejun Heo * A work either has completed or is removed from pending queue,
1476112202d9STejun Heo * decrement nr_in_flight of its pwq and handle workqueue flushing.
1477bf4ede01STejun Heo *
1478bf4ede01STejun Heo * CONTEXT:
1479a9b8a985SSebastian Andrzej Siewior * raw_spin_lock_irq(pool->lock).
1480bf4ede01STejun Heo */
pwq_dec_nr_in_flight(struct pool_workqueue * pwq,unsigned long work_data)1481c4560c2cSLai Jiangshan static void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
1482bf4ede01STejun Heo {
1483c4560c2cSLai Jiangshan int color = get_work_color(work_data);
1484c4560c2cSLai Jiangshan
14855debbff9SGreg Kroah-Hartman if (!(work_data & WORK_STRUCT_INACTIVE)) {
14865debbff9SGreg Kroah-Hartman pwq->nr_active--;
14875debbff9SGreg Kroah-Hartman if (!list_empty(&pwq->inactive_works)) {
14885debbff9SGreg Kroah-Hartman /* one down, submit an inactive one */
1489d8354f26SGreg Kroah-Hartman if (pwq->nr_active < pwq->max_active)
14905debbff9SGreg Kroah-Hartman pwq_activate_first_inactive(pwq);
14915debbff9SGreg Kroah-Hartman }
14925debbff9SGreg Kroah-Hartman }
1493018f3a13SLai Jiangshan
1494018f3a13SLai Jiangshan pwq->nr_in_flight[color]--;
1495bf4ede01STejun Heo
1496bf4ede01STejun Heo /* is flush in progress and are we at the flushing tip? */
1497112202d9STejun Heo if (likely(pwq->flush_color != color))
14988864b4e5STejun Heo goto out_put;
1499bf4ede01STejun Heo
1500bf4ede01STejun Heo /* are there still in-flight works? */
1501112202d9STejun Heo if (pwq->nr_in_flight[color])
15028864b4e5STejun Heo goto out_put;
1503bf4ede01STejun Heo
1504112202d9STejun Heo /* this pwq is done, clear flush_color */
1505112202d9STejun Heo pwq->flush_color = -1;
1506bf4ede01STejun Heo
1507bf4ede01STejun Heo /*
1508112202d9STejun Heo * If this was the last pwq, wake up the first flusher. It
1509bf4ede01STejun Heo * will handle the rest.
1510bf4ede01STejun Heo */
1511112202d9STejun Heo if (atomic_dec_and_test(&pwq->wq->nr_pwqs_to_flush))
1512112202d9STejun Heo complete(&pwq->wq->first_flusher->done);
15138864b4e5STejun Heo out_put:
15148864b4e5STejun Heo put_pwq(pwq);
1515bf4ede01STejun Heo }
1516bf4ede01STejun Heo
151736e227d2STejun Heo /**
1518bbb68dfaSTejun Heo * try_to_grab_pending - steal work item from worklist and disable irq
151936e227d2STejun Heo * @work: work item to steal
152036e227d2STejun Heo * @is_dwork: @work is a delayed_work
1521bbb68dfaSTejun Heo * @flags: place to store irq state
152236e227d2STejun Heo *
152336e227d2STejun Heo * Try to grab PENDING bit of @work. This function can handle @work in any
1524d185af30SYacine Belkadi * stable state - idle, on timer or on worklist.
152536e227d2STejun Heo *
1526d185af30SYacine Belkadi * Return:
15273eb6b31bSMauro Carvalho Chehab *
15283eb6b31bSMauro Carvalho Chehab * ======== ================================================================
152936e227d2STejun Heo * 1 if @work was pending and we successfully stole PENDING
153036e227d2STejun Heo * 0 if @work was idle and we claimed PENDING
153136e227d2STejun Heo * -EAGAIN if PENDING couldn't be grabbed at the moment, safe to busy-retry
1532bbb68dfaSTejun Heo * -ENOENT if someone else is canceling @work, this state may persist
1533bbb68dfaSTejun Heo * for arbitrarily long
15343eb6b31bSMauro Carvalho Chehab * ======== ================================================================
153536e227d2STejun Heo *
1536d185af30SYacine Belkadi * Note:
1537bbb68dfaSTejun Heo * On >= 0 return, the caller owns @work's PENDING bit. To avoid getting
1538e0aecdd8STejun Heo * interrupted while holding PENDING and @work off queue, irq must be
1539e0aecdd8STejun Heo * disabled on entry. This, combined with delayed_work->timer being
1540e0aecdd8STejun Heo * irqsafe, ensures that we return -EAGAIN for finite short period of time.
1541bbb68dfaSTejun Heo *
1542bbb68dfaSTejun Heo * On successful return, >= 0, irq is disabled and the caller is
1543bbb68dfaSTejun Heo * responsible for releasing it using local_irq_restore(*@flags).
1544bbb68dfaSTejun Heo *
1545e0aecdd8STejun Heo * This function is safe to call from any context including IRQ handler.
1546bf4ede01STejun Heo */
try_to_grab_pending(struct work_struct * work,bool is_dwork,unsigned long * flags)1547bbb68dfaSTejun Heo static int try_to_grab_pending(struct work_struct *work, bool is_dwork,
1548bbb68dfaSTejun Heo unsigned long *flags)
1549bf4ede01STejun Heo {
1550d565ed63STejun Heo struct worker_pool *pool;
1551112202d9STejun Heo struct pool_workqueue *pwq;
1552bf4ede01STejun Heo
1553bbb68dfaSTejun Heo local_irq_save(*flags);
1554bbb68dfaSTejun Heo
155536e227d2STejun Heo /* try to steal the timer if it exists */
155636e227d2STejun Heo if (is_dwork) {
155736e227d2STejun Heo struct delayed_work *dwork = to_delayed_work(work);
155836e227d2STejun Heo
1559e0aecdd8STejun Heo /*
1560e0aecdd8STejun Heo * dwork->timer is irqsafe. If del_timer() fails, it's
1561e0aecdd8STejun Heo * guaranteed that the timer is not queued anywhere and not
1562e0aecdd8STejun Heo * running on the local CPU.
1563e0aecdd8STejun Heo */
156436e227d2STejun Heo if (likely(del_timer(&dwork->timer)))
156536e227d2STejun Heo return 1;
156636e227d2STejun Heo }
156736e227d2STejun Heo
156836e227d2STejun Heo /* try to claim PENDING the normal way */
1569bf4ede01STejun Heo if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
1570bf4ede01STejun Heo return 0;
1571bf4ede01STejun Heo
157224acfb71SThomas Gleixner rcu_read_lock();
1573bf4ede01STejun Heo /*
1574bf4ede01STejun Heo * The queueing is in progress, or it is already queued. Try to
1575bf4ede01STejun Heo * steal it from ->worklist without clearing WORK_STRUCT_PENDING.
1576bf4ede01STejun Heo */
1577d565ed63STejun Heo pool = get_work_pool(work);
1578d565ed63STejun Heo if (!pool)
1579bbb68dfaSTejun Heo goto fail;
1580bf4ede01STejun Heo
1581a9b8a985SSebastian Andrzej Siewior raw_spin_lock(&pool->lock);
1582bf4ede01STejun Heo /*
1583112202d9STejun Heo * work->data is guaranteed to point to pwq only while the work
1584112202d9STejun Heo * item is queued on pwq->wq, and both updating work->data to point
1585112202d9STejun Heo * to pwq on queueing and to pool on dequeueing are done under
1586112202d9STejun Heo * pwq->pool->lock. This in turn guarantees that, if work->data
1587112202d9STejun Heo * points to pwq which is associated with a locked pool, the work
15880b3dae68SLai Jiangshan * item is currently queued on that pool.
1589bf4ede01STejun Heo */
1590112202d9STejun Heo pwq = get_work_pwq(work);
1591112202d9STejun Heo if (pwq && pwq->pool == pool) {
1592bf4ede01STejun Heo debug_work_deactivate(work);
15933aa62497SLai Jiangshan
15943aa62497SLai Jiangshan /*
1595018f3a13SLai Jiangshan * A cancelable inactive work item must be in the
1596018f3a13SLai Jiangshan * pwq->inactive_works since a queued barrier can't be
1597018f3a13SLai Jiangshan * canceled (see the comments in insert_wq_barrier()).
1598018f3a13SLai Jiangshan *
1599f97a4a1aSLai Jiangshan * An inactive work item cannot be grabbed directly because
1600d812796eSLai Jiangshan * it might have linked barrier work items which, if left
1601f97a4a1aSLai Jiangshan * on the inactive_works list, will confuse pwq->nr_active
160216062836STejun Heo * management later on and cause stall. Make sure the work
160316062836STejun Heo * item is activated before grabbing.
16043aa62497SLai Jiangshan */
1605957578ecSGreg Kroah-Hartman if (*work_data_bits(work) & WORK_STRUCT_INACTIVE)
1606957578ecSGreg Kroah-Hartman pwq_activate_inactive_work(work);
16073aa62497SLai Jiangshan
1608bf4ede01STejun Heo list_del_init(&work->entry);
1609c4560c2cSLai Jiangshan pwq_dec_nr_in_flight(pwq, *work_data_bits(work));
161036e227d2STejun Heo
1611112202d9STejun Heo /* work->data points to pwq iff queued, point to pool */
16124468a00fSLai Jiangshan set_work_pool_and_keep_pending(work, pool->id);
16134468a00fSLai Jiangshan
1614a9b8a985SSebastian Andrzej Siewior raw_spin_unlock(&pool->lock);
161524acfb71SThomas Gleixner rcu_read_unlock();
161636e227d2STejun Heo return 1;
1617bf4ede01STejun Heo }
1618a9b8a985SSebastian Andrzej Siewior raw_spin_unlock(&pool->lock);
1619bbb68dfaSTejun Heo fail:
162024acfb71SThomas Gleixner rcu_read_unlock();
1621bbb68dfaSTejun Heo local_irq_restore(*flags);
1622bbb68dfaSTejun Heo if (work_is_canceling(work))
1623bbb68dfaSTejun Heo return -ENOENT;
1624bbb68dfaSTejun Heo cpu_relax();
162536e227d2STejun Heo return -EAGAIN;
1626bf4ede01STejun Heo }
1627bf4ede01STejun Heo
1628bf4ede01STejun Heo /**
1629706026c2STejun Heo * insert_work - insert a work into a pool
1630112202d9STejun Heo * @pwq: pwq @work belongs to
16314690c4abSTejun Heo * @work: work to insert
16324690c4abSTejun Heo * @head: insertion point
16334690c4abSTejun Heo * @extra_flags: extra WORK_STRUCT_* flags to set
16344690c4abSTejun Heo *
1635112202d9STejun Heo * Insert @work which belongs to @pwq after @head. @extra_flags is or'd to
1636706026c2STejun Heo * work_struct flags.
16374690c4abSTejun Heo *
16384690c4abSTejun Heo * CONTEXT:
1639a9b8a985SSebastian Andrzej Siewior * raw_spin_lock_irq(pool->lock).
1640365970a1SDavid Howells */
insert_work(struct pool_workqueue * pwq,struct work_struct * work,struct list_head * head,unsigned int extra_flags)1641112202d9STejun Heo static void insert_work(struct pool_workqueue *pwq, struct work_struct *work,
1642112202d9STejun Heo struct list_head *head, unsigned int extra_flags)
1643b89deed3SOleg Nesterov {
1644fe089f87STejun Heo debug_work_activate(work);
1645e1d8aa9fSFrederic Weisbecker
1646e89a85d6SWalter Wu /* record the work call stack in order to print it in KASAN reports */
1647f70da745SMarco Elver kasan_record_aux_stack_noalloc(work);
1648e89a85d6SWalter Wu
16494690c4abSTejun Heo /* we own @work, set data and link */
1650112202d9STejun Heo set_work_pwq(work, pwq, extra_flags);
16511a4d9b0aSOleg Nesterov list_add_tail(&work->entry, head);
16528864b4e5STejun Heo get_pwq(pwq);
1653b89deed3SOleg Nesterov }
1654b89deed3SOleg Nesterov
1655c8efcc25STejun Heo /*
1656c8efcc25STejun Heo * Test whether @work is being queued from another work executing on the
16578d03ecfeSTejun Heo * same workqueue.
1658c8efcc25STejun Heo */
is_chained_work(struct workqueue_struct * wq)1659c8efcc25STejun Heo static bool is_chained_work(struct workqueue_struct *wq)
1660c8efcc25STejun Heo {
1661c8efcc25STejun Heo struct worker *worker;
1662c8efcc25STejun Heo
16638d03ecfeSTejun Heo worker = current_wq_worker();
1664c8efcc25STejun Heo /*
1665bf393fd4SBart Van Assche * Return %true iff I'm a worker executing a work item on @wq. If
16668d03ecfeSTejun Heo * I'm @worker, it's safe to dereference it without locking.
1667c8efcc25STejun Heo */
1668112202d9STejun Heo return worker && worker->current_pwq->wq == wq;
1669c8efcc25STejun Heo }
1670c8efcc25STejun Heo
1671ef557180SMike Galbraith /*
1672ef557180SMike Galbraith * When queueing an unbound work item to a wq, prefer local CPU if allowed
1673ef557180SMike Galbraith * by wq_unbound_cpumask. Otherwise, round robin among the allowed ones to
1674ef557180SMike Galbraith * avoid perturbing sensitive tasks.
1675ef557180SMike Galbraith */
wq_select_unbound_cpu(int cpu)1676ef557180SMike Galbraith static int wq_select_unbound_cpu(int cpu)
1677ef557180SMike Galbraith {
1678ef557180SMike Galbraith int new_cpu;
1679ef557180SMike Galbraith
1680f303fccbSTejun Heo if (likely(!wq_debug_force_rr_cpu)) {
1681ef557180SMike Galbraith if (cpumask_test_cpu(cpu, wq_unbound_cpumask))
1682ef557180SMike Galbraith return cpu;
1683a8ec5880SAmmar Faizi } else {
1684a8ec5880SAmmar Faizi pr_warn_once("workqueue: round-robin CPU selection forced, expect performance impact\n");
1685f303fccbSTejun Heo }
1686f303fccbSTejun Heo
1687ef557180SMike Galbraith new_cpu = __this_cpu_read(wq_rr_cpu_last);
1688ef557180SMike Galbraith new_cpu = cpumask_next_and(new_cpu, wq_unbound_cpumask, cpu_online_mask);
1689ef557180SMike Galbraith if (unlikely(new_cpu >= nr_cpu_ids)) {
1690ef557180SMike Galbraith new_cpu = cpumask_first_and(wq_unbound_cpumask, cpu_online_mask);
1691ef557180SMike Galbraith if (unlikely(new_cpu >= nr_cpu_ids))
1692ef557180SMike Galbraith return cpu;
1693ef557180SMike Galbraith }
1694ef557180SMike Galbraith __this_cpu_write(wq_rr_cpu_last, new_cpu);
1695ef557180SMike Galbraith
1696ef557180SMike Galbraith return new_cpu;
1697ef557180SMike Galbraith }
1698ef557180SMike Galbraith
__queue_work(int cpu,struct workqueue_struct * wq,struct work_struct * work)1699d84ff051STejun Heo static void __queue_work(int cpu, struct workqueue_struct *wq,
17001da177e4SLinus Torvalds struct work_struct *work)
17011da177e4SLinus Torvalds {
1702112202d9STejun Heo struct pool_workqueue *pwq;
1703fe089f87STejun Heo struct worker_pool *last_pool, *pool;
17048a2e8e5dSTejun Heo unsigned int work_flags;
1705b75cac93SJoonsoo Kim unsigned int req_cpu = cpu;
17068930cabaSTejun Heo
17078930cabaSTejun Heo /*
17088930cabaSTejun Heo * While a work item is PENDING && off queue, a task trying to
17098930cabaSTejun Heo * steal the PENDING will busy-loop waiting for it to either get
17108930cabaSTejun Heo * queued or lose PENDING. Grabbing PENDING and queueing should
17118930cabaSTejun Heo * happen with IRQ disabled.
17128930cabaSTejun Heo */
17138e8eb730SFrederic Weisbecker lockdep_assert_irqs_disabled();
17141da177e4SLinus Torvalds
17151e19ffc6STejun Heo
171633e3f0a3SRichard Clark /*
171733e3f0a3SRichard Clark * For a draining wq, only works from the same workqueue are
171833e3f0a3SRichard Clark * allowed. The __WQ_DESTROYING helps to spot the issue that
171933e3f0a3SRichard Clark * queues a new work item to a wq after destroy_workqueue(wq).
172033e3f0a3SRichard Clark */
172133e3f0a3SRichard Clark if (unlikely(wq->flags & (__WQ_DESTROYING | __WQ_DRAINING) &&
172233e3f0a3SRichard Clark WARN_ON_ONCE(!is_chained_work(wq))))
1723e41e704bSTejun Heo return;
172424acfb71SThomas Gleixner rcu_read_lock();
17259e8cd2f5STejun Heo retry:
1726aa202f1fSHillf Danton /* pwq which will be used unless @work is executing elsewhere */
1727636b927eSTejun Heo if (req_cpu == WORK_CPU_UNBOUND) {
1728636b927eSTejun Heo if (wq->flags & WQ_UNBOUND)
1729ef557180SMike Galbraith cpu = wq_select_unbound_cpu(raw_smp_processor_id());
1730636b927eSTejun Heo else
1731aa202f1fSHillf Danton cpu = raw_smp_processor_id();
1732aa202f1fSHillf Danton }
1733f3421797STejun Heo
1734636b927eSTejun Heo pwq = rcu_dereference(*per_cpu_ptr(wq->cpu_pwq, cpu));
1735fe089f87STejun Heo pool = pwq->pool;
1736fe089f87STejun Heo
173718aa9effSTejun Heo /*
1738c9178087STejun Heo * If @work was previously on a different pool, it might still be
1739c9178087STejun Heo * running there, in which case the work needs to be queued on that
1740c9178087STejun Heo * pool to guarantee non-reentrancy.
174118aa9effSTejun Heo */
1742c9e7cf27STejun Heo last_pool = get_work_pool(work);
1743fe089f87STejun Heo if (last_pool && last_pool != pool) {
174418aa9effSTejun Heo struct worker *worker;
174518aa9effSTejun Heo
1746a9b8a985SSebastian Andrzej Siewior raw_spin_lock(&last_pool->lock);
174718aa9effSTejun Heo
1748c9e7cf27STejun Heo worker = find_worker_executing_work(last_pool, work);
174918aa9effSTejun Heo
1750112202d9STejun Heo if (worker && worker->current_pwq->wq == wq) {
1751c9178087STejun Heo pwq = worker->current_pwq;
1752fe089f87STejun Heo pool = pwq->pool;
1753fe089f87STejun Heo WARN_ON_ONCE(pool != last_pool);
17548594fadeSLai Jiangshan } else {
175518aa9effSTejun Heo /* meh... not running there, queue here */
1756a9b8a985SSebastian Andrzej Siewior raw_spin_unlock(&last_pool->lock);
1757fe089f87STejun Heo raw_spin_lock(&pool->lock);
175818aa9effSTejun Heo }
17598930cabaSTejun Heo } else {
1760fe089f87STejun Heo raw_spin_lock(&pool->lock);
17618930cabaSTejun Heo }
1762502ca9d8STejun Heo
17639e8cd2f5STejun Heo /*
1764636b927eSTejun Heo * pwq is determined and locked. For unbound pools, we could have raced
1765636b927eSTejun Heo * with pwq release and it could already be dead. If its refcnt is zero,
1766636b927eSTejun Heo * repeat pwq selection. Note that unbound pwqs never die without
1767636b927eSTejun Heo * another pwq replacing it in cpu_pwq or while work items are executing
1768636b927eSTejun Heo * on it, so the retrying is guaranteed to make forward-progress.
17699e8cd2f5STejun Heo */
17709e8cd2f5STejun Heo if (unlikely(!pwq->refcnt)) {
17719e8cd2f5STejun Heo if (wq->flags & WQ_UNBOUND) {
1772fe089f87STejun Heo raw_spin_unlock(&pool->lock);
17739e8cd2f5STejun Heo cpu_relax();
17749e8cd2f5STejun Heo goto retry;
17759e8cd2f5STejun Heo }
17769e8cd2f5STejun Heo /* oops */
17779e8cd2f5STejun Heo WARN_ONCE(true, "workqueue: per-cpu pwq for %s on cpu%d has 0 refcnt",
17789e8cd2f5STejun Heo wq->name, cpu);
17799e8cd2f5STejun Heo }
17809e8cd2f5STejun Heo
1781112202d9STejun Heo /* pwq determined, queue */
1782112202d9STejun Heo trace_workqueue_queue_work(req_cpu, pwq, work);
1783502ca9d8STejun Heo
178424acfb71SThomas Gleixner if (WARN_ON(!list_empty(&work->entry)))
178524acfb71SThomas Gleixner goto out;
17861e19ffc6STejun Heo
1787112202d9STejun Heo pwq->nr_in_flight[pwq->work_color]++;
1788112202d9STejun Heo work_flags = work_color_to_flags(pwq->work_color);
17891e19ffc6STejun Heo
1790d8354f26SGreg Kroah-Hartman if (likely(pwq->nr_active < pwq->max_active)) {
1791fe089f87STejun Heo if (list_empty(&pool->worklist))
1792fe089f87STejun Heo pool->watchdog_ts = jiffies;
1793fe089f87STejun Heo
1794cdadf009STejun Heo trace_workqueue_activate_work(work);
17955debbff9SGreg Kroah-Hartman pwq->nr_active++;
1796fe089f87STejun Heo insert_work(pwq, work, &pool->worklist, work_flags);
17970219a352STejun Heo kick_pool(pool);
17988a2e8e5dSTejun Heo } else {
1799f97a4a1aSLai Jiangshan work_flags |= WORK_STRUCT_INACTIVE;
1800fe089f87STejun Heo insert_work(pwq, work, &pwq->inactive_works, work_flags);
18018a2e8e5dSTejun Heo }
18021e19ffc6STejun Heo
180324acfb71SThomas Gleixner out:
1804fe089f87STejun Heo raw_spin_unlock(&pool->lock);
180524acfb71SThomas Gleixner rcu_read_unlock();
18061da177e4SLinus Torvalds }
18071da177e4SLinus Torvalds
18080fcb78c2SRolf Eike Beer /**
1809c1a220e7SZhang Rui * queue_work_on - queue work on specific cpu
1810c1a220e7SZhang Rui * @cpu: CPU number to execute work on
1811c1a220e7SZhang Rui * @wq: workqueue to use
1812c1a220e7SZhang Rui * @work: work to queue
1813c1a220e7SZhang Rui *
1814c1a220e7SZhang Rui * We queue the work to a specific CPU, the caller must ensure it
1815443378f0SPaul E. McKenney * can't go away. Callers that fail to ensure that the specified
1816443378f0SPaul E. McKenney * CPU cannot go away will execute on a randomly chosen CPU.
1817854f5cc5SPaul E. McKenney * But note well that callers specifying a CPU that never has been
1818854f5cc5SPaul E. McKenney * online will get a splat.
1819d185af30SYacine Belkadi *
1820d185af30SYacine Belkadi * Return: %false if @work was already on a queue, %true otherwise.
1821c1a220e7SZhang Rui */
queue_work_on(int cpu,struct workqueue_struct * wq,struct work_struct * work)1822d4283e93STejun Heo bool queue_work_on(int cpu, struct workqueue_struct *wq,
1823d4283e93STejun Heo struct work_struct *work)
1824c1a220e7SZhang Rui {
1825d4283e93STejun Heo bool ret = false;
18268930cabaSTejun Heo unsigned long flags;
18278930cabaSTejun Heo
18288930cabaSTejun Heo local_irq_save(flags);
1829c1a220e7SZhang Rui
183022df02bbSTejun Heo if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
18314690c4abSTejun Heo __queue_work(cpu, wq, work);
1832d4283e93STejun Heo ret = true;
1833c1a220e7SZhang Rui }
18348930cabaSTejun Heo
18358930cabaSTejun Heo local_irq_restore(flags);
1836c1a220e7SZhang Rui return ret;
1837c1a220e7SZhang Rui }
1838ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_work_on);
1839c1a220e7SZhang Rui
18408204e0c1SAlexander Duyck /**
1841fef59c9cSTejun Heo * select_numa_node_cpu - Select a CPU based on NUMA node
18428204e0c1SAlexander Duyck * @node: NUMA node ID that we want to select a CPU from
18438204e0c1SAlexander Duyck *
18448204e0c1SAlexander Duyck * This function will attempt to find a "random" cpu available on a given
18458204e0c1SAlexander Duyck * node. If there are no CPUs available on the given node it will return
18468204e0c1SAlexander Duyck * WORK_CPU_UNBOUND indicating that we should just schedule to any
18478204e0c1SAlexander Duyck * available CPU if we need to schedule this work.
18488204e0c1SAlexander Duyck */
select_numa_node_cpu(int node)1849fef59c9cSTejun Heo static int select_numa_node_cpu(int node)
18508204e0c1SAlexander Duyck {
18518204e0c1SAlexander Duyck int cpu;
18528204e0c1SAlexander Duyck
18538204e0c1SAlexander Duyck /* Delay binding to CPU if node is not valid or online */
18548204e0c1SAlexander Duyck if (node < 0 || node >= MAX_NUMNODES || !node_online(node))
18558204e0c1SAlexander Duyck return WORK_CPU_UNBOUND;
18568204e0c1SAlexander Duyck
18578204e0c1SAlexander Duyck /* Use local node/cpu if we are already there */
18588204e0c1SAlexander Duyck cpu = raw_smp_processor_id();
18598204e0c1SAlexander Duyck if (node == cpu_to_node(cpu))
18608204e0c1SAlexander Duyck return cpu;
18618204e0c1SAlexander Duyck
18628204e0c1SAlexander Duyck /* Use "random" otherwise know as "first" online CPU of node */
18638204e0c1SAlexander Duyck cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
18648204e0c1SAlexander Duyck
18658204e0c1SAlexander Duyck /* If CPU is valid return that, otherwise just defer */
18668204e0c1SAlexander Duyck return cpu < nr_cpu_ids ? cpu : WORK_CPU_UNBOUND;
18678204e0c1SAlexander Duyck }
18688204e0c1SAlexander Duyck
18698204e0c1SAlexander Duyck /**
18708204e0c1SAlexander Duyck * queue_work_node - queue work on a "random" cpu for a given NUMA node
18718204e0c1SAlexander Duyck * @node: NUMA node that we are targeting the work for
18728204e0c1SAlexander Duyck * @wq: workqueue to use
18738204e0c1SAlexander Duyck * @work: work to queue
18748204e0c1SAlexander Duyck *
18758204e0c1SAlexander Duyck * We queue the work to a "random" CPU within a given NUMA node. The basic
18768204e0c1SAlexander Duyck * idea here is to provide a way to somehow associate work with a given
18778204e0c1SAlexander Duyck * NUMA node.
18788204e0c1SAlexander Duyck *
18798204e0c1SAlexander Duyck * This function will only make a best effort attempt at getting this onto
18808204e0c1SAlexander Duyck * the right NUMA node. If no node is requested or the requested node is
18818204e0c1SAlexander Duyck * offline then we just fall back to standard queue_work behavior.
18828204e0c1SAlexander Duyck *
18838204e0c1SAlexander Duyck * Currently the "random" CPU ends up being the first available CPU in the
18848204e0c1SAlexander Duyck * intersection of cpu_online_mask and the cpumask of the node, unless we
18858204e0c1SAlexander Duyck * are running on the node. In that case we just use the current CPU.
18868204e0c1SAlexander Duyck *
18878204e0c1SAlexander Duyck * Return: %false if @work was already on a queue, %true otherwise.
18888204e0c1SAlexander Duyck */
queue_work_node(int node,struct workqueue_struct * wq,struct work_struct * work)18898204e0c1SAlexander Duyck bool queue_work_node(int node, struct workqueue_struct *wq,
18908204e0c1SAlexander Duyck struct work_struct *work)
18918204e0c1SAlexander Duyck {
18928204e0c1SAlexander Duyck unsigned long flags;
18938204e0c1SAlexander Duyck bool ret = false;
18948204e0c1SAlexander Duyck
18958204e0c1SAlexander Duyck /*
18968204e0c1SAlexander Duyck * This current implementation is specific to unbound workqueues.
18978204e0c1SAlexander Duyck * Specifically we only return the first available CPU for a given
18988204e0c1SAlexander Duyck * node instead of cycling through individual CPUs within the node.
18998204e0c1SAlexander Duyck *
19008204e0c1SAlexander Duyck * If this is used with a per-cpu workqueue then the logic in
19018204e0c1SAlexander Duyck * workqueue_select_cpu_near would need to be updated to allow for
19028204e0c1SAlexander Duyck * some round robin type logic.
19038204e0c1SAlexander Duyck */
19048204e0c1SAlexander Duyck WARN_ON_ONCE(!(wq->flags & WQ_UNBOUND));
19058204e0c1SAlexander Duyck
19068204e0c1SAlexander Duyck local_irq_save(flags);
19078204e0c1SAlexander Duyck
19088204e0c1SAlexander Duyck if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
1909fef59c9cSTejun Heo int cpu = select_numa_node_cpu(node);
19108204e0c1SAlexander Duyck
19118204e0c1SAlexander Duyck __queue_work(cpu, wq, work);
19128204e0c1SAlexander Duyck ret = true;
19138204e0c1SAlexander Duyck }
19148204e0c1SAlexander Duyck
19158204e0c1SAlexander Duyck local_irq_restore(flags);
19168204e0c1SAlexander Duyck return ret;
19178204e0c1SAlexander Duyck }
19188204e0c1SAlexander Duyck EXPORT_SYMBOL_GPL(queue_work_node);
19198204e0c1SAlexander Duyck
delayed_work_timer_fn(struct timer_list * t)19208c20feb6SKees Cook void delayed_work_timer_fn(struct timer_list *t)
19211da177e4SLinus Torvalds {
19228c20feb6SKees Cook struct delayed_work *dwork = from_timer(dwork, t, timer);
19231da177e4SLinus Torvalds
1924e0aecdd8STejun Heo /* should have been called from irqsafe timer with irq already off */
192560c057bcSLai Jiangshan __queue_work(dwork->cpu, dwork->wq, &dwork->work);
19261da177e4SLinus Torvalds }
19271438ade5SKonstantin Khlebnikov EXPORT_SYMBOL(delayed_work_timer_fn);
19281da177e4SLinus Torvalds
__queue_delayed_work(int cpu,struct workqueue_struct * wq,struct delayed_work * dwork,unsigned long delay)19297beb2edfSTejun Heo static void __queue_delayed_work(int cpu, struct workqueue_struct *wq,
193052bad64dSDavid Howells struct delayed_work *dwork, unsigned long delay)
19311da177e4SLinus Torvalds {
19327beb2edfSTejun Heo struct timer_list *timer = &dwork->timer;
19337beb2edfSTejun Heo struct work_struct *work = &dwork->work;
19341da177e4SLinus Torvalds
1935637fdbaeSTejun Heo WARN_ON_ONCE(!wq);
19364b243563SSami Tolvanen WARN_ON_ONCE(timer->function != delayed_work_timer_fn);
1937fc4b514fSTejun Heo WARN_ON_ONCE(timer_pending(timer));
1938fc4b514fSTejun Heo WARN_ON_ONCE(!list_empty(&work->entry));
19397beb2edfSTejun Heo
19408852aac2STejun Heo /*
19418852aac2STejun Heo * If @delay is 0, queue @dwork->work immediately. This is for
19428852aac2STejun Heo * both optimization and correctness. The earliest @timer can
19438852aac2STejun Heo * expire is on the closest next tick and delayed_work users depend
19448852aac2STejun Heo * on that there's no such delay when @delay is 0.
19458852aac2STejun Heo */
19468852aac2STejun Heo if (!delay) {
19478852aac2STejun Heo __queue_work(cpu, wq, &dwork->work);
19488852aac2STejun Heo return;
19498852aac2STejun Heo }
19508852aac2STejun Heo
195160c057bcSLai Jiangshan dwork->wq = wq;
19521265057fSTejun Heo dwork->cpu = cpu;
19537beb2edfSTejun Heo timer->expires = jiffies + delay;
19547beb2edfSTejun Heo
1955041bd12eSTejun Heo if (unlikely(cpu != WORK_CPU_UNBOUND))
19567beb2edfSTejun Heo add_timer_on(timer, cpu);
1957041bd12eSTejun Heo else
1958041bd12eSTejun Heo add_timer(timer);
19597beb2edfSTejun Heo }
19601da177e4SLinus Torvalds
19610fcb78c2SRolf Eike Beer /**
19620fcb78c2SRolf Eike Beer * queue_delayed_work_on - queue work on specific CPU after delay
19630fcb78c2SRolf Eike Beer * @cpu: CPU number to execute work on
19640fcb78c2SRolf Eike Beer * @wq: workqueue to use
1965af9997e4SRandy Dunlap * @dwork: work to queue
19660fcb78c2SRolf Eike Beer * @delay: number of jiffies to wait before queueing
19670fcb78c2SRolf Eike Beer *
1968d185af30SYacine Belkadi * Return: %false if @work was already on a queue, %true otherwise. If
1969715f1300STejun Heo * @delay is zero and @dwork is idle, it will be scheduled for immediate
1970715f1300STejun Heo * execution.
19710fcb78c2SRolf Eike Beer */
queue_delayed_work_on(int cpu,struct workqueue_struct * wq,struct delayed_work * dwork,unsigned long delay)1972d4283e93STejun Heo bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
197352bad64dSDavid Howells struct delayed_work *dwork, unsigned long delay)
19747a6bc1cdSVenkatesh Pallipadi {
197552bad64dSDavid Howells struct work_struct *work = &dwork->work;
1976d4283e93STejun Heo bool ret = false;
19778930cabaSTejun Heo unsigned long flags;
19788930cabaSTejun Heo
19798930cabaSTejun Heo /* read the comment in __queue_work() */
19808930cabaSTejun Heo local_irq_save(flags);
19817a6bc1cdSVenkatesh Pallipadi
198222df02bbSTejun Heo if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
19837beb2edfSTejun Heo __queue_delayed_work(cpu, wq, dwork, delay);
1984d4283e93STejun Heo ret = true;
19857a6bc1cdSVenkatesh Pallipadi }
19868930cabaSTejun Heo
19878930cabaSTejun Heo local_irq_restore(flags);
19887a6bc1cdSVenkatesh Pallipadi return ret;
19897a6bc1cdSVenkatesh Pallipadi }
1990ad7b1f84SMarc Dionne EXPORT_SYMBOL(queue_delayed_work_on);
19911da177e4SLinus Torvalds
1992c8e55f36STejun Heo /**
19938376fe22STejun Heo * mod_delayed_work_on - modify delay of or queue a delayed work on specific CPU
19948376fe22STejun Heo * @cpu: CPU number to execute work on
19958376fe22STejun Heo * @wq: workqueue to use
19968376fe22STejun Heo * @dwork: work to queue
19978376fe22STejun Heo * @delay: number of jiffies to wait before queueing
19988376fe22STejun Heo *
19998376fe22STejun Heo * If @dwork is idle, equivalent to queue_delayed_work_on(); otherwise,
20008376fe22STejun Heo * modify @dwork's timer so that it expires after @delay. If @delay is
20018376fe22STejun Heo * zero, @work is guaranteed to be scheduled immediately regardless of its
20028376fe22STejun Heo * current state.
20038376fe22STejun Heo *
2004d185af30SYacine Belkadi * Return: %false if @dwork was idle and queued, %true if @dwork was
20058376fe22STejun Heo * pending and its timer was modified.
20068376fe22STejun Heo *
2007e0aecdd8STejun Heo * This function is safe to call from any context including IRQ handler.
20088376fe22STejun Heo * See try_to_grab_pending() for details.
20098376fe22STejun Heo */
mod_delayed_work_on(int cpu,struct workqueue_struct * wq,struct delayed_work * dwork,unsigned long delay)20108376fe22STejun Heo bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq,
20118376fe22STejun Heo struct delayed_work *dwork, unsigned long delay)
20128376fe22STejun Heo {
20138376fe22STejun Heo unsigned long flags;
20148376fe22STejun Heo int ret;
20158376fe22STejun Heo
20168376fe22STejun Heo do {
20178376fe22STejun Heo ret = try_to_grab_pending(&dwork->work, true, &flags);
20188376fe22STejun Heo } while (unlikely(ret == -EAGAIN));
20198376fe22STejun Heo
20208376fe22STejun Heo if (likely(ret >= 0)) {
20218376fe22STejun Heo __queue_delayed_work(cpu, wq, dwork, delay);
20228376fe22STejun Heo local_irq_restore(flags);
20238376fe22STejun Heo }
20248376fe22STejun Heo
20258376fe22STejun Heo /* -ENOENT from try_to_grab_pending() becomes %true */
20268376fe22STejun Heo return ret;
20278376fe22STejun Heo }
20288376fe22STejun Heo EXPORT_SYMBOL_GPL(mod_delayed_work_on);
20298376fe22STejun Heo
rcu_work_rcufn(struct rcu_head * rcu)203005f0fe6bSTejun Heo static void rcu_work_rcufn(struct rcu_head *rcu)
203105f0fe6bSTejun Heo {
203205f0fe6bSTejun Heo struct rcu_work *rwork = container_of(rcu, struct rcu_work, rcu);
203305f0fe6bSTejun Heo
203405f0fe6bSTejun Heo /* read the comment in __queue_work() */
203505f0fe6bSTejun Heo local_irq_disable();
203605f0fe6bSTejun Heo __queue_work(WORK_CPU_UNBOUND, rwork->wq, &rwork->work);
203705f0fe6bSTejun Heo local_irq_enable();
203805f0fe6bSTejun Heo }
203905f0fe6bSTejun Heo
204005f0fe6bSTejun Heo /**
204105f0fe6bSTejun Heo * queue_rcu_work - queue work after a RCU grace period
204205f0fe6bSTejun Heo * @wq: workqueue to use
204305f0fe6bSTejun Heo * @rwork: work to queue
204405f0fe6bSTejun Heo *
204505f0fe6bSTejun Heo * Return: %false if @rwork was already pending, %true otherwise. Note
204605f0fe6bSTejun Heo * that a full RCU grace period is guaranteed only after a %true return.
2047bf393fd4SBart Van Assche * While @rwork is guaranteed to be executed after a %false return, the
204805f0fe6bSTejun Heo * execution may happen before a full RCU grace period has passed.
204905f0fe6bSTejun Heo */
queue_rcu_work(struct workqueue_struct * wq,struct rcu_work * rwork)205005f0fe6bSTejun Heo bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
205105f0fe6bSTejun Heo {
205205f0fe6bSTejun Heo struct work_struct *work = &rwork->work;
205305f0fe6bSTejun Heo
205405f0fe6bSTejun Heo if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
205505f0fe6bSTejun Heo rwork->wq = wq;
2056a7e30c0eSUladzislau Rezki call_rcu_hurry(&rwork->rcu, rcu_work_rcufn);
205705f0fe6bSTejun Heo return true;
205805f0fe6bSTejun Heo }
205905f0fe6bSTejun Heo
206005f0fe6bSTejun Heo return false;
206105f0fe6bSTejun Heo }
206205f0fe6bSTejun Heo EXPORT_SYMBOL(queue_rcu_work);
206305f0fe6bSTejun Heo
alloc_worker(int node)2064f7537df5SLai Jiangshan static struct worker *alloc_worker(int node)
2065c34056a3STejun Heo {
2066c34056a3STejun Heo struct worker *worker;
2067c34056a3STejun Heo
2068f7537df5SLai Jiangshan worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, node);
2069c8e55f36STejun Heo if (worker) {
2070c8e55f36STejun Heo INIT_LIST_HEAD(&worker->entry);
2071affee4b2STejun Heo INIT_LIST_HEAD(&worker->scheduled);
2072da028469SLai Jiangshan INIT_LIST_HEAD(&worker->node);
2073e22bee78STejun Heo /* on creation a worker is in !idle && prep state */
2074e22bee78STejun Heo worker->flags = WORKER_PREP;
2075c8e55f36STejun Heo }
2076c34056a3STejun Heo return worker;
2077c34056a3STejun Heo }
2078c34056a3STejun Heo
pool_allowed_cpus(struct worker_pool * pool)20799546b29eSTejun Heo static cpumask_t *pool_allowed_cpus(struct worker_pool *pool)
20809546b29eSTejun Heo {
20818639ecebSTejun Heo if (pool->cpu < 0 && pool->attrs->affn_strict)
20829546b29eSTejun Heo return pool->attrs->__pod_cpumask;
20838639ecebSTejun Heo else
20848639ecebSTejun Heo return pool->attrs->cpumask;
20859546b29eSTejun Heo }
20869546b29eSTejun Heo
2087c34056a3STejun Heo /**
20884736cbf7SLai Jiangshan * worker_attach_to_pool() - attach a worker to a pool
20894736cbf7SLai Jiangshan * @worker: worker to be attached
20904736cbf7SLai Jiangshan * @pool: the target pool
20914736cbf7SLai Jiangshan *
20924736cbf7SLai Jiangshan * Attach @worker to @pool. Once attached, the %WORKER_UNBOUND flag and
20934736cbf7SLai Jiangshan * cpu-binding of @worker are kept coordinated with the pool across
20944736cbf7SLai Jiangshan * cpu-[un]hotplugs.
20954736cbf7SLai Jiangshan */
worker_attach_to_pool(struct worker * worker,struct worker_pool * pool)20964736cbf7SLai Jiangshan static void worker_attach_to_pool(struct worker *worker,
20974736cbf7SLai Jiangshan struct worker_pool *pool)
20984736cbf7SLai Jiangshan {
20991258fae7STejun Heo mutex_lock(&wq_pool_attach_mutex);
21004736cbf7SLai Jiangshan
21014736cbf7SLai Jiangshan /*
21021258fae7STejun Heo * The wq_pool_attach_mutex ensures %POOL_DISASSOCIATED remains
21031258fae7STejun Heo * stable across this function. See the comments above the flag
21041258fae7STejun Heo * definition for details.
21054736cbf7SLai Jiangshan */
21064736cbf7SLai Jiangshan if (pool->flags & POOL_DISASSOCIATED)
21074736cbf7SLai Jiangshan worker->flags |= WORKER_UNBOUND;
21085c25b5ffSPeter Zijlstra else
21095c25b5ffSPeter Zijlstra kthread_set_per_cpu(worker->task, pool->cpu);
21104736cbf7SLai Jiangshan
2111640f17c8SPeter Zijlstra if (worker->rescue_wq)
21129546b29eSTejun Heo set_cpus_allowed_ptr(worker->task, pool_allowed_cpus(pool));
2113640f17c8SPeter Zijlstra
21144736cbf7SLai Jiangshan list_add_tail(&worker->node, &pool->workers);
2115a2d812a2STejun Heo worker->pool = pool;
21164736cbf7SLai Jiangshan
21171258fae7STejun Heo mutex_unlock(&wq_pool_attach_mutex);
21184736cbf7SLai Jiangshan }
21194736cbf7SLai Jiangshan
21204736cbf7SLai Jiangshan /**
212160f5a4bcSLai Jiangshan * worker_detach_from_pool() - detach a worker from its pool
212260f5a4bcSLai Jiangshan * @worker: worker which is attached to its pool
212360f5a4bcSLai Jiangshan *
21244736cbf7SLai Jiangshan * Undo the attaching which had been done in worker_attach_to_pool(). The
21254736cbf7SLai Jiangshan * caller worker shouldn't access to the pool after detached except it has
21264736cbf7SLai Jiangshan * other reference to the pool.
212760f5a4bcSLai Jiangshan */
worker_detach_from_pool(struct worker * worker)2128a2d812a2STejun Heo static void worker_detach_from_pool(struct worker *worker)
212960f5a4bcSLai Jiangshan {
2130a2d812a2STejun Heo struct worker_pool *pool = worker->pool;
213160f5a4bcSLai Jiangshan struct completion *detach_completion = NULL;
213260f5a4bcSLai Jiangshan
21331258fae7STejun Heo mutex_lock(&wq_pool_attach_mutex);
2134a2d812a2STejun Heo
21355c25b5ffSPeter Zijlstra kthread_set_per_cpu(worker->task, -1);
2136da028469SLai Jiangshan list_del(&worker->node);
2137a2d812a2STejun Heo worker->pool = NULL;
2138a2d812a2STejun Heo
2139e02b9312SValentin Schneider if (list_empty(&pool->workers) && list_empty(&pool->dying_workers))
214060f5a4bcSLai Jiangshan detach_completion = pool->detach_completion;
21411258fae7STejun Heo mutex_unlock(&wq_pool_attach_mutex);
214260f5a4bcSLai Jiangshan
2143b62c0751SLai Jiangshan /* clear leftover flags without pool->lock after it is detached */
2144b62c0751SLai Jiangshan worker->flags &= ~(WORKER_UNBOUND | WORKER_REBOUND);
2145b62c0751SLai Jiangshan
214660f5a4bcSLai Jiangshan if (detach_completion)
214760f5a4bcSLai Jiangshan complete(detach_completion);
214860f5a4bcSLai Jiangshan }
214960f5a4bcSLai Jiangshan
215060f5a4bcSLai Jiangshan /**
2151c34056a3STejun Heo * create_worker - create a new workqueue worker
215263d95a91STejun Heo * @pool: pool the new worker will belong to
2153c34056a3STejun Heo *
2154051e1850SLai Jiangshan * Create and start a new worker which is attached to @pool.
2155c34056a3STejun Heo *
2156c34056a3STejun Heo * CONTEXT:
2157c34056a3STejun Heo * Might sleep. Does GFP_KERNEL allocations.
2158c34056a3STejun Heo *
2159d185af30SYacine Belkadi * Return:
2160c34056a3STejun Heo * Pointer to the newly created worker.
2161c34056a3STejun Heo */
create_worker(struct worker_pool * pool)2162bc2ae0f5STejun Heo static struct worker *create_worker(struct worker_pool *pool)
2163c34056a3STejun Heo {
2164e441b56fSZhen Lei struct worker *worker;
2165e441b56fSZhen Lei int id;
21665d9c7a1eSLucy Mielke char id_buf[23];
2167c34056a3STejun Heo
21687cda9aaeSLai Jiangshan /* ID is needed to determine kthread name */
2169e441b56fSZhen Lei id = ida_alloc(&pool->worker_ida, GFP_KERNEL);
21703f0ea0b8SPetr Mladek if (id < 0) {
21713f0ea0b8SPetr Mladek pr_err_once("workqueue: Failed to allocate a worker ID: %pe\n",
21723f0ea0b8SPetr Mladek ERR_PTR(id));
2173e441b56fSZhen Lei return NULL;
21743f0ea0b8SPetr Mladek }
2175c34056a3STejun Heo
2176f7537df5SLai Jiangshan worker = alloc_worker(pool->node);
21773f0ea0b8SPetr Mladek if (!worker) {
21783f0ea0b8SPetr Mladek pr_err_once("workqueue: Failed to allocate a worker\n");
2179c34056a3STejun Heo goto fail;
21803f0ea0b8SPetr Mladek }
2181c34056a3STejun Heo
2182c34056a3STejun Heo worker->id = id;
2183c34056a3STejun Heo
218429c91e99STejun Heo if (pool->cpu >= 0)
2185e3c916a4STejun Heo snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id,
2186e3c916a4STejun Heo pool->attrs->nice < 0 ? "H" : "");
2187f3421797STejun Heo else
2188e3c916a4STejun Heo snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id);
2189e3c916a4STejun Heo
2190f3f90ad4STejun Heo worker->task = kthread_create_on_node(worker_thread, worker, pool->node,
2191e3c916a4STejun Heo "kworker/%s", id_buf);
21923f0ea0b8SPetr Mladek if (IS_ERR(worker->task)) {
219360f54038SPetr Mladek if (PTR_ERR(worker->task) == -EINTR) {
219460f54038SPetr Mladek pr_err("workqueue: Interrupted when creating a worker thread \"kworker/%s\"\n",
219560f54038SPetr Mladek id_buf);
219660f54038SPetr Mladek } else {
21973f0ea0b8SPetr Mladek pr_err_once("workqueue: Failed to create a worker thread: %pe",
21983f0ea0b8SPetr Mladek worker->task);
219960f54038SPetr Mladek }
2200c34056a3STejun Heo goto fail;
22013f0ea0b8SPetr Mladek }
2202c34056a3STejun Heo
220391151228SOleg Nesterov set_user_nice(worker->task, pool->attrs->nice);
22049546b29eSTejun Heo kthread_bind_mask(worker->task, pool_allowed_cpus(pool));
220591151228SOleg Nesterov
2206da028469SLai Jiangshan /* successful, attach the worker to the pool */
22074736cbf7SLai Jiangshan worker_attach_to_pool(worker, pool);
2208822d8405STejun Heo
2209051e1850SLai Jiangshan /* start the newly created worker */
2210a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pool->lock);
22110219a352STejun Heo
2212051e1850SLai Jiangshan worker->pool->nr_workers++;
2213051e1850SLai Jiangshan worker_enter_idle(worker);
22140219a352STejun Heo kick_pool(pool);
22150219a352STejun Heo
22160219a352STejun Heo /*
22170219a352STejun Heo * @worker is waiting on a completion in kthread() and will trigger hung
22180219a352STejun Heo * check if not woken up soon. As kick_pool() might not have waken it
22190219a352STejun Heo * up, wake it up explicitly once more.
22200219a352STejun Heo */
2221051e1850SLai Jiangshan wake_up_process(worker->task);
22220219a352STejun Heo
2223a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
2224051e1850SLai Jiangshan
2225c34056a3STejun Heo return worker;
2226822d8405STejun Heo
2227c34056a3STejun Heo fail:
2228e441b56fSZhen Lei ida_free(&pool->worker_ida, id);
2229c34056a3STejun Heo kfree(worker);
2230c34056a3STejun Heo return NULL;
2231c34056a3STejun Heo }
2232c34056a3STejun Heo
unbind_worker(struct worker * worker)2233793777bcSValentin Schneider static void unbind_worker(struct worker *worker)
2234793777bcSValentin Schneider {
2235793777bcSValentin Schneider lockdep_assert_held(&wq_pool_attach_mutex);
2236793777bcSValentin Schneider
2237793777bcSValentin Schneider kthread_set_per_cpu(worker->task, -1);
2238793777bcSValentin Schneider if (cpumask_intersects(wq_unbound_cpumask, cpu_active_mask))
2239793777bcSValentin Schneider WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, wq_unbound_cpumask) < 0);
2240793777bcSValentin Schneider else
2241793777bcSValentin Schneider WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, cpu_possible_mask) < 0);
2242793777bcSValentin Schneider }
2243793777bcSValentin Schneider
wake_dying_workers(struct list_head * cull_list)2244e02b9312SValentin Schneider static void wake_dying_workers(struct list_head *cull_list)
2245e02b9312SValentin Schneider {
2246e02b9312SValentin Schneider struct worker *worker, *tmp;
2247e02b9312SValentin Schneider
2248e02b9312SValentin Schneider list_for_each_entry_safe(worker, tmp, cull_list, entry) {
2249e02b9312SValentin Schneider list_del_init(&worker->entry);
2250e02b9312SValentin Schneider unbind_worker(worker);
2251e02b9312SValentin Schneider /*
2252e02b9312SValentin Schneider * If the worker was somehow already running, then it had to be
2253e02b9312SValentin Schneider * in pool->idle_list when set_worker_dying() happened or we
2254e02b9312SValentin Schneider * wouldn't have gotten here.
2255c34056a3STejun Heo *
2256e02b9312SValentin Schneider * Thus, the worker must either have observed the WORKER_DIE
2257e02b9312SValentin Schneider * flag, or have set its state to TASK_IDLE. Either way, the
2258e02b9312SValentin Schneider * below will be observed by the worker and is safe to do
2259e02b9312SValentin Schneider * outside of pool->lock.
2260e02b9312SValentin Schneider */
2261e02b9312SValentin Schneider wake_up_process(worker->task);
2262e02b9312SValentin Schneider }
2263e02b9312SValentin Schneider }
2264e02b9312SValentin Schneider
2265e02b9312SValentin Schneider /**
2266e02b9312SValentin Schneider * set_worker_dying - Tag a worker for destruction
2267e02b9312SValentin Schneider * @worker: worker to be destroyed
2268e02b9312SValentin Schneider * @list: transfer worker away from its pool->idle_list and into list
2269e02b9312SValentin Schneider *
2270e02b9312SValentin Schneider * Tag @worker for destruction and adjust @pool stats accordingly. The worker
2271e02b9312SValentin Schneider * should be idle.
2272c8e55f36STejun Heo *
2273c8e55f36STejun Heo * CONTEXT:
2274a9b8a985SSebastian Andrzej Siewior * raw_spin_lock_irq(pool->lock).
2275c34056a3STejun Heo */
set_worker_dying(struct worker * worker,struct list_head * list)2276e02b9312SValentin Schneider static void set_worker_dying(struct worker *worker, struct list_head *list)
2277c34056a3STejun Heo {
2278bd7bdd43STejun Heo struct worker_pool *pool = worker->pool;
2279c34056a3STejun Heo
2280cd549687STejun Heo lockdep_assert_held(&pool->lock);
2281e02b9312SValentin Schneider lockdep_assert_held(&wq_pool_attach_mutex);
2282cd549687STejun Heo
2283c34056a3STejun Heo /* sanity check frenzy */
22846183c009STejun Heo if (WARN_ON(worker->current_work) ||
228573eb7fe7SLai Jiangshan WARN_ON(!list_empty(&worker->scheduled)) ||
228673eb7fe7SLai Jiangshan WARN_ON(!(worker->flags & WORKER_IDLE)))
22876183c009STejun Heo return;
2288c34056a3STejun Heo
2289bd7bdd43STejun Heo pool->nr_workers--;
2290bd7bdd43STejun Heo pool->nr_idle--;
2291c8e55f36STejun Heo
2292cb444766STejun Heo worker->flags |= WORKER_DIE;
2293e02b9312SValentin Schneider
2294e02b9312SValentin Schneider list_move(&worker->entry, list);
2295e02b9312SValentin Schneider list_move(&worker->node, &pool->dying_workers);
2296c34056a3STejun Heo }
2297c34056a3STejun Heo
22983f959aa3SValentin Schneider /**
22993f959aa3SValentin Schneider * idle_worker_timeout - check if some idle workers can now be deleted.
23003f959aa3SValentin Schneider * @t: The pool's idle_timer that just expired
23013f959aa3SValentin Schneider *
23023f959aa3SValentin Schneider * The timer is armed in worker_enter_idle(). Note that it isn't disarmed in
23033f959aa3SValentin Schneider * worker_leave_idle(), as a worker flicking between idle and active while its
23043f959aa3SValentin Schneider * pool is at the too_many_workers() tipping point would cause too much timer
23053f959aa3SValentin Schneider * housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
23063f959aa3SValentin Schneider * it expire and re-evaluate things from there.
23073f959aa3SValentin Schneider */
idle_worker_timeout(struct timer_list * t)230832a6c723SKees Cook static void idle_worker_timeout(struct timer_list *t)
2309e22bee78STejun Heo {
231032a6c723SKees Cook struct worker_pool *pool = from_timer(pool, t, idle_timer);
23113f959aa3SValentin Schneider bool do_cull = false;
23123f959aa3SValentin Schneider
23133f959aa3SValentin Schneider if (work_pending(&pool->idle_cull_work))
23143f959aa3SValentin Schneider return;
23153f959aa3SValentin Schneider
23163f959aa3SValentin Schneider raw_spin_lock_irq(&pool->lock);
23173f959aa3SValentin Schneider
23183f959aa3SValentin Schneider if (too_many_workers(pool)) {
23193f959aa3SValentin Schneider struct worker *worker;
23203f959aa3SValentin Schneider unsigned long expires;
23213f959aa3SValentin Schneider
23223f959aa3SValentin Schneider /* idle_list is kept in LIFO order, check the last one */
23233f959aa3SValentin Schneider worker = list_entry(pool->idle_list.prev, struct worker, entry);
23243f959aa3SValentin Schneider expires = worker->last_active + IDLE_WORKER_TIMEOUT;
23253f959aa3SValentin Schneider do_cull = !time_before(jiffies, expires);
23263f959aa3SValentin Schneider
23273f959aa3SValentin Schneider if (!do_cull)
23283f959aa3SValentin Schneider mod_timer(&pool->idle_timer, expires);
23293f959aa3SValentin Schneider }
23303f959aa3SValentin Schneider raw_spin_unlock_irq(&pool->lock);
23313f959aa3SValentin Schneider
23323f959aa3SValentin Schneider if (do_cull)
23333f959aa3SValentin Schneider queue_work(system_unbound_wq, &pool->idle_cull_work);
23343f959aa3SValentin Schneider }
23353f959aa3SValentin Schneider
23363f959aa3SValentin Schneider /**
23373f959aa3SValentin Schneider * idle_cull_fn - cull workers that have been idle for too long.
23383f959aa3SValentin Schneider * @work: the pool's work for handling these idle workers
23393f959aa3SValentin Schneider *
23403f959aa3SValentin Schneider * This goes through a pool's idle workers and gets rid of those that have been
23413f959aa3SValentin Schneider * idle for at least IDLE_WORKER_TIMEOUT seconds.
2342e02b9312SValentin Schneider *
2343e02b9312SValentin Schneider * We don't want to disturb isolated CPUs because of a pcpu kworker being
2344e02b9312SValentin Schneider * culled, so this also resets worker affinity. This requires a sleepable
2345e02b9312SValentin Schneider * context, hence the split between timer callback and work item.
23463f959aa3SValentin Schneider */
idle_cull_fn(struct work_struct * work)23473f959aa3SValentin Schneider static void idle_cull_fn(struct work_struct *work)
23483f959aa3SValentin Schneider {
23493f959aa3SValentin Schneider struct worker_pool *pool = container_of(work, struct worker_pool, idle_cull_work);
23509680540cSYang Yingliang LIST_HEAD(cull_list);
2351e22bee78STejun Heo
2352e02b9312SValentin Schneider /*
2353e02b9312SValentin Schneider * Grabbing wq_pool_attach_mutex here ensures an already-running worker
2354e02b9312SValentin Schneider * cannot proceed beyong worker_detach_from_pool() in its self-destruct
2355e02b9312SValentin Schneider * path. This is required as a previously-preempted worker could run after
2356e02b9312SValentin Schneider * set_worker_dying() has happened but before wake_dying_workers() did.
2357e02b9312SValentin Schneider */
2358e02b9312SValentin Schneider mutex_lock(&wq_pool_attach_mutex);
2359a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pool->lock);
2360e22bee78STejun Heo
23613347fc9fSLai Jiangshan while (too_many_workers(pool)) {
2362e22bee78STejun Heo struct worker *worker;
2363e22bee78STejun Heo unsigned long expires;
2364e22bee78STejun Heo
236563d95a91STejun Heo worker = list_entry(pool->idle_list.prev, struct worker, entry);
2366e22bee78STejun Heo expires = worker->last_active + IDLE_WORKER_TIMEOUT;
2367e22bee78STejun Heo
23683347fc9fSLai Jiangshan if (time_before(jiffies, expires)) {
236963d95a91STejun Heo mod_timer(&pool->idle_timer, expires);
23703347fc9fSLai Jiangshan break;
2371e22bee78STejun Heo }
23723347fc9fSLai Jiangshan
2373e02b9312SValentin Schneider set_worker_dying(worker, &cull_list);
2374e22bee78STejun Heo }
2375e22bee78STejun Heo
2376a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
2377e02b9312SValentin Schneider wake_dying_workers(&cull_list);
2378e02b9312SValentin Schneider mutex_unlock(&wq_pool_attach_mutex);
2379e22bee78STejun Heo }
2380e22bee78STejun Heo
send_mayday(struct work_struct * work)2381493a1724STejun Heo static void send_mayday(struct work_struct *work)
2382e22bee78STejun Heo {
2383112202d9STejun Heo struct pool_workqueue *pwq = get_work_pwq(work);
2384112202d9STejun Heo struct workqueue_struct *wq = pwq->wq;
2385493a1724STejun Heo
23862e109a28STejun Heo lockdep_assert_held(&wq_mayday_lock);
2387e22bee78STejun Heo
2388493008a8STejun Heo if (!wq->rescuer)
2389493a1724STejun Heo return;
2390e22bee78STejun Heo
2391e22bee78STejun Heo /* mayday mayday mayday */
2392493a1724STejun Heo if (list_empty(&pwq->mayday_node)) {
239377668c8bSLai Jiangshan /*
239477668c8bSLai Jiangshan * If @pwq is for an unbound wq, its base ref may be put at
239577668c8bSLai Jiangshan * any time due to an attribute change. Pin @pwq until the
239677668c8bSLai Jiangshan * rescuer is done with it.
239777668c8bSLai Jiangshan */
239877668c8bSLai Jiangshan get_pwq(pwq);
2399493a1724STejun Heo list_add_tail(&pwq->mayday_node, &wq->maydays);
2400e22bee78STejun Heo wake_up_process(wq->rescuer->task);
2401725e8ec5STejun Heo pwq->stats[PWQ_STAT_MAYDAY]++;
2402493a1724STejun Heo }
2403e22bee78STejun Heo }
2404e22bee78STejun Heo
pool_mayday_timeout(struct timer_list * t)240532a6c723SKees Cook static void pool_mayday_timeout(struct timer_list *t)
2406e22bee78STejun Heo {
240732a6c723SKees Cook struct worker_pool *pool = from_timer(pool, t, mayday_timer);
2408e22bee78STejun Heo struct work_struct *work;
2409e22bee78STejun Heo
2410a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pool->lock);
2411a9b8a985SSebastian Andrzej Siewior raw_spin_lock(&wq_mayday_lock); /* for wq->maydays */
2412e22bee78STejun Heo
241363d95a91STejun Heo if (need_to_create_worker(pool)) {
2414e22bee78STejun Heo /*
2415e22bee78STejun Heo * We've been trying to create a new worker but
2416e22bee78STejun Heo * haven't been successful. We might be hitting an
2417e22bee78STejun Heo * allocation deadlock. Send distress signals to
2418e22bee78STejun Heo * rescuers.
2419e22bee78STejun Heo */
242063d95a91STejun Heo list_for_each_entry(work, &pool->worklist, entry)
2421e22bee78STejun Heo send_mayday(work);
2422e22bee78STejun Heo }
2423e22bee78STejun Heo
2424a9b8a985SSebastian Andrzej Siewior raw_spin_unlock(&wq_mayday_lock);
2425a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
2426e22bee78STejun Heo
242763d95a91STejun Heo mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
2428e22bee78STejun Heo }
2429e22bee78STejun Heo
2430e22bee78STejun Heo /**
2431e22bee78STejun Heo * maybe_create_worker - create a new worker if necessary
243263d95a91STejun Heo * @pool: pool to create a new worker for
2433e22bee78STejun Heo *
243463d95a91STejun Heo * Create a new worker for @pool if necessary. @pool is guaranteed to
2435e22bee78STejun Heo * have at least one idle worker on return from this function. If
2436e22bee78STejun Heo * creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
243763d95a91STejun Heo * sent to all rescuers with works scheduled on @pool to resolve
2438e22bee78STejun Heo * possible allocation deadlock.
2439e22bee78STejun Heo *
2440c5aa87bbSTejun Heo * On return, need_to_create_worker() is guaranteed to be %false and
2441c5aa87bbSTejun Heo * may_start_working() %true.
2442e22bee78STejun Heo *
2443e22bee78STejun Heo * LOCKING:
2444a9b8a985SSebastian Andrzej Siewior * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2445e22bee78STejun Heo * multiple times. Does GFP_KERNEL allocations. Called only from
2446e22bee78STejun Heo * manager.
2447e22bee78STejun Heo */
maybe_create_worker(struct worker_pool * pool)244829187a9eSTejun Heo static void maybe_create_worker(struct worker_pool *pool)
2449d565ed63STejun Heo __releases(&pool->lock)
2450d565ed63STejun Heo __acquires(&pool->lock)
2451e22bee78STejun Heo {
2452e22bee78STejun Heo restart:
2453a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
24549f9c2364STejun Heo
2455e22bee78STejun Heo /* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
245663d95a91STejun Heo mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
2457e22bee78STejun Heo
2458e22bee78STejun Heo while (true) {
2459051e1850SLai Jiangshan if (create_worker(pool) || !need_to_create_worker(pool))
2460e22bee78STejun Heo break;
2461e22bee78STejun Heo
2462e212f361SLai Jiangshan schedule_timeout_interruptible(CREATE_COOLDOWN);
24639f9c2364STejun Heo
246463d95a91STejun Heo if (!need_to_create_worker(pool))
2465e22bee78STejun Heo break;
2466e22bee78STejun Heo }
2467e22bee78STejun Heo
246863d95a91STejun Heo del_timer_sync(&pool->mayday_timer);
2469a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pool->lock);
2470051e1850SLai Jiangshan /*
2471051e1850SLai Jiangshan * This is necessary even after a new worker was just successfully
2472051e1850SLai Jiangshan * created as @pool->lock was dropped and the new worker might have
2473051e1850SLai Jiangshan * already become busy.
2474051e1850SLai Jiangshan */
247563d95a91STejun Heo if (need_to_create_worker(pool))
2476e22bee78STejun Heo goto restart;
2477e22bee78STejun Heo }
2478e22bee78STejun Heo
2479e22bee78STejun Heo /**
2480e22bee78STejun Heo * manage_workers - manage worker pool
2481e22bee78STejun Heo * @worker: self
2482e22bee78STejun Heo *
2483706026c2STejun Heo * Assume the manager role and manage the worker pool @worker belongs
2484e22bee78STejun Heo * to. At any given time, there can be only zero or one manager per
2485706026c2STejun Heo * pool. The exclusion is handled automatically by this function.
2486e22bee78STejun Heo *
2487e22bee78STejun Heo * The caller can safely start processing works on false return. On
2488e22bee78STejun Heo * true return, it's guaranteed that need_to_create_worker() is false
2489e22bee78STejun Heo * and may_start_working() is true.
2490e22bee78STejun Heo *
2491e22bee78STejun Heo * CONTEXT:
2492a9b8a985SSebastian Andrzej Siewior * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2493e22bee78STejun Heo * multiple times. Does GFP_KERNEL allocations.
2494e22bee78STejun Heo *
2495d185af30SYacine Belkadi * Return:
249629187a9eSTejun Heo * %false if the pool doesn't need management and the caller can safely
249729187a9eSTejun Heo * start processing works, %true if management function was performed and
249829187a9eSTejun Heo * the conditions that the caller verified before calling the function may
249929187a9eSTejun Heo * no longer be true.
2500e22bee78STejun Heo */
manage_workers(struct worker * worker)2501e22bee78STejun Heo static bool manage_workers(struct worker *worker)
2502e22bee78STejun Heo {
250363d95a91STejun Heo struct worker_pool *pool = worker->pool;
2504e22bee78STejun Heo
2505692b4825STejun Heo if (pool->flags & POOL_MANAGER_ACTIVE)
250629187a9eSTejun Heo return false;
2507692b4825STejun Heo
2508692b4825STejun Heo pool->flags |= POOL_MANAGER_ACTIVE;
25092607d7a6STejun Heo pool->manager = worker;
2510e22bee78STejun Heo
251129187a9eSTejun Heo maybe_create_worker(pool);
2512e22bee78STejun Heo
25132607d7a6STejun Heo pool->manager = NULL;
2514692b4825STejun Heo pool->flags &= ~POOL_MANAGER_ACTIVE;
2515d8bb65abSSebastian Andrzej Siewior rcuwait_wake_up(&manager_wait);
251629187a9eSTejun Heo return true;
2517e22bee78STejun Heo }
2518e22bee78STejun Heo
2519a62428c0STejun Heo /**
2520a62428c0STejun Heo * process_one_work - process single work
2521c34056a3STejun Heo * @worker: self
2522a62428c0STejun Heo * @work: work to process
2523a62428c0STejun Heo *
2524a62428c0STejun Heo * Process @work. This function contains all the logics necessary to
2525a62428c0STejun Heo * process a single work including synchronization against and
2526a62428c0STejun Heo * interaction with other workers on the same cpu, queueing and
2527a62428c0STejun Heo * flushing. As long as context requirement is met, any worker can
2528a62428c0STejun Heo * call this function to process a work.
2529a62428c0STejun Heo *
2530a62428c0STejun Heo * CONTEXT:
2531a9b8a985SSebastian Andrzej Siewior * raw_spin_lock_irq(pool->lock) which is released and regrabbed.
2532a62428c0STejun Heo */
process_one_work(struct worker * worker,struct work_struct * work)2533c34056a3STejun Heo static void process_one_work(struct worker *worker, struct work_struct *work)
2534d565ed63STejun Heo __releases(&pool->lock)
2535d565ed63STejun Heo __acquires(&pool->lock)
25361da177e4SLinus Torvalds {
2537112202d9STejun Heo struct pool_workqueue *pwq = get_work_pwq(work);
2538bd7bdd43STejun Heo struct worker_pool *pool = worker->pool;
2539c4560c2cSLai Jiangshan unsigned long work_data;
25404e6045f1SJohannes Berg #ifdef CONFIG_LOCKDEP
25414e6045f1SJohannes Berg /*
2542a62428c0STejun Heo * It is permissible to free the struct work_struct from
2543a62428c0STejun Heo * inside the function that is called from it, this we need to
2544a62428c0STejun Heo * take into account for lockdep too. To avoid bogus "held
2545a62428c0STejun Heo * lock freed" warnings as well as problems when looking into
2546a62428c0STejun Heo * work->lockdep_map, make a copy and use that here.
25474e6045f1SJohannes Berg */
25484d82a1deSPeter Zijlstra struct lockdep_map lockdep_map;
25494d82a1deSPeter Zijlstra
25504d82a1deSPeter Zijlstra lockdep_copy_map(&lockdep_map, &work->lockdep_map);
25514e6045f1SJohannes Berg #endif
2552807407c0SLai Jiangshan /* ensure we're on the correct CPU */
255385327af6SLai Jiangshan WARN_ON_ONCE(!(pool->flags & POOL_DISASSOCIATED) &&
2554ec22ca5eSTejun Heo raw_smp_processor_id() != pool->cpu);
255525511a47STejun Heo
25568930cabaSTejun Heo /* claim and dequeue */
2557dc186ad7SThomas Gleixner debug_work_deactivate(work);
2558c9e7cf27STejun Heo hash_add(pool->busy_hash, &worker->hentry, (unsigned long)work);
2559c34056a3STejun Heo worker->current_work = work;
2560a2c1c57bSTejun Heo worker->current_func = work->func;
2561112202d9STejun Heo worker->current_pwq = pwq;
2562616db877STejun Heo worker->current_at = worker->task->se.sum_exec_runtime;
2563c4560c2cSLai Jiangshan work_data = *work_data_bits(work);
2564d812796eSLai Jiangshan worker->current_color = get_work_color(work_data);
25657a22ad75STejun Heo
25668bf89593STejun Heo /*
25678bf89593STejun Heo * Record wq name for cmdline and debug reporting, may get
25688bf89593STejun Heo * overridden through set_worker_desc().
25698bf89593STejun Heo */
25708bf89593STejun Heo strscpy(worker->desc, pwq->wq->name, WORKER_DESC_LEN);
25718bf89593STejun Heo
2572a62428c0STejun Heo list_del_init(&work->entry);
2573a62428c0STejun Heo
2574649027d7STejun Heo /*
2575228f1d00SLai Jiangshan * CPU intensive works don't participate in concurrency management.
2576228f1d00SLai Jiangshan * They're the scheduler's responsibility. This takes @worker out
2577228f1d00SLai Jiangshan * of concurrency management and the next code block will chain
2578228f1d00SLai Jiangshan * execution of the pending work items.
2579fb0e7bebSTejun Heo */
2580616db877STejun Heo if (unlikely(pwq->wq->flags & WQ_CPU_INTENSIVE))
2581228f1d00SLai Jiangshan worker_set_flags(worker, WORKER_CPU_INTENSIVE);
2582fb0e7bebSTejun Heo
2583974271c4STejun Heo /*
25840219a352STejun Heo * Kick @pool if necessary. It's always noop for per-cpu worker pools
25850219a352STejun Heo * since nr_running would always be >= 1 at this point. This is used to
25860219a352STejun Heo * chain execution of the pending work items for WORKER_NOT_RUNNING
25870219a352STejun Heo * workers such as the UNBOUND and CPU_INTENSIVE ones.
2588974271c4STejun Heo */
25890219a352STejun Heo kick_pool(pool);
2590974271c4STejun Heo
25918930cabaSTejun Heo /*
25927c3eed5cSTejun Heo * Record the last pool and clear PENDING which should be the last
2593d565ed63STejun Heo * update to @work. Also, do this inside @pool->lock so that
259423657bb1STejun Heo * PENDING and queued state changes happen together while IRQ is
259523657bb1STejun Heo * disabled.
25968930cabaSTejun Heo */
25977c3eed5cSTejun Heo set_work_pool_and_clear_pending(work, pool->id);
25981da177e4SLinus Torvalds
2599fe48ba7dSMirsad Goran Todorovac pwq->stats[PWQ_STAT_STARTED]++;
2600a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
2601365970a1SDavid Howells
2602a1d14934SPeter Zijlstra lock_map_acquire(&pwq->wq->lockdep_map);
26033295f0efSIngo Molnar lock_map_acquire(&lockdep_map);
2604e6f3faa7SPeter Zijlstra /*
2605f52be570SPeter Zijlstra * Strictly speaking we should mark the invariant state without holding
2606f52be570SPeter Zijlstra * any locks, that is, before these two lock_map_acquire()'s.
2607e6f3faa7SPeter Zijlstra *
2608e6f3faa7SPeter Zijlstra * However, that would result in:
2609e6f3faa7SPeter Zijlstra *
2610e6f3faa7SPeter Zijlstra * A(W1)
2611e6f3faa7SPeter Zijlstra * WFC(C)
2612e6f3faa7SPeter Zijlstra * A(W1)
2613e6f3faa7SPeter Zijlstra * C(C)
2614e6f3faa7SPeter Zijlstra *
2615e6f3faa7SPeter Zijlstra * Which would create W1->C->W1 dependencies, even though there is no
2616e6f3faa7SPeter Zijlstra * actual deadlock possible. There are two solutions, using a
2617e6f3faa7SPeter Zijlstra * read-recursive acquire on the work(queue) 'locks', but this will then
2618f52be570SPeter Zijlstra * hit the lockdep limitation on recursive locks, or simply discard
2619e6f3faa7SPeter Zijlstra * these locks.
2620e6f3faa7SPeter Zijlstra *
2621e6f3faa7SPeter Zijlstra * AFAICT there is no possible deadlock scenario between the
2622e6f3faa7SPeter Zijlstra * flush_work() and complete() primitives (except for single-threaded
2623e6f3faa7SPeter Zijlstra * workqueues), so hiding them isn't a problem.
2624e6f3faa7SPeter Zijlstra */
2625f52be570SPeter Zijlstra lockdep_invariant_state(true);
2626e36c886aSArjan van de Ven trace_workqueue_execute_start(work);
2627a2c1c57bSTejun Heo worker->current_func(work);
2628e36c886aSArjan van de Ven /*
2629e36c886aSArjan van de Ven * While we must be careful to not use "work" after this, the trace
2630e36c886aSArjan van de Ven * point will only record its address.
2631e36c886aSArjan van de Ven */
26321c5da0ecSDaniel Jordan trace_workqueue_execute_end(work, worker->current_func);
2633725e8ec5STejun Heo pwq->stats[PWQ_STAT_COMPLETED]++;
26343295f0efSIngo Molnar lock_map_release(&lockdep_map);
2635112202d9STejun Heo lock_map_release(&pwq->wq->lockdep_map);
26361da177e4SLinus Torvalds
2637d5abe669SPeter Zijlstra if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
2638044c782cSValentin Ilie pr_err("BUG: workqueue leaked lock or atomic: %s/0x%08x/%d\n"
2639d75f773cSSakari Ailus " last function: %ps\n",
2640a2c1c57bSTejun Heo current->comm, preempt_count(), task_pid_nr(current),
2641a2c1c57bSTejun Heo worker->current_func);
2642d5abe669SPeter Zijlstra debug_show_held_locks(current);
2643d5abe669SPeter Zijlstra dump_stack();
2644d5abe669SPeter Zijlstra }
2645d5abe669SPeter Zijlstra
2646b22ce278STejun Heo /*
2647025f50f3SSebastian Andrzej Siewior * The following prevents a kworker from hogging CPU on !PREEMPTION
2648b22ce278STejun Heo * kernels, where a requeueing work item waiting for something to
2649b22ce278STejun Heo * happen could deadlock with stop_machine as such work item could
2650b22ce278STejun Heo * indefinitely requeue itself while all other CPUs are trapped in
2651789cbbecSJoe Lawrence * stop_machine. At the same time, report a quiescent RCU state so
2652789cbbecSJoe Lawrence * the same condition doesn't freeze RCU.
2653b22ce278STejun Heo */
2654a7e6425eSPaul E. McKenney cond_resched();
2655b22ce278STejun Heo
2656a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pool->lock);
2657a62428c0STejun Heo
2658616db877STejun Heo /*
2659616db877STejun Heo * In addition to %WQ_CPU_INTENSIVE, @worker may also have been marked
2660616db877STejun Heo * CPU intensive by wq_worker_tick() if @work hogged CPU longer than
2661616db877STejun Heo * wq_cpu_intensive_thresh_us. Clear it.
2662616db877STejun Heo */
2663fb0e7bebSTejun Heo worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
2664fb0e7bebSTejun Heo
26651b69ac6bSJohannes Weiner /* tag the worker for identification in schedule() */
26661b69ac6bSJohannes Weiner worker->last_func = worker->current_func;
26671b69ac6bSJohannes Weiner
2668a62428c0STejun Heo /* we're done with it, release */
266942f8570fSSasha Levin hash_del(&worker->hentry);
2670c34056a3STejun Heo worker->current_work = NULL;
2671a2c1c57bSTejun Heo worker->current_func = NULL;
2672112202d9STejun Heo worker->current_pwq = NULL;
2673d812796eSLai Jiangshan worker->current_color = INT_MAX;
2674c4560c2cSLai Jiangshan pwq_dec_nr_in_flight(pwq, work_data);
26751da177e4SLinus Torvalds }
26761da177e4SLinus Torvalds
2677affee4b2STejun Heo /**
2678affee4b2STejun Heo * process_scheduled_works - process scheduled works
2679affee4b2STejun Heo * @worker: self
2680affee4b2STejun Heo *
2681affee4b2STejun Heo * Process all scheduled works. Please note that the scheduled list
2682affee4b2STejun Heo * may change while processing a work, so this function repeatedly
2683affee4b2STejun Heo * fetches a work from the top and executes it.
2684affee4b2STejun Heo *
2685affee4b2STejun Heo * CONTEXT:
2686a9b8a985SSebastian Andrzej Siewior * raw_spin_lock_irq(pool->lock) which may be released and regrabbed
2687affee4b2STejun Heo * multiple times.
2688affee4b2STejun Heo */
process_scheduled_works(struct worker * worker)2689affee4b2STejun Heo static void process_scheduled_works(struct worker *worker)
26901da177e4SLinus Torvalds {
2691c0ab017dSTejun Heo struct work_struct *work;
2692c0ab017dSTejun Heo bool first = true;
2693c0ab017dSTejun Heo
2694c0ab017dSTejun Heo while ((work = list_first_entry_or_null(&worker->scheduled,
2695c0ab017dSTejun Heo struct work_struct, entry))) {
2696c0ab017dSTejun Heo if (first) {
2697c0ab017dSTejun Heo worker->pool->watchdog_ts = jiffies;
2698c0ab017dSTejun Heo first = false;
2699c0ab017dSTejun Heo }
2700c34056a3STejun Heo process_one_work(worker, work);
2701a62428c0STejun Heo }
27021da177e4SLinus Torvalds }
27031da177e4SLinus Torvalds
set_pf_worker(bool val)2704197f6accSTejun Heo static void set_pf_worker(bool val)
2705197f6accSTejun Heo {
2706197f6accSTejun Heo mutex_lock(&wq_pool_attach_mutex);
2707197f6accSTejun Heo if (val)
2708197f6accSTejun Heo current->flags |= PF_WQ_WORKER;
2709197f6accSTejun Heo else
2710197f6accSTejun Heo current->flags &= ~PF_WQ_WORKER;
2711197f6accSTejun Heo mutex_unlock(&wq_pool_attach_mutex);
2712197f6accSTejun Heo }
2713197f6accSTejun Heo
27144690c4abSTejun Heo /**
27154690c4abSTejun Heo * worker_thread - the worker thread function
2716c34056a3STejun Heo * @__worker: self
27174690c4abSTejun Heo *
2718c5aa87bbSTejun Heo * The worker thread function. All workers belong to a worker_pool -
2719c5aa87bbSTejun Heo * either a per-cpu one or dynamic unbound one. These workers process all
2720c5aa87bbSTejun Heo * work items regardless of their specific target workqueue. The only
2721c5aa87bbSTejun Heo * exception is work items which belong to workqueues with a rescuer which
2722c5aa87bbSTejun Heo * will be explained in rescuer_thread().
2723d185af30SYacine Belkadi *
2724d185af30SYacine Belkadi * Return: 0
27254690c4abSTejun Heo */
worker_thread(void * __worker)2726c34056a3STejun Heo static int worker_thread(void *__worker)
27271da177e4SLinus Torvalds {
2728c34056a3STejun Heo struct worker *worker = __worker;
2729bd7bdd43STejun Heo struct worker_pool *pool = worker->pool;
27301da177e4SLinus Torvalds
2731e22bee78STejun Heo /* tell the scheduler that this is a workqueue worker */
2732197f6accSTejun Heo set_pf_worker(true);
2733c8e55f36STejun Heo woke_up:
2734a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pool->lock);
2735affee4b2STejun Heo
2736a9ab775bSTejun Heo /* am I supposed to die? */
2737a9ab775bSTejun Heo if (unlikely(worker->flags & WORKER_DIE)) {
2738a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
2739197f6accSTejun Heo set_pf_worker(false);
274060f5a4bcSLai Jiangshan
274160f5a4bcSLai Jiangshan set_task_comm(worker->task, "kworker/dying");
2742e441b56fSZhen Lei ida_free(&pool->worker_ida, worker->id);
2743a2d812a2STejun Heo worker_detach_from_pool(worker);
2744e02b9312SValentin Schneider WARN_ON_ONCE(!list_empty(&worker->entry));
274560f5a4bcSLai Jiangshan kfree(worker);
2746c8e55f36STejun Heo return 0;
2747c8e55f36STejun Heo }
2748c8e55f36STejun Heo
2749c8e55f36STejun Heo worker_leave_idle(worker);
2750db7bccf4STejun Heo recheck:
2751e22bee78STejun Heo /* no more worker necessary? */
275263d95a91STejun Heo if (!need_more_worker(pool))
2753e22bee78STejun Heo goto sleep;
2754e22bee78STejun Heo
2755e22bee78STejun Heo /* do we need to manage? */
275663d95a91STejun Heo if (unlikely(!may_start_working(pool)) && manage_workers(worker))
2757e22bee78STejun Heo goto recheck;
2758e22bee78STejun Heo
2759c8e55f36STejun Heo /*
2760c8e55f36STejun Heo * ->scheduled list can only be filled while a worker is
2761c8e55f36STejun Heo * preparing to process a work or actually processing it.
2762c8e55f36STejun Heo * Make sure nobody diddled with it while I was sleeping.
2763c8e55f36STejun Heo */
27646183c009STejun Heo WARN_ON_ONCE(!list_empty(&worker->scheduled));
2765c8e55f36STejun Heo
2766e22bee78STejun Heo /*
2767a9ab775bSTejun Heo * Finish PREP stage. We're guaranteed to have at least one idle
2768a9ab775bSTejun Heo * worker or that someone else has already assumed the manager
2769a9ab775bSTejun Heo * role. This is where @worker starts participating in concurrency
2770a9ab775bSTejun Heo * management if applicable and concurrency management is restored
2771a9ab775bSTejun Heo * after being rebound. See rebind_workers() for details.
2772e22bee78STejun Heo */
2773a9ab775bSTejun Heo worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND);
2774e22bee78STejun Heo
2775e22bee78STejun Heo do {
2776affee4b2STejun Heo struct work_struct *work =
2777bd7bdd43STejun Heo list_first_entry(&pool->worklist,
2778affee4b2STejun Heo struct work_struct, entry);
2779affee4b2STejun Heo
2780873eaca6STejun Heo if (assign_work(work, worker, NULL))
2781affee4b2STejun Heo process_scheduled_works(worker);
278263d95a91STejun Heo } while (keep_working(pool));
2783affee4b2STejun Heo
2784228f1d00SLai Jiangshan worker_set_flags(worker, WORKER_PREP);
2785d313dd85STejun Heo sleep:
2786c8e55f36STejun Heo /*
2787d565ed63STejun Heo * pool->lock is held and there's no work to process and no need to
2788d565ed63STejun Heo * manage, sleep. Workers are woken up only while holding
2789d565ed63STejun Heo * pool->lock or from local cpu, so setting the current state
2790d565ed63STejun Heo * before releasing pool->lock is enough to prevent losing any
2791d565ed63STejun Heo * event.
2792c8e55f36STejun Heo */
2793c8e55f36STejun Heo worker_enter_idle(worker);
2794c5a94a61SPeter Zijlstra __set_current_state(TASK_IDLE);
2795a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
27961da177e4SLinus Torvalds schedule();
2797c8e55f36STejun Heo goto woke_up;
27981da177e4SLinus Torvalds }
27991da177e4SLinus Torvalds
2800e22bee78STejun Heo /**
2801e22bee78STejun Heo * rescuer_thread - the rescuer thread function
2802111c225aSTejun Heo * @__rescuer: self
2803e22bee78STejun Heo *
2804e22bee78STejun Heo * Workqueue rescuer thread function. There's one rescuer for each
2805493008a8STejun Heo * workqueue which has WQ_MEM_RECLAIM set.
2806e22bee78STejun Heo *
2807706026c2STejun Heo * Regular work processing on a pool may block trying to create a new
2808e22bee78STejun Heo * worker which uses GFP_KERNEL allocation which has slight chance of
2809e22bee78STejun Heo * developing into deadlock if some works currently on the same queue
2810e22bee78STejun Heo * need to be processed to satisfy the GFP_KERNEL allocation. This is
2811e22bee78STejun Heo * the problem rescuer solves.
2812e22bee78STejun Heo *
2813706026c2STejun Heo * When such condition is possible, the pool summons rescuers of all
2814706026c2STejun Heo * workqueues which have works queued on the pool and let them process
2815e22bee78STejun Heo * those works so that forward progress can be guaranteed.
2816e22bee78STejun Heo *
2817e22bee78STejun Heo * This should happen rarely.
2818d185af30SYacine Belkadi *
2819d185af30SYacine Belkadi * Return: 0
2820e22bee78STejun Heo */
rescuer_thread(void * __rescuer)2821111c225aSTejun Heo static int rescuer_thread(void *__rescuer)
2822e22bee78STejun Heo {
2823111c225aSTejun Heo struct worker *rescuer = __rescuer;
2824111c225aSTejun Heo struct workqueue_struct *wq = rescuer->rescue_wq;
28254d595b86SLai Jiangshan bool should_stop;
2826e22bee78STejun Heo
2827e22bee78STejun Heo set_user_nice(current, RESCUER_NICE_LEVEL);
2828111c225aSTejun Heo
2829111c225aSTejun Heo /*
2830111c225aSTejun Heo * Mark rescuer as worker too. As WORKER_PREP is never cleared, it
2831111c225aSTejun Heo * doesn't participate in concurrency management.
2832111c225aSTejun Heo */
2833197f6accSTejun Heo set_pf_worker(true);
2834e22bee78STejun Heo repeat:
2835c5a94a61SPeter Zijlstra set_current_state(TASK_IDLE);
28361da177e4SLinus Torvalds
28374d595b86SLai Jiangshan /*
28384d595b86SLai Jiangshan * By the time the rescuer is requested to stop, the workqueue
28394d595b86SLai Jiangshan * shouldn't have any work pending, but @wq->maydays may still have
28404d595b86SLai Jiangshan * pwq(s) queued. This can happen by non-rescuer workers consuming
28414d595b86SLai Jiangshan * all the work items before the rescuer got to them. Go through
28424d595b86SLai Jiangshan * @wq->maydays processing before acting on should_stop so that the
28434d595b86SLai Jiangshan * list is always empty on exit.
28444d595b86SLai Jiangshan */
28454d595b86SLai Jiangshan should_stop = kthread_should_stop();
28461da177e4SLinus Torvalds
2847493a1724STejun Heo /* see whether any pwq is asking for help */
2848a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&wq_mayday_lock);
2849493a1724STejun Heo
2850493a1724STejun Heo while (!list_empty(&wq->maydays)) {
2851493a1724STejun Heo struct pool_workqueue *pwq = list_first_entry(&wq->maydays,
2852493a1724STejun Heo struct pool_workqueue, mayday_node);
2853112202d9STejun Heo struct worker_pool *pool = pwq->pool;
2854e22bee78STejun Heo struct work_struct *work, *n;
2855e22bee78STejun Heo
2856e22bee78STejun Heo __set_current_state(TASK_RUNNING);
2857493a1724STejun Heo list_del_init(&pwq->mayday_node);
2858493a1724STejun Heo
2859a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&wq_mayday_lock);
2860e22bee78STejun Heo
286151697d39SLai Jiangshan worker_attach_to_pool(rescuer, pool);
286251697d39SLai Jiangshan
2863a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pool->lock);
2864e22bee78STejun Heo
2865e22bee78STejun Heo /*
2866e22bee78STejun Heo * Slurp in all works issued via this workqueue and
2867e22bee78STejun Heo * process'em.
2868e22bee78STejun Heo */
2869873eaca6STejun Heo WARN_ON_ONCE(!list_empty(&rescuer->scheduled));
287082607adcSTejun Heo list_for_each_entry_safe(work, n, &pool->worklist, entry) {
2871873eaca6STejun Heo if (get_work_pwq(work) == pwq &&
2872873eaca6STejun Heo assign_work(work, rescuer, &n))
2873725e8ec5STejun Heo pwq->stats[PWQ_STAT_RESCUED]++;
287482607adcSTejun Heo }
2875e22bee78STejun Heo
2876873eaca6STejun Heo if (!list_empty(&rescuer->scheduled)) {
2877e22bee78STejun Heo process_scheduled_works(rescuer);
28787576958aSTejun Heo
28797576958aSTejun Heo /*
2880008847f6SNeilBrown * The above execution of rescued work items could
2881008847f6SNeilBrown * have created more to rescue through
2882f97a4a1aSLai Jiangshan * pwq_activate_first_inactive() or chained
2883008847f6SNeilBrown * queueing. Let's put @pwq back on mayday list so
2884008847f6SNeilBrown * that such back-to-back work items, which may be
2885008847f6SNeilBrown * being used to relieve memory pressure, don't
2886008847f6SNeilBrown * incur MAYDAY_INTERVAL delay inbetween.
2887008847f6SNeilBrown */
28884f3f4cf3SLai Jiangshan if (pwq->nr_active && need_to_create_worker(pool)) {
2889a9b8a985SSebastian Andrzej Siewior raw_spin_lock(&wq_mayday_lock);
2890e66b39afSTejun Heo /*
2891e66b39afSTejun Heo * Queue iff we aren't racing destruction
2892e66b39afSTejun Heo * and somebody else hasn't queued it already.
2893e66b39afSTejun Heo */
2894e66b39afSTejun Heo if (wq->rescuer && list_empty(&pwq->mayday_node)) {
2895008847f6SNeilBrown get_pwq(pwq);
2896e66b39afSTejun Heo list_add_tail(&pwq->mayday_node, &wq->maydays);
2897e66b39afSTejun Heo }
2898a9b8a985SSebastian Andrzej Siewior raw_spin_unlock(&wq_mayday_lock);
2899008847f6SNeilBrown }
2900008847f6SNeilBrown }
2901008847f6SNeilBrown
2902008847f6SNeilBrown /*
290377668c8bSLai Jiangshan * Put the reference grabbed by send_mayday(). @pool won't
290413b1d625SLai Jiangshan * go away while we're still attached to it.
290577668c8bSLai Jiangshan */
290677668c8bSLai Jiangshan put_pwq(pwq);
290777668c8bSLai Jiangshan
290877668c8bSLai Jiangshan /*
29090219a352STejun Heo * Leave this pool. Notify regular workers; otherwise, we end up
29100219a352STejun Heo * with 0 concurrency and stalling the execution.
29117576958aSTejun Heo */
29120219a352STejun Heo kick_pool(pool);
29137576958aSTejun Heo
2914a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
291513b1d625SLai Jiangshan
2916a2d812a2STejun Heo worker_detach_from_pool(rescuer);
291713b1d625SLai Jiangshan
2918a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&wq_mayday_lock);
29191da177e4SLinus Torvalds }
29201da177e4SLinus Torvalds
2921a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&wq_mayday_lock);
2922493a1724STejun Heo
29234d595b86SLai Jiangshan if (should_stop) {
29244d595b86SLai Jiangshan __set_current_state(TASK_RUNNING);
2925197f6accSTejun Heo set_pf_worker(false);
29264d595b86SLai Jiangshan return 0;
29274d595b86SLai Jiangshan }
29284d595b86SLai Jiangshan
2929111c225aSTejun Heo /* rescuers should never participate in concurrency management */
2930111c225aSTejun Heo WARN_ON_ONCE(!(rescuer->flags & WORKER_NOT_RUNNING));
2931e22bee78STejun Heo schedule();
2932e22bee78STejun Heo goto repeat;
29331da177e4SLinus Torvalds }
29341da177e4SLinus Torvalds
2935fca839c0STejun Heo /**
2936fca839c0STejun Heo * check_flush_dependency - check for flush dependency sanity
2937fca839c0STejun Heo * @target_wq: workqueue being flushed
2938fca839c0STejun Heo * @target_work: work item being flushed (NULL for workqueue flushes)
2939fca839c0STejun Heo *
2940fca839c0STejun Heo * %current is trying to flush the whole @target_wq or @target_work on it.
2941fca839c0STejun Heo * If @target_wq doesn't have %WQ_MEM_RECLAIM, verify that %current is not
2942fca839c0STejun Heo * reclaiming memory or running on a workqueue which doesn't have
2943fca839c0STejun Heo * %WQ_MEM_RECLAIM as that can break forward-progress guarantee leading to
2944fca839c0STejun Heo * a deadlock.
2945fca839c0STejun Heo */
check_flush_dependency(struct workqueue_struct * target_wq,struct work_struct * target_work)2946fca839c0STejun Heo static void check_flush_dependency(struct workqueue_struct *target_wq,
2947fca839c0STejun Heo struct work_struct *target_work)
2948fca839c0STejun Heo {
2949fca839c0STejun Heo work_func_t target_func = target_work ? target_work->func : NULL;
2950fca839c0STejun Heo struct worker *worker;
2951fca839c0STejun Heo
2952fca839c0STejun Heo if (target_wq->flags & WQ_MEM_RECLAIM)
2953fca839c0STejun Heo return;
2954fca839c0STejun Heo
2955fca839c0STejun Heo worker = current_wq_worker();
2956fca839c0STejun Heo
2957fca839c0STejun Heo WARN_ONCE(current->flags & PF_MEMALLOC,
2958d75f773cSSakari Ailus "workqueue: PF_MEMALLOC task %d(%s) is flushing !WQ_MEM_RECLAIM %s:%ps",
2959fca839c0STejun Heo current->pid, current->comm, target_wq->name, target_func);
296023d11a58STejun Heo WARN_ONCE(worker && ((worker->current_pwq->wq->flags &
296123d11a58STejun Heo (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM),
2962d75f773cSSakari Ailus "workqueue: WQ_MEM_RECLAIM %s:%ps is flushing !WQ_MEM_RECLAIM %s:%ps",
2963fca839c0STejun Heo worker->current_pwq->wq->name, worker->current_func,
2964fca839c0STejun Heo target_wq->name, target_func);
2965fca839c0STejun Heo }
2966fca839c0STejun Heo
2967fc2e4d70SOleg Nesterov struct wq_barrier {
2968fc2e4d70SOleg Nesterov struct work_struct work;
2969fc2e4d70SOleg Nesterov struct completion done;
29702607d7a6STejun Heo struct task_struct *task; /* purely informational */
2971fc2e4d70SOleg Nesterov };
2972fc2e4d70SOleg Nesterov
wq_barrier_func(struct work_struct * work)2973fc2e4d70SOleg Nesterov static void wq_barrier_func(struct work_struct *work)
2974fc2e4d70SOleg Nesterov {
2975fc2e4d70SOleg Nesterov struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
2976fc2e4d70SOleg Nesterov complete(&barr->done);
2977fc2e4d70SOleg Nesterov }
2978fc2e4d70SOleg Nesterov
29794690c4abSTejun Heo /**
29804690c4abSTejun Heo * insert_wq_barrier - insert a barrier work
2981112202d9STejun Heo * @pwq: pwq to insert barrier into
29824690c4abSTejun Heo * @barr: wq_barrier to insert
2983affee4b2STejun Heo * @target: target work to attach @barr to
2984affee4b2STejun Heo * @worker: worker currently executing @target, NULL if @target is not executing
29854690c4abSTejun Heo *
2986affee4b2STejun Heo * @barr is linked to @target such that @barr is completed only after
2987affee4b2STejun Heo * @target finishes execution. Please note that the ordering
2988affee4b2STejun Heo * guarantee is observed only with respect to @target and on the local
2989affee4b2STejun Heo * cpu.
2990affee4b2STejun Heo *
2991affee4b2STejun Heo * Currently, a queued barrier can't be canceled. This is because
2992affee4b2STejun Heo * try_to_grab_pending() can't determine whether the work to be
2993affee4b2STejun Heo * grabbed is at the head of the queue and thus can't clear LINKED
2994affee4b2STejun Heo * flag of the previous work while there must be a valid next work
2995affee4b2STejun Heo * after a work with LINKED flag set.
2996affee4b2STejun Heo *
2997affee4b2STejun Heo * Note that when @worker is non-NULL, @target may be modified
2998112202d9STejun Heo * underneath us, so we can't reliably determine pwq from @target.
29994690c4abSTejun Heo *
30004690c4abSTejun Heo * CONTEXT:
3001a9b8a985SSebastian Andrzej Siewior * raw_spin_lock_irq(pool->lock).
30024690c4abSTejun Heo */
insert_wq_barrier(struct pool_workqueue * pwq,struct wq_barrier * barr,struct work_struct * target,struct worker * worker)3003112202d9STejun Heo static void insert_wq_barrier(struct pool_workqueue *pwq,
3004affee4b2STejun Heo struct wq_barrier *barr,
3005affee4b2STejun Heo struct work_struct *target, struct worker *worker)
3006fc2e4d70SOleg Nesterov {
3007d812796eSLai Jiangshan unsigned int work_flags = 0;
3008d812796eSLai Jiangshan unsigned int work_color;
3009affee4b2STejun Heo struct list_head *head;
3010affee4b2STejun Heo
3011dc186ad7SThomas Gleixner /*
3012d565ed63STejun Heo * debugobject calls are safe here even with pool->lock locked
3013dc186ad7SThomas Gleixner * as we know for sure that this will not trigger any of the
3014dc186ad7SThomas Gleixner * checks and call back into the fixup functions where we
3015dc186ad7SThomas Gleixner * might deadlock.
3016dc186ad7SThomas Gleixner */
3017ca1cab37SAndrew Morton INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
301822df02bbSTejun Heo __set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
301952fa5bc5SBoqun Feng
3020fd1a5b04SByungchul Park init_completion_map(&barr->done, &target->lockdep_map);
3021fd1a5b04SByungchul Park
30222607d7a6STejun Heo barr->task = current;
302383c22520SOleg Nesterov
30246741dd3fSGreg Kroah-Hartman /* The barrier work item does not participate in pwq->nr_active. */
3025018f3a13SLai Jiangshan work_flags |= WORK_STRUCT_INACTIVE;
3026018f3a13SLai Jiangshan
3027affee4b2STejun Heo /*
3028affee4b2STejun Heo * If @target is currently being executed, schedule the
3029affee4b2STejun Heo * barrier to the worker; otherwise, put it after @target.
3030affee4b2STejun Heo */
3031d812796eSLai Jiangshan if (worker) {
3032affee4b2STejun Heo head = worker->scheduled.next;
3033d812796eSLai Jiangshan work_color = worker->current_color;
3034d812796eSLai Jiangshan } else {
3035affee4b2STejun Heo unsigned long *bits = work_data_bits(target);
3036affee4b2STejun Heo
3037affee4b2STejun Heo head = target->entry.next;
3038affee4b2STejun Heo /* there can already be other linked works, inherit and set */
3039d21cece0SLai Jiangshan work_flags |= *bits & WORK_STRUCT_LINKED;
3040d812796eSLai Jiangshan work_color = get_work_color(*bits);
3041affee4b2STejun Heo __set_bit(WORK_STRUCT_LINKED_BIT, bits);
3042affee4b2STejun Heo }
3043affee4b2STejun Heo
3044d812796eSLai Jiangshan pwq->nr_in_flight[work_color]++;
3045d812796eSLai Jiangshan work_flags |= work_color_to_flags(work_color);
3046d812796eSLai Jiangshan
3047d21cece0SLai Jiangshan insert_work(pwq, &barr->work, head, work_flags);
3048fc2e4d70SOleg Nesterov }
3049fc2e4d70SOleg Nesterov
305073f53c4aSTejun Heo /**
3051112202d9STejun Heo * flush_workqueue_prep_pwqs - prepare pwqs for workqueue flushing
305273f53c4aSTejun Heo * @wq: workqueue being flushed
305373f53c4aSTejun Heo * @flush_color: new flush color, < 0 for no-op
305473f53c4aSTejun Heo * @work_color: new work color, < 0 for no-op
305573f53c4aSTejun Heo *
3056112202d9STejun Heo * Prepare pwqs for workqueue flushing.
305773f53c4aSTejun Heo *
3058112202d9STejun Heo * If @flush_color is non-negative, flush_color on all pwqs should be
3059112202d9STejun Heo * -1. If no pwq has in-flight commands at the specified color, all
3060112202d9STejun Heo * pwq->flush_color's stay at -1 and %false is returned. If any pwq
3061112202d9STejun Heo * has in flight commands, its pwq->flush_color is set to
3062112202d9STejun Heo * @flush_color, @wq->nr_pwqs_to_flush is updated accordingly, pwq
306373f53c4aSTejun Heo * wakeup logic is armed and %true is returned.
306473f53c4aSTejun Heo *
306573f53c4aSTejun Heo * The caller should have initialized @wq->first_flusher prior to
306673f53c4aSTejun Heo * calling this function with non-negative @flush_color. If
306773f53c4aSTejun Heo * @flush_color is negative, no flush color update is done and %false
306873f53c4aSTejun Heo * is returned.
306973f53c4aSTejun Heo *
3070112202d9STejun Heo * If @work_color is non-negative, all pwqs should have the same
307173f53c4aSTejun Heo * work_color which is previous to @work_color and all will be
307273f53c4aSTejun Heo * advanced to @work_color.
307373f53c4aSTejun Heo *
307473f53c4aSTejun Heo * CONTEXT:
30753c25a55dSLai Jiangshan * mutex_lock(wq->mutex).
307673f53c4aSTejun Heo *
3077d185af30SYacine Belkadi * Return:
307873f53c4aSTejun Heo * %true if @flush_color >= 0 and there's something to flush. %false
307973f53c4aSTejun Heo * otherwise.
308073f53c4aSTejun Heo */
flush_workqueue_prep_pwqs(struct workqueue_struct * wq,int flush_color,int work_color)3081112202d9STejun Heo static bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq,
308273f53c4aSTejun Heo int flush_color, int work_color)
30831da177e4SLinus Torvalds {
308473f53c4aSTejun Heo bool wait = false;
308549e3cf44STejun Heo struct pool_workqueue *pwq;
30861da177e4SLinus Torvalds
308773f53c4aSTejun Heo if (flush_color >= 0) {
30886183c009STejun Heo WARN_ON_ONCE(atomic_read(&wq->nr_pwqs_to_flush));
3089112202d9STejun Heo atomic_set(&wq->nr_pwqs_to_flush, 1);
3090dc186ad7SThomas Gleixner }
309114441960SOleg Nesterov
309249e3cf44STejun Heo for_each_pwq(pwq, wq) {
3093112202d9STejun Heo struct worker_pool *pool = pwq->pool;
30941da177e4SLinus Torvalds
3095a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pool->lock);
309673f53c4aSTejun Heo
309773f53c4aSTejun Heo if (flush_color >= 0) {
30986183c009STejun Heo WARN_ON_ONCE(pwq->flush_color != -1);
309973f53c4aSTejun Heo
3100112202d9STejun Heo if (pwq->nr_in_flight[flush_color]) {
3101112202d9STejun Heo pwq->flush_color = flush_color;
3102112202d9STejun Heo atomic_inc(&wq->nr_pwqs_to_flush);
310373f53c4aSTejun Heo wait = true;
31041da177e4SLinus Torvalds }
310573f53c4aSTejun Heo }
310673f53c4aSTejun Heo
310773f53c4aSTejun Heo if (work_color >= 0) {
31086183c009STejun Heo WARN_ON_ONCE(work_color != work_next_color(pwq->work_color));
3109112202d9STejun Heo pwq->work_color = work_color;
311073f53c4aSTejun Heo }
311173f53c4aSTejun Heo
3112a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
31131da177e4SLinus Torvalds }
31141da177e4SLinus Torvalds
3115112202d9STejun Heo if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_pwqs_to_flush))
311673f53c4aSTejun Heo complete(&wq->first_flusher->done);
311773f53c4aSTejun Heo
311873f53c4aSTejun Heo return wait;
311983c22520SOleg Nesterov }
31201da177e4SLinus Torvalds
31210fcb78c2SRolf Eike Beer /**
3122c4f135d6STetsuo Handa * __flush_workqueue - ensure that any scheduled work has run to completion.
31230fcb78c2SRolf Eike Beer * @wq: workqueue to flush
31241da177e4SLinus Torvalds *
3125c5aa87bbSTejun Heo * This function sleeps until all work items which were queued on entry
3126c5aa87bbSTejun Heo * have finished execution, but it is not livelocked by new incoming ones.
31271da177e4SLinus Torvalds */
__flush_workqueue(struct workqueue_struct * wq)3128c4f135d6STetsuo Handa void __flush_workqueue(struct workqueue_struct *wq)
31291da177e4SLinus Torvalds {
313073f53c4aSTejun Heo struct wq_flusher this_flusher = {
313173f53c4aSTejun Heo .list = LIST_HEAD_INIT(this_flusher.list),
313273f53c4aSTejun Heo .flush_color = -1,
3133fd1a5b04SByungchul Park .done = COMPLETION_INITIALIZER_ONSTACK_MAP(this_flusher.done, wq->lockdep_map),
313473f53c4aSTejun Heo };
313573f53c4aSTejun Heo int next_color;
3136b1f4ec17SOleg Nesterov
31373347fa09STejun Heo if (WARN_ON(!wq_online))
31383347fa09STejun Heo return;
31393347fa09STejun Heo
314087915adcSJohannes Berg lock_map_acquire(&wq->lockdep_map);
314187915adcSJohannes Berg lock_map_release(&wq->lockdep_map);
314287915adcSJohannes Berg
31433c25a55dSLai Jiangshan mutex_lock(&wq->mutex);
314473f53c4aSTejun Heo
314573f53c4aSTejun Heo /*
314673f53c4aSTejun Heo * Start-to-wait phase
314773f53c4aSTejun Heo */
314873f53c4aSTejun Heo next_color = work_next_color(wq->work_color);
314973f53c4aSTejun Heo
315073f53c4aSTejun Heo if (next_color != wq->flush_color) {
315173f53c4aSTejun Heo /*
315273f53c4aSTejun Heo * Color space is not full. The current work_color
315373f53c4aSTejun Heo * becomes our flush_color and work_color is advanced
315473f53c4aSTejun Heo * by one.
315573f53c4aSTejun Heo */
31566183c009STejun Heo WARN_ON_ONCE(!list_empty(&wq->flusher_overflow));
315773f53c4aSTejun Heo this_flusher.flush_color = wq->work_color;
315873f53c4aSTejun Heo wq->work_color = next_color;
315973f53c4aSTejun Heo
316073f53c4aSTejun Heo if (!wq->first_flusher) {
316173f53c4aSTejun Heo /* no flush in progress, become the first flusher */
31626183c009STejun Heo WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
316373f53c4aSTejun Heo
316473f53c4aSTejun Heo wq->first_flusher = &this_flusher;
316573f53c4aSTejun Heo
3166112202d9STejun Heo if (!flush_workqueue_prep_pwqs(wq, wq->flush_color,
316773f53c4aSTejun Heo wq->work_color)) {
316873f53c4aSTejun Heo /* nothing to flush, done */
316973f53c4aSTejun Heo wq->flush_color = next_color;
317073f53c4aSTejun Heo wq->first_flusher = NULL;
317173f53c4aSTejun Heo goto out_unlock;
317273f53c4aSTejun Heo }
317373f53c4aSTejun Heo } else {
317473f53c4aSTejun Heo /* wait in queue */
31756183c009STejun Heo WARN_ON_ONCE(wq->flush_color == this_flusher.flush_color);
317673f53c4aSTejun Heo list_add_tail(&this_flusher.list, &wq->flusher_queue);
3177112202d9STejun Heo flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
317873f53c4aSTejun Heo }
317973f53c4aSTejun Heo } else {
318073f53c4aSTejun Heo /*
318173f53c4aSTejun Heo * Oops, color space is full, wait on overflow queue.
318273f53c4aSTejun Heo * The next flush completion will assign us
318373f53c4aSTejun Heo * flush_color and transfer to flusher_queue.
318473f53c4aSTejun Heo */
318573f53c4aSTejun Heo list_add_tail(&this_flusher.list, &wq->flusher_overflow);
318673f53c4aSTejun Heo }
318773f53c4aSTejun Heo
3188fca839c0STejun Heo check_flush_dependency(wq, NULL);
3189fca839c0STejun Heo
31903c25a55dSLai Jiangshan mutex_unlock(&wq->mutex);
319173f53c4aSTejun Heo
319273f53c4aSTejun Heo wait_for_completion(&this_flusher.done);
319373f53c4aSTejun Heo
319473f53c4aSTejun Heo /*
319573f53c4aSTejun Heo * Wake-up-and-cascade phase
319673f53c4aSTejun Heo *
319773f53c4aSTejun Heo * First flushers are responsible for cascading flushes and
319873f53c4aSTejun Heo * handling overflow. Non-first flushers can simply return.
319973f53c4aSTejun Heo */
320000d5d15bSChris Wilson if (READ_ONCE(wq->first_flusher) != &this_flusher)
320173f53c4aSTejun Heo return;
320273f53c4aSTejun Heo
32033c25a55dSLai Jiangshan mutex_lock(&wq->mutex);
320473f53c4aSTejun Heo
32054ce48b37STejun Heo /* we might have raced, check again with mutex held */
32064ce48b37STejun Heo if (wq->first_flusher != &this_flusher)
32074ce48b37STejun Heo goto out_unlock;
32084ce48b37STejun Heo
320900d5d15bSChris Wilson WRITE_ONCE(wq->first_flusher, NULL);
321073f53c4aSTejun Heo
32116183c009STejun Heo WARN_ON_ONCE(!list_empty(&this_flusher.list));
32126183c009STejun Heo WARN_ON_ONCE(wq->flush_color != this_flusher.flush_color);
321373f53c4aSTejun Heo
321473f53c4aSTejun Heo while (true) {
321573f53c4aSTejun Heo struct wq_flusher *next, *tmp;
321673f53c4aSTejun Heo
321773f53c4aSTejun Heo /* complete all the flushers sharing the current flush color */
321873f53c4aSTejun Heo list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
321973f53c4aSTejun Heo if (next->flush_color != wq->flush_color)
322073f53c4aSTejun Heo break;
322173f53c4aSTejun Heo list_del_init(&next->list);
322273f53c4aSTejun Heo complete(&next->done);
322373f53c4aSTejun Heo }
322473f53c4aSTejun Heo
32256183c009STejun Heo WARN_ON_ONCE(!list_empty(&wq->flusher_overflow) &&
322673f53c4aSTejun Heo wq->flush_color != work_next_color(wq->work_color));
322773f53c4aSTejun Heo
322873f53c4aSTejun Heo /* this flush_color is finished, advance by one */
322973f53c4aSTejun Heo wq->flush_color = work_next_color(wq->flush_color);
323073f53c4aSTejun Heo
323173f53c4aSTejun Heo /* one color has been freed, handle overflow queue */
323273f53c4aSTejun Heo if (!list_empty(&wq->flusher_overflow)) {
323373f53c4aSTejun Heo /*
323473f53c4aSTejun Heo * Assign the same color to all overflowed
323573f53c4aSTejun Heo * flushers, advance work_color and append to
323673f53c4aSTejun Heo * flusher_queue. This is the start-to-wait
323773f53c4aSTejun Heo * phase for these overflowed flushers.
323873f53c4aSTejun Heo */
323973f53c4aSTejun Heo list_for_each_entry(tmp, &wq->flusher_overflow, list)
324073f53c4aSTejun Heo tmp->flush_color = wq->work_color;
324173f53c4aSTejun Heo
324273f53c4aSTejun Heo wq->work_color = work_next_color(wq->work_color);
324373f53c4aSTejun Heo
324473f53c4aSTejun Heo list_splice_tail_init(&wq->flusher_overflow,
324573f53c4aSTejun Heo &wq->flusher_queue);
3246112202d9STejun Heo flush_workqueue_prep_pwqs(wq, -1, wq->work_color);
324773f53c4aSTejun Heo }
324873f53c4aSTejun Heo
324973f53c4aSTejun Heo if (list_empty(&wq->flusher_queue)) {
32506183c009STejun Heo WARN_ON_ONCE(wq->flush_color != wq->work_color);
325173f53c4aSTejun Heo break;
325273f53c4aSTejun Heo }
325373f53c4aSTejun Heo
325473f53c4aSTejun Heo /*
325573f53c4aSTejun Heo * Need to flush more colors. Make the next flusher
3256112202d9STejun Heo * the new first flusher and arm pwqs.
325773f53c4aSTejun Heo */
32586183c009STejun Heo WARN_ON_ONCE(wq->flush_color == wq->work_color);
32596183c009STejun Heo WARN_ON_ONCE(wq->flush_color != next->flush_color);
326073f53c4aSTejun Heo
326173f53c4aSTejun Heo list_del_init(&next->list);
326273f53c4aSTejun Heo wq->first_flusher = next;
326373f53c4aSTejun Heo
3264112202d9STejun Heo if (flush_workqueue_prep_pwqs(wq, wq->flush_color, -1))
326573f53c4aSTejun Heo break;
326673f53c4aSTejun Heo
326773f53c4aSTejun Heo /*
326873f53c4aSTejun Heo * Meh... this color is already done, clear first
326973f53c4aSTejun Heo * flusher and repeat cascading.
327073f53c4aSTejun Heo */
327173f53c4aSTejun Heo wq->first_flusher = NULL;
327273f53c4aSTejun Heo }
327373f53c4aSTejun Heo
327473f53c4aSTejun Heo out_unlock:
32753c25a55dSLai Jiangshan mutex_unlock(&wq->mutex);
32761da177e4SLinus Torvalds }
3277c4f135d6STetsuo Handa EXPORT_SYMBOL(__flush_workqueue);
32781da177e4SLinus Torvalds
32799c5a2ba7STejun Heo /**
32809c5a2ba7STejun Heo * drain_workqueue - drain a workqueue
32819c5a2ba7STejun Heo * @wq: workqueue to drain
32829c5a2ba7STejun Heo *
32839c5a2ba7STejun Heo * Wait until the workqueue becomes empty. While draining is in progress,
32849c5a2ba7STejun Heo * only chain queueing is allowed. IOW, only currently pending or running
32859c5a2ba7STejun Heo * work items on @wq can queue further work items on it. @wq is flushed
3286b749b1b6SChen Hanxiao * repeatedly until it becomes empty. The number of flushing is determined
32879c5a2ba7STejun Heo * by the depth of chaining and should be relatively short. Whine if it
32889c5a2ba7STejun Heo * takes too long.
32899c5a2ba7STejun Heo */
drain_workqueue(struct workqueue_struct * wq)32909c5a2ba7STejun Heo void drain_workqueue(struct workqueue_struct *wq)
32919c5a2ba7STejun Heo {
32929c5a2ba7STejun Heo unsigned int flush_cnt = 0;
329349e3cf44STejun Heo struct pool_workqueue *pwq;
32949c5a2ba7STejun Heo
32959c5a2ba7STejun Heo /*
32969c5a2ba7STejun Heo * __queue_work() needs to test whether there are drainers, is much
32979c5a2ba7STejun Heo * hotter than drain_workqueue() and already looks at @wq->flags.
3298618b01ebSTejun Heo * Use __WQ_DRAINING so that queue doesn't have to check nr_drainers.
32999c5a2ba7STejun Heo */
330087fc741eSLai Jiangshan mutex_lock(&wq->mutex);
33019c5a2ba7STejun Heo if (!wq->nr_drainers++)
3302618b01ebSTejun Heo wq->flags |= __WQ_DRAINING;
330387fc741eSLai Jiangshan mutex_unlock(&wq->mutex);
33049c5a2ba7STejun Heo reflush:
3305c4f135d6STetsuo Handa __flush_workqueue(wq);
33069c5a2ba7STejun Heo
3307b09f4fd3SLai Jiangshan mutex_lock(&wq->mutex);
330876af4d93STejun Heo
330949e3cf44STejun Heo for_each_pwq(pwq, wq) {
3310fa2563e4SThomas Tuttle bool drained;
33119c5a2ba7STejun Heo
3312a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pwq->pool->lock);
331335bf38ddSGreg Kroah-Hartman drained = !pwq->nr_active && list_empty(&pwq->inactive_works);
3314a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pwq->pool->lock);
3315fa2563e4SThomas Tuttle
3316fa2563e4SThomas Tuttle if (drained)
33179c5a2ba7STejun Heo continue;
33189c5a2ba7STejun Heo
33199c5a2ba7STejun Heo if (++flush_cnt == 10 ||
33209c5a2ba7STejun Heo (flush_cnt % 100 == 0 && flush_cnt <= 1000))
3321e9ad2eb3SStephen Zhang pr_warn("workqueue %s: %s() isn't complete after %u tries\n",
3322e9ad2eb3SStephen Zhang wq->name, __func__, flush_cnt);
332376af4d93STejun Heo
3324b09f4fd3SLai Jiangshan mutex_unlock(&wq->mutex);
33259c5a2ba7STejun Heo goto reflush;
33269c5a2ba7STejun Heo }
33279c5a2ba7STejun Heo
33289c5a2ba7STejun Heo if (!--wq->nr_drainers)
3329618b01ebSTejun Heo wq->flags &= ~__WQ_DRAINING;
333087fc741eSLai Jiangshan mutex_unlock(&wq->mutex);
33319c5a2ba7STejun Heo }
33329c5a2ba7STejun Heo EXPORT_SYMBOL_GPL(drain_workqueue);
33339c5a2ba7STejun Heo
start_flush_work(struct work_struct * work,struct wq_barrier * barr,bool from_cancel)3334d6e89786SJohannes Berg static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
3335d6e89786SJohannes Berg bool from_cancel)
3336baf59022STejun Heo {
3337baf59022STejun Heo struct worker *worker = NULL;
3338c9e7cf27STejun Heo struct worker_pool *pool;
3339112202d9STejun Heo struct pool_workqueue *pwq;
3340baf59022STejun Heo
3341baf59022STejun Heo might_sleep();
3342baf59022STejun Heo
334324acfb71SThomas Gleixner rcu_read_lock();
3344fa1b54e6STejun Heo pool = get_work_pool(work);
3345fa1b54e6STejun Heo if (!pool) {
334624acfb71SThomas Gleixner rcu_read_unlock();
3347fa1b54e6STejun Heo return false;
3348fa1b54e6STejun Heo }
3349fa1b54e6STejun Heo
3350a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pool->lock);
33510b3dae68SLai Jiangshan /* see the comment in try_to_grab_pending() with the same code */
3352112202d9STejun Heo pwq = get_work_pwq(work);
3353112202d9STejun Heo if (pwq) {
3354112202d9STejun Heo if (unlikely(pwq->pool != pool))
3355baf59022STejun Heo goto already_gone;
3356606a5020STejun Heo } else {
3357c9e7cf27STejun Heo worker = find_worker_executing_work(pool, work);
3358baf59022STejun Heo if (!worker)
3359baf59022STejun Heo goto already_gone;
3360112202d9STejun Heo pwq = worker->current_pwq;
3361606a5020STejun Heo }
3362baf59022STejun Heo
3363fca839c0STejun Heo check_flush_dependency(pwq->wq, work);
3364fca839c0STejun Heo
3365112202d9STejun Heo insert_wq_barrier(pwq, barr, work, worker);
3366a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
3367baf59022STejun Heo
3368e159489bSTejun Heo /*
3369a1d14934SPeter Zijlstra * Force a lock recursion deadlock when using flush_work() inside a
3370a1d14934SPeter Zijlstra * single-threaded or rescuer equipped workqueue.
3371a1d14934SPeter Zijlstra *
3372a1d14934SPeter Zijlstra * For single threaded workqueues the deadlock happens when the work
3373a1d14934SPeter Zijlstra * is after the work issuing the flush_work(). For rescuer equipped
3374a1d14934SPeter Zijlstra * workqueues the deadlock happens when the rescuer stalls, blocking
3375a1d14934SPeter Zijlstra * forward progress.
3376e159489bSTejun Heo */
3377d6e89786SJohannes Berg if (!from_cancel &&
3378d6e89786SJohannes Berg (pwq->wq->saved_max_active == 1 || pwq->wq->rescuer)) {
3379112202d9STejun Heo lock_map_acquire(&pwq->wq->lockdep_map);
3380112202d9STejun Heo lock_map_release(&pwq->wq->lockdep_map);
3381a1d14934SPeter Zijlstra }
338224acfb71SThomas Gleixner rcu_read_unlock();
3383baf59022STejun Heo return true;
3384baf59022STejun Heo already_gone:
3385a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
338624acfb71SThomas Gleixner rcu_read_unlock();
3387baf59022STejun Heo return false;
3388baf59022STejun Heo }
3389baf59022STejun Heo
__flush_work(struct work_struct * work,bool from_cancel)3390d6e89786SJohannes Berg static bool __flush_work(struct work_struct *work, bool from_cancel)
3391d6e89786SJohannes Berg {
3392d6e89786SJohannes Berg struct wq_barrier barr;
3393d6e89786SJohannes Berg
3394d6e89786SJohannes Berg if (WARN_ON(!wq_online))
3395d6e89786SJohannes Berg return false;
3396d6e89786SJohannes Berg
33974d43d395STetsuo Handa if (WARN_ON(!work->func))
33984d43d395STetsuo Handa return false;
33994d43d395STetsuo Handa
340087915adcSJohannes Berg lock_map_acquire(&work->lockdep_map);
340187915adcSJohannes Berg lock_map_release(&work->lockdep_map);
340287915adcSJohannes Berg
3403d6e89786SJohannes Berg if (start_flush_work(work, &barr, from_cancel)) {
3404d6e89786SJohannes Berg wait_for_completion(&barr.done);
3405d6e89786SJohannes Berg destroy_work_on_stack(&barr.work);
3406d6e89786SJohannes Berg return true;
3407d6e89786SJohannes Berg } else {
3408d6e89786SJohannes Berg return false;
3409d6e89786SJohannes Berg }
3410d6e89786SJohannes Berg }
3411d6e89786SJohannes Berg
3412db700897SOleg Nesterov /**
3413401a8d04STejun Heo * flush_work - wait for a work to finish executing the last queueing instance
3414401a8d04STejun Heo * @work: the work to flush
3415db700897SOleg Nesterov *
3416606a5020STejun Heo * Wait until @work has finished execution. @work is guaranteed to be idle
3417606a5020STejun Heo * on return if it hasn't been requeued since flush started.
3418401a8d04STejun Heo *
3419d185af30SYacine Belkadi * Return:
3420401a8d04STejun Heo * %true if flush_work() waited for the work to finish execution,
3421401a8d04STejun Heo * %false if it was already idle.
3422db700897SOleg Nesterov */
flush_work(struct work_struct * work)3423401a8d04STejun Heo bool flush_work(struct work_struct *work)
3424db700897SOleg Nesterov {
3425d6e89786SJohannes Berg return __flush_work(work, false);
3426606a5020STejun Heo }
3427db700897SOleg Nesterov EXPORT_SYMBOL_GPL(flush_work);
3428db700897SOleg Nesterov
34298603e1b3STejun Heo struct cwt_wait {
3430ac6424b9SIngo Molnar wait_queue_entry_t wait;
34318603e1b3STejun Heo struct work_struct *work;
34328603e1b3STejun Heo };
34338603e1b3STejun Heo
cwt_wakefn(wait_queue_entry_t * wait,unsigned mode,int sync,void * key)3434ac6424b9SIngo Molnar static int cwt_wakefn(wait_queue_entry_t *wait, unsigned mode, int sync, void *key)
34358603e1b3STejun Heo {
34368603e1b3STejun Heo struct cwt_wait *cwait = container_of(wait, struct cwt_wait, wait);
34378603e1b3STejun Heo
34388603e1b3STejun Heo if (cwait->work != key)
34398603e1b3STejun Heo return 0;
34408603e1b3STejun Heo return autoremove_wake_function(wait, mode, sync, key);
34418603e1b3STejun Heo }
34428603e1b3STejun Heo
__cancel_work_timer(struct work_struct * work,bool is_dwork)344336e227d2STejun Heo static bool __cancel_work_timer(struct work_struct *work, bool is_dwork)
3444401a8d04STejun Heo {
34458603e1b3STejun Heo static DECLARE_WAIT_QUEUE_HEAD(cancel_waitq);
3446bbb68dfaSTejun Heo unsigned long flags;
34471f1f642eSOleg Nesterov int ret;
34481f1f642eSOleg Nesterov
34491f1f642eSOleg Nesterov do {
3450bbb68dfaSTejun Heo ret = try_to_grab_pending(work, is_dwork, &flags);
3451bbb68dfaSTejun Heo /*
34528603e1b3STejun Heo * If someone else is already canceling, wait for it to
34538603e1b3STejun Heo * finish. flush_work() doesn't work for PREEMPT_NONE
34548603e1b3STejun Heo * because we may get scheduled between @work's completion
34558603e1b3STejun Heo * and the other canceling task resuming and clearing
34568603e1b3STejun Heo * CANCELING - flush_work() will return false immediately
34578603e1b3STejun Heo * as @work is no longer busy, try_to_grab_pending() will
34588603e1b3STejun Heo * return -ENOENT as @work is still being canceled and the
34598603e1b3STejun Heo * other canceling task won't be able to clear CANCELING as
34608603e1b3STejun Heo * we're hogging the CPU.
34618603e1b3STejun Heo *
34628603e1b3STejun Heo * Let's wait for completion using a waitqueue. As this
34638603e1b3STejun Heo * may lead to the thundering herd problem, use a custom
34648603e1b3STejun Heo * wake function which matches @work along with exclusive
34658603e1b3STejun Heo * wait and wakeup.
3466bbb68dfaSTejun Heo */
34678603e1b3STejun Heo if (unlikely(ret == -ENOENT)) {
34688603e1b3STejun Heo struct cwt_wait cwait;
34698603e1b3STejun Heo
34708603e1b3STejun Heo init_wait(&cwait.wait);
34718603e1b3STejun Heo cwait.wait.func = cwt_wakefn;
34728603e1b3STejun Heo cwait.work = work;
34738603e1b3STejun Heo
34748603e1b3STejun Heo prepare_to_wait_exclusive(&cancel_waitq, &cwait.wait,
34758603e1b3STejun Heo TASK_UNINTERRUPTIBLE);
34768603e1b3STejun Heo if (work_is_canceling(work))
34778603e1b3STejun Heo schedule();
34788603e1b3STejun Heo finish_wait(&cancel_waitq, &cwait.wait);
34798603e1b3STejun Heo }
34801f1f642eSOleg Nesterov } while (unlikely(ret < 0));
34811f1f642eSOleg Nesterov
3482bbb68dfaSTejun Heo /* tell other tasks trying to grab @work to back off */
3483bbb68dfaSTejun Heo mark_work_canceling(work);
3484bbb68dfaSTejun Heo local_irq_restore(flags);
3485bbb68dfaSTejun Heo
34863347fa09STejun Heo /*
34873347fa09STejun Heo * This allows canceling during early boot. We know that @work
34883347fa09STejun Heo * isn't executing.
34893347fa09STejun Heo */
34903347fa09STejun Heo if (wq_online)
3491d6e89786SJohannes Berg __flush_work(work, true);
34923347fa09STejun Heo
34937a22ad75STejun Heo clear_work_data(work);
34948603e1b3STejun Heo
34958603e1b3STejun Heo /*
34968603e1b3STejun Heo * Paired with prepare_to_wait() above so that either
34978603e1b3STejun Heo * waitqueue_active() is visible here or !work_is_canceling() is
34988603e1b3STejun Heo * visible there.
34998603e1b3STejun Heo */
35008603e1b3STejun Heo smp_mb();
35018603e1b3STejun Heo if (waitqueue_active(&cancel_waitq))
35028603e1b3STejun Heo __wake_up(&cancel_waitq, TASK_NORMAL, 1, work);
35038603e1b3STejun Heo
35041f1f642eSOleg Nesterov return ret;
35051f1f642eSOleg Nesterov }
35061f1f642eSOleg Nesterov
35076e84d644SOleg Nesterov /**
3508401a8d04STejun Heo * cancel_work_sync - cancel a work and wait for it to finish
3509401a8d04STejun Heo * @work: the work to cancel
35106e84d644SOleg Nesterov *
3511401a8d04STejun Heo * Cancel @work and wait for its execution to finish. This function
3512401a8d04STejun Heo * can be used even if the work re-queues itself or migrates to
3513401a8d04STejun Heo * another workqueue. On return from this function, @work is
3514401a8d04STejun Heo * guaranteed to be not pending or executing on any CPU.
35151f1f642eSOleg Nesterov *
3516401a8d04STejun Heo * cancel_work_sync(&delayed_work->work) must not be used for
3517401a8d04STejun Heo * delayed_work's. Use cancel_delayed_work_sync() instead.
35186e84d644SOleg Nesterov *
3519401a8d04STejun Heo * The caller must ensure that the workqueue on which @work was last
35206e84d644SOleg Nesterov * queued can't be destroyed before this function returns.
3521401a8d04STejun Heo *
3522d185af30SYacine Belkadi * Return:
3523401a8d04STejun Heo * %true if @work was pending, %false otherwise.
35246e84d644SOleg Nesterov */
cancel_work_sync(struct work_struct * work)3525401a8d04STejun Heo bool cancel_work_sync(struct work_struct *work)
35266e84d644SOleg Nesterov {
352736e227d2STejun Heo return __cancel_work_timer(work, false);
3528b89deed3SOleg Nesterov }
352928e53bddSOleg Nesterov EXPORT_SYMBOL_GPL(cancel_work_sync);
3530b89deed3SOleg Nesterov
35316e84d644SOleg Nesterov /**
3532401a8d04STejun Heo * flush_delayed_work - wait for a dwork to finish executing the last queueing
3533401a8d04STejun Heo * @dwork: the delayed work to flush
35346e84d644SOleg Nesterov *
3535401a8d04STejun Heo * Delayed timer is cancelled and the pending work is queued for
3536401a8d04STejun Heo * immediate execution. Like flush_work(), this function only
3537401a8d04STejun Heo * considers the last queueing instance of @dwork.
35381f1f642eSOleg Nesterov *
3539d185af30SYacine Belkadi * Return:
3540401a8d04STejun Heo * %true if flush_work() waited for the work to finish execution,
3541401a8d04STejun Heo * %false if it was already idle.
35426e84d644SOleg Nesterov */
flush_delayed_work(struct delayed_work * dwork)3543401a8d04STejun Heo bool flush_delayed_work(struct delayed_work *dwork)
3544401a8d04STejun Heo {
35458930cabaSTejun Heo local_irq_disable();
3546401a8d04STejun Heo if (del_timer_sync(&dwork->timer))
354760c057bcSLai Jiangshan __queue_work(dwork->cpu, dwork->wq, &dwork->work);
35488930cabaSTejun Heo local_irq_enable();
3549401a8d04STejun Heo return flush_work(&dwork->work);
3550401a8d04STejun Heo }
3551401a8d04STejun Heo EXPORT_SYMBOL(flush_delayed_work);
3552401a8d04STejun Heo
355305f0fe6bSTejun Heo /**
355405f0fe6bSTejun Heo * flush_rcu_work - wait for a rwork to finish executing the last queueing
355505f0fe6bSTejun Heo * @rwork: the rcu work to flush
355605f0fe6bSTejun Heo *
355705f0fe6bSTejun Heo * Return:
355805f0fe6bSTejun Heo * %true if flush_rcu_work() waited for the work to finish execution,
355905f0fe6bSTejun Heo * %false if it was already idle.
356005f0fe6bSTejun Heo */
flush_rcu_work(struct rcu_work * rwork)356105f0fe6bSTejun Heo bool flush_rcu_work(struct rcu_work *rwork)
356205f0fe6bSTejun Heo {
356305f0fe6bSTejun Heo if (test_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&rwork->work))) {
356405f0fe6bSTejun Heo rcu_barrier();
356505f0fe6bSTejun Heo flush_work(&rwork->work);
356605f0fe6bSTejun Heo return true;
356705f0fe6bSTejun Heo } else {
356805f0fe6bSTejun Heo return flush_work(&rwork->work);
356905f0fe6bSTejun Heo }
357005f0fe6bSTejun Heo }
357105f0fe6bSTejun Heo EXPORT_SYMBOL(flush_rcu_work);
357205f0fe6bSTejun Heo
__cancel_work(struct work_struct * work,bool is_dwork)3573f72b8792SJens Axboe static bool __cancel_work(struct work_struct *work, bool is_dwork)
3574f72b8792SJens Axboe {
3575f72b8792SJens Axboe unsigned long flags;
3576f72b8792SJens Axboe int ret;
3577f72b8792SJens Axboe
3578f72b8792SJens Axboe do {
3579f72b8792SJens Axboe ret = try_to_grab_pending(work, is_dwork, &flags);
3580f72b8792SJens Axboe } while (unlikely(ret == -EAGAIN));
3581f72b8792SJens Axboe
3582f72b8792SJens Axboe if (unlikely(ret < 0))
3583f72b8792SJens Axboe return false;
3584f72b8792SJens Axboe
3585f72b8792SJens Axboe set_work_pool_and_clear_pending(work, get_work_pool_id(work));
3586f72b8792SJens Axboe local_irq_restore(flags);
3587f72b8792SJens Axboe return ret;
3588f72b8792SJens Axboe }
3589f72b8792SJens Axboe
359073b4b532SAndrey Grodzovsky /*
359173b4b532SAndrey Grodzovsky * See cancel_delayed_work()
359273b4b532SAndrey Grodzovsky */
cancel_work(struct work_struct * work)359373b4b532SAndrey Grodzovsky bool cancel_work(struct work_struct *work)
359473b4b532SAndrey Grodzovsky {
359573b4b532SAndrey Grodzovsky return __cancel_work(work, false);
359673b4b532SAndrey Grodzovsky }
359773b4b532SAndrey Grodzovsky EXPORT_SYMBOL(cancel_work);
359873b4b532SAndrey Grodzovsky
3599401a8d04STejun Heo /**
360057b30ae7STejun Heo * cancel_delayed_work - cancel a delayed work
360157b30ae7STejun Heo * @dwork: delayed_work to cancel
360209383498STejun Heo *
3603d185af30SYacine Belkadi * Kill off a pending delayed_work.
3604d185af30SYacine Belkadi *
3605d185af30SYacine Belkadi * Return: %true if @dwork was pending and canceled; %false if it wasn't
3606d185af30SYacine Belkadi * pending.
3607d185af30SYacine Belkadi *
3608d185af30SYacine Belkadi * Note:
3609d185af30SYacine Belkadi * The work callback function may still be running on return, unless
3610d185af30SYacine Belkadi * it returns %true and the work doesn't re-arm itself. Explicitly flush or
3611d185af30SYacine Belkadi * use cancel_delayed_work_sync() to wait on it.
361209383498STejun Heo *
361357b30ae7STejun Heo * This function is safe to call from any context including IRQ handler.
361409383498STejun Heo */
cancel_delayed_work(struct delayed_work * dwork)361557b30ae7STejun Heo bool cancel_delayed_work(struct delayed_work *dwork)
361609383498STejun Heo {
3617f72b8792SJens Axboe return __cancel_work(&dwork->work, true);
361809383498STejun Heo }
361957b30ae7STejun Heo EXPORT_SYMBOL(cancel_delayed_work);
362009383498STejun Heo
362109383498STejun Heo /**
3622401a8d04STejun Heo * cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
3623401a8d04STejun Heo * @dwork: the delayed work cancel
3624401a8d04STejun Heo *
3625401a8d04STejun Heo * This is cancel_work_sync() for delayed works.
3626401a8d04STejun Heo *
3627d185af30SYacine Belkadi * Return:
3628401a8d04STejun Heo * %true if @dwork was pending, %false otherwise.
3629401a8d04STejun Heo */
cancel_delayed_work_sync(struct delayed_work * dwork)3630401a8d04STejun Heo bool cancel_delayed_work_sync(struct delayed_work *dwork)
36316e84d644SOleg Nesterov {
363236e227d2STejun Heo return __cancel_work_timer(&dwork->work, true);
36336e84d644SOleg Nesterov }
3634f5a421a4SOleg Nesterov EXPORT_SYMBOL(cancel_delayed_work_sync);
36351da177e4SLinus Torvalds
36360fcb78c2SRolf Eike Beer /**
363731ddd871STejun Heo * schedule_on_each_cpu - execute a function synchronously on each online CPU
3638b6136773SAndrew Morton * @func: the function to call
3639b6136773SAndrew Morton *
364031ddd871STejun Heo * schedule_on_each_cpu() executes @func on each online CPU using the
364131ddd871STejun Heo * system workqueue and blocks until all CPUs have completed.
3642b6136773SAndrew Morton * schedule_on_each_cpu() is very slow.
364331ddd871STejun Heo *
3644d185af30SYacine Belkadi * Return:
364531ddd871STejun Heo * 0 on success, -errno on failure.
3646b6136773SAndrew Morton */
schedule_on_each_cpu(work_func_t func)364765f27f38SDavid Howells int schedule_on_each_cpu(work_func_t func)
364815316ba8SChristoph Lameter {
364915316ba8SChristoph Lameter int cpu;
365038f51568SNamhyung Kim struct work_struct __percpu *works;
365115316ba8SChristoph Lameter
3652b6136773SAndrew Morton works = alloc_percpu(struct work_struct);
3653b6136773SAndrew Morton if (!works)
365415316ba8SChristoph Lameter return -ENOMEM;
3655b6136773SAndrew Morton
3656ffd8bea8SSebastian Andrzej Siewior cpus_read_lock();
365793981800STejun Heo
365815316ba8SChristoph Lameter for_each_online_cpu(cpu) {
36599bfb1839SIngo Molnar struct work_struct *work = per_cpu_ptr(works, cpu);
36609bfb1839SIngo Molnar
36619bfb1839SIngo Molnar INIT_WORK(work, func);
36628de6d308SOleg Nesterov schedule_work_on(cpu, work);
366315316ba8SChristoph Lameter }
366493981800STejun Heo
366593981800STejun Heo for_each_online_cpu(cpu)
36668616a89aSOleg Nesterov flush_work(per_cpu_ptr(works, cpu));
366793981800STejun Heo
3668ffd8bea8SSebastian Andrzej Siewior cpus_read_unlock();
3669b6136773SAndrew Morton free_percpu(works);
367015316ba8SChristoph Lameter return 0;
367115316ba8SChristoph Lameter }
367215316ba8SChristoph Lameter
3673eef6a7d5SAlan Stern /**
36741fa44ecaSJames Bottomley * execute_in_process_context - reliably execute the routine with user context
36751fa44ecaSJames Bottomley * @fn: the function to execute
36761fa44ecaSJames Bottomley * @ew: guaranteed storage for the execute work structure (must
36771fa44ecaSJames Bottomley * be available when the work executes)
36781fa44ecaSJames Bottomley *
36791fa44ecaSJames Bottomley * Executes the function immediately if process context is available,
36801fa44ecaSJames Bottomley * otherwise schedules the function for delayed execution.
36811fa44ecaSJames Bottomley *
3682d185af30SYacine Belkadi * Return: 0 - function was executed
36831fa44ecaSJames Bottomley * 1 - function was scheduled for execution
36841fa44ecaSJames Bottomley */
execute_in_process_context(work_func_t fn,struct execute_work * ew)368565f27f38SDavid Howells int execute_in_process_context(work_func_t fn, struct execute_work *ew)
36861fa44ecaSJames Bottomley {
36871fa44ecaSJames Bottomley if (!in_interrupt()) {
368865f27f38SDavid Howells fn(&ew->work);
36891fa44ecaSJames Bottomley return 0;
36901fa44ecaSJames Bottomley }
36911fa44ecaSJames Bottomley
369265f27f38SDavid Howells INIT_WORK(&ew->work, fn);
36931fa44ecaSJames Bottomley schedule_work(&ew->work);
36941fa44ecaSJames Bottomley
36951fa44ecaSJames Bottomley return 1;
36961fa44ecaSJames Bottomley }
36971fa44ecaSJames Bottomley EXPORT_SYMBOL_GPL(execute_in_process_context);
36981fa44ecaSJames Bottomley
36997a4e344cSTejun Heo /**
37007a4e344cSTejun Heo * free_workqueue_attrs - free a workqueue_attrs
37017a4e344cSTejun Heo * @attrs: workqueue_attrs to free
37027a4e344cSTejun Heo *
37037a4e344cSTejun Heo * Undo alloc_workqueue_attrs().
37047a4e344cSTejun Heo */
free_workqueue_attrs(struct workqueue_attrs * attrs)3705513c98d0SDaniel Jordan void free_workqueue_attrs(struct workqueue_attrs *attrs)
37067a4e344cSTejun Heo {
37077a4e344cSTejun Heo if (attrs) {
37087a4e344cSTejun Heo free_cpumask_var(attrs->cpumask);
37099546b29eSTejun Heo free_cpumask_var(attrs->__pod_cpumask);
37107a4e344cSTejun Heo kfree(attrs);
37117a4e344cSTejun Heo }
37127a4e344cSTejun Heo }
37137a4e344cSTejun Heo
37147a4e344cSTejun Heo /**
37157a4e344cSTejun Heo * alloc_workqueue_attrs - allocate a workqueue_attrs
37167a4e344cSTejun Heo *
37177a4e344cSTejun Heo * Allocate a new workqueue_attrs, initialize with default settings and
3718d185af30SYacine Belkadi * return it.
3719d185af30SYacine Belkadi *
3720d185af30SYacine Belkadi * Return: The allocated new workqueue_attr on success. %NULL on failure.
37217a4e344cSTejun Heo */
alloc_workqueue_attrs(void)3722513c98d0SDaniel Jordan struct workqueue_attrs *alloc_workqueue_attrs(void)
37237a4e344cSTejun Heo {
37247a4e344cSTejun Heo struct workqueue_attrs *attrs;
37257a4e344cSTejun Heo
3726be69d00dSThomas Gleixner attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
37277a4e344cSTejun Heo if (!attrs)
37287a4e344cSTejun Heo goto fail;
3729be69d00dSThomas Gleixner if (!alloc_cpumask_var(&attrs->cpumask, GFP_KERNEL))
37307a4e344cSTejun Heo goto fail;
37319546b29eSTejun Heo if (!alloc_cpumask_var(&attrs->__pod_cpumask, GFP_KERNEL))
37329546b29eSTejun Heo goto fail;
37337a4e344cSTejun Heo
373413e2e556STejun Heo cpumask_copy(attrs->cpumask, cpu_possible_mask);
3735523a301eSTejun Heo attrs->affn_scope = WQ_AFFN_DFL;
37367a4e344cSTejun Heo return attrs;
37377a4e344cSTejun Heo fail:
37387a4e344cSTejun Heo free_workqueue_attrs(attrs);
37397a4e344cSTejun Heo return NULL;
37407a4e344cSTejun Heo }
37417a4e344cSTejun Heo
copy_workqueue_attrs(struct workqueue_attrs * to,const struct workqueue_attrs * from)374229c91e99STejun Heo static void copy_workqueue_attrs(struct workqueue_attrs *to,
374329c91e99STejun Heo const struct workqueue_attrs *from)
374429c91e99STejun Heo {
374529c91e99STejun Heo to->nice = from->nice;
374629c91e99STejun Heo cpumask_copy(to->cpumask, from->cpumask);
37479546b29eSTejun Heo cpumask_copy(to->__pod_cpumask, from->__pod_cpumask);
37488639ecebSTejun Heo to->affn_strict = from->affn_strict;
374984193c07STejun Heo
37502865a8fbSShaohua Li /*
375184193c07STejun Heo * Unlike hash and equality test, copying shouldn't ignore wq-only
375284193c07STejun Heo * fields as copying is used for both pool and wq attrs. Instead,
375384193c07STejun Heo * get_unbound_pool() explicitly clears the fields.
37542865a8fbSShaohua Li */
375584193c07STejun Heo to->affn_scope = from->affn_scope;
3756af73f5c9STejun Heo to->ordered = from->ordered;
375729c91e99STejun Heo }
375829c91e99STejun Heo
37595de7a03cSTejun Heo /*
37605de7a03cSTejun Heo * Some attrs fields are workqueue-only. Clear them for worker_pool's. See the
37615de7a03cSTejun Heo * comments in 'struct workqueue_attrs' definition.
37625de7a03cSTejun Heo */
wqattrs_clear_for_pool(struct workqueue_attrs * attrs)37635de7a03cSTejun Heo static void wqattrs_clear_for_pool(struct workqueue_attrs *attrs)
37645de7a03cSTejun Heo {
376584193c07STejun Heo attrs->affn_scope = WQ_AFFN_NR_TYPES;
37665de7a03cSTejun Heo attrs->ordered = false;
37675de7a03cSTejun Heo }
37685de7a03cSTejun Heo
376929c91e99STejun Heo /* hash value of the content of @attr */
wqattrs_hash(const struct workqueue_attrs * attrs)377029c91e99STejun Heo static u32 wqattrs_hash(const struct workqueue_attrs *attrs)
377129c91e99STejun Heo {
377229c91e99STejun Heo u32 hash = 0;
377329c91e99STejun Heo
377429c91e99STejun Heo hash = jhash_1word(attrs->nice, hash);
377513e2e556STejun Heo hash = jhash(cpumask_bits(attrs->cpumask),
377613e2e556STejun Heo BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
37779546b29eSTejun Heo hash = jhash(cpumask_bits(attrs->__pod_cpumask),
37789546b29eSTejun Heo BITS_TO_LONGS(nr_cpumask_bits) * sizeof(long), hash);
37798639ecebSTejun Heo hash = jhash_1word(attrs->affn_strict, hash);
378029c91e99STejun Heo return hash;
378129c91e99STejun Heo }
378229c91e99STejun Heo
378329c91e99STejun Heo /* content equality test */
wqattrs_equal(const struct workqueue_attrs * a,const struct workqueue_attrs * b)378429c91e99STejun Heo static bool wqattrs_equal(const struct workqueue_attrs *a,
378529c91e99STejun Heo const struct workqueue_attrs *b)
378629c91e99STejun Heo {
378729c91e99STejun Heo if (a->nice != b->nice)
378829c91e99STejun Heo return false;
378929c91e99STejun Heo if (!cpumask_equal(a->cpumask, b->cpumask))
379029c91e99STejun Heo return false;
37919546b29eSTejun Heo if (!cpumask_equal(a->__pod_cpumask, b->__pod_cpumask))
37929546b29eSTejun Heo return false;
37938639ecebSTejun Heo if (a->affn_strict != b->affn_strict)
37948639ecebSTejun Heo return false;
379529c91e99STejun Heo return true;
379629c91e99STejun Heo }
379729c91e99STejun Heo
37980f36ee24STejun Heo /* Update @attrs with actually available CPUs */
wqattrs_actualize_cpumask(struct workqueue_attrs * attrs,const cpumask_t * unbound_cpumask)37990f36ee24STejun Heo static void wqattrs_actualize_cpumask(struct workqueue_attrs *attrs,
38000f36ee24STejun Heo const cpumask_t *unbound_cpumask)
38010f36ee24STejun Heo {
38020f36ee24STejun Heo /*
38030f36ee24STejun Heo * Calculate the effective CPU mask of @attrs given @unbound_cpumask. If
38040f36ee24STejun Heo * @attrs->cpumask doesn't overlap with @unbound_cpumask, we fallback to
38050f36ee24STejun Heo * @unbound_cpumask.
38060f36ee24STejun Heo */
38070f36ee24STejun Heo cpumask_and(attrs->cpumask, attrs->cpumask, unbound_cpumask);
38080f36ee24STejun Heo if (unlikely(cpumask_empty(attrs->cpumask)))
38090f36ee24STejun Heo cpumask_copy(attrs->cpumask, unbound_cpumask);
38100f36ee24STejun Heo }
38110f36ee24STejun Heo
381284193c07STejun Heo /* find wq_pod_type to use for @attrs */
381384193c07STejun Heo static const struct wq_pod_type *
wqattrs_pod_type(const struct workqueue_attrs * attrs)381484193c07STejun Heo wqattrs_pod_type(const struct workqueue_attrs *attrs)
381584193c07STejun Heo {
3816523a301eSTejun Heo enum wq_affn_scope scope;
3817523a301eSTejun Heo struct wq_pod_type *pt;
3818523a301eSTejun Heo
3819523a301eSTejun Heo /* to synchronize access to wq_affn_dfl */
3820523a301eSTejun Heo lockdep_assert_held(&wq_pool_mutex);
3821523a301eSTejun Heo
3822523a301eSTejun Heo if (attrs->affn_scope == WQ_AFFN_DFL)
3823523a301eSTejun Heo scope = wq_affn_dfl;
3824523a301eSTejun Heo else
3825523a301eSTejun Heo scope = attrs->affn_scope;
3826523a301eSTejun Heo
3827523a301eSTejun Heo pt = &wq_pod_types[scope];
382884193c07STejun Heo
382984193c07STejun Heo if (!WARN_ON_ONCE(attrs->affn_scope == WQ_AFFN_NR_TYPES) &&
383084193c07STejun Heo likely(pt->nr_pods))
383184193c07STejun Heo return pt;
383284193c07STejun Heo
383384193c07STejun Heo /*
383484193c07STejun Heo * Before workqueue_init_topology(), only SYSTEM is available which is
383584193c07STejun Heo * initialized in workqueue_init_early().
383684193c07STejun Heo */
383784193c07STejun Heo pt = &wq_pod_types[WQ_AFFN_SYSTEM];
383884193c07STejun Heo BUG_ON(!pt->nr_pods);
383984193c07STejun Heo return pt;
384084193c07STejun Heo }
384184193c07STejun Heo
38427a4e344cSTejun Heo /**
38437a4e344cSTejun Heo * init_worker_pool - initialize a newly zalloc'd worker_pool
38447a4e344cSTejun Heo * @pool: worker_pool to initialize
38457a4e344cSTejun Heo *
3846402dd89dSShailendra Verma * Initialize a newly zalloc'd @pool. It also allocates @pool->attrs.
3847d185af30SYacine Belkadi *
3848d185af30SYacine Belkadi * Return: 0 on success, -errno on failure. Even on failure, all fields
384929c91e99STejun Heo * inside @pool proper are initialized and put_unbound_pool() can be called
385029c91e99STejun Heo * on @pool safely to release it.
38517a4e344cSTejun Heo */
init_worker_pool(struct worker_pool * pool)38527a4e344cSTejun Heo static int init_worker_pool(struct worker_pool *pool)
38534e1a1f9aSTejun Heo {
3854a9b8a985SSebastian Andrzej Siewior raw_spin_lock_init(&pool->lock);
385529c91e99STejun Heo pool->id = -1;
385629c91e99STejun Heo pool->cpu = -1;
3857f3f90ad4STejun Heo pool->node = NUMA_NO_NODE;
38584e1a1f9aSTejun Heo pool->flags |= POOL_DISASSOCIATED;
385982607adcSTejun Heo pool->watchdog_ts = jiffies;
38604e1a1f9aSTejun Heo INIT_LIST_HEAD(&pool->worklist);
38614e1a1f9aSTejun Heo INIT_LIST_HEAD(&pool->idle_list);
38624e1a1f9aSTejun Heo hash_init(pool->busy_hash);
38634e1a1f9aSTejun Heo
386432a6c723SKees Cook timer_setup(&pool->idle_timer, idle_worker_timeout, TIMER_DEFERRABLE);
38653f959aa3SValentin Schneider INIT_WORK(&pool->idle_cull_work, idle_cull_fn);
38664e1a1f9aSTejun Heo
386732a6c723SKees Cook timer_setup(&pool->mayday_timer, pool_mayday_timeout, 0);
38684e1a1f9aSTejun Heo
3869da028469SLai Jiangshan INIT_LIST_HEAD(&pool->workers);
3870e02b9312SValentin Schneider INIT_LIST_HEAD(&pool->dying_workers);
38717a4e344cSTejun Heo
38727cda9aaeSLai Jiangshan ida_init(&pool->worker_ida);
387329c91e99STejun Heo INIT_HLIST_NODE(&pool->hash_node);
387429c91e99STejun Heo pool->refcnt = 1;
387529c91e99STejun Heo
387629c91e99STejun Heo /* shouldn't fail above this point */
3877be69d00dSThomas Gleixner pool->attrs = alloc_workqueue_attrs();
38787a4e344cSTejun Heo if (!pool->attrs)
38797a4e344cSTejun Heo return -ENOMEM;
38805de7a03cSTejun Heo
38815de7a03cSTejun Heo wqattrs_clear_for_pool(pool->attrs);
38825de7a03cSTejun Heo
38837a4e344cSTejun Heo return 0;
38844e1a1f9aSTejun Heo }
38854e1a1f9aSTejun Heo
3886669de8bdSBart Van Assche #ifdef CONFIG_LOCKDEP
wq_init_lockdep(struct workqueue_struct * wq)3887669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3888669de8bdSBart Van Assche {
3889669de8bdSBart Van Assche char *lock_name;
3890669de8bdSBart Van Assche
3891669de8bdSBart Van Assche lockdep_register_key(&wq->key);
3892669de8bdSBart Van Assche lock_name = kasprintf(GFP_KERNEL, "%s%s", "(wq_completion)", wq->name);
3893669de8bdSBart Van Assche if (!lock_name)
3894669de8bdSBart Van Assche lock_name = wq->name;
389569a106c0SQian Cai
389669a106c0SQian Cai wq->lock_name = lock_name;
3897669de8bdSBart Van Assche lockdep_init_map(&wq->lockdep_map, lock_name, &wq->key, 0);
3898669de8bdSBart Van Assche }
3899669de8bdSBart Van Assche
wq_unregister_lockdep(struct workqueue_struct * wq)3900669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3901669de8bdSBart Van Assche {
3902669de8bdSBart Van Assche lockdep_unregister_key(&wq->key);
3903669de8bdSBart Van Assche }
3904669de8bdSBart Van Assche
wq_free_lockdep(struct workqueue_struct * wq)3905669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3906669de8bdSBart Van Assche {
3907669de8bdSBart Van Assche if (wq->lock_name != wq->name)
3908669de8bdSBart Van Assche kfree(wq->lock_name);
3909669de8bdSBart Van Assche }
3910669de8bdSBart Van Assche #else
wq_init_lockdep(struct workqueue_struct * wq)3911669de8bdSBart Van Assche static void wq_init_lockdep(struct workqueue_struct *wq)
3912669de8bdSBart Van Assche {
3913669de8bdSBart Van Assche }
3914669de8bdSBart Van Assche
wq_unregister_lockdep(struct workqueue_struct * wq)3915669de8bdSBart Van Assche static void wq_unregister_lockdep(struct workqueue_struct *wq)
3916669de8bdSBart Van Assche {
3917669de8bdSBart Van Assche }
3918669de8bdSBart Van Assche
wq_free_lockdep(struct workqueue_struct * wq)3919669de8bdSBart Van Assche static void wq_free_lockdep(struct workqueue_struct *wq)
3920669de8bdSBart Van Assche {
3921669de8bdSBart Van Assche }
3922669de8bdSBart Van Assche #endif
3923669de8bdSBart Van Assche
rcu_free_wq(struct rcu_head * rcu)3924e2dca7adSTejun Heo static void rcu_free_wq(struct rcu_head *rcu)
3925e2dca7adSTejun Heo {
3926e2dca7adSTejun Heo struct workqueue_struct *wq =
3927e2dca7adSTejun Heo container_of(rcu, struct workqueue_struct, rcu);
3928e2dca7adSTejun Heo
3929669de8bdSBart Van Assche wq_free_lockdep(wq);
3930ee1ceef7STejun Heo free_percpu(wq->cpu_pwq);
3931e2dca7adSTejun Heo free_workqueue_attrs(wq->unbound_attrs);
3932e2dca7adSTejun Heo kfree(wq);
3933e2dca7adSTejun Heo }
3934e2dca7adSTejun Heo
rcu_free_pool(struct rcu_head * rcu)393529c91e99STejun Heo static void rcu_free_pool(struct rcu_head *rcu)
393629c91e99STejun Heo {
393729c91e99STejun Heo struct worker_pool *pool = container_of(rcu, struct worker_pool, rcu);
393829c91e99STejun Heo
39397cda9aaeSLai Jiangshan ida_destroy(&pool->worker_ida);
394029c91e99STejun Heo free_workqueue_attrs(pool->attrs);
394129c91e99STejun Heo kfree(pool);
394229c91e99STejun Heo }
394329c91e99STejun Heo
394429c91e99STejun Heo /**
394529c91e99STejun Heo * put_unbound_pool - put a worker_pool
394629c91e99STejun Heo * @pool: worker_pool to put
394729c91e99STejun Heo *
394824acfb71SThomas Gleixner * Put @pool. If its refcnt reaches zero, it gets destroyed in RCU
3949c5aa87bbSTejun Heo * safe manner. get_unbound_pool() calls this function on its failure path
3950c5aa87bbSTejun Heo * and this function should be able to release pools which went through,
3951c5aa87bbSTejun Heo * successfully or not, init_worker_pool().
3952a892caccSTejun Heo *
3953a892caccSTejun Heo * Should be called with wq_pool_mutex held.
395429c91e99STejun Heo */
put_unbound_pool(struct worker_pool * pool)395529c91e99STejun Heo static void put_unbound_pool(struct worker_pool *pool)
395629c91e99STejun Heo {
395760f5a4bcSLai Jiangshan DECLARE_COMPLETION_ONSTACK(detach_completion);
395829c91e99STejun Heo struct worker *worker;
39599680540cSYang Yingliang LIST_HEAD(cull_list);
3960e02b9312SValentin Schneider
3961a892caccSTejun Heo lockdep_assert_held(&wq_pool_mutex);
3962a892caccSTejun Heo
3963a892caccSTejun Heo if (--pool->refcnt)
396429c91e99STejun Heo return;
396529c91e99STejun Heo
396629c91e99STejun Heo /* sanity checks */
396761d0fbb4SLai Jiangshan if (WARN_ON(!(pool->cpu < 0)) ||
3968a892caccSTejun Heo WARN_ON(!list_empty(&pool->worklist)))
396929c91e99STejun Heo return;
397029c91e99STejun Heo
397129c91e99STejun Heo /* release id and unhash */
397229c91e99STejun Heo if (pool->id >= 0)
397329c91e99STejun Heo idr_remove(&worker_pool_idr, pool->id);
397429c91e99STejun Heo hash_del(&pool->hash_node);
397529c91e99STejun Heo
3976c5aa87bbSTejun Heo /*
3977692b4825STejun Heo * Become the manager and destroy all workers. This prevents
3978692b4825STejun Heo * @pool's workers from blocking on attach_mutex. We're the last
3979692b4825STejun Heo * manager and @pool gets freed with the flag set.
39809ab03be4SValentin Schneider *
39819ab03be4SValentin Schneider * Having a concurrent manager is quite unlikely to happen as we can
39829ab03be4SValentin Schneider * only get here with
39839ab03be4SValentin Schneider * pwq->refcnt == pool->refcnt == 0
39849ab03be4SValentin Schneider * which implies no work queued to the pool, which implies no worker can
39859ab03be4SValentin Schneider * become the manager. However a worker could have taken the role of
39869ab03be4SValentin Schneider * manager before the refcnts dropped to 0, since maybe_create_worker()
39879ab03be4SValentin Schneider * drops pool->lock
3988c5aa87bbSTejun Heo */
39899ab03be4SValentin Schneider while (true) {
39909ab03be4SValentin Schneider rcuwait_wait_event(&manager_wait,
39919ab03be4SValentin Schneider !(pool->flags & POOL_MANAGER_ACTIVE),
3992d8bb65abSSebastian Andrzej Siewior TASK_UNINTERRUPTIBLE);
3993e02b9312SValentin Schneider
3994e02b9312SValentin Schneider mutex_lock(&wq_pool_attach_mutex);
39959ab03be4SValentin Schneider raw_spin_lock_irq(&pool->lock);
39969ab03be4SValentin Schneider if (!(pool->flags & POOL_MANAGER_ACTIVE)) {
3997692b4825STejun Heo pool->flags |= POOL_MANAGER_ACTIVE;
39989ab03be4SValentin Schneider break;
39999ab03be4SValentin Schneider }
40009ab03be4SValentin Schneider raw_spin_unlock_irq(&pool->lock);
4001e02b9312SValentin Schneider mutex_unlock(&wq_pool_attach_mutex);
40029ab03be4SValentin Schneider }
4003692b4825STejun Heo
40041037de36SLai Jiangshan while ((worker = first_idle_worker(pool)))
4005e02b9312SValentin Schneider set_worker_dying(worker, &cull_list);
400629c91e99STejun Heo WARN_ON(pool->nr_workers || pool->nr_idle);
4007a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
400860f5a4bcSLai Jiangshan
4009e02b9312SValentin Schneider wake_dying_workers(&cull_list);
4010e02b9312SValentin Schneider
4011e02b9312SValentin Schneider if (!list_empty(&pool->workers) || !list_empty(&pool->dying_workers))
401260f5a4bcSLai Jiangshan pool->detach_completion = &detach_completion;
40131258fae7STejun Heo mutex_unlock(&wq_pool_attach_mutex);
401460f5a4bcSLai Jiangshan
401560f5a4bcSLai Jiangshan if (pool->detach_completion)
401660f5a4bcSLai Jiangshan wait_for_completion(pool->detach_completion);
401760f5a4bcSLai Jiangshan
401829c91e99STejun Heo /* shut down the timers */
401929c91e99STejun Heo del_timer_sync(&pool->idle_timer);
40203f959aa3SValentin Schneider cancel_work_sync(&pool->idle_cull_work);
402129c91e99STejun Heo del_timer_sync(&pool->mayday_timer);
402229c91e99STejun Heo
402324acfb71SThomas Gleixner /* RCU protected to allow dereferences from get_work_pool() */
402425b00775SPaul E. McKenney call_rcu(&pool->rcu, rcu_free_pool);
402529c91e99STejun Heo }
402629c91e99STejun Heo
402729c91e99STejun Heo /**
402829c91e99STejun Heo * get_unbound_pool - get a worker_pool with the specified attributes
402929c91e99STejun Heo * @attrs: the attributes of the worker_pool to get
403029c91e99STejun Heo *
403129c91e99STejun Heo * Obtain a worker_pool which has the same attributes as @attrs, bump the
403229c91e99STejun Heo * reference count and return it. If there already is a matching
403329c91e99STejun Heo * worker_pool, it will be used; otherwise, this function attempts to
4034d185af30SYacine Belkadi * create a new one.
4035a892caccSTejun Heo *
4036a892caccSTejun Heo * Should be called with wq_pool_mutex held.
4037d185af30SYacine Belkadi *
4038d185af30SYacine Belkadi * Return: On success, a worker_pool with the same attributes as @attrs.
4039d185af30SYacine Belkadi * On failure, %NULL.
404029c91e99STejun Heo */
get_unbound_pool(const struct workqueue_attrs * attrs)404129c91e99STejun Heo static struct worker_pool *get_unbound_pool(const struct workqueue_attrs *attrs)
404229c91e99STejun Heo {
404384193c07STejun Heo struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_NUMA];
404429c91e99STejun Heo u32 hash = wqattrs_hash(attrs);
404529c91e99STejun Heo struct worker_pool *pool;
404684193c07STejun Heo int pod, node = NUMA_NO_NODE;
404729c91e99STejun Heo
4048a892caccSTejun Heo lockdep_assert_held(&wq_pool_mutex);
404929c91e99STejun Heo
405029c91e99STejun Heo /* do we already have a matching pool? */
405129c91e99STejun Heo hash_for_each_possible(unbound_pool_hash, pool, hash_node, hash) {
405229c91e99STejun Heo if (wqattrs_equal(pool->attrs, attrs)) {
405329c91e99STejun Heo pool->refcnt++;
40543fb1823cSLai Jiangshan return pool;
405529c91e99STejun Heo }
405629c91e99STejun Heo }
405729c91e99STejun Heo
40589546b29eSTejun Heo /* If __pod_cpumask is contained inside a NUMA pod, that's our node */
405984193c07STejun Heo for (pod = 0; pod < pt->nr_pods; pod++) {
40609546b29eSTejun Heo if (cpumask_subset(attrs->__pod_cpumask, pt->pod_cpus[pod])) {
406184193c07STejun Heo node = pt->pod_node[pod];
4062e2273584SXunlei Pang break;
4063e2273584SXunlei Pang }
4064e2273584SXunlei Pang }
4065e2273584SXunlei Pang
406629c91e99STejun Heo /* nope, create a new one */
406784193c07STejun Heo pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, node);
406829c91e99STejun Heo if (!pool || init_worker_pool(pool) < 0)
406929c91e99STejun Heo goto fail;
407029c91e99STejun Heo
407184193c07STejun Heo pool->node = node;
40725de7a03cSTejun Heo copy_workqueue_attrs(pool->attrs, attrs);
40735de7a03cSTejun Heo wqattrs_clear_for_pool(pool->attrs);
40742865a8fbSShaohua Li
407529c91e99STejun Heo if (worker_pool_assign_id(pool) < 0)
407629c91e99STejun Heo goto fail;
407729c91e99STejun Heo
407829c91e99STejun Heo /* create and start the initial worker */
40793347fa09STejun Heo if (wq_online && !create_worker(pool))
408029c91e99STejun Heo goto fail;
408129c91e99STejun Heo
408229c91e99STejun Heo /* install */
408329c91e99STejun Heo hash_add(unbound_pool_hash, &pool->hash_node, hash);
40843fb1823cSLai Jiangshan
408529c91e99STejun Heo return pool;
408629c91e99STejun Heo fail:
408729c91e99STejun Heo if (pool)
408829c91e99STejun Heo put_unbound_pool(pool);
408929c91e99STejun Heo return NULL;
409029c91e99STejun Heo }
409129c91e99STejun Heo
rcu_free_pwq(struct rcu_head * rcu)40928864b4e5STejun Heo static void rcu_free_pwq(struct rcu_head *rcu)
40938864b4e5STejun Heo {
40948864b4e5STejun Heo kmem_cache_free(pwq_cache,
40958864b4e5STejun Heo container_of(rcu, struct pool_workqueue, rcu));
40968864b4e5STejun Heo }
40978864b4e5STejun Heo
40988864b4e5STejun Heo /*
4099967b494eSTejun Heo * Scheduled on pwq_release_worker by put_pwq() when an unbound pwq hits zero
4100967b494eSTejun Heo * refcnt and needs to be destroyed.
41018864b4e5STejun Heo */
pwq_release_workfn(struct kthread_work * work)4102687a9aa5STejun Heo static void pwq_release_workfn(struct kthread_work *work)
41038864b4e5STejun Heo {
41048864b4e5STejun Heo struct pool_workqueue *pwq = container_of(work, struct pool_workqueue,
4105687a9aa5STejun Heo release_work);
41068864b4e5STejun Heo struct workqueue_struct *wq = pwq->wq;
41078864b4e5STejun Heo struct worker_pool *pool = pwq->pool;
4108b42b0bddSYang Yingliang bool is_last = false;
41098864b4e5STejun Heo
4110b42b0bddSYang Yingliang /*
4111687a9aa5STejun Heo * When @pwq is not linked, it doesn't hold any reference to the
4112b42b0bddSYang Yingliang * @wq, and @wq is invalid to access.
4113b42b0bddSYang Yingliang */
4114b42b0bddSYang Yingliang if (!list_empty(&pwq->pwqs_node)) {
41153c25a55dSLai Jiangshan mutex_lock(&wq->mutex);
41168864b4e5STejun Heo list_del_rcu(&pwq->pwqs_node);
4117bc0caf09STejun Heo is_last = list_empty(&wq->pwqs);
41183c25a55dSLai Jiangshan mutex_unlock(&wq->mutex);
4119b42b0bddSYang Yingliang }
41208864b4e5STejun Heo
4121687a9aa5STejun Heo if (wq->flags & WQ_UNBOUND) {
4122a892caccSTejun Heo mutex_lock(&wq_pool_mutex);
41238864b4e5STejun Heo put_unbound_pool(pool);
4124a892caccSTejun Heo mutex_unlock(&wq_pool_mutex);
4125687a9aa5STejun Heo }
4126a892caccSTejun Heo
412725b00775SPaul E. McKenney call_rcu(&pwq->rcu, rcu_free_pwq);
41288864b4e5STejun Heo
41298864b4e5STejun Heo /*
41308864b4e5STejun Heo * If we're the last pwq going away, @wq is already dead and no one
4131e2dca7adSTejun Heo * is gonna access it anymore. Schedule RCU free.
41328864b4e5STejun Heo */
4133669de8bdSBart Van Assche if (is_last) {
4134669de8bdSBart Van Assche wq_unregister_lockdep(wq);
413525b00775SPaul E. McKenney call_rcu(&wq->rcu, rcu_free_wq);
41366029a918STejun Heo }
4137669de8bdSBart Van Assche }
41388864b4e5STejun Heo
4139d8354f26SGreg Kroah-Hartman /**
4140d8354f26SGreg Kroah-Hartman * pwq_adjust_max_active - update a pwq's max_active to the current setting
4141d8354f26SGreg Kroah-Hartman * @pwq: target pool_workqueue
4142d8354f26SGreg Kroah-Hartman *
4143d8354f26SGreg Kroah-Hartman * If @pwq isn't freezing, set @pwq->max_active to the associated
4144d8354f26SGreg Kroah-Hartman * workqueue's saved_max_active and activate inactive work items
4145d8354f26SGreg Kroah-Hartman * accordingly. If @pwq is freezing, clear @pwq->max_active to zero.
4146d8354f26SGreg Kroah-Hartman */
pwq_adjust_max_active(struct pool_workqueue * pwq)4147d8354f26SGreg Kroah-Hartman static void pwq_adjust_max_active(struct pool_workqueue *pwq)
4148d8354f26SGreg Kroah-Hartman {
4149d8354f26SGreg Kroah-Hartman struct workqueue_struct *wq = pwq->wq;
4150d8354f26SGreg Kroah-Hartman bool freezable = wq->flags & WQ_FREEZABLE;
4151d8354f26SGreg Kroah-Hartman unsigned long flags;
4152d8354f26SGreg Kroah-Hartman
4153d8354f26SGreg Kroah-Hartman /* for @wq->saved_max_active */
4154d8354f26SGreg Kroah-Hartman lockdep_assert_held(&wq->mutex);
4155d8354f26SGreg Kroah-Hartman
4156d8354f26SGreg Kroah-Hartman /* fast exit for non-freezable wqs */
4157d8354f26SGreg Kroah-Hartman if (!freezable && pwq->max_active == wq->saved_max_active)
4158d8354f26SGreg Kroah-Hartman return;
4159d8354f26SGreg Kroah-Hartman
4160d8354f26SGreg Kroah-Hartman /* this function can be called during early boot w/ irq disabled */
4161d8354f26SGreg Kroah-Hartman raw_spin_lock_irqsave(&pwq->pool->lock, flags);
4162d8354f26SGreg Kroah-Hartman
4163d8354f26SGreg Kroah-Hartman /*
4164d8354f26SGreg Kroah-Hartman * During [un]freezing, the caller is responsible for ensuring that
4165d8354f26SGreg Kroah-Hartman * this function is called at least once after @workqueue_freezing
4166d8354f26SGreg Kroah-Hartman * is updated and visible.
4167d8354f26SGreg Kroah-Hartman */
4168d8354f26SGreg Kroah-Hartman if (!freezable || !workqueue_freezing) {
4169d8354f26SGreg Kroah-Hartman pwq->max_active = wq->saved_max_active;
4170d8354f26SGreg Kroah-Hartman
4171d8354f26SGreg Kroah-Hartman while (!list_empty(&pwq->inactive_works) &&
4172d8354f26SGreg Kroah-Hartman pwq->nr_active < pwq->max_active)
4173d8354f26SGreg Kroah-Hartman pwq_activate_first_inactive(pwq);
4174d8354f26SGreg Kroah-Hartman
4175d8354f26SGreg Kroah-Hartman kick_pool(pwq->pool);
4176d8354f26SGreg Kroah-Hartman } else {
4177d8354f26SGreg Kroah-Hartman pwq->max_active = 0;
4178d8354f26SGreg Kroah-Hartman }
4179d8354f26SGreg Kroah-Hartman
4180d8354f26SGreg Kroah-Hartman raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
4181d8354f26SGreg Kroah-Hartman }
4182d8354f26SGreg Kroah-Hartman
418367dc8325SCai Huoqing /* initialize newly allocated @pwq which is associated with @wq and @pool */
init_pwq(struct pool_workqueue * pwq,struct workqueue_struct * wq,struct worker_pool * pool)4184f147f29eSTejun Heo static void init_pwq(struct pool_workqueue *pwq, struct workqueue_struct *wq,
4185f147f29eSTejun Heo struct worker_pool *pool)
4186d2c1d404STejun Heo {
4187d2c1d404STejun Heo BUG_ON((unsigned long)pwq & WORK_STRUCT_FLAG_MASK);
4188d2c1d404STejun Heo
4189e50aba9aSTejun Heo memset(pwq, 0, sizeof(*pwq));
4190e50aba9aSTejun Heo
4191d2c1d404STejun Heo pwq->pool = pool;
4192d2c1d404STejun Heo pwq->wq = wq;
4193d2c1d404STejun Heo pwq->flush_color = -1;
41948864b4e5STejun Heo pwq->refcnt = 1;
4195f97a4a1aSLai Jiangshan INIT_LIST_HEAD(&pwq->inactive_works);
41961befcf30STejun Heo INIT_LIST_HEAD(&pwq->pwqs_node);
4197d2c1d404STejun Heo INIT_LIST_HEAD(&pwq->mayday_node);
4198687a9aa5STejun Heo kthread_init_work(&pwq->release_work, pwq_release_workfn);
4199f147f29eSTejun Heo }
4200d2c1d404STejun Heo
4201f147f29eSTejun Heo /* sync @pwq with the current state of its associated wq and link it */
link_pwq(struct pool_workqueue * pwq)42021befcf30STejun Heo static void link_pwq(struct pool_workqueue *pwq)
4203f147f29eSTejun Heo {
4204f147f29eSTejun Heo struct workqueue_struct *wq = pwq->wq;
4205f147f29eSTejun Heo
4206f147f29eSTejun Heo lockdep_assert_held(&wq->mutex);
420775ccf595STejun Heo
42081befcf30STejun Heo /* may be called multiple times, ignore if already linked */
42091befcf30STejun Heo if (!list_empty(&pwq->pwqs_node))
42101befcf30STejun Heo return;
42111befcf30STejun Heo
421229b1cb41SLai Jiangshan /* set the matching work_color */
421375ccf595STejun Heo pwq->work_color = wq->work_color;
4214983ca25eSTejun Heo
4215d8354f26SGreg Kroah-Hartman /* sync max_active to the current setting */
4216d8354f26SGreg Kroah-Hartman pwq_adjust_max_active(pwq);
4217d8354f26SGreg Kroah-Hartman
4218983ca25eSTejun Heo /* link in @pwq */
42199e8cd2f5STejun Heo list_add_rcu(&pwq->pwqs_node, &wq->pwqs);
4220df2d5ae4STejun Heo }
42216029a918STejun Heo
4222f147f29eSTejun Heo /* obtain a pool matching @attr and create a pwq associating the pool and @wq */
alloc_unbound_pwq(struct workqueue_struct * wq,const struct workqueue_attrs * attrs)4223f147f29eSTejun Heo static struct pool_workqueue *alloc_unbound_pwq(struct workqueue_struct *wq,
4224f147f29eSTejun Heo const struct workqueue_attrs *attrs)
4225f147f29eSTejun Heo {
4226f147f29eSTejun Heo struct worker_pool *pool;
4227f147f29eSTejun Heo struct pool_workqueue *pwq;
4228f147f29eSTejun Heo
4229f147f29eSTejun Heo lockdep_assert_held(&wq_pool_mutex);
4230f147f29eSTejun Heo
4231f147f29eSTejun Heo pool = get_unbound_pool(attrs);
4232f147f29eSTejun Heo if (!pool)
4233f147f29eSTejun Heo return NULL;
4234f147f29eSTejun Heo
4235e50aba9aSTejun Heo pwq = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL, pool->node);
4236f147f29eSTejun Heo if (!pwq) {
4237f147f29eSTejun Heo put_unbound_pool(pool);
4238f147f29eSTejun Heo return NULL;
4239f147f29eSTejun Heo }
4240f147f29eSTejun Heo
4241f147f29eSTejun Heo init_pwq(pwq, wq, pool);
4242f147f29eSTejun Heo return pwq;
4243d2c1d404STejun Heo }
4244d2c1d404STejun Heo
42454c16bd32STejun Heo /**
4246fef59c9cSTejun Heo * wq_calc_pod_cpumask - calculate a wq_attrs' cpumask for a pod
4247042f7df1SLai Jiangshan * @attrs: the wq_attrs of the default pwq of the target workqueue
424884193c07STejun Heo * @cpu: the target CPU
42494c16bd32STejun Heo * @cpu_going_down: if >= 0, the CPU to consider as offline
42504c16bd32STejun Heo *
4251fef59c9cSTejun Heo * Calculate the cpumask a workqueue with @attrs should use on @pod. If
4252fef59c9cSTejun Heo * @cpu_going_down is >= 0, that cpu is considered offline during calculation.
42539546b29eSTejun Heo * The result is stored in @attrs->__pod_cpumask.
42544c16bd32STejun Heo *
4255fef59c9cSTejun Heo * If pod affinity is not enabled, @attrs->cpumask is always used. If enabled
4256fef59c9cSTejun Heo * and @pod has online CPUs requested by @attrs, the returned cpumask is the
4257fef59c9cSTejun Heo * intersection of the possible CPUs of @pod and @attrs->cpumask.
42584c16bd32STejun Heo *
4259fef59c9cSTejun Heo * The caller is responsible for ensuring that the cpumask of @pod stays stable.
42604c16bd32STejun Heo */
wq_calc_pod_cpumask(struct workqueue_attrs * attrs,int cpu,int cpu_going_down)42619546b29eSTejun Heo static void wq_calc_pod_cpumask(struct workqueue_attrs *attrs, int cpu,
42629546b29eSTejun Heo int cpu_going_down)
42634c16bd32STejun Heo {
426484193c07STejun Heo const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
426584193c07STejun Heo int pod = pt->cpu_pod[cpu];
42664c16bd32STejun Heo
4267fef59c9cSTejun Heo /* does @pod have any online CPUs @attrs wants? */
42689546b29eSTejun Heo cpumask_and(attrs->__pod_cpumask, pt->pod_cpus[pod], attrs->cpumask);
42699546b29eSTejun Heo cpumask_and(attrs->__pod_cpumask, attrs->__pod_cpumask, cpu_online_mask);
42704c16bd32STejun Heo if (cpu_going_down >= 0)
42719546b29eSTejun Heo cpumask_clear_cpu(cpu_going_down, attrs->__pod_cpumask);
42724c16bd32STejun Heo
42739546b29eSTejun Heo if (cpumask_empty(attrs->__pod_cpumask)) {
42749546b29eSTejun Heo cpumask_copy(attrs->__pod_cpumask, attrs->cpumask);
427584193c07STejun Heo return;
427684193c07STejun Heo }
42774c16bd32STejun Heo
4278fef59c9cSTejun Heo /* yeap, return possible CPUs in @pod that @attrs wants */
42799546b29eSTejun Heo cpumask_and(attrs->__pod_cpumask, attrs->cpumask, pt->pod_cpus[pod]);
42801ad0f0a7SMichael Bringmann
42819546b29eSTejun Heo if (cpumask_empty(attrs->__pod_cpumask))
42821ad0f0a7SMichael Bringmann pr_warn_once("WARNING: workqueue cpumask: online intersect > "
42831ad0f0a7SMichael Bringmann "possible intersect\n");
42844c16bd32STejun Heo }
42854c16bd32STejun Heo
4286f3c11cb2SGreg Kroah-Hartman /* install @pwq into @wq's cpu_pwq and return the old pwq */
install_unbound_pwq(struct workqueue_struct * wq,int cpu,struct pool_workqueue * pwq)4287636b927eSTejun Heo static struct pool_workqueue *install_unbound_pwq(struct workqueue_struct *wq,
4288636b927eSTejun Heo int cpu, struct pool_workqueue *pwq)
42891befcf30STejun Heo {
42901befcf30STejun Heo struct pool_workqueue *old_pwq;
42911befcf30STejun Heo
42925b95e1afSLai Jiangshan lockdep_assert_held(&wq_pool_mutex);
42931befcf30STejun Heo lockdep_assert_held(&wq->mutex);
42941befcf30STejun Heo
42951befcf30STejun Heo /* link_pwq() can handle duplicate calls */
42961befcf30STejun Heo link_pwq(pwq);
42971befcf30STejun Heo
4298f3c11cb2SGreg Kroah-Hartman old_pwq = rcu_access_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu));
4299f3c11cb2SGreg Kroah-Hartman rcu_assign_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu), pwq);
43001befcf30STejun Heo return old_pwq;
43011befcf30STejun Heo }
43021befcf30STejun Heo
43032d5f0764SLai Jiangshan /* context to store the prepared attrs & pwqs before applying */
43042d5f0764SLai Jiangshan struct apply_wqattrs_ctx {
43052d5f0764SLai Jiangshan struct workqueue_struct *wq; /* target workqueue */
43062d5f0764SLai Jiangshan struct workqueue_attrs *attrs; /* attrs to apply */
4307042f7df1SLai Jiangshan struct list_head list; /* queued for batching commit */
43082d5f0764SLai Jiangshan struct pool_workqueue *dfl_pwq;
43092d5f0764SLai Jiangshan struct pool_workqueue *pwq_tbl[];
43102d5f0764SLai Jiangshan };
43112d5f0764SLai Jiangshan
43122d5f0764SLai Jiangshan /* free the resources after success or abort */
apply_wqattrs_cleanup(struct apply_wqattrs_ctx * ctx)43132d5f0764SLai Jiangshan static void apply_wqattrs_cleanup(struct apply_wqattrs_ctx *ctx)
43142d5f0764SLai Jiangshan {
43152d5f0764SLai Jiangshan if (ctx) {
4316636b927eSTejun Heo int cpu;
43172d5f0764SLai Jiangshan
4318636b927eSTejun Heo for_each_possible_cpu(cpu)
4319636b927eSTejun Heo put_pwq_unlocked(ctx->pwq_tbl[cpu]);
43202d5f0764SLai Jiangshan put_pwq_unlocked(ctx->dfl_pwq);
43212d5f0764SLai Jiangshan
43222d5f0764SLai Jiangshan free_workqueue_attrs(ctx->attrs);
43232d5f0764SLai Jiangshan
43242d5f0764SLai Jiangshan kfree(ctx);
43252d5f0764SLai Jiangshan }
43262d5f0764SLai Jiangshan }
43272d5f0764SLai Jiangshan
43282d5f0764SLai Jiangshan /* allocate the attrs and pwqs for later installation */
43292d5f0764SLai Jiangshan static struct apply_wqattrs_ctx *
apply_wqattrs_prepare(struct workqueue_struct * wq,const struct workqueue_attrs * attrs,const cpumask_var_t unbound_cpumask)43302d5f0764SLai Jiangshan apply_wqattrs_prepare(struct workqueue_struct *wq,
433199c621efSLai Jiangshan const struct workqueue_attrs *attrs,
433299c621efSLai Jiangshan const cpumask_var_t unbound_cpumask)
43332d5f0764SLai Jiangshan {
43342d5f0764SLai Jiangshan struct apply_wqattrs_ctx *ctx;
43359546b29eSTejun Heo struct workqueue_attrs *new_attrs;
4336636b927eSTejun Heo int cpu;
43372d5f0764SLai Jiangshan
43382d5f0764SLai Jiangshan lockdep_assert_held(&wq_pool_mutex);
43392d5f0764SLai Jiangshan
434084193c07STejun Heo if (WARN_ON(attrs->affn_scope < 0 ||
434184193c07STejun Heo attrs->affn_scope >= WQ_AFFN_NR_TYPES))
434284193c07STejun Heo return ERR_PTR(-EINVAL);
434384193c07STejun Heo
4344636b927eSTejun Heo ctx = kzalloc(struct_size(ctx, pwq_tbl, nr_cpu_ids), GFP_KERNEL);
43452d5f0764SLai Jiangshan
4346be69d00dSThomas Gleixner new_attrs = alloc_workqueue_attrs();
43479546b29eSTejun Heo if (!ctx || !new_attrs)
43482d5f0764SLai Jiangshan goto out_free;
43492d5f0764SLai Jiangshan
4350042f7df1SLai Jiangshan /*
43512d5f0764SLai Jiangshan * If something goes wrong during CPU up/down, we'll fall back to
43522d5f0764SLai Jiangshan * the default pwq covering whole @attrs->cpumask. Always create
43532d5f0764SLai Jiangshan * it even if we don't use it immediately.
43542d5f0764SLai Jiangshan */
43550f36ee24STejun Heo copy_workqueue_attrs(new_attrs, attrs);
43560f36ee24STejun Heo wqattrs_actualize_cpumask(new_attrs, unbound_cpumask);
43579546b29eSTejun Heo cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
43582d5f0764SLai Jiangshan ctx->dfl_pwq = alloc_unbound_pwq(wq, new_attrs);
43592d5f0764SLai Jiangshan if (!ctx->dfl_pwq)
43602d5f0764SLai Jiangshan goto out_free;
43612d5f0764SLai Jiangshan
4362636b927eSTejun Heo for_each_possible_cpu(cpu) {
4363af73f5c9STejun Heo if (new_attrs->ordered) {
43642d5f0764SLai Jiangshan ctx->dfl_pwq->refcnt++;
4365636b927eSTejun Heo ctx->pwq_tbl[cpu] = ctx->dfl_pwq;
4366636b927eSTejun Heo } else {
43679546b29eSTejun Heo wq_calc_pod_cpumask(new_attrs, cpu, -1);
43689546b29eSTejun Heo ctx->pwq_tbl[cpu] = alloc_unbound_pwq(wq, new_attrs);
4369636b927eSTejun Heo if (!ctx->pwq_tbl[cpu])
4370636b927eSTejun Heo goto out_free;
43712d5f0764SLai Jiangshan }
43722d5f0764SLai Jiangshan }
43732d5f0764SLai Jiangshan
4374042f7df1SLai Jiangshan /* save the user configured attrs and sanitize it. */
4375042f7df1SLai Jiangshan copy_workqueue_attrs(new_attrs, attrs);
4376042f7df1SLai Jiangshan cpumask_and(new_attrs->cpumask, new_attrs->cpumask, cpu_possible_mask);
43779546b29eSTejun Heo cpumask_copy(new_attrs->__pod_cpumask, new_attrs->cpumask);
43782d5f0764SLai Jiangshan ctx->attrs = new_attrs;
4379042f7df1SLai Jiangshan
43802d5f0764SLai Jiangshan ctx->wq = wq;
43812d5f0764SLai Jiangshan return ctx;
43822d5f0764SLai Jiangshan
43832d5f0764SLai Jiangshan out_free:
43842d5f0764SLai Jiangshan free_workqueue_attrs(new_attrs);
43852d5f0764SLai Jiangshan apply_wqattrs_cleanup(ctx);
438684193c07STejun Heo return ERR_PTR(-ENOMEM);
43872d5f0764SLai Jiangshan }
43882d5f0764SLai Jiangshan
43892d5f0764SLai Jiangshan /* set attrs and install prepared pwqs, @ctx points to old pwqs on return */
apply_wqattrs_commit(struct apply_wqattrs_ctx * ctx)43902d5f0764SLai Jiangshan static void apply_wqattrs_commit(struct apply_wqattrs_ctx *ctx)
43912d5f0764SLai Jiangshan {
4392636b927eSTejun Heo int cpu;
43932d5f0764SLai Jiangshan
43942d5f0764SLai Jiangshan /* all pwqs have been created successfully, let's install'em */
43952d5f0764SLai Jiangshan mutex_lock(&ctx->wq->mutex);
43962d5f0764SLai Jiangshan
43972d5f0764SLai Jiangshan copy_workqueue_attrs(ctx->wq->unbound_attrs, ctx->attrs);
43982d5f0764SLai Jiangshan
4399f3c11cb2SGreg Kroah-Hartman /* save the previous pwq and install the new one */
4400636b927eSTejun Heo for_each_possible_cpu(cpu)
4401636b927eSTejun Heo ctx->pwq_tbl[cpu] = install_unbound_pwq(ctx->wq, cpu,
4402636b927eSTejun Heo ctx->pwq_tbl[cpu]);
4403f3c11cb2SGreg Kroah-Hartman
4404f3c11cb2SGreg Kroah-Hartman /* @dfl_pwq might not have been used, ensure it's linked */
4405f3c11cb2SGreg Kroah-Hartman link_pwq(ctx->dfl_pwq);
4406f3c11cb2SGreg Kroah-Hartman swap(ctx->wq->dfl_pwq, ctx->dfl_pwq);
44072d5f0764SLai Jiangshan
44082d5f0764SLai Jiangshan mutex_unlock(&ctx->wq->mutex);
44092d5f0764SLai Jiangshan }
44102d5f0764SLai Jiangshan
apply_wqattrs_lock(void)4411a0111cf6SLai Jiangshan static void apply_wqattrs_lock(void)
4412a0111cf6SLai Jiangshan {
4413a0111cf6SLai Jiangshan /* CPUs should stay stable across pwq creations and installations */
4414ffd8bea8SSebastian Andrzej Siewior cpus_read_lock();
4415a0111cf6SLai Jiangshan mutex_lock(&wq_pool_mutex);
4416a0111cf6SLai Jiangshan }
4417a0111cf6SLai Jiangshan
apply_wqattrs_unlock(void)4418a0111cf6SLai Jiangshan static void apply_wqattrs_unlock(void)
4419a0111cf6SLai Jiangshan {
4420a0111cf6SLai Jiangshan mutex_unlock(&wq_pool_mutex);
4421ffd8bea8SSebastian Andrzej Siewior cpus_read_unlock();
4422a0111cf6SLai Jiangshan }
4423a0111cf6SLai Jiangshan
apply_workqueue_attrs_locked(struct workqueue_struct * wq,const struct workqueue_attrs * attrs)4424a0111cf6SLai Jiangshan static int apply_workqueue_attrs_locked(struct workqueue_struct *wq,
4425a0111cf6SLai Jiangshan const struct workqueue_attrs *attrs)
4426a0111cf6SLai Jiangshan {
4427a0111cf6SLai Jiangshan struct apply_wqattrs_ctx *ctx;
4428a0111cf6SLai Jiangshan
4429a0111cf6SLai Jiangshan /* only unbound workqueues can change attributes */
4430a0111cf6SLai Jiangshan if (WARN_ON(!(wq->flags & WQ_UNBOUND)))
4431a0111cf6SLai Jiangshan return -EINVAL;
4432a0111cf6SLai Jiangshan
4433a0111cf6SLai Jiangshan /* creating multiple pwqs breaks ordering guarantee */
44340a94efb5STejun Heo if (!list_empty(&wq->pwqs)) {
44350a94efb5STejun Heo if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
4436a0111cf6SLai Jiangshan return -EINVAL;
4437a0111cf6SLai Jiangshan
44380a94efb5STejun Heo wq->flags &= ~__WQ_ORDERED;
44390a94efb5STejun Heo }
44400a94efb5STejun Heo
444199c621efSLai Jiangshan ctx = apply_wqattrs_prepare(wq, attrs, wq_unbound_cpumask);
444284193c07STejun Heo if (IS_ERR(ctx))
444384193c07STejun Heo return PTR_ERR(ctx);
4444a0111cf6SLai Jiangshan
4445a0111cf6SLai Jiangshan /* the ctx has been prepared successfully, let's commit it */
4446a0111cf6SLai Jiangshan apply_wqattrs_commit(ctx);
4447a0111cf6SLai Jiangshan apply_wqattrs_cleanup(ctx);
4448a0111cf6SLai Jiangshan
44496201171eSwanghaibin return 0;
4450a0111cf6SLai Jiangshan }
4451a0111cf6SLai Jiangshan
44529e8cd2f5STejun Heo /**
44539e8cd2f5STejun Heo * apply_workqueue_attrs - apply new workqueue_attrs to an unbound workqueue
44549e8cd2f5STejun Heo * @wq: the target workqueue
44559e8cd2f5STejun Heo * @attrs: the workqueue_attrs to apply, allocated with alloc_workqueue_attrs()
44569e8cd2f5STejun Heo *
4457fef59c9cSTejun Heo * Apply @attrs to an unbound workqueue @wq. Unless disabled, this function maps
4458fef59c9cSTejun Heo * a separate pwq to each CPU pod with possibles CPUs in @attrs->cpumask so that
4459fef59c9cSTejun Heo * work items are affine to the pod it was issued on. Older pwqs are released as
4460fef59c9cSTejun Heo * in-flight work items finish. Note that a work item which repeatedly requeues
4461fef59c9cSTejun Heo * itself back-to-back will stay on its current pwq.
44629e8cd2f5STejun Heo *
4463d185af30SYacine Belkadi * Performs GFP_KERNEL allocations.
4464d185af30SYacine Belkadi *
4465ffd8bea8SSebastian Andrzej Siewior * Assumes caller has CPU hotplug read exclusion, i.e. cpus_read_lock().
4466509b3204SDaniel Jordan *
4467d185af30SYacine Belkadi * Return: 0 on success and -errno on failure.
44689e8cd2f5STejun Heo */
apply_workqueue_attrs(struct workqueue_struct * wq,const struct workqueue_attrs * attrs)4469513c98d0SDaniel Jordan int apply_workqueue_attrs(struct workqueue_struct *wq,
44709e8cd2f5STejun Heo const struct workqueue_attrs *attrs)
44719e8cd2f5STejun Heo {
4472a0111cf6SLai Jiangshan int ret;
44739e8cd2f5STejun Heo
4474509b3204SDaniel Jordan lockdep_assert_cpus_held();
4475509b3204SDaniel Jordan
4476509b3204SDaniel Jordan mutex_lock(&wq_pool_mutex);
4477a0111cf6SLai Jiangshan ret = apply_workqueue_attrs_locked(wq, attrs);
4478509b3204SDaniel Jordan mutex_unlock(&wq_pool_mutex);
44792d5f0764SLai Jiangshan
44802d5f0764SLai Jiangshan return ret;
44819e8cd2f5STejun Heo }
44829e8cd2f5STejun Heo
44834c16bd32STejun Heo /**
4484fef59c9cSTejun Heo * wq_update_pod - update pod affinity of a wq for CPU hot[un]plug
44854c16bd32STejun Heo * @wq: the target workqueue
44864cbfd3deSTejun Heo * @cpu: the CPU to update pool association for
44874cbfd3deSTejun Heo * @hotplug_cpu: the CPU coming up or going down
44884c16bd32STejun Heo * @online: whether @cpu is coming up or going down
44894c16bd32STejun Heo *
44904c16bd32STejun Heo * This function is to be called from %CPU_DOWN_PREPARE, %CPU_ONLINE and
4491fef59c9cSTejun Heo * %CPU_DOWN_FAILED. @cpu is being hot[un]plugged, update pod affinity of
44924c16bd32STejun Heo * @wq accordingly.
44934c16bd32STejun Heo *
44944c16bd32STejun Heo *
4495fef59c9cSTejun Heo * If pod affinity can't be adjusted due to memory allocation failure, it falls
4496fef59c9cSTejun Heo * back to @wq->dfl_pwq which may not be optimal but is always correct.
4497fef59c9cSTejun Heo *
4498fef59c9cSTejun Heo * Note that when the last allowed CPU of a pod goes offline for a workqueue
4499fef59c9cSTejun Heo * with a cpumask spanning multiple pods, the workers which were already
4500fef59c9cSTejun Heo * executing the work items for the workqueue will lose their CPU affinity and
4501fef59c9cSTejun Heo * may execute on any CPU. This is similar to how per-cpu workqueues behave on
4502fef59c9cSTejun Heo * CPU_DOWN. If a workqueue user wants strict affinity, it's the user's
4503fef59c9cSTejun Heo * responsibility to flush the work item from CPU_DOWN_PREPARE.
45044c16bd32STejun Heo */
wq_update_pod(struct workqueue_struct * wq,int cpu,int hotplug_cpu,bool online)4505fef59c9cSTejun Heo static void wq_update_pod(struct workqueue_struct *wq, int cpu,
45064cbfd3deSTejun Heo int hotplug_cpu, bool online)
45074c16bd32STejun Heo {
45084cbfd3deSTejun Heo int off_cpu = online ? -1 : hotplug_cpu;
45094c16bd32STejun Heo struct pool_workqueue *old_pwq = NULL, *pwq;
45104c16bd32STejun Heo struct workqueue_attrs *target_attrs;
45114c16bd32STejun Heo
45124c16bd32STejun Heo lockdep_assert_held(&wq_pool_mutex);
45134c16bd32STejun Heo
451484193c07STejun Heo if (!(wq->flags & WQ_UNBOUND) || wq->unbound_attrs->ordered)
45154c16bd32STejun Heo return;
45164c16bd32STejun Heo
45174c16bd32STejun Heo /*
45184c16bd32STejun Heo * We don't wanna alloc/free wq_attrs for each wq for each CPU.
45194c16bd32STejun Heo * Let's use a preallocated one. The following buf is protected by
45204c16bd32STejun Heo * CPU hotplug exclusion.
45214c16bd32STejun Heo */
4522fef59c9cSTejun Heo target_attrs = wq_update_pod_attrs_buf;
45234c16bd32STejun Heo
45244c16bd32STejun Heo copy_workqueue_attrs(target_attrs, wq->unbound_attrs);
45250f36ee24STejun Heo wqattrs_actualize_cpumask(target_attrs, wq_unbound_cpumask);
45264c16bd32STejun Heo
4527636b927eSTejun Heo /* nothing to do if the target cpumask matches the current pwq */
45289546b29eSTejun Heo wq_calc_pod_cpumask(target_attrs, cpu, off_cpu);
4529f3c11cb2SGreg Kroah-Hartman pwq = rcu_dereference_protected(*per_cpu_ptr(wq->cpu_pwq, cpu),
4530f3c11cb2SGreg Kroah-Hartman lockdep_is_held(&wq_pool_mutex));
4531f3c11cb2SGreg Kroah-Hartman if (wqattrs_equal(target_attrs, pwq->pool->attrs))
4532f7142ed4SLai Jiangshan return;
45334c16bd32STejun Heo
45344c16bd32STejun Heo /* create a new pwq */
45354c16bd32STejun Heo pwq = alloc_unbound_pwq(wq, target_attrs);
45364c16bd32STejun Heo if (!pwq) {
4537fef59c9cSTejun Heo pr_warn("workqueue: allocation failed while updating CPU pod affinity of \"%s\"\n",
45384c16bd32STejun Heo wq->name);
453977f300b1SDaeseok Youn goto use_dfl_pwq;
45404c16bd32STejun Heo }
45414c16bd32STejun Heo
4542f7142ed4SLai Jiangshan /* Install the new pwq. */
45434c16bd32STejun Heo mutex_lock(&wq->mutex);
4544636b927eSTejun Heo old_pwq = install_unbound_pwq(wq, cpu, pwq);
45454c16bd32STejun Heo goto out_unlock;
45464c16bd32STejun Heo
45474c16bd32STejun Heo use_dfl_pwq:
4548f7142ed4SLai Jiangshan mutex_lock(&wq->mutex);
4549f3c11cb2SGreg Kroah-Hartman raw_spin_lock_irq(&wq->dfl_pwq->pool->lock);
4550f3c11cb2SGreg Kroah-Hartman get_pwq(wq->dfl_pwq);
4551f3c11cb2SGreg Kroah-Hartman raw_spin_unlock_irq(&wq->dfl_pwq->pool->lock);
4552f3c11cb2SGreg Kroah-Hartman old_pwq = install_unbound_pwq(wq, cpu, wq->dfl_pwq);
45534c16bd32STejun Heo out_unlock:
45544c16bd32STejun Heo mutex_unlock(&wq->mutex);
45554c16bd32STejun Heo put_pwq_unlocked(old_pwq);
45564c16bd32STejun Heo }
45574c16bd32STejun Heo
alloc_and_link_pwqs(struct workqueue_struct * wq)455830cdf249STejun Heo static int alloc_and_link_pwqs(struct workqueue_struct *wq)
45591da177e4SLinus Torvalds {
456049e3cf44STejun Heo bool highpri = wq->flags & WQ_HIGHPRI;
45618a2b7538STejun Heo int cpu, ret;
4562e1d8aa9fSFrederic Weisbecker
4563687a9aa5STejun Heo wq->cpu_pwq = alloc_percpu(struct pool_workqueue *);
4564ee1ceef7STejun Heo if (!wq->cpu_pwq)
4565687a9aa5STejun Heo goto enomem;
456630cdf249STejun Heo
4567636b927eSTejun Heo if (!(wq->flags & WQ_UNBOUND)) {
456830cdf249STejun Heo for_each_possible_cpu(cpu) {
4569687a9aa5STejun Heo struct pool_workqueue **pwq_p =
4570ee1ceef7STejun Heo per_cpu_ptr(wq->cpu_pwq, cpu);
4571687a9aa5STejun Heo struct worker_pool *pool =
4572687a9aa5STejun Heo &(per_cpu_ptr(cpu_worker_pools, cpu)[highpri]);
457330cdf249STejun Heo
4574687a9aa5STejun Heo *pwq_p = kmem_cache_alloc_node(pwq_cache, GFP_KERNEL,
4575687a9aa5STejun Heo pool->node);
4576687a9aa5STejun Heo if (!*pwq_p)
4577687a9aa5STejun Heo goto enomem;
4578687a9aa5STejun Heo
4579687a9aa5STejun Heo init_pwq(*pwq_p, wq, pool);
4580f147f29eSTejun Heo
4581f147f29eSTejun Heo mutex_lock(&wq->mutex);
4582687a9aa5STejun Heo link_pwq(*pwq_p);
4583f147f29eSTejun Heo mutex_unlock(&wq->mutex);
458430cdf249STejun Heo }
458530cdf249STejun Heo return 0;
4586509b3204SDaniel Jordan }
4587509b3204SDaniel Jordan
4588ffd8bea8SSebastian Andrzej Siewior cpus_read_lock();
4589509b3204SDaniel Jordan if (wq->flags & __WQ_ORDERED) {
45908a2b7538STejun Heo ret = apply_workqueue_attrs(wq, ordered_wq_attrs[highpri]);
45918a2b7538STejun Heo /* there should only be single pwq for ordering guarantee */
4592f3c11cb2SGreg Kroah-Hartman WARN(!ret && (wq->pwqs.next != &wq->dfl_pwq->pwqs_node ||
4593f3c11cb2SGreg Kroah-Hartman wq->pwqs.prev != &wq->dfl_pwq->pwqs_node),
45948a2b7538STejun Heo "ordering guarantee broken for workqueue %s\n", wq->name);
45959e8cd2f5STejun Heo } else {
4596509b3204SDaniel Jordan ret = apply_workqueue_attrs(wq, unbound_std_wq_attrs[highpri]);
45979e8cd2f5STejun Heo }
4598ffd8bea8SSebastian Andrzej Siewior cpus_read_unlock();
4599509b3204SDaniel Jordan
460064344553SZqiang /* for unbound pwq, flush the pwq_release_worker ensures that the
460164344553SZqiang * pwq_release_workfn() completes before calling kfree(wq).
460264344553SZqiang */
460364344553SZqiang if (ret)
460464344553SZqiang kthread_flush_worker(pwq_release_worker);
460564344553SZqiang
4606509b3204SDaniel Jordan return ret;
4607687a9aa5STejun Heo
4608687a9aa5STejun Heo enomem:
4609687a9aa5STejun Heo if (wq->cpu_pwq) {
46107b42f401SZqiang for_each_possible_cpu(cpu) {
46117b42f401SZqiang struct pool_workqueue *pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
46127b42f401SZqiang
46137b42f401SZqiang if (pwq)
46147b42f401SZqiang kmem_cache_free(pwq_cache, pwq);
46157b42f401SZqiang }
4616687a9aa5STejun Heo free_percpu(wq->cpu_pwq);
4617687a9aa5STejun Heo wq->cpu_pwq = NULL;
4618687a9aa5STejun Heo }
4619687a9aa5STejun Heo return -ENOMEM;
46200f900049STejun Heo }
46210f900049STejun Heo
wq_clamp_max_active(int max_active,unsigned int flags,const char * name)4622f3421797STejun Heo static int wq_clamp_max_active(int max_active, unsigned int flags,
4623f3421797STejun Heo const char *name)
4624b71ab8c2STejun Heo {
4625636b927eSTejun Heo if (max_active < 1 || max_active > WQ_MAX_ACTIVE)
4626044c782cSValentin Ilie pr_warn("workqueue: max_active %d requested for %s is out of range, clamping between %d and %d\n",
4627636b927eSTejun Heo max_active, name, 1, WQ_MAX_ACTIVE);
4628b71ab8c2STejun Heo
4629636b927eSTejun Heo return clamp_val(max_active, 1, WQ_MAX_ACTIVE);
4630b71ab8c2STejun Heo }
4631b71ab8c2STejun Heo
4632983c7515STejun Heo /*
4633983c7515STejun Heo * Workqueues which may be used during memory reclaim should have a rescuer
4634983c7515STejun Heo * to guarantee forward progress.
4635983c7515STejun Heo */
init_rescuer(struct workqueue_struct * wq)4636983c7515STejun Heo static int init_rescuer(struct workqueue_struct *wq)
4637983c7515STejun Heo {
4638983c7515STejun Heo struct worker *rescuer;
4639b92b36eaSDan Carpenter int ret;
4640983c7515STejun Heo
4641983c7515STejun Heo if (!(wq->flags & WQ_MEM_RECLAIM))
4642983c7515STejun Heo return 0;
4643983c7515STejun Heo
4644983c7515STejun Heo rescuer = alloc_worker(NUMA_NO_NODE);
46454c0736a7SPetr Mladek if (!rescuer) {
46464c0736a7SPetr Mladek pr_err("workqueue: Failed to allocate a rescuer for wq \"%s\"\n",
46474c0736a7SPetr Mladek wq->name);
4648983c7515STejun Heo return -ENOMEM;
46494c0736a7SPetr Mladek }
4650983c7515STejun Heo
4651983c7515STejun Heo rescuer->rescue_wq = wq;
4652b6a46f72SAaron Tomlin rescuer->task = kthread_create(rescuer_thread, rescuer, "kworker/R-%s", wq->name);
4653f187b697SSean Fu if (IS_ERR(rescuer->task)) {
4654b92b36eaSDan Carpenter ret = PTR_ERR(rescuer->task);
46554c0736a7SPetr Mladek pr_err("workqueue: Failed to create a rescuer kthread for wq \"%s\": %pe",
46564c0736a7SPetr Mladek wq->name, ERR_PTR(ret));
4657983c7515STejun Heo kfree(rescuer);
4658b92b36eaSDan Carpenter return ret;
4659983c7515STejun Heo }
4660983c7515STejun Heo
4661983c7515STejun Heo wq->rescuer = rescuer;
4662983c7515STejun Heo kthread_bind_mask(rescuer->task, cpu_possible_mask);
4663983c7515STejun Heo wake_up_process(rescuer->task);
4664983c7515STejun Heo
4665983c7515STejun Heo return 0;
4666983c7515STejun Heo }
4667983c7515STejun Heo
4668a2775bbcSMathieu Malaterre __printf(1, 4)
alloc_workqueue(const char * fmt,unsigned int flags,int max_active,...)4669669de8bdSBart Van Assche struct workqueue_struct *alloc_workqueue(const char *fmt,
467097e37d7bSTejun Heo unsigned int flags,
4671669de8bdSBart Van Assche int max_active, ...)
46723af24433SOleg Nesterov {
4673ecf6881fSTejun Heo va_list args;
46743af24433SOleg Nesterov struct workqueue_struct *wq;
4675d8354f26SGreg Kroah-Hartman struct pool_workqueue *pwq;
4676b196be89STejun Heo
46775c0338c6STejun Heo /*
4678fef59c9cSTejun Heo * Unbound && max_active == 1 used to imply ordered, which is no longer
4679fef59c9cSTejun Heo * the case on many machines due to per-pod pools. While
46805c0338c6STejun Heo * alloc_ordered_workqueue() is the right way to create an ordered
4681fef59c9cSTejun Heo * workqueue, keep the previous behavior to avoid subtle breakages.
46825c0338c6STejun Heo */
46835c0338c6STejun Heo if ((flags & WQ_UNBOUND) && max_active == 1)
46845c0338c6STejun Heo flags |= __WQ_ORDERED;
46855c0338c6STejun Heo
4686cee22a15SViresh Kumar /* see the comment above the definition of WQ_POWER_EFFICIENT */
4687cee22a15SViresh Kumar if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
4688cee22a15SViresh Kumar flags |= WQ_UNBOUND;
4689cee22a15SViresh Kumar
4690ecf6881fSTejun Heo /* allocate wq and format name */
4691bfb429f3SGreg Kroah-Hartman wq = kzalloc(sizeof(*wq), GFP_KERNEL);
4692b196be89STejun Heo if (!wq)
4693d2c1d404STejun Heo return NULL;
4694b196be89STejun Heo
46956029a918STejun Heo if (flags & WQ_UNBOUND) {
4696be69d00dSThomas Gleixner wq->unbound_attrs = alloc_workqueue_attrs();
46976029a918STejun Heo if (!wq->unbound_attrs)
46986029a918STejun Heo goto err_free_wq;
46996029a918STejun Heo }
47006029a918STejun Heo
4701669de8bdSBart Van Assche va_start(args, max_active);
4702a99d7274SGreg Kroah-Hartman vsnprintf(wq->name, sizeof(wq->name), fmt, args);
4703b196be89STejun Heo va_end(args);
47043af24433SOleg Nesterov
4705d320c038STejun Heo max_active = max_active ?: WQ_DFL_ACTIVE;
4706b196be89STejun Heo max_active = wq_clamp_max_active(max_active, flags, wq->name);
47073af24433SOleg Nesterov
4708b196be89STejun Heo /* init wq */
470997e37d7bSTejun Heo wq->flags = flags;
47106741dd3fSGreg Kroah-Hartman wq->saved_max_active = max_active;
47113c25a55dSLai Jiangshan mutex_init(&wq->mutex);
4712112202d9STejun Heo atomic_set(&wq->nr_pwqs_to_flush, 0);
471330cdf249STejun Heo INIT_LIST_HEAD(&wq->pwqs);
471473f53c4aSTejun Heo INIT_LIST_HEAD(&wq->flusher_queue);
471573f53c4aSTejun Heo INIT_LIST_HEAD(&wq->flusher_overflow);
4716493a1724STejun Heo INIT_LIST_HEAD(&wq->maydays);
47173af24433SOleg Nesterov
4718669de8bdSBart Van Assche wq_init_lockdep(wq);
4719cce1a165SOleg Nesterov INIT_LIST_HEAD(&wq->list);
47203af24433SOleg Nesterov
4721b522229aSTejun Heo if (alloc_and_link_pwqs(wq) < 0)
4722bfb429f3SGreg Kroah-Hartman goto err_unreg_lockdep;
47231537663fSTejun Heo
472440c17f75STejun Heo if (wq_online && init_rescuer(wq) < 0)
4725d2c1d404STejun Heo goto err_destroy;
4726e22bee78STejun Heo
4727226223abSTejun Heo if ((wq->flags & WQ_SYSFS) && workqueue_sysfs_register(wq))
4728226223abSTejun Heo goto err_destroy;
4729226223abSTejun Heo
47306af8bf3dSOleg Nesterov /*
473168e13a67SLai Jiangshan * wq_pool_mutex protects global freeze state and workqueues list.
473268e13a67SLai Jiangshan * Grab it, adjust max_active and add the new @wq to workqueues
473368e13a67SLai Jiangshan * list.
47346af8bf3dSOleg Nesterov */
473568e13a67SLai Jiangshan mutex_lock(&wq_pool_mutex);
4736a0a1a5fdSTejun Heo
4737a357fc03SLai Jiangshan mutex_lock(&wq->mutex);
4738d8354f26SGreg Kroah-Hartman for_each_pwq(pwq, wq)
4739d8354f26SGreg Kroah-Hartman pwq_adjust_max_active(pwq);
4740a357fc03SLai Jiangshan mutex_unlock(&wq->mutex);
4741a0a1a5fdSTejun Heo
4742e2dca7adSTejun Heo list_add_tail_rcu(&wq->list, &workqueues);
4743a0a1a5fdSTejun Heo
474468e13a67SLai Jiangshan mutex_unlock(&wq_pool_mutex);
47453af24433SOleg Nesterov
47463af24433SOleg Nesterov return wq;
4747d2c1d404STejun Heo
474882efcab3SBart Van Assche err_unreg_lockdep:
4749009bb421SBart Van Assche wq_unregister_lockdep(wq);
4750009bb421SBart Van Assche wq_free_lockdep(wq);
475182efcab3SBart Van Assche err_free_wq:
47526029a918STejun Heo free_workqueue_attrs(wq->unbound_attrs);
47534690c4abSTejun Heo kfree(wq);
4754d2c1d404STejun Heo return NULL;
4755d2c1d404STejun Heo err_destroy:
4756d2c1d404STejun Heo destroy_workqueue(wq);
47574690c4abSTejun Heo return NULL;
47581da177e4SLinus Torvalds }
4759669de8bdSBart Van Assche EXPORT_SYMBOL_GPL(alloc_workqueue);
47601da177e4SLinus Torvalds
pwq_busy(struct pool_workqueue * pwq)4761c29eb853STejun Heo static bool pwq_busy(struct pool_workqueue *pwq)
4762c29eb853STejun Heo {
4763c29eb853STejun Heo int i;
4764c29eb853STejun Heo
4765c29eb853STejun Heo for (i = 0; i < WORK_NR_COLORS; i++)
4766c29eb853STejun Heo if (pwq->nr_in_flight[i])
4767c29eb853STejun Heo return true;
4768c29eb853STejun Heo
4769f3c11cb2SGreg Kroah-Hartman if ((pwq != pwq->wq->dfl_pwq) && (pwq->refcnt > 1))
4770c29eb853STejun Heo return true;
477135bf38ddSGreg Kroah-Hartman if (pwq->nr_active || !list_empty(&pwq->inactive_works))
4772c29eb853STejun Heo return true;
4773c29eb853STejun Heo
4774c29eb853STejun Heo return false;
4775c29eb853STejun Heo }
4776c29eb853STejun Heo
47773af24433SOleg Nesterov /**
47783af24433SOleg Nesterov * destroy_workqueue - safely terminate a workqueue
47793af24433SOleg Nesterov * @wq: target workqueue
47803af24433SOleg Nesterov *
47813af24433SOleg Nesterov * Safely destroy a workqueue. All work currently pending will be done first.
47823af24433SOleg Nesterov */
destroy_workqueue(struct workqueue_struct * wq)47833af24433SOleg Nesterov void destroy_workqueue(struct workqueue_struct *wq)
47843af24433SOleg Nesterov {
478549e3cf44STejun Heo struct pool_workqueue *pwq;
4786636b927eSTejun Heo int cpu;
47873af24433SOleg Nesterov
4788def98c84STejun Heo /*
4789def98c84STejun Heo * Remove it from sysfs first so that sanity check failure doesn't
4790def98c84STejun Heo * lead to sysfs name conflicts.
4791def98c84STejun Heo */
4792def98c84STejun Heo workqueue_sysfs_unregister(wq);
4793def98c84STejun Heo
479433e3f0a3SRichard Clark /* mark the workqueue destruction is in progress */
479533e3f0a3SRichard Clark mutex_lock(&wq->mutex);
479633e3f0a3SRichard Clark wq->flags |= __WQ_DESTROYING;
479733e3f0a3SRichard Clark mutex_unlock(&wq->mutex);
479833e3f0a3SRichard Clark
47999c5a2ba7STejun Heo /* drain it before proceeding with destruction */
48009c5a2ba7STejun Heo drain_workqueue(wq);
4801c8efcc25STejun Heo
4802def98c84STejun Heo /* kill rescuer, if sanity checks fail, leave it w/o rescuer */
4803def98c84STejun Heo if (wq->rescuer) {
4804def98c84STejun Heo struct worker *rescuer = wq->rescuer;
4805def98c84STejun Heo
4806def98c84STejun Heo /* this prevents new queueing */
4807a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&wq_mayday_lock);
4808def98c84STejun Heo wq->rescuer = NULL;
4809a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&wq_mayday_lock);
4810def98c84STejun Heo
4811def98c84STejun Heo /* rescuer will empty maydays list before exiting */
4812def98c84STejun Heo kthread_stop(rescuer->task);
48138efe1223STejun Heo kfree(rescuer);
4814def98c84STejun Heo }
4815def98c84STejun Heo
4816c29eb853STejun Heo /*
4817c29eb853STejun Heo * Sanity checks - grab all the locks so that we wait for all
4818c29eb853STejun Heo * in-flight operations which may do put_pwq().
4819c29eb853STejun Heo */
4820c29eb853STejun Heo mutex_lock(&wq_pool_mutex);
4821b09f4fd3SLai Jiangshan mutex_lock(&wq->mutex);
482249e3cf44STejun Heo for_each_pwq(pwq, wq) {
4823a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pwq->pool->lock);
4824c29eb853STejun Heo if (WARN_ON(pwq_busy(pwq))) {
48251d9a6159SKefeng Wang pr_warn("%s: %s has the following busy pwq\n",
4826e66b39afSTejun Heo __func__, wq->name);
4827c29eb853STejun Heo show_pwq(pwq);
4828a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pwq->pool->lock);
4829b09f4fd3SLai Jiangshan mutex_unlock(&wq->mutex);
4830c29eb853STejun Heo mutex_unlock(&wq_pool_mutex);
483155df0933SImran Khan show_one_workqueue(wq);
48326183c009STejun Heo return;
483376af4d93STejun Heo }
4834a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pwq->pool->lock);
483576af4d93STejun Heo }
4836b09f4fd3SLai Jiangshan mutex_unlock(&wq->mutex);
48376183c009STejun Heo
4838a0a1a5fdSTejun Heo /*
4839a0a1a5fdSTejun Heo * wq list is used to freeze wq, remove from list after
4840a0a1a5fdSTejun Heo * flushing is complete in case freeze races us.
4841a0a1a5fdSTejun Heo */
4842e2dca7adSTejun Heo list_del_rcu(&wq->list);
484368e13a67SLai Jiangshan mutex_unlock(&wq_pool_mutex);
48443af24433SOleg Nesterov
48458864b4e5STejun Heo /*
4846636b927eSTejun Heo * We're the sole accessor of @wq. Directly access cpu_pwq and dfl_pwq
4847636b927eSTejun Heo * to put the base refs. @wq will be auto-destroyed from the last
4848636b927eSTejun Heo * pwq_put. RCU read lock prevents @wq from going away from under us.
48498864b4e5STejun Heo */
4850636b927eSTejun Heo rcu_read_lock();
4851636b927eSTejun Heo
4852636b927eSTejun Heo for_each_possible_cpu(cpu) {
4853f3c11cb2SGreg Kroah-Hartman pwq = rcu_access_pointer(*per_cpu_ptr(wq->cpu_pwq, cpu));
4854f3c11cb2SGreg Kroah-Hartman RCU_INIT_POINTER(*per_cpu_ptr(wq->cpu_pwq, cpu), NULL);
4855f3c11cb2SGreg Kroah-Hartman put_pwq_unlocked(pwq);
48564c16bd32STejun Heo }
48574c16bd32STejun Heo
4858f3c11cb2SGreg Kroah-Hartman put_pwq_unlocked(wq->dfl_pwq);
4859f3c11cb2SGreg Kroah-Hartman wq->dfl_pwq = NULL;
4860636b927eSTejun Heo
4861636b927eSTejun Heo rcu_read_unlock();
48623af24433SOleg Nesterov }
48633af24433SOleg Nesterov EXPORT_SYMBOL_GPL(destroy_workqueue);
48643af24433SOleg Nesterov
4865dcd989cbSTejun Heo /**
4866dcd989cbSTejun Heo * workqueue_set_max_active - adjust max_active of a workqueue
4867dcd989cbSTejun Heo * @wq: target workqueue
4868dcd989cbSTejun Heo * @max_active: new max_active value.
4869dcd989cbSTejun Heo *
48706741dd3fSGreg Kroah-Hartman * Set max_active of @wq to @max_active.
4871dcd989cbSTejun Heo *
4872dcd989cbSTejun Heo * CONTEXT:
4873dcd989cbSTejun Heo * Don't call from IRQ context.
4874dcd989cbSTejun Heo */
workqueue_set_max_active(struct workqueue_struct * wq,int max_active)4875dcd989cbSTejun Heo void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
4876dcd989cbSTejun Heo {
4877d8354f26SGreg Kroah-Hartman struct pool_workqueue *pwq;
4878d8354f26SGreg Kroah-Hartman
48798719dceaSTejun Heo /* disallow meddling with max_active for ordered workqueues */
48800a94efb5STejun Heo if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
48818719dceaSTejun Heo return;
48828719dceaSTejun Heo
4883f3421797STejun Heo max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
4884dcd989cbSTejun Heo
4885a357fc03SLai Jiangshan mutex_lock(&wq->mutex);
4886dcd989cbSTejun Heo
48870a94efb5STejun Heo wq->flags &= ~__WQ_ORDERED;
4888dcd989cbSTejun Heo wq->saved_max_active = max_active;
4889d8354f26SGreg Kroah-Hartman
4890d8354f26SGreg Kroah-Hartman for_each_pwq(pwq, wq)
4891d8354f26SGreg Kroah-Hartman pwq_adjust_max_active(pwq);
4892dcd989cbSTejun Heo
4893a357fc03SLai Jiangshan mutex_unlock(&wq->mutex);
4894dcd989cbSTejun Heo }
4895dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_set_max_active);
4896dcd989cbSTejun Heo
4897dcd989cbSTejun Heo /**
489827d4ee03SLukas Wunner * current_work - retrieve %current task's work struct
489927d4ee03SLukas Wunner *
490027d4ee03SLukas Wunner * Determine if %current task is a workqueue worker and what it's working on.
490127d4ee03SLukas Wunner * Useful to find out the context that the %current task is running in.
490227d4ee03SLukas Wunner *
490327d4ee03SLukas Wunner * Return: work struct if %current task is a workqueue worker, %NULL otherwise.
490427d4ee03SLukas Wunner */
current_work(void)490527d4ee03SLukas Wunner struct work_struct *current_work(void)
490627d4ee03SLukas Wunner {
490727d4ee03SLukas Wunner struct worker *worker = current_wq_worker();
490827d4ee03SLukas Wunner
490927d4ee03SLukas Wunner return worker ? worker->current_work : NULL;
491027d4ee03SLukas Wunner }
491127d4ee03SLukas Wunner EXPORT_SYMBOL(current_work);
491227d4ee03SLukas Wunner
491327d4ee03SLukas Wunner /**
4914e6267616STejun Heo * current_is_workqueue_rescuer - is %current workqueue rescuer?
4915e6267616STejun Heo *
4916e6267616STejun Heo * Determine whether %current is a workqueue rescuer. Can be used from
4917e6267616STejun Heo * work functions to determine whether it's being run off the rescuer task.
4918d185af30SYacine Belkadi *
4919d185af30SYacine Belkadi * Return: %true if %current is a workqueue rescuer. %false otherwise.
4920e6267616STejun Heo */
current_is_workqueue_rescuer(void)4921e6267616STejun Heo bool current_is_workqueue_rescuer(void)
4922e6267616STejun Heo {
4923e6267616STejun Heo struct worker *worker = current_wq_worker();
4924e6267616STejun Heo
49256a092dfdSLai Jiangshan return worker && worker->rescue_wq;
4926e6267616STejun Heo }
4927e6267616STejun Heo
4928e6267616STejun Heo /**
4929dcd989cbSTejun Heo * workqueue_congested - test whether a workqueue is congested
4930dcd989cbSTejun Heo * @cpu: CPU in question
4931dcd989cbSTejun Heo * @wq: target workqueue
4932dcd989cbSTejun Heo *
4933dcd989cbSTejun Heo * Test whether @wq's cpu workqueue for @cpu is congested. There is
4934dcd989cbSTejun Heo * no synchronization around this function and the test result is
4935dcd989cbSTejun Heo * unreliable and only useful as advisory hints or for debugging.
4936dcd989cbSTejun Heo *
4937d3251859STejun Heo * If @cpu is WORK_CPU_UNBOUND, the test is performed on the local CPU.
4938636b927eSTejun Heo *
4939636b927eSTejun Heo * With the exception of ordered workqueues, all workqueues have per-cpu
4940636b927eSTejun Heo * pool_workqueues, each with its own congested state. A workqueue being
4941636b927eSTejun Heo * congested on one CPU doesn't mean that the workqueue is contested on any
4942636b927eSTejun Heo * other CPUs.
4943d3251859STejun Heo *
4944d185af30SYacine Belkadi * Return:
4945dcd989cbSTejun Heo * %true if congested, %false otherwise.
4946dcd989cbSTejun Heo */
workqueue_congested(int cpu,struct workqueue_struct * wq)4947d84ff051STejun Heo bool workqueue_congested(int cpu, struct workqueue_struct *wq)
4948dcd989cbSTejun Heo {
49497fb98ea7STejun Heo struct pool_workqueue *pwq;
495076af4d93STejun Heo bool ret;
495176af4d93STejun Heo
495224acfb71SThomas Gleixner rcu_read_lock();
495324acfb71SThomas Gleixner preempt_disable();
49547fb98ea7STejun Heo
4955d3251859STejun Heo if (cpu == WORK_CPU_UNBOUND)
4956d3251859STejun Heo cpu = smp_processor_id();
4957d3251859STejun Heo
4958687a9aa5STejun Heo pwq = *per_cpu_ptr(wq->cpu_pwq, cpu);
4959f97a4a1aSLai Jiangshan ret = !list_empty(&pwq->inactive_works);
4960636b927eSTejun Heo
496124acfb71SThomas Gleixner preempt_enable();
496224acfb71SThomas Gleixner rcu_read_unlock();
496376af4d93STejun Heo
496476af4d93STejun Heo return ret;
4965dcd989cbSTejun Heo }
4966dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(workqueue_congested);
4967dcd989cbSTejun Heo
4968dcd989cbSTejun Heo /**
4969dcd989cbSTejun Heo * work_busy - test whether a work is currently pending or running
4970dcd989cbSTejun Heo * @work: the work to be tested
4971dcd989cbSTejun Heo *
4972dcd989cbSTejun Heo * Test whether @work is currently pending or running. There is no
4973dcd989cbSTejun Heo * synchronization around this function and the test result is
4974dcd989cbSTejun Heo * unreliable and only useful as advisory hints or for debugging.
4975dcd989cbSTejun Heo *
4976d185af30SYacine Belkadi * Return:
4977dcd989cbSTejun Heo * OR'd bitmask of WORK_BUSY_* bits.
4978dcd989cbSTejun Heo */
work_busy(struct work_struct * work)4979dcd989cbSTejun Heo unsigned int work_busy(struct work_struct *work)
4980dcd989cbSTejun Heo {
4981fa1b54e6STejun Heo struct worker_pool *pool;
4982dcd989cbSTejun Heo unsigned long flags;
4983dcd989cbSTejun Heo unsigned int ret = 0;
4984dcd989cbSTejun Heo
4985dcd989cbSTejun Heo if (work_pending(work))
4986dcd989cbSTejun Heo ret |= WORK_BUSY_PENDING;
4987038366c5SLai Jiangshan
498824acfb71SThomas Gleixner rcu_read_lock();
4989fa1b54e6STejun Heo pool = get_work_pool(work);
4990038366c5SLai Jiangshan if (pool) {
4991a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irqsave(&pool->lock, flags);
4992c9e7cf27STejun Heo if (find_worker_executing_work(pool, work))
4993dcd989cbSTejun Heo ret |= WORK_BUSY_RUNNING;
4994a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irqrestore(&pool->lock, flags);
4995038366c5SLai Jiangshan }
499624acfb71SThomas Gleixner rcu_read_unlock();
4997dcd989cbSTejun Heo
4998dcd989cbSTejun Heo return ret;
4999dcd989cbSTejun Heo }
5000dcd989cbSTejun Heo EXPORT_SYMBOL_GPL(work_busy);
5001dcd989cbSTejun Heo
50023d1cb205STejun Heo /**
50033d1cb205STejun Heo * set_worker_desc - set description for the current work item
50043d1cb205STejun Heo * @fmt: printf-style format string
50053d1cb205STejun Heo * @...: arguments for the format string
50063d1cb205STejun Heo *
50073d1cb205STejun Heo * This function can be called by a running work function to describe what
50083d1cb205STejun Heo * the work item is about. If the worker task gets dumped, this
50093d1cb205STejun Heo * information will be printed out together to help debugging. The
50103d1cb205STejun Heo * description can be at most WORKER_DESC_LEN including the trailing '\0'.
50113d1cb205STejun Heo */
set_worker_desc(const char * fmt,...)50123d1cb205STejun Heo void set_worker_desc(const char *fmt, ...)
50133d1cb205STejun Heo {
50143d1cb205STejun Heo struct worker *worker = current_wq_worker();
50153d1cb205STejun Heo va_list args;
50163d1cb205STejun Heo
50173d1cb205STejun Heo if (worker) {
50183d1cb205STejun Heo va_start(args, fmt);
50193d1cb205STejun Heo vsnprintf(worker->desc, sizeof(worker->desc), fmt, args);
50203d1cb205STejun Heo va_end(args);
50213d1cb205STejun Heo }
50223d1cb205STejun Heo }
50235c750d58SSteffen Maier EXPORT_SYMBOL_GPL(set_worker_desc);
50243d1cb205STejun Heo
50253d1cb205STejun Heo /**
50263d1cb205STejun Heo * print_worker_info - print out worker information and description
50273d1cb205STejun Heo * @log_lvl: the log level to use when printing
50283d1cb205STejun Heo * @task: target task
50293d1cb205STejun Heo *
50303d1cb205STejun Heo * If @task is a worker and currently executing a work item, print out the
50313d1cb205STejun Heo * name of the workqueue being serviced and worker description set with
50323d1cb205STejun Heo * set_worker_desc() by the currently executing work item.
50333d1cb205STejun Heo *
50343d1cb205STejun Heo * This function can be safely called on any task as long as the
50353d1cb205STejun Heo * task_struct itself is accessible. While safe, this function isn't
50363d1cb205STejun Heo * synchronized and may print out mixups or garbages of limited length.
50373d1cb205STejun Heo */
print_worker_info(const char * log_lvl,struct task_struct * task)50383d1cb205STejun Heo void print_worker_info(const char *log_lvl, struct task_struct *task)
50393d1cb205STejun Heo {
50403d1cb205STejun Heo work_func_t *fn = NULL;
50413d1cb205STejun Heo char name[WQ_NAME_LEN] = { };
50423d1cb205STejun Heo char desc[WORKER_DESC_LEN] = { };
50433d1cb205STejun Heo struct pool_workqueue *pwq = NULL;
50443d1cb205STejun Heo struct workqueue_struct *wq = NULL;
50453d1cb205STejun Heo struct worker *worker;
50463d1cb205STejun Heo
50473d1cb205STejun Heo if (!(task->flags & PF_WQ_WORKER))
50483d1cb205STejun Heo return;
50493d1cb205STejun Heo
50503d1cb205STejun Heo /*
50513d1cb205STejun Heo * This function is called without any synchronization and @task
50523d1cb205STejun Heo * could be in any state. Be careful with dereferences.
50533d1cb205STejun Heo */
5054e700591aSPetr Mladek worker = kthread_probe_data(task);
50553d1cb205STejun Heo
50563d1cb205STejun Heo /*
50578bf89593STejun Heo * Carefully copy the associated workqueue's workfn, name and desc.
50588bf89593STejun Heo * Keep the original last '\0' in case the original is garbage.
50593d1cb205STejun Heo */
5060fe557319SChristoph Hellwig copy_from_kernel_nofault(&fn, &worker->current_func, sizeof(fn));
5061fe557319SChristoph Hellwig copy_from_kernel_nofault(&pwq, &worker->current_pwq, sizeof(pwq));
5062fe557319SChristoph Hellwig copy_from_kernel_nofault(&wq, &pwq->wq, sizeof(wq));
5063fe557319SChristoph Hellwig copy_from_kernel_nofault(name, wq->name, sizeof(name) - 1);
5064fe557319SChristoph Hellwig copy_from_kernel_nofault(desc, worker->desc, sizeof(desc) - 1);
50653d1cb205STejun Heo
50663d1cb205STejun Heo if (fn || name[0] || desc[0]) {
5067d75f773cSSakari Ailus printk("%sWorkqueue: %s %ps", log_lvl, name, fn);
50688bf89593STejun Heo if (strcmp(name, desc))
50693d1cb205STejun Heo pr_cont(" (%s)", desc);
50703d1cb205STejun Heo pr_cont("\n");
50713d1cb205STejun Heo }
50723d1cb205STejun Heo }
50733d1cb205STejun Heo
pr_cont_pool_info(struct worker_pool * pool)50743494fc30STejun Heo static void pr_cont_pool_info(struct worker_pool *pool)
50753494fc30STejun Heo {
50763494fc30STejun Heo pr_cont(" cpus=%*pbl", nr_cpumask_bits, pool->attrs->cpumask);
50773494fc30STejun Heo if (pool->node != NUMA_NO_NODE)
50783494fc30STejun Heo pr_cont(" node=%d", pool->node);
50793494fc30STejun Heo pr_cont(" flags=0x%x nice=%d", pool->flags, pool->attrs->nice);
50803494fc30STejun Heo }
50813494fc30STejun Heo
5082c76feb0dSPaul E. McKenney struct pr_cont_work_struct {
5083c76feb0dSPaul E. McKenney bool comma;
5084c76feb0dSPaul E. McKenney work_func_t func;
5085c76feb0dSPaul E. McKenney long ctr;
5086c76feb0dSPaul E. McKenney };
5087c76feb0dSPaul E. McKenney
pr_cont_work_flush(bool comma,work_func_t func,struct pr_cont_work_struct * pcwsp)5088c76feb0dSPaul E. McKenney static void pr_cont_work_flush(bool comma, work_func_t func, struct pr_cont_work_struct *pcwsp)
5089c76feb0dSPaul E. McKenney {
5090c76feb0dSPaul E. McKenney if (!pcwsp->ctr)
5091c76feb0dSPaul E. McKenney goto out_record;
5092c76feb0dSPaul E. McKenney if (func == pcwsp->func) {
5093c76feb0dSPaul E. McKenney pcwsp->ctr++;
5094c76feb0dSPaul E. McKenney return;
5095c76feb0dSPaul E. McKenney }
5096c76feb0dSPaul E. McKenney if (pcwsp->ctr == 1)
5097c76feb0dSPaul E. McKenney pr_cont("%s %ps", pcwsp->comma ? "," : "", pcwsp->func);
5098c76feb0dSPaul E. McKenney else
5099c76feb0dSPaul E. McKenney pr_cont("%s %ld*%ps", pcwsp->comma ? "," : "", pcwsp->ctr, pcwsp->func);
5100c76feb0dSPaul E. McKenney pcwsp->ctr = 0;
5101c76feb0dSPaul E. McKenney out_record:
5102c76feb0dSPaul E. McKenney if ((long)func == -1L)
5103c76feb0dSPaul E. McKenney return;
5104c76feb0dSPaul E. McKenney pcwsp->comma = comma;
5105c76feb0dSPaul E. McKenney pcwsp->func = func;
5106c76feb0dSPaul E. McKenney pcwsp->ctr = 1;
5107c76feb0dSPaul E. McKenney }
5108c76feb0dSPaul E. McKenney
pr_cont_work(bool comma,struct work_struct * work,struct pr_cont_work_struct * pcwsp)5109c76feb0dSPaul E. McKenney static void pr_cont_work(bool comma, struct work_struct *work, struct pr_cont_work_struct *pcwsp)
51103494fc30STejun Heo {
51113494fc30STejun Heo if (work->func == wq_barrier_func) {
51123494fc30STejun Heo struct wq_barrier *barr;
51133494fc30STejun Heo
51143494fc30STejun Heo barr = container_of(work, struct wq_barrier, work);
51153494fc30STejun Heo
5116c76feb0dSPaul E. McKenney pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
51173494fc30STejun Heo pr_cont("%s BAR(%d)", comma ? "," : "",
51183494fc30STejun Heo task_pid_nr(barr->task));
51193494fc30STejun Heo } else {
5120c76feb0dSPaul E. McKenney if (!comma)
5121c76feb0dSPaul E. McKenney pr_cont_work_flush(comma, (work_func_t)-1, pcwsp);
5122c76feb0dSPaul E. McKenney pr_cont_work_flush(comma, work->func, pcwsp);
51233494fc30STejun Heo }
51243494fc30STejun Heo }
51253494fc30STejun Heo
show_pwq(struct pool_workqueue * pwq)51263494fc30STejun Heo static void show_pwq(struct pool_workqueue *pwq)
51273494fc30STejun Heo {
5128c76feb0dSPaul E. McKenney struct pr_cont_work_struct pcws = { .ctr = 0, };
51293494fc30STejun Heo struct worker_pool *pool = pwq->pool;
51303494fc30STejun Heo struct work_struct *work;
51313494fc30STejun Heo struct worker *worker;
51323494fc30STejun Heo bool has_in_flight = false, has_pending = false;
51333494fc30STejun Heo int bkt;
51343494fc30STejun Heo
51353494fc30STejun Heo pr_info(" pwq %d:", pool->id);
51363494fc30STejun Heo pr_cont_pool_info(pool);
51373494fc30STejun Heo
5138d8354f26SGreg Kroah-Hartman pr_cont(" active=%d/%d refcnt=%d%s\n",
5139d8354f26SGreg Kroah-Hartman pwq->nr_active, pwq->max_active, pwq->refcnt,
51403494fc30STejun Heo !list_empty(&pwq->mayday_node) ? " MAYDAY" : "");
51413494fc30STejun Heo
51423494fc30STejun Heo hash_for_each(pool->busy_hash, bkt, worker, hentry) {
51433494fc30STejun Heo if (worker->current_pwq == pwq) {
51443494fc30STejun Heo has_in_flight = true;
51453494fc30STejun Heo break;
51463494fc30STejun Heo }
51473494fc30STejun Heo }
51483494fc30STejun Heo if (has_in_flight) {
51493494fc30STejun Heo bool comma = false;
51503494fc30STejun Heo
51513494fc30STejun Heo pr_info(" in-flight:");
51523494fc30STejun Heo hash_for_each(pool->busy_hash, bkt, worker, hentry) {
51533494fc30STejun Heo if (worker->current_pwq != pwq)
51543494fc30STejun Heo continue;
51553494fc30STejun Heo
5156d75f773cSSakari Ailus pr_cont("%s %d%s:%ps", comma ? "," : "",
51573494fc30STejun Heo task_pid_nr(worker->task),
515830ae2fc0STejun Heo worker->rescue_wq ? "(RESCUER)" : "",
51593494fc30STejun Heo worker->current_func);
51603494fc30STejun Heo list_for_each_entry(work, &worker->scheduled, entry)
5161c76feb0dSPaul E. McKenney pr_cont_work(false, work, &pcws);
5162c76feb0dSPaul E. McKenney pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
51633494fc30STejun Heo comma = true;
51643494fc30STejun Heo }
51653494fc30STejun Heo pr_cont("\n");
51663494fc30STejun Heo }
51673494fc30STejun Heo
51683494fc30STejun Heo list_for_each_entry(work, &pool->worklist, entry) {
51693494fc30STejun Heo if (get_work_pwq(work) == pwq) {
51703494fc30STejun Heo has_pending = true;
51713494fc30STejun Heo break;
51723494fc30STejun Heo }
51733494fc30STejun Heo }
51743494fc30STejun Heo if (has_pending) {
51753494fc30STejun Heo bool comma = false;
51763494fc30STejun Heo
51773494fc30STejun Heo pr_info(" pending:");
51783494fc30STejun Heo list_for_each_entry(work, &pool->worklist, entry) {
51793494fc30STejun Heo if (get_work_pwq(work) != pwq)
51803494fc30STejun Heo continue;
51813494fc30STejun Heo
5182c76feb0dSPaul E. McKenney pr_cont_work(comma, work, &pcws);
51833494fc30STejun Heo comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
51843494fc30STejun Heo }
5185c76feb0dSPaul E. McKenney pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
51863494fc30STejun Heo pr_cont("\n");
51873494fc30STejun Heo }
51883494fc30STejun Heo
5189f97a4a1aSLai Jiangshan if (!list_empty(&pwq->inactive_works)) {
51903494fc30STejun Heo bool comma = false;
51913494fc30STejun Heo
5192f97a4a1aSLai Jiangshan pr_info(" inactive:");
5193f97a4a1aSLai Jiangshan list_for_each_entry(work, &pwq->inactive_works, entry) {
5194c76feb0dSPaul E. McKenney pr_cont_work(comma, work, &pcws);
51953494fc30STejun Heo comma = !(*work_data_bits(work) & WORK_STRUCT_LINKED);
51963494fc30STejun Heo }
5197c76feb0dSPaul E. McKenney pr_cont_work_flush(comma, (work_func_t)-1L, &pcws);
51983494fc30STejun Heo pr_cont("\n");
51993494fc30STejun Heo }
52003494fc30STejun Heo }
52013494fc30STejun Heo
52023494fc30STejun Heo /**
520355df0933SImran Khan * show_one_workqueue - dump state of specified workqueue
520455df0933SImran Khan * @wq: workqueue whose state will be printed
52053494fc30STejun Heo */
show_one_workqueue(struct workqueue_struct * wq)520655df0933SImran Khan void show_one_workqueue(struct workqueue_struct *wq)
52073494fc30STejun Heo {
52083494fc30STejun Heo struct pool_workqueue *pwq;
52093494fc30STejun Heo bool idle = true;
521055df0933SImran Khan unsigned long flags;
52113494fc30STejun Heo
52123494fc30STejun Heo for_each_pwq(pwq, wq) {
521335bf38ddSGreg Kroah-Hartman if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
52143494fc30STejun Heo idle = false;
52153494fc30STejun Heo break;
52163494fc30STejun Heo }
52173494fc30STejun Heo }
521855df0933SImran Khan if (idle) /* Nothing to print for idle workqueue */
521955df0933SImran Khan return;
52203494fc30STejun Heo
52213494fc30STejun Heo pr_info("workqueue %s: flags=0x%x\n", wq->name, wq->flags);
52223494fc30STejun Heo
52233494fc30STejun Heo for_each_pwq(pwq, wq) {
5224a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irqsave(&pwq->pool->lock, flags);
522535bf38ddSGreg Kroah-Hartman if (pwq->nr_active || !list_empty(&pwq->inactive_works)) {
522657116ce1SJohan Hovold /*
522757116ce1SJohan Hovold * Defer printing to avoid deadlocks in console
522857116ce1SJohan Hovold * drivers that queue work while holding locks
522957116ce1SJohan Hovold * also taken in their write paths.
523057116ce1SJohan Hovold */
523157116ce1SJohan Hovold printk_deferred_enter();
52323494fc30STejun Heo show_pwq(pwq);
523357116ce1SJohan Hovold printk_deferred_exit();
523457116ce1SJohan Hovold }
5235a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irqrestore(&pwq->pool->lock, flags);
523662635ea8SSergey Senozhatsky /*
523762635ea8SSergey Senozhatsky * We could be printing a lot from atomic context, e.g.
523855df0933SImran Khan * sysrq-t -> show_all_workqueues(). Avoid triggering
523962635ea8SSergey Senozhatsky * hard lockup.
524062635ea8SSergey Senozhatsky */
524162635ea8SSergey Senozhatsky touch_nmi_watchdog();
52423494fc30STejun Heo }
524355df0933SImran Khan
52443494fc30STejun Heo }
52453494fc30STejun Heo
524655df0933SImran Khan /**
524755df0933SImran Khan * show_one_worker_pool - dump state of specified worker pool
524855df0933SImran Khan * @pool: worker pool whose state will be printed
524955df0933SImran Khan */
show_one_worker_pool(struct worker_pool * pool)525055df0933SImran Khan static void show_one_worker_pool(struct worker_pool *pool)
525155df0933SImran Khan {
52523494fc30STejun Heo struct worker *worker;
52533494fc30STejun Heo bool first = true;
525455df0933SImran Khan unsigned long flags;
5255335a42ebSPetr Mladek unsigned long hung = 0;
52563494fc30STejun Heo
5257a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irqsave(&pool->lock, flags);
52583494fc30STejun Heo if (pool->nr_workers == pool->nr_idle)
52593494fc30STejun Heo goto next_pool;
5260335a42ebSPetr Mladek
5261335a42ebSPetr Mladek /* How long the first pending work is waiting for a worker. */
5262335a42ebSPetr Mladek if (!list_empty(&pool->worklist))
5263335a42ebSPetr Mladek hung = jiffies_to_msecs(jiffies - pool->watchdog_ts) / 1000;
5264335a42ebSPetr Mladek
526557116ce1SJohan Hovold /*
526657116ce1SJohan Hovold * Defer printing to avoid deadlocks in console drivers that
526757116ce1SJohan Hovold * queue work while holding locks also taken in their write
526857116ce1SJohan Hovold * paths.
526957116ce1SJohan Hovold */
527057116ce1SJohan Hovold printk_deferred_enter();
52713494fc30STejun Heo pr_info("pool %d:", pool->id);
52723494fc30STejun Heo pr_cont_pool_info(pool);
5273335a42ebSPetr Mladek pr_cont(" hung=%lus workers=%d", hung, pool->nr_workers);
52743494fc30STejun Heo if (pool->manager)
52753494fc30STejun Heo pr_cont(" manager: %d",
52763494fc30STejun Heo task_pid_nr(pool->manager->task));
52773494fc30STejun Heo list_for_each_entry(worker, &pool->idle_list, entry) {
52783494fc30STejun Heo pr_cont(" %s%d", first ? "idle: " : "",
52793494fc30STejun Heo task_pid_nr(worker->task));
52803494fc30STejun Heo first = false;
52813494fc30STejun Heo }
52823494fc30STejun Heo pr_cont("\n");
528357116ce1SJohan Hovold printk_deferred_exit();
52843494fc30STejun Heo next_pool:
5285a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irqrestore(&pool->lock, flags);
528662635ea8SSergey Senozhatsky /*
528762635ea8SSergey Senozhatsky * We could be printing a lot from atomic context, e.g.
528855df0933SImran Khan * sysrq-t -> show_all_workqueues(). Avoid triggering
528962635ea8SSergey Senozhatsky * hard lockup.
529062635ea8SSergey Senozhatsky */
529162635ea8SSergey Senozhatsky touch_nmi_watchdog();
529255df0933SImran Khan
52933494fc30STejun Heo }
52943494fc30STejun Heo
529555df0933SImran Khan /**
529655df0933SImran Khan * show_all_workqueues - dump workqueue state
529755df0933SImran Khan *
5298704bc669SJungseung Lee * Called from a sysrq handler and prints out all busy workqueues and pools.
529955df0933SImran Khan */
show_all_workqueues(void)530055df0933SImran Khan void show_all_workqueues(void)
530155df0933SImran Khan {
530255df0933SImran Khan struct workqueue_struct *wq;
530355df0933SImran Khan struct worker_pool *pool;
530455df0933SImran Khan int pi;
530555df0933SImran Khan
530655df0933SImran Khan rcu_read_lock();
530755df0933SImran Khan
530855df0933SImran Khan pr_info("Showing busy workqueues and worker pools:\n");
530955df0933SImran Khan
531055df0933SImran Khan list_for_each_entry_rcu(wq, &workqueues, list)
531155df0933SImran Khan show_one_workqueue(wq);
531255df0933SImran Khan
531355df0933SImran Khan for_each_pool(pool, pi)
531455df0933SImran Khan show_one_worker_pool(pool);
531555df0933SImran Khan
531624acfb71SThomas Gleixner rcu_read_unlock();
53173494fc30STejun Heo }
53183494fc30STejun Heo
5319704bc669SJungseung Lee /**
5320704bc669SJungseung Lee * show_freezable_workqueues - dump freezable workqueue state
5321704bc669SJungseung Lee *
5322704bc669SJungseung Lee * Called from try_to_freeze_tasks() and prints out all freezable workqueues
5323704bc669SJungseung Lee * still busy.
5324704bc669SJungseung Lee */
show_freezable_workqueues(void)5325704bc669SJungseung Lee void show_freezable_workqueues(void)
5326704bc669SJungseung Lee {
5327704bc669SJungseung Lee struct workqueue_struct *wq;
5328704bc669SJungseung Lee
5329704bc669SJungseung Lee rcu_read_lock();
5330704bc669SJungseung Lee
5331704bc669SJungseung Lee pr_info("Showing freezable workqueues that are still busy:\n");
5332704bc669SJungseung Lee
5333704bc669SJungseung Lee list_for_each_entry_rcu(wq, &workqueues, list) {
5334704bc669SJungseung Lee if (!(wq->flags & WQ_FREEZABLE))
5335704bc669SJungseung Lee continue;
5336704bc669SJungseung Lee show_one_workqueue(wq);
5337704bc669SJungseung Lee }
5338704bc669SJungseung Lee
5339704bc669SJungseung Lee rcu_read_unlock();
5340704bc669SJungseung Lee }
5341704bc669SJungseung Lee
53426b59808bSTejun Heo /* used to show worker information through /proc/PID/{comm,stat,status} */
wq_worker_comm(char * buf,size_t size,struct task_struct * task)53436b59808bSTejun Heo void wq_worker_comm(char *buf, size_t size, struct task_struct *task)
53446b59808bSTejun Heo {
53456b59808bSTejun Heo int off;
53466b59808bSTejun Heo
53476b59808bSTejun Heo /* always show the actual comm */
53486b59808bSTejun Heo off = strscpy(buf, task->comm, size);
53496b59808bSTejun Heo if (off < 0)
53506b59808bSTejun Heo return;
53516b59808bSTejun Heo
5352197f6accSTejun Heo /* stabilize PF_WQ_WORKER and worker pool association */
53536b59808bSTejun Heo mutex_lock(&wq_pool_attach_mutex);
53546b59808bSTejun Heo
5355197f6accSTejun Heo if (task->flags & PF_WQ_WORKER) {
5356197f6accSTejun Heo struct worker *worker = kthread_data(task);
5357197f6accSTejun Heo struct worker_pool *pool = worker->pool;
53586b59808bSTejun Heo
53596b59808bSTejun Heo if (pool) {
5360a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pool->lock);
53616b59808bSTejun Heo /*
5362197f6accSTejun Heo * ->desc tracks information (wq name or
5363197f6accSTejun Heo * set_worker_desc()) for the latest execution. If
5364197f6accSTejun Heo * current, prepend '+', otherwise '-'.
53656b59808bSTejun Heo */
53666b59808bSTejun Heo if (worker->desc[0] != '\0') {
53676b59808bSTejun Heo if (worker->current_work)
53686b59808bSTejun Heo scnprintf(buf + off, size - off, "+%s",
53696b59808bSTejun Heo worker->desc);
53706b59808bSTejun Heo else
53716b59808bSTejun Heo scnprintf(buf + off, size - off, "-%s",
53726b59808bSTejun Heo worker->desc);
53736b59808bSTejun Heo }
5374a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
53756b59808bSTejun Heo }
5376197f6accSTejun Heo }
53776b59808bSTejun Heo
53786b59808bSTejun Heo mutex_unlock(&wq_pool_attach_mutex);
53796b59808bSTejun Heo }
53806b59808bSTejun Heo
538166448bc2SMathieu Malaterre #ifdef CONFIG_SMP
538266448bc2SMathieu Malaterre
5383db7bccf4STejun Heo /*
5384db7bccf4STejun Heo * CPU hotplug.
5385db7bccf4STejun Heo *
5386e22bee78STejun Heo * There are two challenges in supporting CPU hotplug. Firstly, there
5387112202d9STejun Heo * are a lot of assumptions on strong associations among work, pwq and
5388706026c2STejun Heo * pool which make migrating pending and scheduled works very
5389e22bee78STejun Heo * difficult to implement without impacting hot paths. Secondly,
539094cf58bbSTejun Heo * worker pools serve mix of short, long and very long running works making
5391e22bee78STejun Heo * blocked draining impractical.
5392e22bee78STejun Heo *
539324647570STejun Heo * This is solved by allowing the pools to be disassociated from the CPU
5394628c78e7STejun Heo * running as an unbound one and allowing it to be reattached later if the
5395628c78e7STejun Heo * cpu comes back online.
5396db7bccf4STejun Heo */
5397db7bccf4STejun Heo
unbind_workers(int cpu)5398e8b3f8dbSLai Jiangshan static void unbind_workers(int cpu)
5399db7bccf4STejun Heo {
54004ce62e9eSTejun Heo struct worker_pool *pool;
5401db7bccf4STejun Heo struct worker *worker;
5402db7bccf4STejun Heo
5403f02ae73aSTejun Heo for_each_cpu_worker_pool(pool, cpu) {
54041258fae7STejun Heo mutex_lock(&wq_pool_attach_mutex);
5405a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pool->lock);
5406e22bee78STejun Heo
5407f2d5a0eeSTejun Heo /*
540892f9c5c4SLai Jiangshan * We've blocked all attach/detach operations. Make all workers
540994cf58bbSTejun Heo * unbound and set DISASSOCIATED. Before this, all workers
541011b45b0bSLai Jiangshan * must be on the cpu. After this, they may become diasporas.
5411b4ac9384SLai Jiangshan * And the preemption disabled section in their sched callbacks
5412b4ac9384SLai Jiangshan * are guaranteed to see WORKER_UNBOUND since the code here
5413b4ac9384SLai Jiangshan * is on the same cpu.
5414f2d5a0eeSTejun Heo */
5415da028469SLai Jiangshan for_each_pool_worker(worker, pool)
5416403c821dSTejun Heo worker->flags |= WORKER_UNBOUND;
5417db7bccf4STejun Heo
541824647570STejun Heo pool->flags |= POOL_DISASSOCIATED;
5419f2d5a0eeSTejun Heo
5420e22bee78STejun Heo /*
5421989442d7SLai Jiangshan * The handling of nr_running in sched callbacks are disabled
5422989442d7SLai Jiangshan * now. Zap nr_running. After this, nr_running stays zero and
5423989442d7SLai Jiangshan * need_more_worker() and keep_working() are always true as
5424989442d7SLai Jiangshan * long as the worklist is not empty. This pool now behaves as
5425989442d7SLai Jiangshan * an unbound (in terms of concurrency management) pool which
5426eb283428SLai Jiangshan * are served by workers tied to the pool.
5427e22bee78STejun Heo */
5428bc35f7efSLai Jiangshan pool->nr_running = 0;
5429eb283428SLai Jiangshan
5430eb283428SLai Jiangshan /*
5431eb283428SLai Jiangshan * With concurrency management just turned off, a busy
5432eb283428SLai Jiangshan * worker blocking could lead to lengthy stalls. Kick off
5433eb283428SLai Jiangshan * unbound chain execution of currently pending work items.
5434eb283428SLai Jiangshan */
54350219a352STejun Heo kick_pool(pool);
5436989442d7SLai Jiangshan
5437a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
5438989442d7SLai Jiangshan
5439793777bcSValentin Schneider for_each_pool_worker(worker, pool)
5440793777bcSValentin Schneider unbind_worker(worker);
5441989442d7SLai Jiangshan
5442989442d7SLai Jiangshan mutex_unlock(&wq_pool_attach_mutex);
5443eb283428SLai Jiangshan }
5444db7bccf4STejun Heo }
5445db7bccf4STejun Heo
5446bd7c089eSTejun Heo /**
5447bd7c089eSTejun Heo * rebind_workers - rebind all workers of a pool to the associated CPU
5448bd7c089eSTejun Heo * @pool: pool of interest
5449bd7c089eSTejun Heo *
5450a9ab775bSTejun Heo * @pool->cpu is coming online. Rebind all workers to the CPU.
5451bd7c089eSTejun Heo */
rebind_workers(struct worker_pool * pool)5452bd7c089eSTejun Heo static void rebind_workers(struct worker_pool *pool)
5453bd7c089eSTejun Heo {
5454a9ab775bSTejun Heo struct worker *worker;
5455bd7c089eSTejun Heo
54561258fae7STejun Heo lockdep_assert_held(&wq_pool_attach_mutex);
5457bd7c089eSTejun Heo
5458bd7c089eSTejun Heo /*
5459a9ab775bSTejun Heo * Restore CPU affinity of all workers. As all idle workers should
5460a9ab775bSTejun Heo * be on the run-queue of the associated CPU before any local
5461402dd89dSShailendra Verma * wake-ups for concurrency management happen, restore CPU affinity
5462a9ab775bSTejun Heo * of all workers first and then clear UNBOUND. As we're called
5463a9ab775bSTejun Heo * from CPU_ONLINE, the following shouldn't fail.
5464bd7c089eSTejun Heo */
5465c63a2e52SValentin Schneider for_each_pool_worker(worker, pool) {
5466c63a2e52SValentin Schneider kthread_set_per_cpu(worker->task, pool->cpu);
5467c63a2e52SValentin Schneider WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task,
54689546b29eSTejun Heo pool_allowed_cpus(pool)) < 0);
5469c63a2e52SValentin Schneider }
5470a9ab775bSTejun Heo
5471a9b8a985SSebastian Andrzej Siewior raw_spin_lock_irq(&pool->lock);
5472f7c17d26SWanpeng Li
54733de5e884SLai Jiangshan pool->flags &= ~POOL_DISASSOCIATED;
5474a9ab775bSTejun Heo
5475da028469SLai Jiangshan for_each_pool_worker(worker, pool) {
5476a9ab775bSTejun Heo unsigned int worker_flags = worker->flags;
5477a9ab775bSTejun Heo
5478a9ab775bSTejun Heo /*
5479a9ab775bSTejun Heo * We want to clear UNBOUND but can't directly call
5480a9ab775bSTejun Heo * worker_clr_flags() or adjust nr_running. Atomically
5481a9ab775bSTejun Heo * replace UNBOUND with another NOT_RUNNING flag REBOUND.
5482a9ab775bSTejun Heo * @worker will clear REBOUND using worker_clr_flags() when
5483a9ab775bSTejun Heo * it initiates the next execution cycle thus restoring
5484a9ab775bSTejun Heo * concurrency management. Note that when or whether
5485a9ab775bSTejun Heo * @worker clears REBOUND doesn't affect correctness.
5486a9ab775bSTejun Heo *
5487c95491edSMark Rutland * WRITE_ONCE() is necessary because @worker->flags may be
5488a9ab775bSTejun Heo * tested without holding any lock in
54896d25be57SThomas Gleixner * wq_worker_running(). Without it, NOT_RUNNING test may
5490a9ab775bSTejun Heo * fail incorrectly leading to premature concurrency
5491a9ab775bSTejun Heo * management operations.
5492bd7c089eSTejun Heo */
5493a9ab775bSTejun Heo WARN_ON_ONCE(!(worker_flags & WORKER_UNBOUND));
5494a9ab775bSTejun Heo worker_flags |= WORKER_REBOUND;
5495a9ab775bSTejun Heo worker_flags &= ~WORKER_UNBOUND;
5496c95491edSMark Rutland WRITE_ONCE(worker->flags, worker_flags);
5497bd7c089eSTejun Heo }
5498a9ab775bSTejun Heo
5499a9b8a985SSebastian Andrzej Siewior raw_spin_unlock_irq(&pool->lock);
5500bd7c089eSTejun Heo }
5501bd7c089eSTejun Heo
55027dbc725eSTejun Heo /**
55037dbc725eSTejun Heo * restore_unbound_workers_cpumask - restore cpumask of unbound workers
55047dbc725eSTejun Heo * @pool: unbound pool of interest
55057dbc725eSTejun Heo * @cpu: the CPU which is coming up
55067dbc725eSTejun Heo *
55077dbc725eSTejun Heo * An unbound pool may end up with a cpumask which doesn't have any online
55087dbc725eSTejun Heo * CPUs. When a worker of such pool get scheduled, the scheduler resets
55097dbc725eSTejun Heo * its cpus_allowed. If @cpu is in @pool's cpumask which didn't have any
55107dbc725eSTejun Heo * online CPU before, cpus_allowed of all its workers should be restored.
55117dbc725eSTejun Heo */
restore_unbound_workers_cpumask(struct worker_pool * pool,int cpu)55127dbc725eSTejun Heo static void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
55137dbc725eSTejun Heo {
55147dbc725eSTejun Heo static cpumask_t cpumask;
55157dbc725eSTejun Heo struct worker *worker;
55167dbc725eSTejun Heo
55171258fae7STejun Heo lockdep_assert_held(&wq_pool_attach_mutex);
55187dbc725eSTejun Heo
55197dbc725eSTejun Heo /* is @cpu allowed for @pool? */
55207dbc725eSTejun Heo if (!cpumask_test_cpu(cpu, pool->attrs->cpumask))
55217dbc725eSTejun Heo return;
55227dbc725eSTejun Heo
55237dbc725eSTejun Heo cpumask_and(&cpumask, pool->attrs->cpumask, cpu_online_mask);
55247dbc725eSTejun Heo
55257dbc725eSTejun Heo /* as we're called from CPU_ONLINE, the following shouldn't fail */
5526da028469SLai Jiangshan for_each_pool_worker(worker, pool)
5527d945b5e9SPeter Zijlstra WARN_ON_ONCE(set_cpus_allowed_ptr(worker->task, &cpumask) < 0);
55287dbc725eSTejun Heo }
55297dbc725eSTejun Heo
workqueue_prepare_cpu(unsigned int cpu)55307ee681b2SThomas Gleixner int workqueue_prepare_cpu(unsigned int cpu)
55311da177e4SLinus Torvalds {
55324ce62e9eSTejun Heo struct worker_pool *pool;
55331da177e4SLinus Torvalds
5534f02ae73aSTejun Heo for_each_cpu_worker_pool(pool, cpu) {
55353ce63377STejun Heo if (pool->nr_workers)
55363ce63377STejun Heo continue;
5537051e1850SLai Jiangshan if (!create_worker(pool))
55387ee681b2SThomas Gleixner return -ENOMEM;
55393af24433SOleg Nesterov }
55407ee681b2SThomas Gleixner return 0;
55417ee681b2SThomas Gleixner }
55421da177e4SLinus Torvalds
workqueue_online_cpu(unsigned int cpu)55437ee681b2SThomas Gleixner int workqueue_online_cpu(unsigned int cpu)
55447ee681b2SThomas Gleixner {
55457ee681b2SThomas Gleixner struct worker_pool *pool;
55467ee681b2SThomas Gleixner struct workqueue_struct *wq;
55477ee681b2SThomas Gleixner int pi;
55487ee681b2SThomas Gleixner
554968e13a67SLai Jiangshan mutex_lock(&wq_pool_mutex);
55507dbc725eSTejun Heo
55517dbc725eSTejun Heo for_each_pool(pool, pi) {
55521258fae7STejun Heo mutex_lock(&wq_pool_attach_mutex);
555394cf58bbSTejun Heo
5554f05b558dSLai Jiangshan if (pool->cpu == cpu)
555594cf58bbSTejun Heo rebind_workers(pool);
5556f05b558dSLai Jiangshan else if (pool->cpu < 0)
55577dbc725eSTejun Heo restore_unbound_workers_cpumask(pool, cpu);
555894cf58bbSTejun Heo
55591258fae7STejun Heo mutex_unlock(&wq_pool_attach_mutex);
556094cf58bbSTejun Heo }
55617dbc725eSTejun Heo
5562fef59c9cSTejun Heo /* update pod affinity of unbound workqueues */
55634cbfd3deSTejun Heo list_for_each_entry(wq, &workqueues, list) {
556484193c07STejun Heo struct workqueue_attrs *attrs = wq->unbound_attrs;
556584193c07STejun Heo
556684193c07STejun Heo if (attrs) {
556784193c07STejun Heo const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
55684cbfd3deSTejun Heo int tcpu;
55694cbfd3deSTejun Heo
557084193c07STejun Heo for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
5571fef59c9cSTejun Heo wq_update_pod(wq, tcpu, cpu, true);
55724cbfd3deSTejun Heo }
55734cbfd3deSTejun Heo }
55744c16bd32STejun Heo
557568e13a67SLai Jiangshan mutex_unlock(&wq_pool_mutex);
55767ee681b2SThomas Gleixner return 0;
557765758202STejun Heo }
557865758202STejun Heo
workqueue_offline_cpu(unsigned int cpu)55797ee681b2SThomas Gleixner int workqueue_offline_cpu(unsigned int cpu)
558065758202STejun Heo {
55814c16bd32STejun Heo struct workqueue_struct *wq;
55828db25e78STejun Heo
55834c16bd32STejun Heo /* unbinding per-cpu workers should happen on the local CPU */
5584e8b3f8dbSLai Jiangshan if (WARN_ON(cpu != smp_processor_id()))
5585e8b3f8dbSLai Jiangshan return -1;
5586e8b3f8dbSLai Jiangshan
5587e8b3f8dbSLai Jiangshan unbind_workers(cpu);
55884c16bd32STejun Heo
5589fef59c9cSTejun Heo /* update pod affinity of unbound workqueues */
55904c16bd32STejun Heo mutex_lock(&wq_pool_mutex);
55914cbfd3deSTejun Heo list_for_each_entry(wq, &workqueues, list) {
559284193c07STejun Heo struct workqueue_attrs *attrs = wq->unbound_attrs;
559384193c07STejun Heo
559484193c07STejun Heo if (attrs) {
559584193c07STejun Heo const struct wq_pod_type *pt = wqattrs_pod_type(attrs);
55964cbfd3deSTejun Heo int tcpu;
55974cbfd3deSTejun Heo
559884193c07STejun Heo for_each_cpu(tcpu, pt->pod_cpus[pt->cpu_pod[cpu]])
5599fef59c9cSTejun Heo wq_update_pod(wq, tcpu, cpu, false);
56004cbfd3deSTejun Heo }
56014cbfd3deSTejun Heo }
56024c16bd32STejun Heo mutex_unlock(&wq_pool_mutex);
56034c16bd32STejun Heo
56047ee681b2SThomas Gleixner return 0;
560565758202STejun Heo }
560665758202STejun Heo
56072d3854a3SRusty Russell struct work_for_cpu {
5608ed48ece2STejun Heo struct work_struct work;
56092d3854a3SRusty Russell long (*fn)(void *);
56102d3854a3SRusty Russell void *arg;
56112d3854a3SRusty Russell long ret;
56122d3854a3SRusty Russell };
56132d3854a3SRusty Russell
work_for_cpu_fn(struct work_struct * work)5614ed48ece2STejun Heo static void work_for_cpu_fn(struct work_struct *work)
56152d3854a3SRusty Russell {
5616ed48ece2STejun Heo struct work_for_cpu *wfc = container_of(work, struct work_for_cpu, work);
5617ed48ece2STejun Heo
56182d3854a3SRusty Russell wfc->ret = wfc->fn(wfc->arg);
56192d3854a3SRusty Russell }
56202d3854a3SRusty Russell
56212d3854a3SRusty Russell /**
5622be2355b7SFrederic Weisbecker * work_on_cpu_key - run a function in thread context on a particular cpu
56232d3854a3SRusty Russell * @cpu: the cpu to run on
56242d3854a3SRusty Russell * @fn: the function to run
56252d3854a3SRusty Russell * @arg: the function arg
5626be2355b7SFrederic Weisbecker * @key: The lock class key for lock debugging purposes
56272d3854a3SRusty Russell *
562831ad9081SRusty Russell * It is up to the caller to ensure that the cpu doesn't go offline.
56296b44003eSAndrew Morton * The caller must not hold any locks which would prevent @fn from completing.
5630d185af30SYacine Belkadi *
5631d185af30SYacine Belkadi * Return: The value @fn returns.
56322d3854a3SRusty Russell */
work_on_cpu_key(int cpu,long (* fn)(void *),void * arg,struct lock_class_key * key)5633be2355b7SFrederic Weisbecker long work_on_cpu_key(int cpu, long (*fn)(void *),
5634be2355b7SFrederic Weisbecker void *arg, struct lock_class_key *key)
56352d3854a3SRusty Russell {
5636ed48ece2STejun Heo struct work_for_cpu wfc = { .fn = fn, .arg = arg };
56372d3854a3SRusty Russell
5638be2355b7SFrederic Weisbecker INIT_WORK_ONSTACK_KEY(&wfc.work, work_for_cpu_fn, key);
5639ed48ece2STejun Heo schedule_work_on(cpu, &wfc.work);
564012997d1aSBjorn Helgaas flush_work(&wfc.work);
5641440a1136SChuansheng Liu destroy_work_on_stack(&wfc.work);
56422d3854a3SRusty Russell return wfc.ret;
56432d3854a3SRusty Russell }
5644be2355b7SFrederic Weisbecker EXPORT_SYMBOL_GPL(work_on_cpu_key);
56450e8d6a93SThomas Gleixner
56460e8d6a93SThomas Gleixner /**
5647be2355b7SFrederic Weisbecker * work_on_cpu_safe_key - run a function in thread context on a particular cpu
56480e8d6a93SThomas Gleixner * @cpu: the cpu to run on
56490e8d6a93SThomas Gleixner * @fn: the function to run
56500e8d6a93SThomas Gleixner * @arg: the function argument
5651be2355b7SFrederic Weisbecker * @key: The lock class key for lock debugging purposes
56520e8d6a93SThomas Gleixner *
56530e8d6a93SThomas Gleixner * Disables CPU hotplug and calls work_on_cpu(). The caller must not hold
56540e8d6a93SThomas Gleixner * any locks which would prevent @fn from completing.
56550e8d6a93SThomas Gleixner *
56560e8d6a93SThomas Gleixner * Return: The value @fn returns.
56570e8d6a93SThomas Gleixner */
work_on_cpu_safe_key(int cpu,long (* fn)(void *),void * arg,struct lock_class_key * key)5658be2355b7SFrederic Weisbecker long work_on_cpu_safe_key(int cpu, long (*fn)(void *),
5659be2355b7SFrederic Weisbecker void *arg, struct lock_class_key *key)
56600e8d6a93SThomas Gleixner {
56610e8d6a93SThomas Gleixner long ret = -ENODEV;
56620e8d6a93SThomas Gleixner
5663ffd8bea8SSebastian Andrzej Siewior cpus_read_lock();
56640e8d6a93SThomas Gleixner if (cpu_online(cpu))
5665be2355b7SFrederic Weisbecker ret = work_on_cpu_key(cpu, fn, arg, key);
5666ffd8bea8SSebastian Andrzej Siewior cpus_read_unlock();
56670e8d6a93SThomas Gleixner return ret;
56680e8d6a93SThomas Gleixner }
5669be2355b7SFrederic Weisbecker EXPORT_SYMBOL_GPL(work_on_cpu_safe_key);
56702d3854a3SRusty Russell #endif /* CONFIG_SMP */
56712d3854a3SRusty Russell
5672a0a1a5fdSTejun Heo #ifdef CONFIG_FREEZER
5673e7577c50SRusty Russell
5674a0a1a5fdSTejun Heo /**
5675a0a1a5fdSTejun Heo * freeze_workqueues_begin - begin freezing workqueues
5676a0a1a5fdSTejun Heo *
567758a69cb4STejun Heo * Start freezing workqueues. After this function returns, all freezable
5678f97a4a1aSLai Jiangshan * workqueues will queue new works to their inactive_works list instead of
5679706026c2STejun Heo * pool->worklist.
5680a0a1a5fdSTejun Heo *
5681a0a1a5fdSTejun Heo * CONTEXT:
5682a357fc03SLai Jiangshan * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5683a0a1a5fdSTejun Heo */
freeze_workqueues_begin(void)5684a0a1a5fdSTejun Heo void freeze_workqueues_begin(void)
5685a0a1a5fdSTejun Heo {
568624b8a847STejun Heo struct workqueue_struct *wq;
5687d8354f26SGreg Kroah-Hartman struct pool_workqueue *pwq;
5688a0a1a5fdSTejun Heo
568968e13a67SLai Jiangshan mutex_lock(&wq_pool_mutex);
5690a0a1a5fdSTejun Heo
56916183c009STejun Heo WARN_ON_ONCE(workqueue_freezing);
5692a0a1a5fdSTejun Heo workqueue_freezing = true;
5693a0a1a5fdSTejun Heo
569424b8a847STejun Heo list_for_each_entry(wq, &workqueues, list) {
5695a357fc03SLai Jiangshan mutex_lock(&wq->mutex);
5696d8354f26SGreg Kroah-Hartman for_each_pwq(pwq, wq)
5697d8354f26SGreg Kroah-Hartman pwq_adjust_max_active(pwq);
5698a357fc03SLai Jiangshan mutex_unlock(&wq->mutex);
5699a1056305STejun Heo }
57005bcab335STejun Heo
570168e13a67SLai Jiangshan mutex_unlock(&wq_pool_mutex);
5702a0a1a5fdSTejun Heo }
5703a0a1a5fdSTejun Heo
5704a0a1a5fdSTejun Heo /**
570558a69cb4STejun Heo * freeze_workqueues_busy - are freezable workqueues still busy?
5706a0a1a5fdSTejun Heo *
5707a0a1a5fdSTejun Heo * Check whether freezing is complete. This function must be called
5708a0a1a5fdSTejun Heo * between freeze_workqueues_begin() and thaw_workqueues().
5709a0a1a5fdSTejun Heo *
5710a0a1a5fdSTejun Heo * CONTEXT:
571168e13a67SLai Jiangshan * Grabs and releases wq_pool_mutex.
5712a0a1a5fdSTejun Heo *
5713d185af30SYacine Belkadi * Return:
571458a69cb4STejun Heo * %true if some freezable workqueues are still busy. %false if freezing
571558a69cb4STejun Heo * is complete.
5716a0a1a5fdSTejun Heo */
freeze_workqueues_busy(void)5717a0a1a5fdSTejun Heo bool freeze_workqueues_busy(void)
5718a0a1a5fdSTejun Heo {
5719a0a1a5fdSTejun Heo bool busy = false;
572024b8a847STejun Heo struct workqueue_struct *wq;
572124b8a847STejun Heo struct pool_workqueue *pwq;
5722a0a1a5fdSTejun Heo
572368e13a67SLai Jiangshan mutex_lock(&wq_pool_mutex);
5724a0a1a5fdSTejun Heo
57256183c009STejun Heo WARN_ON_ONCE(!workqueue_freezing);
5726a0a1a5fdSTejun Heo
572724b8a847STejun Heo list_for_each_entry(wq, &workqueues, list) {
572824b8a847STejun Heo if (!(wq->flags & WQ_FREEZABLE))
572924b8a847STejun Heo continue;
5730a0a1a5fdSTejun Heo /*
5731a0a1a5fdSTejun Heo * nr_active is monotonically decreasing. It's safe
5732a0a1a5fdSTejun Heo * to peek without lock.
5733a0a1a5fdSTejun Heo */
573424acfb71SThomas Gleixner rcu_read_lock();
573524b8a847STejun Heo for_each_pwq(pwq, wq) {
57366183c009STejun Heo WARN_ON_ONCE(pwq->nr_active < 0);
5737112202d9STejun Heo if (pwq->nr_active) {
5738a0a1a5fdSTejun Heo busy = true;
573924acfb71SThomas Gleixner rcu_read_unlock();
5740a0a1a5fdSTejun Heo goto out_unlock;
5741a0a1a5fdSTejun Heo }
5742a0a1a5fdSTejun Heo }
574324acfb71SThomas Gleixner rcu_read_unlock();
5744a0a1a5fdSTejun Heo }
5745a0a1a5fdSTejun Heo out_unlock:
574668e13a67SLai Jiangshan mutex_unlock(&wq_pool_mutex);
5747a0a1a5fdSTejun Heo return busy;
5748a0a1a5fdSTejun Heo }
5749a0a1a5fdSTejun Heo
5750a0a1a5fdSTejun Heo /**
5751a0a1a5fdSTejun Heo * thaw_workqueues - thaw workqueues
5752a0a1a5fdSTejun Heo *
5753a0a1a5fdSTejun Heo * Thaw workqueues. Normal queueing is restored and all collected
5754706026c2STejun Heo * frozen works are transferred to their respective pool worklists.
5755a0a1a5fdSTejun Heo *
5756a0a1a5fdSTejun Heo * CONTEXT:
5757a357fc03SLai Jiangshan * Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.
5758a0a1a5fdSTejun Heo */
thaw_workqueues(void)5759a0a1a5fdSTejun Heo void thaw_workqueues(void)
5760a0a1a5fdSTejun Heo {
576124b8a847STejun Heo struct workqueue_struct *wq;
5762d8354f26SGreg Kroah-Hartman struct pool_workqueue *pwq;
5763a0a1a5fdSTejun Heo
576468e13a67SLai Jiangshan mutex_lock(&wq_pool_mutex);
5765a0a1a5fdSTejun Heo
5766a0a1a5fdSTejun Heo if (!workqueue_freezing)
5767a0a1a5fdSTejun Heo goto out_unlock;
5768a0a1a5fdSTejun Heo
576974b414eaSLai Jiangshan workqueue_freezing = false;
577024b8a847STejun Heo
577124b8a847STejun Heo /* restore max_active and repopulate worklist */
577224b8a847STejun Heo list_for_each_entry(wq, &workqueues, list) {
5773a357fc03SLai Jiangshan mutex_lock(&wq->mutex);
5774d8354f26SGreg Kroah-Hartman for_each_pwq(pwq, wq)
5775d8354f26SGreg Kroah-Hartman pwq_adjust_max_active(pwq);
5776a357fc03SLai Jiangshan mutex_unlock(&wq->mutex);
577724b8a847STejun Heo }
577824b8a847STejun Heo
5779a0a1a5fdSTejun Heo out_unlock:
578068e13a67SLai Jiangshan mutex_unlock(&wq_pool_mutex);
5781a0a1a5fdSTejun Heo }
5782a0a1a5fdSTejun Heo #endif /* CONFIG_FREEZER */
5783a0a1a5fdSTejun Heo
workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)578499c621efSLai Jiangshan static int workqueue_apply_unbound_cpumask(const cpumask_var_t unbound_cpumask)
5785042f7df1SLai Jiangshan {
5786042f7df1SLai Jiangshan LIST_HEAD(ctxs);
5787042f7df1SLai Jiangshan int ret = 0;
5788042f7df1SLai Jiangshan struct workqueue_struct *wq;
5789042f7df1SLai Jiangshan struct apply_wqattrs_ctx *ctx, *n;
5790042f7df1SLai Jiangshan
5791042f7df1SLai Jiangshan lockdep_assert_held(&wq_pool_mutex);
5792042f7df1SLai Jiangshan
5793042f7df1SLai Jiangshan list_for_each_entry(wq, &workqueues, list) {
5794042f7df1SLai Jiangshan if (!(wq->flags & WQ_UNBOUND))
5795042f7df1SLai Jiangshan continue;
5796042f7df1SLai Jiangshan /* creating multiple pwqs breaks ordering guarantee */
57975ad73e10STejun Heo if (wq->flags & __WQ_ORDERED)
5798042f7df1SLai Jiangshan continue;
5799042f7df1SLai Jiangshan
580099c621efSLai Jiangshan ctx = apply_wqattrs_prepare(wq, wq->unbound_attrs, unbound_cpumask);
580184193c07STejun Heo if (IS_ERR(ctx)) {
580284193c07STejun Heo ret = PTR_ERR(ctx);
5803042f7df1SLai Jiangshan break;
5804042f7df1SLai Jiangshan }
5805042f7df1SLai Jiangshan
5806042f7df1SLai Jiangshan list_add_tail(&ctx->list, &ctxs);
5807042f7df1SLai Jiangshan }
5808042f7df1SLai Jiangshan
5809042f7df1SLai Jiangshan list_for_each_entry_safe(ctx, n, &ctxs, list) {
5810042f7df1SLai Jiangshan if (!ret)
5811042f7df1SLai Jiangshan apply_wqattrs_commit(ctx);
5812042f7df1SLai Jiangshan apply_wqattrs_cleanup(ctx);
5813042f7df1SLai Jiangshan }
5814042f7df1SLai Jiangshan
581599c621efSLai Jiangshan if (!ret) {
581699c621efSLai Jiangshan mutex_lock(&wq_pool_attach_mutex);
581799c621efSLai Jiangshan cpumask_copy(wq_unbound_cpumask, unbound_cpumask);
581899c621efSLai Jiangshan mutex_unlock(&wq_pool_attach_mutex);
581999c621efSLai Jiangshan }
5820042f7df1SLai Jiangshan return ret;
5821042f7df1SLai Jiangshan }
5822042f7df1SLai Jiangshan
5823042f7df1SLai Jiangshan /**
5824042f7df1SLai Jiangshan * workqueue_set_unbound_cpumask - Set the low-level unbound cpumask
5825042f7df1SLai Jiangshan * @cpumask: the cpumask to set
5826042f7df1SLai Jiangshan *
5827042f7df1SLai Jiangshan * The low-level workqueues cpumask is a global cpumask that limits
5828042f7df1SLai Jiangshan * the affinity of all unbound workqueues. This function check the @cpumask
5829042f7df1SLai Jiangshan * and apply it to all unbound workqueues and updates all pwqs of them.
5830042f7df1SLai Jiangshan *
583167dc8325SCai Huoqing * Return: 0 - Success
5832042f7df1SLai Jiangshan * -EINVAL - Invalid @cpumask
5833042f7df1SLai Jiangshan * -ENOMEM - Failed to allocate memory for attrs or pwqs.
5834042f7df1SLai Jiangshan */
workqueue_set_unbound_cpumask(cpumask_var_t cpumask)5835042f7df1SLai Jiangshan int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
5836042f7df1SLai Jiangshan {
5837042f7df1SLai Jiangshan int ret = -EINVAL;
5838042f7df1SLai Jiangshan
5839c98a9805STal Shorer /*
5840c98a9805STal Shorer * Not excluding isolated cpus on purpose.
5841c98a9805STal Shorer * If the user wishes to include them, we allow that.
5842c98a9805STal Shorer */
5843042f7df1SLai Jiangshan cpumask_and(cpumask, cpumask, cpu_possible_mask);
5844042f7df1SLai Jiangshan if (!cpumask_empty(cpumask)) {
5845a0111cf6SLai Jiangshan apply_wqattrs_lock();
5846d25302e4SMenglong Dong if (cpumask_equal(cpumask, wq_unbound_cpumask)) {
5847d25302e4SMenglong Dong ret = 0;
5848d25302e4SMenglong Dong goto out_unlock;
5849d25302e4SMenglong Dong }
5850d25302e4SMenglong Dong
585199c621efSLai Jiangshan ret = workqueue_apply_unbound_cpumask(cpumask);
5852042f7df1SLai Jiangshan
5853d25302e4SMenglong Dong out_unlock:
5854a0111cf6SLai Jiangshan apply_wqattrs_unlock();
5855042f7df1SLai Jiangshan }
5856042f7df1SLai Jiangshan
5857042f7df1SLai Jiangshan return ret;
5858042f7df1SLai Jiangshan }
5859042f7df1SLai Jiangshan
parse_affn_scope(const char * val)586063c5484eSTejun Heo static int parse_affn_scope(const char *val)
586163c5484eSTejun Heo {
586263c5484eSTejun Heo int i;
586363c5484eSTejun Heo
586463c5484eSTejun Heo for (i = 0; i < ARRAY_SIZE(wq_affn_names); i++) {
586563c5484eSTejun Heo if (!strncasecmp(val, wq_affn_names[i], strlen(wq_affn_names[i])))
586663c5484eSTejun Heo return i;
586763c5484eSTejun Heo }
586863c5484eSTejun Heo return -EINVAL;
586963c5484eSTejun Heo }
587063c5484eSTejun Heo
wq_affn_dfl_set(const char * val,const struct kernel_param * kp)587163c5484eSTejun Heo static int wq_affn_dfl_set(const char *val, const struct kernel_param *kp)
587263c5484eSTejun Heo {
5873523a301eSTejun Heo struct workqueue_struct *wq;
5874523a301eSTejun Heo int affn, cpu;
587563c5484eSTejun Heo
587663c5484eSTejun Heo affn = parse_affn_scope(val);
587763c5484eSTejun Heo if (affn < 0)
587863c5484eSTejun Heo return affn;
5879523a301eSTejun Heo if (affn == WQ_AFFN_DFL)
5880523a301eSTejun Heo return -EINVAL;
5881523a301eSTejun Heo
5882523a301eSTejun Heo cpus_read_lock();
5883523a301eSTejun Heo mutex_lock(&wq_pool_mutex);
588463c5484eSTejun Heo
588563c5484eSTejun Heo wq_affn_dfl = affn;
5886523a301eSTejun Heo
5887523a301eSTejun Heo list_for_each_entry(wq, &workqueues, list) {
5888523a301eSTejun Heo for_each_online_cpu(cpu) {
5889523a301eSTejun Heo wq_update_pod(wq, cpu, cpu, true);
5890523a301eSTejun Heo }
5891523a301eSTejun Heo }
5892523a301eSTejun Heo
5893523a301eSTejun Heo mutex_unlock(&wq_pool_mutex);
5894523a301eSTejun Heo cpus_read_unlock();
5895523a301eSTejun Heo
589663c5484eSTejun Heo return 0;
589763c5484eSTejun Heo }
589863c5484eSTejun Heo
wq_affn_dfl_get(char * buffer,const struct kernel_param * kp)589963c5484eSTejun Heo static int wq_affn_dfl_get(char *buffer, const struct kernel_param *kp)
590063c5484eSTejun Heo {
590163c5484eSTejun Heo return scnprintf(buffer, PAGE_SIZE, "%s\n", wq_affn_names[wq_affn_dfl]);
590263c5484eSTejun Heo }
590363c5484eSTejun Heo
590463c5484eSTejun Heo static const struct kernel_param_ops wq_affn_dfl_ops = {
590563c5484eSTejun Heo .set = wq_affn_dfl_set,
590663c5484eSTejun Heo .get = wq_affn_dfl_get,
590763c5484eSTejun Heo };
590863c5484eSTejun Heo
590963c5484eSTejun Heo module_param_cb(default_affinity_scope, &wq_affn_dfl_ops, NULL, 0644);
591063c5484eSTejun Heo
59116ba94429SFrederic Weisbecker #ifdef CONFIG_SYSFS
59126ba94429SFrederic Weisbecker /*
59136ba94429SFrederic Weisbecker * Workqueues with WQ_SYSFS flag set is visible to userland via
59146ba94429SFrederic Weisbecker * /sys/bus/workqueue/devices/WQ_NAME. All visible workqueues have the
59156ba94429SFrederic Weisbecker * following attributes.
59166ba94429SFrederic Weisbecker *
59176ba94429SFrederic Weisbecker * per_cpu RO bool : whether the workqueue is per-cpu or unbound
59186ba94429SFrederic Weisbecker * max_active RW int : maximum number of in-flight work items
59196ba94429SFrederic Weisbecker *
59206ba94429SFrederic Weisbecker * Unbound workqueues have the following extra attributes.
59216ba94429SFrederic Weisbecker *
59226ba94429SFrederic Weisbecker * nice RW int : nice value of the workers
59236ba94429SFrederic Weisbecker * cpumask RW mask : bitmask of allowed CPUs for the workers
592463c5484eSTejun Heo * affinity_scope RW str : worker CPU affinity scope (cache, numa, none)
59258639ecebSTejun Heo * affinity_strict RW bool : worker CPU affinity is strict
59266ba94429SFrederic Weisbecker */
59276ba94429SFrederic Weisbecker struct wq_device {
59286ba94429SFrederic Weisbecker struct workqueue_struct *wq;
59296ba94429SFrederic Weisbecker struct device dev;
59306ba94429SFrederic Weisbecker };
59316ba94429SFrederic Weisbecker
dev_to_wq(struct device * dev)59326ba94429SFrederic Weisbecker static struct workqueue_struct *dev_to_wq(struct device *dev)
59336ba94429SFrederic Weisbecker {
59346ba94429SFrederic Weisbecker struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
59356ba94429SFrederic Weisbecker
59366ba94429SFrederic Weisbecker return wq_dev->wq;
59376ba94429SFrederic Weisbecker }
59386ba94429SFrederic Weisbecker
per_cpu_show(struct device * dev,struct device_attribute * attr,char * buf)59396ba94429SFrederic Weisbecker static ssize_t per_cpu_show(struct device *dev, struct device_attribute *attr,
59406ba94429SFrederic Weisbecker char *buf)
59416ba94429SFrederic Weisbecker {
59426ba94429SFrederic Weisbecker struct workqueue_struct *wq = dev_to_wq(dev);
59436ba94429SFrederic Weisbecker
59446ba94429SFrederic Weisbecker return scnprintf(buf, PAGE_SIZE, "%d\n", (bool)!(wq->flags & WQ_UNBOUND));
59456ba94429SFrederic Weisbecker }
59466ba94429SFrederic Weisbecker static DEVICE_ATTR_RO(per_cpu);
59476ba94429SFrederic Weisbecker
max_active_show(struct device * dev,struct device_attribute * attr,char * buf)59486ba94429SFrederic Weisbecker static ssize_t max_active_show(struct device *dev,
59496ba94429SFrederic Weisbecker struct device_attribute *attr, char *buf)
59506ba94429SFrederic Weisbecker {
59516ba94429SFrederic Weisbecker struct workqueue_struct *wq = dev_to_wq(dev);
59526ba94429SFrederic Weisbecker
59536ba94429SFrederic Weisbecker return scnprintf(buf, PAGE_SIZE, "%d\n", wq->saved_max_active);
59546ba94429SFrederic Weisbecker }
59556ba94429SFrederic Weisbecker
max_active_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)59566ba94429SFrederic Weisbecker static ssize_t max_active_store(struct device *dev,
59576ba94429SFrederic Weisbecker struct device_attribute *attr, const char *buf,
59586ba94429SFrederic Weisbecker size_t count)
59596ba94429SFrederic Weisbecker {
59606ba94429SFrederic Weisbecker struct workqueue_struct *wq = dev_to_wq(dev);
59616ba94429SFrederic Weisbecker int val;
59626ba94429SFrederic Weisbecker
59636ba94429SFrederic Weisbecker if (sscanf(buf, "%d", &val) != 1 || val <= 0)
59646ba94429SFrederic Weisbecker return -EINVAL;
59656ba94429SFrederic Weisbecker
59666ba94429SFrederic Weisbecker workqueue_set_max_active(wq, val);
59676ba94429SFrederic Weisbecker return count;
59686ba94429SFrederic Weisbecker }
59696ba94429SFrederic Weisbecker static DEVICE_ATTR_RW(max_active);
59706ba94429SFrederic Weisbecker
59716ba94429SFrederic Weisbecker static struct attribute *wq_sysfs_attrs[] = {
59726ba94429SFrederic Weisbecker &dev_attr_per_cpu.attr,
59736ba94429SFrederic Weisbecker &dev_attr_max_active.attr,
59746ba94429SFrederic Weisbecker NULL,
59756ba94429SFrederic Weisbecker };
59766ba94429SFrederic Weisbecker ATTRIBUTE_GROUPS(wq_sysfs);
59776ba94429SFrederic Weisbecker
wq_nice_show(struct device * dev,struct device_attribute * attr,char * buf)59786ba94429SFrederic Weisbecker static ssize_t wq_nice_show(struct device *dev, struct device_attribute *attr,
59796ba94429SFrederic Weisbecker char *buf)
59806ba94429SFrederic Weisbecker {
59816ba94429SFrederic Weisbecker struct workqueue_struct *wq = dev_to_wq(dev);
59826ba94429SFrederic Weisbecker int written;
59836ba94429SFrederic Weisbecker
59846ba94429SFrederic Weisbecker mutex_lock(&wq->mutex);
59856ba94429SFrederic Weisbecker written = scnprintf(buf, PAGE_SIZE, "%d\n", wq->unbound_attrs->nice);
59866ba94429SFrederic Weisbecker mutex_unlock(&wq->mutex);
59876ba94429SFrederic Weisbecker
59886ba94429SFrederic Weisbecker return written;
59896ba94429SFrederic Weisbecker }
59906ba94429SFrederic Weisbecker
59916ba94429SFrederic Weisbecker /* prepare workqueue_attrs for sysfs store operations */
wq_sysfs_prep_attrs(struct workqueue_struct * wq)59926ba94429SFrederic Weisbecker static struct workqueue_attrs *wq_sysfs_prep_attrs(struct workqueue_struct *wq)
59936ba94429SFrederic Weisbecker {
59946ba94429SFrederic Weisbecker struct workqueue_attrs *attrs;
59956ba94429SFrederic Weisbecker
5996899a94feSLai Jiangshan lockdep_assert_held(&wq_pool_mutex);
5997899a94feSLai Jiangshan
5998be69d00dSThomas Gleixner attrs = alloc_workqueue_attrs();
59996ba94429SFrederic Weisbecker if (!attrs)
60006ba94429SFrederic Weisbecker return NULL;
60016ba94429SFrederic Weisbecker
60026ba94429SFrederic Weisbecker copy_workqueue_attrs(attrs, wq->unbound_attrs);
60036ba94429SFrederic Weisbecker return attrs;
60046ba94429SFrederic Weisbecker }
60056ba94429SFrederic Weisbecker
wq_nice_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)60066ba94429SFrederic Weisbecker static ssize_t wq_nice_store(struct device *dev, struct device_attribute *attr,
60076ba94429SFrederic Weisbecker const char *buf, size_t count)
60086ba94429SFrederic Weisbecker {
60096ba94429SFrederic Weisbecker struct workqueue_struct *wq = dev_to_wq(dev);
60106ba94429SFrederic Weisbecker struct workqueue_attrs *attrs;
6011d4d3e257SLai Jiangshan int ret = -ENOMEM;
6012d4d3e257SLai Jiangshan
6013d4d3e257SLai Jiangshan apply_wqattrs_lock();
60146ba94429SFrederic Weisbecker
60156ba94429SFrederic Weisbecker attrs = wq_sysfs_prep_attrs(wq);
60166ba94429SFrederic Weisbecker if (!attrs)
6017d4d3e257SLai Jiangshan goto out_unlock;
60186ba94429SFrederic Weisbecker
60196ba94429SFrederic Weisbecker if (sscanf(buf, "%d", &attrs->nice) == 1 &&
60206ba94429SFrederic Weisbecker attrs->nice >= MIN_NICE && attrs->nice <= MAX_NICE)
6021d4d3e257SLai Jiangshan ret = apply_workqueue_attrs_locked(wq, attrs);
60226ba94429SFrederic Weisbecker else
60236ba94429SFrederic Weisbecker ret = -EINVAL;
60246ba94429SFrederic Weisbecker
6025d4d3e257SLai Jiangshan out_unlock:
6026d4d3e257SLai Jiangshan apply_wqattrs_unlock();
60276ba94429SFrederic Weisbecker free_workqueue_attrs(attrs);
60286ba94429SFrederic Weisbecker return ret ?: count;
60296ba94429SFrederic Weisbecker }
60306ba94429SFrederic Weisbecker
wq_cpumask_show(struct device * dev,struct device_attribute * attr,char * buf)60316ba94429SFrederic Weisbecker static ssize_t wq_cpumask_show(struct device *dev,
60326ba94429SFrederic Weisbecker struct device_attribute *attr, char *buf)
60336ba94429SFrederic Weisbecker {
60346ba94429SFrederic Weisbecker struct workqueue_struct *wq = dev_to_wq(dev);
60356ba94429SFrederic Weisbecker int written;
60366ba94429SFrederic Weisbecker
60376ba94429SFrederic Weisbecker mutex_lock(&wq->mutex);
60386ba94429SFrederic Weisbecker written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
60396ba94429SFrederic Weisbecker cpumask_pr_args(wq->unbound_attrs->cpumask));
60406ba94429SFrederic Weisbecker mutex_unlock(&wq->mutex);
60416ba94429SFrederic Weisbecker return written;
60426ba94429SFrederic Weisbecker }
60436ba94429SFrederic Weisbecker
wq_cpumask_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)60446ba94429SFrederic Weisbecker static ssize_t wq_cpumask_store(struct device *dev,
60456ba94429SFrederic Weisbecker struct device_attribute *attr,
60466ba94429SFrederic Weisbecker const char *buf, size_t count)
60476ba94429SFrederic Weisbecker {
60486ba94429SFrederic Weisbecker struct workqueue_struct *wq = dev_to_wq(dev);
60496ba94429SFrederic Weisbecker struct workqueue_attrs *attrs;
6050d4d3e257SLai Jiangshan int ret = -ENOMEM;
6051d4d3e257SLai Jiangshan
6052d4d3e257SLai Jiangshan apply_wqattrs_lock();
60536ba94429SFrederic Weisbecker
60546ba94429SFrederic Weisbecker attrs = wq_sysfs_prep_attrs(wq);
60556ba94429SFrederic Weisbecker if (!attrs)
6056d4d3e257SLai Jiangshan goto out_unlock;
60576ba94429SFrederic Weisbecker
60586ba94429SFrederic Weisbecker ret = cpumask_parse(buf, attrs->cpumask);
60596ba94429SFrederic Weisbecker if (!ret)
6060d4d3e257SLai Jiangshan ret = apply_workqueue_attrs_locked(wq, attrs);
60616ba94429SFrederic Weisbecker
6062d4d3e257SLai Jiangshan out_unlock:
6063d4d3e257SLai Jiangshan apply_wqattrs_unlock();
60646ba94429SFrederic Weisbecker free_workqueue_attrs(attrs);
60656ba94429SFrederic Weisbecker return ret ?: count;
60666ba94429SFrederic Weisbecker }
60676ba94429SFrederic Weisbecker
wq_affn_scope_show(struct device * dev,struct device_attribute * attr,char * buf)606863c5484eSTejun Heo static ssize_t wq_affn_scope_show(struct device *dev,
606963c5484eSTejun Heo struct device_attribute *attr, char *buf)
607063c5484eSTejun Heo {
607163c5484eSTejun Heo struct workqueue_struct *wq = dev_to_wq(dev);
607263c5484eSTejun Heo int written;
607363c5484eSTejun Heo
607463c5484eSTejun Heo mutex_lock(&wq->mutex);
6075523a301eSTejun Heo if (wq->unbound_attrs->affn_scope == WQ_AFFN_DFL)
6076523a301eSTejun Heo written = scnprintf(buf, PAGE_SIZE, "%s (%s)\n",
6077523a301eSTejun Heo wq_affn_names[WQ_AFFN_DFL],
6078523a301eSTejun Heo wq_affn_names[wq_affn_dfl]);
6079523a301eSTejun Heo else
608063c5484eSTejun Heo written = scnprintf(buf, PAGE_SIZE, "%s\n",
608163c5484eSTejun Heo wq_affn_names[wq->unbound_attrs->affn_scope]);
608263c5484eSTejun Heo mutex_unlock(&wq->mutex);
608363c5484eSTejun Heo
608463c5484eSTejun Heo return written;
608563c5484eSTejun Heo }
608663c5484eSTejun Heo
wq_affn_scope_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)608763c5484eSTejun Heo static ssize_t wq_affn_scope_store(struct device *dev,
608863c5484eSTejun Heo struct device_attribute *attr,
608963c5484eSTejun Heo const char *buf, size_t count)
609063c5484eSTejun Heo {
609163c5484eSTejun Heo struct workqueue_struct *wq = dev_to_wq(dev);
609263c5484eSTejun Heo struct workqueue_attrs *attrs;
609363c5484eSTejun Heo int affn, ret = -ENOMEM;
609463c5484eSTejun Heo
609563c5484eSTejun Heo affn = parse_affn_scope(buf);
609663c5484eSTejun Heo if (affn < 0)
609763c5484eSTejun Heo return affn;
609863c5484eSTejun Heo
609963c5484eSTejun Heo apply_wqattrs_lock();
610063c5484eSTejun Heo attrs = wq_sysfs_prep_attrs(wq);
610163c5484eSTejun Heo if (attrs) {
610263c5484eSTejun Heo attrs->affn_scope = affn;
610363c5484eSTejun Heo ret = apply_workqueue_attrs_locked(wq, attrs);
610463c5484eSTejun Heo }
610563c5484eSTejun Heo apply_wqattrs_unlock();
610663c5484eSTejun Heo free_workqueue_attrs(attrs);
610763c5484eSTejun Heo return ret ?: count;
610863c5484eSTejun Heo }
610963c5484eSTejun Heo
wq_affinity_strict_show(struct device * dev,struct device_attribute * attr,char * buf)61108639ecebSTejun Heo static ssize_t wq_affinity_strict_show(struct device *dev,
61118639ecebSTejun Heo struct device_attribute *attr, char *buf)
61128639ecebSTejun Heo {
61138639ecebSTejun Heo struct workqueue_struct *wq = dev_to_wq(dev);
61148639ecebSTejun Heo
61158639ecebSTejun Heo return scnprintf(buf, PAGE_SIZE, "%d\n",
61168639ecebSTejun Heo wq->unbound_attrs->affn_strict);
61178639ecebSTejun Heo }
61188639ecebSTejun Heo
wq_affinity_strict_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)61198639ecebSTejun Heo static ssize_t wq_affinity_strict_store(struct device *dev,
61208639ecebSTejun Heo struct device_attribute *attr,
61218639ecebSTejun Heo const char *buf, size_t count)
61228639ecebSTejun Heo {
61238639ecebSTejun Heo struct workqueue_struct *wq = dev_to_wq(dev);
61248639ecebSTejun Heo struct workqueue_attrs *attrs;
61258639ecebSTejun Heo int v, ret = -ENOMEM;
61268639ecebSTejun Heo
61278639ecebSTejun Heo if (sscanf(buf, "%d", &v) != 1)
61288639ecebSTejun Heo return -EINVAL;
61298639ecebSTejun Heo
61308639ecebSTejun Heo apply_wqattrs_lock();
61318639ecebSTejun Heo attrs = wq_sysfs_prep_attrs(wq);
61328639ecebSTejun Heo if (attrs) {
61338639ecebSTejun Heo attrs->affn_strict = (bool)v;
61348639ecebSTejun Heo ret = apply_workqueue_attrs_locked(wq, attrs);
61358639ecebSTejun Heo }
61368639ecebSTejun Heo apply_wqattrs_unlock();
61378639ecebSTejun Heo free_workqueue_attrs(attrs);
61388639ecebSTejun Heo return ret ?: count;
61398639ecebSTejun Heo }
61408639ecebSTejun Heo
61416ba94429SFrederic Weisbecker static struct device_attribute wq_sysfs_unbound_attrs[] = {
61426ba94429SFrederic Weisbecker __ATTR(nice, 0644, wq_nice_show, wq_nice_store),
61436ba94429SFrederic Weisbecker __ATTR(cpumask, 0644, wq_cpumask_show, wq_cpumask_store),
614463c5484eSTejun Heo __ATTR(affinity_scope, 0644, wq_affn_scope_show, wq_affn_scope_store),
61458639ecebSTejun Heo __ATTR(affinity_strict, 0644, wq_affinity_strict_show, wq_affinity_strict_store),
61466ba94429SFrederic Weisbecker __ATTR_NULL,
61476ba94429SFrederic Weisbecker };
61486ba94429SFrederic Weisbecker
61496ba94429SFrederic Weisbecker static struct bus_type wq_subsys = {
61506ba94429SFrederic Weisbecker .name = "workqueue",
61516ba94429SFrederic Weisbecker .dev_groups = wq_sysfs_groups,
61526ba94429SFrederic Weisbecker };
61536ba94429SFrederic Weisbecker
wq_unbound_cpumask_show(struct device * dev,struct device_attribute * attr,char * buf)6154b05a7928SFrederic Weisbecker static ssize_t wq_unbound_cpumask_show(struct device *dev,
6155b05a7928SFrederic Weisbecker struct device_attribute *attr, char *buf)
6156b05a7928SFrederic Weisbecker {
6157b05a7928SFrederic Weisbecker int written;
6158b05a7928SFrederic Weisbecker
6159042f7df1SLai Jiangshan mutex_lock(&wq_pool_mutex);
6160b05a7928SFrederic Weisbecker written = scnprintf(buf, PAGE_SIZE, "%*pb\n",
6161b05a7928SFrederic Weisbecker cpumask_pr_args(wq_unbound_cpumask));
6162042f7df1SLai Jiangshan mutex_unlock(&wq_pool_mutex);
6163b05a7928SFrederic Weisbecker
6164b05a7928SFrederic Weisbecker return written;
6165b05a7928SFrederic Weisbecker }
6166b05a7928SFrederic Weisbecker
wq_unbound_cpumask_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)6167042f7df1SLai Jiangshan static ssize_t wq_unbound_cpumask_store(struct device *dev,
6168042f7df1SLai Jiangshan struct device_attribute *attr, const char *buf, size_t count)
6169042f7df1SLai Jiangshan {
6170042f7df1SLai Jiangshan cpumask_var_t cpumask;
6171042f7df1SLai Jiangshan int ret;
6172042f7df1SLai Jiangshan
6173042f7df1SLai Jiangshan if (!zalloc_cpumask_var(&cpumask, GFP_KERNEL))
6174042f7df1SLai Jiangshan return -ENOMEM;
6175042f7df1SLai Jiangshan
6176042f7df1SLai Jiangshan ret = cpumask_parse(buf, cpumask);
6177042f7df1SLai Jiangshan if (!ret)
6178042f7df1SLai Jiangshan ret = workqueue_set_unbound_cpumask(cpumask);
6179042f7df1SLai Jiangshan
6180042f7df1SLai Jiangshan free_cpumask_var(cpumask);
6181042f7df1SLai Jiangshan return ret ? ret : count;
6182042f7df1SLai Jiangshan }
6183042f7df1SLai Jiangshan
6184b05a7928SFrederic Weisbecker static struct device_attribute wq_sysfs_cpumask_attr =
6185042f7df1SLai Jiangshan __ATTR(cpumask, 0644, wq_unbound_cpumask_show,
6186042f7df1SLai Jiangshan wq_unbound_cpumask_store);
6187b05a7928SFrederic Weisbecker
wq_sysfs_init(void)61886ba94429SFrederic Weisbecker static int __init wq_sysfs_init(void)
61896ba94429SFrederic Weisbecker {
6190686f6697SGreg Kroah-Hartman struct device *dev_root;
6191b05a7928SFrederic Weisbecker int err;
6192b05a7928SFrederic Weisbecker
6193b05a7928SFrederic Weisbecker err = subsys_virtual_register(&wq_subsys, NULL);
6194b05a7928SFrederic Weisbecker if (err)
6195b05a7928SFrederic Weisbecker return err;
6196b05a7928SFrederic Weisbecker
6197686f6697SGreg Kroah-Hartman dev_root = bus_get_dev_root(&wq_subsys);
6198686f6697SGreg Kroah-Hartman if (dev_root) {
6199686f6697SGreg Kroah-Hartman err = device_create_file(dev_root, &wq_sysfs_cpumask_attr);
6200686f6697SGreg Kroah-Hartman put_device(dev_root);
6201686f6697SGreg Kroah-Hartman }
6202686f6697SGreg Kroah-Hartman return err;
62036ba94429SFrederic Weisbecker }
62046ba94429SFrederic Weisbecker core_initcall(wq_sysfs_init);
62056ba94429SFrederic Weisbecker
wq_device_release(struct device * dev)62066ba94429SFrederic Weisbecker static void wq_device_release(struct device *dev)
62076ba94429SFrederic Weisbecker {
62086ba94429SFrederic Weisbecker struct wq_device *wq_dev = container_of(dev, struct wq_device, dev);
62096ba94429SFrederic Weisbecker
62106ba94429SFrederic Weisbecker kfree(wq_dev);
62116ba94429SFrederic Weisbecker }
62126ba94429SFrederic Weisbecker
62136ba94429SFrederic Weisbecker /**
62146ba94429SFrederic Weisbecker * workqueue_sysfs_register - make a workqueue visible in sysfs
62156ba94429SFrederic Weisbecker * @wq: the workqueue to register
62166ba94429SFrederic Weisbecker *
62176ba94429SFrederic Weisbecker * Expose @wq in sysfs under /sys/bus/workqueue/devices.
62186ba94429SFrederic Weisbecker * alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
62196ba94429SFrederic Weisbecker * which is the preferred method.
62206ba94429SFrederic Weisbecker *
62216ba94429SFrederic Weisbecker * Workqueue user should use this function directly iff it wants to apply
62226ba94429SFrederic Weisbecker * workqueue_attrs before making the workqueue visible in sysfs; otherwise,
62236ba94429SFrederic Weisbecker * apply_workqueue_attrs() may race against userland updating the
62246ba94429SFrederic Weisbecker * attributes.
62256ba94429SFrederic Weisbecker *
62266ba94429SFrederic Weisbecker * Return: 0 on success, -errno on failure.
62276ba94429SFrederic Weisbecker */
workqueue_sysfs_register(struct workqueue_struct * wq)62286ba94429SFrederic Weisbecker int workqueue_sysfs_register(struct workqueue_struct *wq)
62296ba94429SFrederic Weisbecker {
62306ba94429SFrederic Weisbecker struct wq_device *wq_dev;
62316ba94429SFrederic Weisbecker int ret;
62326ba94429SFrederic Weisbecker
62336ba94429SFrederic Weisbecker /*
6234402dd89dSShailendra Verma * Adjusting max_active or creating new pwqs by applying
62356ba94429SFrederic Weisbecker * attributes breaks ordering guarantee. Disallow exposing ordered
62366ba94429SFrederic Weisbecker * workqueues.
62376ba94429SFrederic Weisbecker */
62380a94efb5STejun Heo if (WARN_ON(wq->flags & __WQ_ORDERED_EXPLICIT))
62396ba94429SFrederic Weisbecker return -EINVAL;
62406ba94429SFrederic Weisbecker
62416ba94429SFrederic Weisbecker wq->wq_dev = wq_dev = kzalloc(sizeof(*wq_dev), GFP_KERNEL);
62426ba94429SFrederic Weisbecker if (!wq_dev)
62436ba94429SFrederic Weisbecker return -ENOMEM;
62446ba94429SFrederic Weisbecker
62456ba94429SFrederic Weisbecker wq_dev->wq = wq;
62466ba94429SFrederic Weisbecker wq_dev->dev.bus = &wq_subsys;
62476ba94429SFrederic Weisbecker wq_dev->dev.release = wq_device_release;
624823217b44SLars-Peter Clausen dev_set_name(&wq_dev->dev, "%s", wq->name);
62496ba94429SFrederic Weisbecker
62506ba94429SFrederic Weisbecker /*
62516ba94429SFrederic Weisbecker * unbound_attrs are created separately. Suppress uevent until
62526ba94429SFrederic Weisbecker * everything is ready.
62536ba94429SFrederic Weisbecker */
62546ba94429SFrederic Weisbecker dev_set_uevent_suppress(&wq_dev->dev, true);
62556ba94429SFrederic Weisbecker
62566ba94429SFrederic Weisbecker ret = device_register(&wq_dev->dev);
62576ba94429SFrederic Weisbecker if (ret) {
6258537f4146SArvind Yadav put_device(&wq_dev->dev);
62596ba94429SFrederic Weisbecker wq->wq_dev = NULL;
62606ba94429SFrederic Weisbecker return ret;
62616ba94429SFrederic Weisbecker }
62626ba94429SFrederic Weisbecker
62636ba94429SFrederic Weisbecker if (wq->flags & WQ_UNBOUND) {
62646ba94429SFrederic Weisbecker struct device_attribute *attr;
62656ba94429SFrederic Weisbecker
62666ba94429SFrederic Weisbecker for (attr = wq_sysfs_unbound_attrs; attr->attr.name; attr++) {
62676ba94429SFrederic Weisbecker ret = device_create_file(&wq_dev->dev, attr);
62686ba94429SFrederic Weisbecker if (ret) {
62696ba94429SFrederic Weisbecker device_unregister(&wq_dev->dev);
62706ba94429SFrederic Weisbecker wq->wq_dev = NULL;
62716ba94429SFrederic Weisbecker return ret;
62726ba94429SFrederic Weisbecker }
62736ba94429SFrederic Weisbecker }
62746ba94429SFrederic Weisbecker }
62756ba94429SFrederic Weisbecker
62766ba94429SFrederic Weisbecker dev_set_uevent_suppress(&wq_dev->dev, false);
62776ba94429SFrederic Weisbecker kobject_uevent(&wq_dev->dev.kobj, KOBJ_ADD);
62786ba94429SFrederic Weisbecker return 0;
62796ba94429SFrederic Weisbecker }
62806ba94429SFrederic Weisbecker
62816ba94429SFrederic Weisbecker /**
62826ba94429SFrederic Weisbecker * workqueue_sysfs_unregister - undo workqueue_sysfs_register()
62836ba94429SFrederic Weisbecker * @wq: the workqueue to unregister
62846ba94429SFrederic Weisbecker *
62856ba94429SFrederic Weisbecker * If @wq is registered to sysfs by workqueue_sysfs_register(), unregister.
62866ba94429SFrederic Weisbecker */
workqueue_sysfs_unregister(struct workqueue_struct * wq)62876ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq)
62886ba94429SFrederic Weisbecker {
62896ba94429SFrederic Weisbecker struct wq_device *wq_dev = wq->wq_dev;
62906ba94429SFrederic Weisbecker
62916ba94429SFrederic Weisbecker if (!wq->wq_dev)
62926ba94429SFrederic Weisbecker return;
62936ba94429SFrederic Weisbecker
62946ba94429SFrederic Weisbecker wq->wq_dev = NULL;
62956ba94429SFrederic Weisbecker device_unregister(&wq_dev->dev);
62966ba94429SFrederic Weisbecker }
62976ba94429SFrederic Weisbecker #else /* CONFIG_SYSFS */
workqueue_sysfs_unregister(struct workqueue_struct * wq)62986ba94429SFrederic Weisbecker static void workqueue_sysfs_unregister(struct workqueue_struct *wq) { }
62996ba94429SFrederic Weisbecker #endif /* CONFIG_SYSFS */
63006ba94429SFrederic Weisbecker
630182607adcSTejun Heo /*
630282607adcSTejun Heo * Workqueue watchdog.
630382607adcSTejun Heo *
630482607adcSTejun Heo * Stall may be caused by various bugs - missing WQ_MEM_RECLAIM, illegal
630582607adcSTejun Heo * flush dependency, a concurrency managed work item which stays RUNNING
630682607adcSTejun Heo * indefinitely. Workqueue stalls can be very difficult to debug as the
630782607adcSTejun Heo * usual warning mechanisms don't trigger and internal workqueue state is
630882607adcSTejun Heo * largely opaque.
630982607adcSTejun Heo *
631082607adcSTejun Heo * Workqueue watchdog monitors all worker pools periodically and dumps
631182607adcSTejun Heo * state if some pools failed to make forward progress for a while where
631282607adcSTejun Heo * forward progress is defined as the first item on ->worklist changing.
631382607adcSTejun Heo *
631482607adcSTejun Heo * This mechanism is controlled through the kernel parameter
631582607adcSTejun Heo * "workqueue.watchdog_thresh" which can be updated at runtime through the
631682607adcSTejun Heo * corresponding sysfs parameter file.
631782607adcSTejun Heo */
631882607adcSTejun Heo #ifdef CONFIG_WQ_WATCHDOG
631982607adcSTejun Heo
632082607adcSTejun Heo static unsigned long wq_watchdog_thresh = 30;
63215cd79d6aSKees Cook static struct timer_list wq_watchdog_timer;
632282607adcSTejun Heo
632382607adcSTejun Heo static unsigned long wq_watchdog_touched = INITIAL_JIFFIES;
632482607adcSTejun Heo static DEFINE_PER_CPU(unsigned long, wq_watchdog_touched_cpu) = INITIAL_JIFFIES;
632582607adcSTejun Heo
6326cd2440d6SPetr Mladek /*
6327cd2440d6SPetr Mladek * Show workers that might prevent the processing of pending work items.
6328cd2440d6SPetr Mladek * The only candidates are CPU-bound workers in the running state.
6329cd2440d6SPetr Mladek * Pending work items should be handled by another idle worker
6330cd2440d6SPetr Mladek * in all other situations.
6331cd2440d6SPetr Mladek */
show_cpu_pool_hog(struct worker_pool * pool)6332cd2440d6SPetr Mladek static void show_cpu_pool_hog(struct worker_pool *pool)
6333cd2440d6SPetr Mladek {
6334cd2440d6SPetr Mladek struct worker *worker;
6335cd2440d6SPetr Mladek unsigned long flags;
6336cd2440d6SPetr Mladek int bkt;
6337cd2440d6SPetr Mladek
6338cd2440d6SPetr Mladek raw_spin_lock_irqsave(&pool->lock, flags);
6339cd2440d6SPetr Mladek
6340cd2440d6SPetr Mladek hash_for_each(pool->busy_hash, bkt, worker, hentry) {
6341cd2440d6SPetr Mladek if (task_is_running(worker->task)) {
6342cd2440d6SPetr Mladek /*
6343cd2440d6SPetr Mladek * Defer printing to avoid deadlocks in console
6344cd2440d6SPetr Mladek * drivers that queue work while holding locks
6345cd2440d6SPetr Mladek * also taken in their write paths.
6346cd2440d6SPetr Mladek */
6347cd2440d6SPetr Mladek printk_deferred_enter();
6348cd2440d6SPetr Mladek
6349cd2440d6SPetr Mladek pr_info("pool %d:\n", pool->id);
6350cd2440d6SPetr Mladek sched_show_task(worker->task);
6351cd2440d6SPetr Mladek
6352cd2440d6SPetr Mladek printk_deferred_exit();
6353cd2440d6SPetr Mladek }
6354cd2440d6SPetr Mladek }
6355cd2440d6SPetr Mladek
6356cd2440d6SPetr Mladek raw_spin_unlock_irqrestore(&pool->lock, flags);
6357cd2440d6SPetr Mladek }
6358cd2440d6SPetr Mladek
show_cpu_pools_hogs(void)6359cd2440d6SPetr Mladek static void show_cpu_pools_hogs(void)
6360cd2440d6SPetr Mladek {
6361cd2440d6SPetr Mladek struct worker_pool *pool;
6362cd2440d6SPetr Mladek int pi;
6363cd2440d6SPetr Mladek
6364cd2440d6SPetr Mladek pr_info("Showing backtraces of running workers in stalled CPU-bound worker pools:\n");
6365cd2440d6SPetr Mladek
6366cd2440d6SPetr Mladek rcu_read_lock();
6367cd2440d6SPetr Mladek
6368cd2440d6SPetr Mladek for_each_pool(pool, pi) {
6369cd2440d6SPetr Mladek if (pool->cpu_stall)
6370cd2440d6SPetr Mladek show_cpu_pool_hog(pool);
6371cd2440d6SPetr Mladek
6372cd2440d6SPetr Mladek }
6373cd2440d6SPetr Mladek
6374cd2440d6SPetr Mladek rcu_read_unlock();
6375cd2440d6SPetr Mladek }
6376cd2440d6SPetr Mladek
wq_watchdog_reset_touched(void)637782607adcSTejun Heo static void wq_watchdog_reset_touched(void)
637882607adcSTejun Heo {
637982607adcSTejun Heo int cpu;
638082607adcSTejun Heo
638182607adcSTejun Heo wq_watchdog_touched = jiffies;
638282607adcSTejun Heo for_each_possible_cpu(cpu)
638382607adcSTejun Heo per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
638482607adcSTejun Heo }
638582607adcSTejun Heo
wq_watchdog_timer_fn(struct timer_list * unused)63865cd79d6aSKees Cook static void wq_watchdog_timer_fn(struct timer_list *unused)
638782607adcSTejun Heo {
638882607adcSTejun Heo unsigned long thresh = READ_ONCE(wq_watchdog_thresh) * HZ;
638982607adcSTejun Heo bool lockup_detected = false;
6390cd2440d6SPetr Mladek bool cpu_pool_stall = false;
6391940d71c6SSergey Senozhatsky unsigned long now = jiffies;
639282607adcSTejun Heo struct worker_pool *pool;
639382607adcSTejun Heo int pi;
639482607adcSTejun Heo
639582607adcSTejun Heo if (!thresh)
639682607adcSTejun Heo return;
639782607adcSTejun Heo
639882607adcSTejun Heo rcu_read_lock();
639982607adcSTejun Heo
640082607adcSTejun Heo for_each_pool(pool, pi) {
640182607adcSTejun Heo unsigned long pool_ts, touched, ts;
640282607adcSTejun Heo
6403cd2440d6SPetr Mladek pool->cpu_stall = false;
640482607adcSTejun Heo if (list_empty(&pool->worklist))
640582607adcSTejun Heo continue;
640682607adcSTejun Heo
6407940d71c6SSergey Senozhatsky /*
6408940d71c6SSergey Senozhatsky * If a virtual machine is stopped by the host it can look to
6409940d71c6SSergey Senozhatsky * the watchdog like a stall.
6410940d71c6SSergey Senozhatsky */
6411940d71c6SSergey Senozhatsky kvm_check_and_clear_guest_paused();
6412940d71c6SSergey Senozhatsky
641382607adcSTejun Heo /* get the latest of pool and touched timestamps */
641489e28ce6SWang Qing if (pool->cpu >= 0)
641589e28ce6SWang Qing touched = READ_ONCE(per_cpu(wq_watchdog_touched_cpu, pool->cpu));
641689e28ce6SWang Qing else
641782607adcSTejun Heo touched = READ_ONCE(wq_watchdog_touched);
641889e28ce6SWang Qing pool_ts = READ_ONCE(pool->watchdog_ts);
641982607adcSTejun Heo
642082607adcSTejun Heo if (time_after(pool_ts, touched))
642182607adcSTejun Heo ts = pool_ts;
642282607adcSTejun Heo else
642382607adcSTejun Heo ts = touched;
642482607adcSTejun Heo
642582607adcSTejun Heo /* did we stall? */
6426940d71c6SSergey Senozhatsky if (time_after(now, ts + thresh)) {
642782607adcSTejun Heo lockup_detected = true;
6428cd2440d6SPetr Mladek if (pool->cpu >= 0) {
6429cd2440d6SPetr Mladek pool->cpu_stall = true;
6430cd2440d6SPetr Mladek cpu_pool_stall = true;
6431cd2440d6SPetr Mladek }
643282607adcSTejun Heo pr_emerg("BUG: workqueue lockup - pool");
643382607adcSTejun Heo pr_cont_pool_info(pool);
643482607adcSTejun Heo pr_cont(" stuck for %us!\n",
6435940d71c6SSergey Senozhatsky jiffies_to_msecs(now - pool_ts) / 1000);
643682607adcSTejun Heo }
6437cd2440d6SPetr Mladek
6438cd2440d6SPetr Mladek
643982607adcSTejun Heo }
644082607adcSTejun Heo
644182607adcSTejun Heo rcu_read_unlock();
644282607adcSTejun Heo
644382607adcSTejun Heo if (lockup_detected)
644455df0933SImran Khan show_all_workqueues();
644582607adcSTejun Heo
6446cd2440d6SPetr Mladek if (cpu_pool_stall)
6447cd2440d6SPetr Mladek show_cpu_pools_hogs();
6448cd2440d6SPetr Mladek
644982607adcSTejun Heo wq_watchdog_reset_touched();
645082607adcSTejun Heo mod_timer(&wq_watchdog_timer, jiffies + thresh);
645182607adcSTejun Heo }
645282607adcSTejun Heo
wq_watchdog_touch(int cpu)6453cb9d7fd5SVincent Whitchurch notrace void wq_watchdog_touch(int cpu)
645482607adcSTejun Heo {
645582607adcSTejun Heo if (cpu >= 0)
645682607adcSTejun Heo per_cpu(wq_watchdog_touched_cpu, cpu) = jiffies;
645789e28ce6SWang Qing
645882607adcSTejun Heo wq_watchdog_touched = jiffies;
645982607adcSTejun Heo }
646082607adcSTejun Heo
wq_watchdog_set_thresh(unsigned long thresh)646182607adcSTejun Heo static void wq_watchdog_set_thresh(unsigned long thresh)
646282607adcSTejun Heo {
646382607adcSTejun Heo wq_watchdog_thresh = 0;
646482607adcSTejun Heo del_timer_sync(&wq_watchdog_timer);
646582607adcSTejun Heo
646682607adcSTejun Heo if (thresh) {
646782607adcSTejun Heo wq_watchdog_thresh = thresh;
646882607adcSTejun Heo wq_watchdog_reset_touched();
646982607adcSTejun Heo mod_timer(&wq_watchdog_timer, jiffies + thresh * HZ);
647082607adcSTejun Heo }
647182607adcSTejun Heo }
647282607adcSTejun Heo
wq_watchdog_param_set_thresh(const char * val,const struct kernel_param * kp)647382607adcSTejun Heo static int wq_watchdog_param_set_thresh(const char *val,
647482607adcSTejun Heo const struct kernel_param *kp)
647582607adcSTejun Heo {
647682607adcSTejun Heo unsigned long thresh;
647782607adcSTejun Heo int ret;
647882607adcSTejun Heo
647982607adcSTejun Heo ret = kstrtoul(val, 0, &thresh);
648082607adcSTejun Heo if (ret)
648182607adcSTejun Heo return ret;
648282607adcSTejun Heo
648382607adcSTejun Heo if (system_wq)
648482607adcSTejun Heo wq_watchdog_set_thresh(thresh);
648582607adcSTejun Heo else
648682607adcSTejun Heo wq_watchdog_thresh = thresh;
648782607adcSTejun Heo
648882607adcSTejun Heo return 0;
648982607adcSTejun Heo }
649082607adcSTejun Heo
649182607adcSTejun Heo static const struct kernel_param_ops wq_watchdog_thresh_ops = {
649282607adcSTejun Heo .set = wq_watchdog_param_set_thresh,
649382607adcSTejun Heo .get = param_get_ulong,
649482607adcSTejun Heo };
649582607adcSTejun Heo
649682607adcSTejun Heo module_param_cb(watchdog_thresh, &wq_watchdog_thresh_ops, &wq_watchdog_thresh,
649782607adcSTejun Heo 0644);
649882607adcSTejun Heo
wq_watchdog_init(void)649982607adcSTejun Heo static void wq_watchdog_init(void)
650082607adcSTejun Heo {
65015cd79d6aSKees Cook timer_setup(&wq_watchdog_timer, wq_watchdog_timer_fn, TIMER_DEFERRABLE);
650282607adcSTejun Heo wq_watchdog_set_thresh(wq_watchdog_thresh);
650382607adcSTejun Heo }
650482607adcSTejun Heo
650582607adcSTejun Heo #else /* CONFIG_WQ_WATCHDOG */
650682607adcSTejun Heo
wq_watchdog_init(void)650782607adcSTejun Heo static inline void wq_watchdog_init(void) { }
650882607adcSTejun Heo
650982607adcSTejun Heo #endif /* CONFIG_WQ_WATCHDOG */
651082607adcSTejun Heo
restrict_unbound_cpumask(const char * name,const struct cpumask * mask)6511b2c562a7STejun Heo static void __init restrict_unbound_cpumask(const char *name, const struct cpumask *mask)
6512b2c562a7STejun Heo {
6513b2c562a7STejun Heo if (!cpumask_intersects(wq_unbound_cpumask, mask)) {
6514b2c562a7STejun Heo pr_warn("workqueue: Restricting unbound_cpumask (%*pb) with %s (%*pb) leaves no CPU, ignoring\n",
6515b2c562a7STejun Heo cpumask_pr_args(wq_unbound_cpumask), name, cpumask_pr_args(mask));
6516b2c562a7STejun Heo return;
6517b2c562a7STejun Heo }
6518b2c562a7STejun Heo
6519b2c562a7STejun Heo cpumask_and(wq_unbound_cpumask, wq_unbound_cpumask, mask);
6520b2c562a7STejun Heo }
6521b2c562a7STejun Heo
65223347fa09STejun Heo /**
65233347fa09STejun Heo * workqueue_init_early - early init for workqueue subsystem
65243347fa09STejun Heo *
65252930155bSTejun Heo * This is the first step of three-staged workqueue subsystem initialization and
65262930155bSTejun Heo * invoked as soon as the bare basics - memory allocation, cpumasks and idr are
65272930155bSTejun Heo * up. It sets up all the data structures and system workqueues and allows early
65282930155bSTejun Heo * boot code to create workqueues and queue/cancel work items. Actual work item
65292930155bSTejun Heo * execution starts only after kthreads can be created and scheduled right
65302930155bSTejun Heo * before early initcalls.
65313347fa09STejun Heo */
workqueue_init_early(void)65322333e829SYu Chen void __init workqueue_init_early(void)
65331da177e4SLinus Torvalds {
653484193c07STejun Heo struct wq_pod_type *pt = &wq_pod_types[WQ_AFFN_SYSTEM];
65357a4e344cSTejun Heo int std_nice[NR_STD_WORKER_POOLS] = { 0, HIGHPRI_NICE_LEVEL };
65367a4e344cSTejun Heo int i, cpu;
6537c34056a3STejun Heo
653810cdb157SLai Jiangshan BUILD_BUG_ON(__alignof__(struct pool_workqueue) < __alignof__(long long));
6539e904e6c2STejun Heo
6540b05a7928SFrederic Weisbecker BUG_ON(!alloc_cpumask_var(&wq_unbound_cpumask, GFP_KERNEL));
6541b2c562a7STejun Heo cpumask_copy(wq_unbound_cpumask, cpu_possible_mask);
6542b2c562a7STejun Heo restrict_unbound_cpumask("HK_TYPE_WQ", housekeeping_cpumask(HK_TYPE_WQ));
6543b2c562a7STejun Heo restrict_unbound_cpumask("HK_TYPE_DOMAIN", housekeeping_cpumask(HK_TYPE_DOMAIN));
6544ace3c549Stiozhang if (!cpumask_empty(&wq_cmdline_cpumask))
6545b2c562a7STejun Heo restrict_unbound_cpumask("workqueue.unbound_cpus", &wq_cmdline_cpumask);
6546ace3c549Stiozhang
6547e904e6c2STejun Heo pwq_cache = KMEM_CACHE(pool_workqueue, SLAB_PANIC);
6548e904e6c2STejun Heo
65492930155bSTejun Heo wq_update_pod_attrs_buf = alloc_workqueue_attrs();
65502930155bSTejun Heo BUG_ON(!wq_update_pod_attrs_buf);
65512930155bSTejun Heo
655284193c07STejun Heo /* initialize WQ_AFFN_SYSTEM pods */
655384193c07STejun Heo pt->pod_cpus = kcalloc(1, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
655484193c07STejun Heo pt->pod_node = kcalloc(1, sizeof(pt->pod_node[0]), GFP_KERNEL);
655584193c07STejun Heo pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
655684193c07STejun Heo BUG_ON(!pt->pod_cpus || !pt->pod_node || !pt->cpu_pod);
655784193c07STejun Heo
655884193c07STejun Heo BUG_ON(!zalloc_cpumask_var_node(&pt->pod_cpus[0], GFP_KERNEL, NUMA_NO_NODE));
655984193c07STejun Heo
656084193c07STejun Heo pt->nr_pods = 1;
656184193c07STejun Heo cpumask_copy(pt->pod_cpus[0], cpu_possible_mask);
656284193c07STejun Heo pt->pod_node[0] = NUMA_NO_NODE;
656384193c07STejun Heo pt->cpu_pod[0] = 0;
656484193c07STejun Heo
6565706026c2STejun Heo /* initialize CPU pools */
656629c91e99STejun Heo for_each_possible_cpu(cpu) {
65674ce62e9eSTejun Heo struct worker_pool *pool;
65688b03ae3cSTejun Heo
65697a4e344cSTejun Heo i = 0;
6570f02ae73aSTejun Heo for_each_cpu_worker_pool(pool, cpu) {
65717a4e344cSTejun Heo BUG_ON(init_worker_pool(pool));
6572ec22ca5eSTejun Heo pool->cpu = cpu;
65737a4e344cSTejun Heo cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu));
65749546b29eSTejun Heo cpumask_copy(pool->attrs->__pod_cpumask, cpumask_of(cpu));
65757a4e344cSTejun Heo pool->attrs->nice = std_nice[i++];
65768639ecebSTejun Heo pool->attrs->affn_strict = true;
6577f3f90ad4STejun Heo pool->node = cpu_to_node(cpu);
65787a4e344cSTejun Heo
65799daf9e67STejun Heo /* alloc pool ID */
658068e13a67SLai Jiangshan mutex_lock(&wq_pool_mutex);
65819daf9e67STejun Heo BUG_ON(worker_pool_assign_id(pool));
658268e13a67SLai Jiangshan mutex_unlock(&wq_pool_mutex);
65834ce62e9eSTejun Heo }
65848b03ae3cSTejun Heo }
65858b03ae3cSTejun Heo
65868a2b7538STejun Heo /* create default unbound and ordered wq attrs */
658729c91e99STejun Heo for (i = 0; i < NR_STD_WORKER_POOLS; i++) {
658829c91e99STejun Heo struct workqueue_attrs *attrs;
658929c91e99STejun Heo
6590be69d00dSThomas Gleixner BUG_ON(!(attrs = alloc_workqueue_attrs()));
659129c91e99STejun Heo attrs->nice = std_nice[i];
659229c91e99STejun Heo unbound_std_wq_attrs[i] = attrs;
65938a2b7538STejun Heo
65948a2b7538STejun Heo /*
65958a2b7538STejun Heo * An ordered wq should have only one pwq as ordering is
65968a2b7538STejun Heo * guaranteed by max_active which is enforced by pwqs.
65978a2b7538STejun Heo */
6598be69d00dSThomas Gleixner BUG_ON(!(attrs = alloc_workqueue_attrs()));
65998a2b7538STejun Heo attrs->nice = std_nice[i];
6600af73f5c9STejun Heo attrs->ordered = true;
66018a2b7538STejun Heo ordered_wq_attrs[i] = attrs;
660229c91e99STejun Heo }
660329c91e99STejun Heo
6604d320c038STejun Heo system_wq = alloc_workqueue("events", 0, 0);
66051aabe902SJoonsoo Kim system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0);
6606d320c038STejun Heo system_long_wq = alloc_workqueue("events_long", 0, 0);
6607f3421797STejun Heo system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
6608636b927eSTejun Heo WQ_MAX_ACTIVE);
660924d51addSTejun Heo system_freezable_wq = alloc_workqueue("events_freezable",
661024d51addSTejun Heo WQ_FREEZABLE, 0);
66110668106cSViresh Kumar system_power_efficient_wq = alloc_workqueue("events_power_efficient",
66120668106cSViresh Kumar WQ_POWER_EFFICIENT, 0);
66137bff1820SGreg Kroah-Hartman system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
66140668106cSViresh Kumar WQ_FREEZABLE | WQ_POWER_EFFICIENT,
66150668106cSViresh Kumar 0);
66161aabe902SJoonsoo Kim BUG_ON(!system_wq || !system_highpri_wq || !system_long_wq ||
66170668106cSViresh Kumar !system_unbound_wq || !system_freezable_wq ||
66180668106cSViresh Kumar !system_power_efficient_wq ||
66190668106cSViresh Kumar !system_freezable_power_efficient_wq);
66203347fa09STejun Heo }
66213347fa09STejun Heo
wq_cpu_intensive_thresh_init(void)6622aa6fde93STejun Heo static void __init wq_cpu_intensive_thresh_init(void)
6623aa6fde93STejun Heo {
6624aa6fde93STejun Heo unsigned long thresh;
6625aa6fde93STejun Heo unsigned long bogo;
6626aa6fde93STejun Heo
6627dd64c873SZqiang pwq_release_worker = kthread_create_worker(0, "pool_workqueue_release");
6628dd64c873SZqiang BUG_ON(IS_ERR(pwq_release_worker));
6629dd64c873SZqiang
6630aa6fde93STejun Heo /* if the user set it to a specific value, keep it */
6631aa6fde93STejun Heo if (wq_cpu_intensive_thresh_us != ULONG_MAX)
6632aa6fde93STejun Heo return;
6633aa6fde93STejun Heo
6634aa6fde93STejun Heo /*
6635aa6fde93STejun Heo * The default of 10ms is derived from the fact that most modern (as of
6636aa6fde93STejun Heo * 2023) processors can do a lot in 10ms and that it's just below what
6637aa6fde93STejun Heo * most consider human-perceivable. However, the kernel also runs on a
6638aa6fde93STejun Heo * lot slower CPUs including microcontrollers where the threshold is way
6639aa6fde93STejun Heo * too low.
6640aa6fde93STejun Heo *
6641aa6fde93STejun Heo * Let's scale up the threshold upto 1 second if BogoMips is below 4000.
6642aa6fde93STejun Heo * This is by no means accurate but it doesn't have to be. The mechanism
6643aa6fde93STejun Heo * is still useful even when the threshold is fully scaled up. Also, as
6644aa6fde93STejun Heo * the reports would usually be applicable to everyone, some machines
6645aa6fde93STejun Heo * operating on longer thresholds won't significantly diminish their
6646aa6fde93STejun Heo * usefulness.
6647aa6fde93STejun Heo */
6648aa6fde93STejun Heo thresh = 10 * USEC_PER_MSEC;
6649aa6fde93STejun Heo
6650aa6fde93STejun Heo /* see init/calibrate.c for lpj -> BogoMIPS calculation */
6651aa6fde93STejun Heo bogo = max_t(unsigned long, loops_per_jiffy / 500000 * HZ, 1);
6652aa6fde93STejun Heo if (bogo < 4000)
6653aa6fde93STejun Heo thresh = min_t(unsigned long, thresh * 4000 / bogo, USEC_PER_SEC);
6654aa6fde93STejun Heo
6655aa6fde93STejun Heo pr_debug("wq_cpu_intensive_thresh: lpj=%lu BogoMIPS=%lu thresh_us=%lu\n",
6656aa6fde93STejun Heo loops_per_jiffy, bogo, thresh);
6657aa6fde93STejun Heo
6658aa6fde93STejun Heo wq_cpu_intensive_thresh_us = thresh;
6659aa6fde93STejun Heo }
6660aa6fde93STejun Heo
66613347fa09STejun Heo /**
66623347fa09STejun Heo * workqueue_init - bring workqueue subsystem fully online
66633347fa09STejun Heo *
66642930155bSTejun Heo * This is the second step of three-staged workqueue subsystem initialization
66652930155bSTejun Heo * and invoked as soon as kthreads can be created and scheduled. Workqueues have
66662930155bSTejun Heo * been created and work items queued on them, but there are no kworkers
66672930155bSTejun Heo * executing the work items yet. Populate the worker pools with the initial
66682930155bSTejun Heo * workers and enable future kworker creations.
66693347fa09STejun Heo */
workqueue_init(void)66702333e829SYu Chen void __init workqueue_init(void)
66713347fa09STejun Heo {
66722186d9f9STejun Heo struct workqueue_struct *wq;
66733347fa09STejun Heo struct worker_pool *pool;
66743347fa09STejun Heo int cpu, bkt;
66753347fa09STejun Heo
6676aa6fde93STejun Heo wq_cpu_intensive_thresh_init();
6677aa6fde93STejun Heo
66782186d9f9STejun Heo mutex_lock(&wq_pool_mutex);
66792186d9f9STejun Heo
66802930155bSTejun Heo /*
66812930155bSTejun Heo * Per-cpu pools created earlier could be missing node hint. Fix them
66822930155bSTejun Heo * up. Also, create a rescuer for workqueues that requested it.
66832930155bSTejun Heo */
66842186d9f9STejun Heo for_each_possible_cpu(cpu) {
66852186d9f9STejun Heo for_each_cpu_worker_pool(pool, cpu) {
66862186d9f9STejun Heo pool->node = cpu_to_node(cpu);
66872186d9f9STejun Heo }
66882186d9f9STejun Heo }
66892186d9f9STejun Heo
669040c17f75STejun Heo list_for_each_entry(wq, &workqueues, list) {
669140c17f75STejun Heo WARN(init_rescuer(wq),
669240c17f75STejun Heo "workqueue: failed to create early rescuer for %s",
669340c17f75STejun Heo wq->name);
669440c17f75STejun Heo }
66952186d9f9STejun Heo
66962186d9f9STejun Heo mutex_unlock(&wq_pool_mutex);
66972186d9f9STejun Heo
66983347fa09STejun Heo /* create the initial workers */
66993347fa09STejun Heo for_each_online_cpu(cpu) {
67003347fa09STejun Heo for_each_cpu_worker_pool(pool, cpu) {
67013347fa09STejun Heo pool->flags &= ~POOL_DISASSOCIATED;
67023347fa09STejun Heo BUG_ON(!create_worker(pool));
67033347fa09STejun Heo }
67043347fa09STejun Heo }
67053347fa09STejun Heo
67063347fa09STejun Heo hash_for_each(unbound_pool_hash, bkt, pool, hash_node)
67073347fa09STejun Heo BUG_ON(!create_worker(pool));
67083347fa09STejun Heo
67093347fa09STejun Heo wq_online = true;
671082607adcSTejun Heo wq_watchdog_init();
67111da177e4SLinus Torvalds }
6712c4f135d6STetsuo Handa
6713025e1684STejun Heo /*
6714025e1684STejun Heo * Initialize @pt by first initializing @pt->cpu_pod[] with pod IDs according to
6715025e1684STejun Heo * @cpu_shares_pod(). Each subset of CPUs that share a pod is assigned a unique
6716025e1684STejun Heo * and consecutive pod ID. The rest of @pt is initialized accordingly.
6717025e1684STejun Heo */
init_pod_type(struct wq_pod_type * pt,bool (* cpus_share_pod)(int,int))6718025e1684STejun Heo static void __init init_pod_type(struct wq_pod_type *pt,
6719025e1684STejun Heo bool (*cpus_share_pod)(int, int))
6720025e1684STejun Heo {
6721025e1684STejun Heo int cur, pre, cpu, pod;
6722025e1684STejun Heo
6723025e1684STejun Heo pt->nr_pods = 0;
6724025e1684STejun Heo
6725025e1684STejun Heo /* init @pt->cpu_pod[] according to @cpus_share_pod() */
6726025e1684STejun Heo pt->cpu_pod = kcalloc(nr_cpu_ids, sizeof(pt->cpu_pod[0]), GFP_KERNEL);
6727025e1684STejun Heo BUG_ON(!pt->cpu_pod);
6728025e1684STejun Heo
6729025e1684STejun Heo for_each_possible_cpu(cur) {
6730025e1684STejun Heo for_each_possible_cpu(pre) {
6731025e1684STejun Heo if (pre >= cur) {
6732025e1684STejun Heo pt->cpu_pod[cur] = pt->nr_pods++;
6733025e1684STejun Heo break;
6734025e1684STejun Heo }
6735025e1684STejun Heo if (cpus_share_pod(cur, pre)) {
6736025e1684STejun Heo pt->cpu_pod[cur] = pt->cpu_pod[pre];
6737025e1684STejun Heo break;
6738025e1684STejun Heo }
6739025e1684STejun Heo }
6740025e1684STejun Heo }
6741025e1684STejun Heo
6742025e1684STejun Heo /* init the rest to match @pt->cpu_pod[] */
6743025e1684STejun Heo pt->pod_cpus = kcalloc(pt->nr_pods, sizeof(pt->pod_cpus[0]), GFP_KERNEL);
6744025e1684STejun Heo pt->pod_node = kcalloc(pt->nr_pods, sizeof(pt->pod_node[0]), GFP_KERNEL);
6745025e1684STejun Heo BUG_ON(!pt->pod_cpus || !pt->pod_node);
6746025e1684STejun Heo
6747025e1684STejun Heo for (pod = 0; pod < pt->nr_pods; pod++)
6748025e1684STejun Heo BUG_ON(!zalloc_cpumask_var(&pt->pod_cpus[pod], GFP_KERNEL));
6749025e1684STejun Heo
6750025e1684STejun Heo for_each_possible_cpu(cpu) {
6751025e1684STejun Heo cpumask_set_cpu(cpu, pt->pod_cpus[pt->cpu_pod[cpu]]);
6752025e1684STejun Heo pt->pod_node[pt->cpu_pod[cpu]] = cpu_to_node(cpu);
6753025e1684STejun Heo }
6754025e1684STejun Heo }
6755025e1684STejun Heo
cpus_dont_share(int cpu0,int cpu1)675663c5484eSTejun Heo static bool __init cpus_dont_share(int cpu0, int cpu1)
675763c5484eSTejun Heo {
675863c5484eSTejun Heo return false;
675963c5484eSTejun Heo }
676063c5484eSTejun Heo
cpus_share_smt(int cpu0,int cpu1)676163c5484eSTejun Heo static bool __init cpus_share_smt(int cpu0, int cpu1)
676263c5484eSTejun Heo {
676363c5484eSTejun Heo #ifdef CONFIG_SCHED_SMT
676463c5484eSTejun Heo return cpumask_test_cpu(cpu0, cpu_smt_mask(cpu1));
676563c5484eSTejun Heo #else
676663c5484eSTejun Heo return false;
676763c5484eSTejun Heo #endif
676863c5484eSTejun Heo }
676963c5484eSTejun Heo
cpus_share_numa(int cpu0,int cpu1)6770025e1684STejun Heo static bool __init cpus_share_numa(int cpu0, int cpu1)
6771025e1684STejun Heo {
6772025e1684STejun Heo return cpu_to_node(cpu0) == cpu_to_node(cpu1);
6773025e1684STejun Heo }
6774025e1684STejun Heo
67752930155bSTejun Heo /**
67762930155bSTejun Heo * workqueue_init_topology - initialize CPU pods for unbound workqueues
67772930155bSTejun Heo *
67782930155bSTejun Heo * This is the third step of there-staged workqueue subsystem initialization and
67792930155bSTejun Heo * invoked after SMP and topology information are fully initialized. It
67802930155bSTejun Heo * initializes the unbound CPU pods accordingly.
67812930155bSTejun Heo */
workqueue_init_topology(void)67822930155bSTejun Heo void __init workqueue_init_topology(void)
6783a86feae6STejun Heo {
67842930155bSTejun Heo struct workqueue_struct *wq;
6785025e1684STejun Heo int cpu;
6786a86feae6STejun Heo
678763c5484eSTejun Heo init_pod_type(&wq_pod_types[WQ_AFFN_CPU], cpus_dont_share);
678863c5484eSTejun Heo init_pod_type(&wq_pod_types[WQ_AFFN_SMT], cpus_share_smt);
678963c5484eSTejun Heo init_pod_type(&wq_pod_types[WQ_AFFN_CACHE], cpus_share_cache);
6790025e1684STejun Heo init_pod_type(&wq_pod_types[WQ_AFFN_NUMA], cpus_share_numa);
6791a86feae6STejun Heo
67922930155bSTejun Heo mutex_lock(&wq_pool_mutex);
6793a86feae6STejun Heo
6794a86feae6STejun Heo /*
67952930155bSTejun Heo * Workqueues allocated earlier would have all CPUs sharing the default
67962930155bSTejun Heo * worker pool. Explicitly call wq_update_pod() on all workqueue and CPU
67972930155bSTejun Heo * combinations to apply per-pod sharing.
67982930155bSTejun Heo */
67992930155bSTejun Heo list_for_each_entry(wq, &workqueues, list) {
68006741dd3fSGreg Kroah-Hartman for_each_online_cpu(cpu) {
68012930155bSTejun Heo wq_update_pod(wq, cpu, cpu, true);
68022930155bSTejun Heo }
68032930155bSTejun Heo }
68042930155bSTejun Heo
68052930155bSTejun Heo mutex_unlock(&wq_pool_mutex);
6806a86feae6STejun Heo }
6807a86feae6STejun Heo
__warn_flushing_systemwide_wq(void)680820bdedafSTetsuo Handa void __warn_flushing_systemwide_wq(void)
680920bdedafSTetsuo Handa {
681020bdedafSTetsuo Handa pr_warn("WARNING: Flushing system-wide workqueues will be prohibited in near future.\n");
681120bdedafSTetsuo Handa dump_stack();
681220bdedafSTetsuo Handa }
6813c4f135d6STetsuo Handa EXPORT_SYMBOL(__warn_flushing_systemwide_wq);
6814ace3c549Stiozhang
workqueue_unbound_cpus_setup(char * str)6815ace3c549Stiozhang static int __init workqueue_unbound_cpus_setup(char *str)
6816ace3c549Stiozhang {
6817ace3c549Stiozhang if (cpulist_parse(str, &wq_cmdline_cpumask) < 0) {
6818ace3c549Stiozhang cpumask_clear(&wq_cmdline_cpumask);
6819ace3c549Stiozhang pr_warn("workqueue.unbound_cpus: incorrect CPU range, using default\n");
6820ace3c549Stiozhang }
6821ace3c549Stiozhang
6822ace3c549Stiozhang return 1;
6823ace3c549Stiozhang }
6824ace3c549Stiozhang __setup("workqueue.unbound_cpus=", workqueue_unbound_cpus_setup);
6825