xref: /freebsd/sys/contrib/openzfs/module/os/linux/spl/spl-taskq.c (revision f9bc005b8ef3b507a5ecbc2d7fe4411ef70eff38)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Copyright (C) 2007-2010 Lawrence Livermore National Security, LLC.
4  *  Copyright (C) 2007 The Regents of the University of California.
5  *  Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
6  *  Written by Brian Behlendorf <behlendorf1@llnl.gov>.
7  *  UCRL-CODE-235197
8  *
9  *  This file is part of the SPL, Solaris Porting Layer.
10  *
11  *  The SPL is free software; you can redistribute it and/or modify it
12  *  under the terms of the GNU General Public License as published by the
13  *  Free Software Foundation; either version 2 of the License, or (at your
14  *  option) any later version.
15  *
16  *  The SPL is distributed in the hope that it will be useful, but WITHOUT
17  *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18  *  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
19  *  for more details.
20  *
21  *  You should have received a copy of the GNU General Public License along
22  *  with the SPL.  If not, see <http://www.gnu.org/licenses/>.
23  *
24  *  Solaris Porting Layer (SPL) Task Queue Implementation.
25  */
26 /*
27  * Copyright (c) 2024, Klara Inc.
28  * Copyright (c) 2024, Syneto
29  */
30 
31 #include <sys/timer.h>
32 #include <sys/taskq.h>
33 #include <sys/kmem.h>
34 #include <sys/tsd.h>
35 #include <sys/time.h>
36 #include <sys/atomic.h>
37 #include <sys/kstat.h>
38 #include <linux/cpuhotplug.h>
39 #include <linux/mod_compat.h>
40 #include <linux/kthread_compat.h>
41 
42 /* Linux 6.2 renamed timer_delete_sync(); point it at its old name for those. */
43 #ifndef HAVE_TIMER_DELETE_SYNC
44 #define	timer_delete_sync(t)	del_timer_sync(t)
45 #endif
46 
47 typedef struct taskq_kstats {
48 	/* static values, for completeness */
49 	kstat_named_t tqks_threads_max;
50 	kstat_named_t tqks_entry_pool_min;
51 	kstat_named_t tqks_entry_pool_max;
52 
53 	/* gauges (inc/dec counters, current value) */
54 	kstat_named_t tqks_threads_active;
55 	kstat_named_t tqks_threads_idle;
56 	kstat_named_t tqks_threads_total;
57 	kstat_named_t tqks_tasks_pending;
58 	kstat_named_t tqks_tasks_priority;
59 	kstat_named_t tqks_tasks_total;
60 	kstat_named_t tqks_tasks_delayed;
61 	kstat_named_t tqks_entries_free;
62 
63 	/* counters (inc only, since taskq creation) */
64 	kstat_named_t tqks_threads_created;
65 	kstat_named_t tqks_threads_destroyed;
66 	kstat_named_t tqks_tasks_dispatched;
67 	kstat_named_t tqks_tasks_dispatched_delayed;
68 	kstat_named_t tqks_tasks_executed_normal;
69 	kstat_named_t tqks_tasks_executed_priority;
70 	kstat_named_t tqks_tasks_executed;
71 	kstat_named_t tqks_tasks_delayed_requeued;
72 	kstat_named_t tqks_tasks_cancelled;
73 	kstat_named_t tqks_thread_wakeups;
74 	kstat_named_t tqks_thread_wakeups_nowork;
75 	kstat_named_t tqks_thread_sleeps;
76 } taskq_kstats_t;
77 
78 static taskq_kstats_t taskq_kstats_template = {
79 	{ "threads_max",		KSTAT_DATA_UINT64 },
80 	{ "entry_pool_min",		KSTAT_DATA_UINT64 },
81 	{ "entry_pool_max",		KSTAT_DATA_UINT64 },
82 	{ "threads_active",		KSTAT_DATA_UINT64 },
83 	{ "threads_idle",		KSTAT_DATA_UINT64 },
84 	{ "threads_total",		KSTAT_DATA_UINT64 },
85 	{ "tasks_pending",		KSTAT_DATA_UINT64 },
86 	{ "tasks_priority",		KSTAT_DATA_UINT64 },
87 	{ "tasks_total",		KSTAT_DATA_UINT64 },
88 	{ "tasks_delayed",		KSTAT_DATA_UINT64 },
89 	{ "entries_free",		KSTAT_DATA_UINT64 },
90 
91 	{ "threads_created",		KSTAT_DATA_UINT64 },
92 	{ "threads_destroyed",		KSTAT_DATA_UINT64 },
93 	{ "tasks_dispatched",		KSTAT_DATA_UINT64 },
94 	{ "tasks_dispatched_delayed",	KSTAT_DATA_UINT64 },
95 	{ "tasks_executed_normal",	KSTAT_DATA_UINT64 },
96 	{ "tasks_executed_priority",	KSTAT_DATA_UINT64 },
97 	{ "tasks_executed",		KSTAT_DATA_UINT64 },
98 	{ "tasks_delayed_requeued",	KSTAT_DATA_UINT64 },
99 	{ "tasks_cancelled",		KSTAT_DATA_UINT64 },
100 	{ "thread_wakeups",		KSTAT_DATA_UINT64 },
101 	{ "thread_wakeups_nowork",	KSTAT_DATA_UINT64 },
102 	{ "thread_sleeps",		KSTAT_DATA_UINT64 },
103 };
104 
105 #define	TQSTAT_INC(tq, stat)	wmsum_add(&tq->tq_sums.tqs_##stat, 1)
106 #define	TQSTAT_DEC(tq, stat)	wmsum_add(&tq->tq_sums.tqs_##stat, -1)
107 
108 #define	_TQSTAT_MOD_LIST(mod, tq, t) do { \
109 	switch (t->tqent_flags & TQENT_LIST_MASK) {			\
110 	case TQENT_LIST_NONE: ASSERT(list_empty(&t->tqent_list)); break;\
111 	case TQENT_LIST_PENDING: mod(tq, tasks_pending); break;		\
112 	case TQENT_LIST_PRIORITY: mod(tq, tasks_priority); break;	\
113 	case TQENT_LIST_DELAY: mod(tq, tasks_delayed); break;		\
114 	}								\
115 } while (0)
116 #define	TQSTAT_INC_LIST(tq, t)	_TQSTAT_MOD_LIST(TQSTAT_INC, tq, t)
117 #define	TQSTAT_DEC_LIST(tq, t)	_TQSTAT_MOD_LIST(TQSTAT_DEC, tq, t)
118 
119 #define	TQENT_SET_LIST(t, l)	\
120 	t->tqent_flags = (t->tqent_flags & ~TQENT_LIST_MASK) | l;
121 
122 static int spl_taskq_thread_bind = 0;
123 module_param(spl_taskq_thread_bind, int, 0644);
124 MODULE_PARM_DESC(spl_taskq_thread_bind, "Bind taskq thread to CPU by default");
125 
126 static uint_t spl_taskq_thread_timeout_ms = 5000;
127 module_param(spl_taskq_thread_timeout_ms, uint, 0644);
128 MODULE_PARM_DESC(spl_taskq_thread_timeout_ms,
129 	"Minimum idle threads exit interval for dynamic taskqs");
130 
131 static int spl_taskq_thread_dynamic = 1;
132 module_param(spl_taskq_thread_dynamic, int, 0444);
133 MODULE_PARM_DESC(spl_taskq_thread_dynamic, "Allow dynamic taskq threads");
134 
135 static int spl_taskq_thread_priority = 1;
136 module_param(spl_taskq_thread_priority, int, 0644);
137 MODULE_PARM_DESC(spl_taskq_thread_priority,
138 	"Allow non-default priority for taskq threads");
139 
140 static uint_t spl_taskq_thread_sequential = 4;
141 module_param(spl_taskq_thread_sequential, uint, 0644);
142 MODULE_PARM_DESC(spl_taskq_thread_sequential,
143 	"Create new taskq threads after N sequential tasks");
144 
145 /*
146  * Global system-wide dynamic task queue available for all consumers. This
147  * taskq is not intended for long-running tasks; instead, a dedicated taskq
148  * should be created.
149  */
150 taskq_t *system_taskq;
151 EXPORT_SYMBOL(system_taskq);
152 /* Global dynamic task queue for long delay */
153 taskq_t *system_delay_taskq;
154 EXPORT_SYMBOL(system_delay_taskq);
155 
156 /* Private dedicated taskq for creating new taskq threads on demand. */
157 static taskq_t *dynamic_taskq;
158 static taskq_thread_t *taskq_thread_create(taskq_t *);
159 
160 /* Multi-callback id for cpu hotplugging. */
161 static int spl_taskq_cpuhp_state;
162 
163 /* List of all taskqs */
164 LIST_HEAD(tq_list);
165 struct rw_semaphore tq_list_sem;
166 static uint_t taskq_tsd;
167 
168 static int
169 task_km_flags(uint_t flags)
170 {
171 	if (flags & TQ_NOSLEEP)
172 		return (KM_NOSLEEP);
173 
174 	if (flags & TQ_PUSHPAGE)
175 		return (KM_PUSHPAGE);
176 
177 	return (KM_SLEEP);
178 }
179 
180 /*
181  * taskq_find_by_name - Find the largest instance number of a named taskq.
182  */
183 static int
184 taskq_find_by_name(const char *name)
185 {
186 	struct list_head *tql = NULL;
187 	taskq_t *tq;
188 
189 	list_for_each_prev(tql, &tq_list) {
190 		tq = list_entry(tql, taskq_t, tq_taskqs);
191 		if (strcmp(name, tq->tq_name) == 0)
192 			return (tq->tq_instance);
193 	}
194 	return (-1);
195 }
196 
197 /*
198  * NOTE: Must be called with tq->tq_lock held, returns a list_t which
199  * is not attached to the free, work, or pending taskq lists.
200  */
201 static taskq_ent_t *
202 task_alloc(taskq_t *tq, uint_t flags, unsigned long *irqflags)
203 {
204 	taskq_ent_t *t;
205 	int count = 0;
206 
207 	ASSERT(tq);
208 retry:
209 	/* Acquire taskq_ent_t's from free list if available */
210 	if (!list_empty(&tq->tq_free_list) && !(flags & TQ_NEW)) {
211 		t = list_entry(tq->tq_free_list.next, taskq_ent_t, tqent_list);
212 
213 		ASSERT(!(t->tqent_flags & TQENT_FLAG_PREALLOC));
214 		ASSERT(!(t->tqent_flags & TQENT_FLAG_CANCEL));
215 		ASSERT(!timer_pending(&t->tqent_timer));
216 
217 		list_del_init(&t->tqent_list);
218 		TQSTAT_DEC(tq, entries_free);
219 		return (t);
220 	}
221 
222 	/* Free list is empty and memory allocations are prohibited */
223 	if (flags & TQ_NOALLOC)
224 		return (NULL);
225 
226 	/* Hit maximum taskq_ent_t pool size */
227 	if (tq->tq_nalloc >= tq->tq_maxalloc) {
228 		if (flags & TQ_NOSLEEP)
229 			return (NULL);
230 
231 		/*
232 		 * Sleep periodically polling the free list for an available
233 		 * taskq_ent_t. Dispatching with TQ_SLEEP should always succeed
234 		 * but we cannot block forever waiting for an taskq_ent_t to
235 		 * show up in the free list, otherwise a deadlock can happen.
236 		 *
237 		 * Therefore, we need to allocate a new task even if the number
238 		 * of allocated tasks is above tq->tq_maxalloc, but we still
239 		 * end up delaying the task allocation by one second, thereby
240 		 * throttling the task dispatch rate.
241 		 */
242 		spin_unlock_irqrestore(&tq->tq_lock, *irqflags);
243 		schedule_timeout_interruptible(HZ / 100);
244 		spin_lock_irqsave_nested(&tq->tq_lock, *irqflags,
245 		    tq->tq_lock_class);
246 		if (count < 100) {
247 			count++;
248 			goto retry;
249 		}
250 	}
251 
252 	spin_unlock_irqrestore(&tq->tq_lock, *irqflags);
253 	t = kmem_alloc(sizeof (taskq_ent_t), task_km_flags(flags));
254 	spin_lock_irqsave_nested(&tq->tq_lock, *irqflags, tq->tq_lock_class);
255 
256 	if (t) {
257 		taskq_init_ent(t);
258 		tq->tq_nalloc++;
259 	}
260 
261 	return (t);
262 }
263 
264 /*
265  * NOTE: Must be called with tq->tq_lock held, expects the taskq_ent_t
266  * to already be removed from the free, work, or pending taskq lists.
267  */
268 static void
269 task_free(taskq_t *tq, taskq_ent_t *t)
270 {
271 	ASSERT(tq);
272 	ASSERT(t);
273 	ASSERT(list_empty(&t->tqent_list));
274 	ASSERT(!timer_pending(&t->tqent_timer));
275 
276 	kmem_free(t, sizeof (taskq_ent_t));
277 	tq->tq_nalloc--;
278 }
279 
280 /*
281  * NOTE: Must be called with tq->tq_lock held, either destroys the
282  * taskq_ent_t if too many exist or moves it to the free list for later use.
283  */
284 static void
285 task_done(taskq_t *tq, taskq_ent_t *t)
286 {
287 	ASSERT(tq);
288 	ASSERT(t);
289 	ASSERT(list_empty(&t->tqent_list));
290 
291 	/* Wake tasks blocked in taskq_wait_id() */
292 	wake_up_all(&t->tqent_waitq);
293 
294 	if (tq->tq_nalloc <= tq->tq_minalloc) {
295 		t->tqent_id = TASKQID_INVALID;
296 		t->tqent_func = NULL;
297 		t->tqent_arg = NULL;
298 		t->tqent_flags = 0;
299 
300 		list_add_tail(&t->tqent_list, &tq->tq_free_list);
301 		TQSTAT_INC(tq, entries_free);
302 	} else {
303 		task_free(tq, t);
304 	}
305 }
306 
307 /*
308  * When a delayed task timer expires remove it from the delay list and
309  * add it to the priority list in order for immediate processing.
310  */
311 static void
312 task_expire_impl(taskq_ent_t *t)
313 {
314 	taskq_ent_t *w;
315 	taskq_t *tq = t->tqent_taskq;
316 	struct list_head *l = NULL;
317 	unsigned long flags;
318 
319 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
320 
321 	if (t->tqent_flags & TQENT_FLAG_CANCEL) {
322 		ASSERT(list_empty(&t->tqent_list));
323 		spin_unlock_irqrestore(&tq->tq_lock, flags);
324 		return;
325 	}
326 
327 	t->tqent_birth = jiffies;
328 
329 	/*
330 	 * The priority list must be maintained in strict task id order
331 	 * from lowest to highest for lowest_id to be easily calculable.
332 	 */
333 	list_del(&t->tqent_list);
334 	list_for_each_prev(l, &tq->tq_prio_list) {
335 		w = list_entry(l, taskq_ent_t, tqent_list);
336 		if (w->tqent_id < t->tqent_id) {
337 			list_add(&t->tqent_list, l);
338 			break;
339 		}
340 	}
341 	if (l == &tq->tq_prio_list)
342 		list_add(&t->tqent_list, &tq->tq_prio_list);
343 
344 	spin_unlock_irqrestore(&tq->tq_lock, flags);
345 
346 	wake_up(&tq->tq_work_waitq);
347 
348 	TQSTAT_INC(tq, tasks_delayed_requeued);
349 }
350 
351 static void
352 task_expire(struct timer_list *tl)
353 {
354 	struct timer_list *tmr = (struct timer_list *)tl;
355 	taskq_ent_t *t = from_timer(t, tmr, tqent_timer);
356 	task_expire_impl(t);
357 }
358 
359 /*
360  * Returns the lowest incomplete taskqid_t.  The taskqid_t may
361  * be queued on the pending list, on the priority list, on the
362  * delay list, or on the work list currently being handled, but
363  * it is not 100% complete yet.
364  */
365 static taskqid_t
366 taskq_lowest_id(taskq_t *tq)
367 {
368 	taskqid_t lowest_id = tq->tq_next_id;
369 	taskq_ent_t *t;
370 	taskq_thread_t *tqt;
371 
372 	if (!list_empty(&tq->tq_pend_list)) {
373 		t = list_entry(tq->tq_pend_list.next, taskq_ent_t, tqent_list);
374 		lowest_id = MIN(lowest_id, t->tqent_id);
375 	}
376 
377 	if (!list_empty(&tq->tq_prio_list)) {
378 		t = list_entry(tq->tq_prio_list.next, taskq_ent_t, tqent_list);
379 		lowest_id = MIN(lowest_id, t->tqent_id);
380 	}
381 
382 	if (!list_empty(&tq->tq_delay_list)) {
383 		t = list_entry(tq->tq_delay_list.next, taskq_ent_t, tqent_list);
384 		lowest_id = MIN(lowest_id, t->tqent_id);
385 	}
386 
387 	if (!list_empty(&tq->tq_active_list)) {
388 		tqt = list_entry(tq->tq_active_list.next, taskq_thread_t,
389 		    tqt_active_list);
390 		ASSERT(tqt->tqt_id != TASKQID_INVALID);
391 		lowest_id = MIN(lowest_id, tqt->tqt_id);
392 	}
393 
394 	return (lowest_id);
395 }
396 
397 /*
398  * Insert a task into a list keeping the list sorted by increasing taskqid.
399  */
400 static void
401 taskq_insert_in_order(taskq_t *tq, taskq_thread_t *tqt)
402 {
403 	taskq_thread_t *w;
404 	struct list_head *l = NULL;
405 
406 	ASSERT(tq);
407 	ASSERT(tqt);
408 
409 	list_for_each_prev(l, &tq->tq_active_list) {
410 		w = list_entry(l, taskq_thread_t, tqt_active_list);
411 		if (w->tqt_id < tqt->tqt_id) {
412 			list_add(&tqt->tqt_active_list, l);
413 			break;
414 		}
415 	}
416 	if (l == &tq->tq_active_list)
417 		list_add(&tqt->tqt_active_list, &tq->tq_active_list);
418 }
419 
420 /*
421  * Find and return a task from the given list if it exists.  The list
422  * must be in lowest to highest task id order.
423  */
424 static taskq_ent_t *
425 taskq_find_list(taskq_t *tq, struct list_head *lh, taskqid_t id)
426 {
427 	struct list_head *l = NULL;
428 	taskq_ent_t *t;
429 
430 	list_for_each(l, lh) {
431 		t = list_entry(l, taskq_ent_t, tqent_list);
432 
433 		if (t->tqent_id == id)
434 			return (t);
435 
436 		if (t->tqent_id > id)
437 			break;
438 	}
439 
440 	return (NULL);
441 }
442 
443 /*
444  * Find an already dispatched task given the task id regardless of what
445  * state it is in.  If a task is still pending it will be returned.
446  * If a task is executing, then -EBUSY will be returned instead.
447  * If the task has already been run then NULL is returned.
448  */
449 static taskq_ent_t *
450 taskq_find(taskq_t *tq, taskqid_t id)
451 {
452 	taskq_thread_t *tqt;
453 	struct list_head *l = NULL;
454 	taskq_ent_t *t;
455 
456 	t = taskq_find_list(tq, &tq->tq_delay_list, id);
457 	if (t)
458 		return (t);
459 
460 	t = taskq_find_list(tq, &tq->tq_prio_list, id);
461 	if (t)
462 		return (t);
463 
464 	t = taskq_find_list(tq, &tq->tq_pend_list, id);
465 	if (t)
466 		return (t);
467 
468 	list_for_each(l, &tq->tq_active_list) {
469 		tqt = list_entry(l, taskq_thread_t, tqt_active_list);
470 		if (tqt->tqt_id == id) {
471 			/*
472 			 * Instead of returning tqt_task, we just return a non
473 			 * NULL value to prevent misuse, since tqt_task only
474 			 * has two valid fields.
475 			 */
476 			return (ERR_PTR(-EBUSY));
477 		}
478 	}
479 
480 	return (NULL);
481 }
482 
483 /*
484  * Theory for the taskq_wait_id(), taskq_wait_outstanding(), and
485  * taskq_wait() functions below.
486  *
487  * Taskq waiting is accomplished by tracking the lowest outstanding task
488  * id and the next available task id.  As tasks are dispatched they are
489  * added to the tail of the pending, priority, or delay lists.  As worker
490  * threads become available the tasks are removed from the heads of these
491  * lists and linked to the worker threads.  This ensures the lists are
492  * kept sorted by lowest to highest task id.
493  *
494  * Therefore the lowest outstanding task id can be quickly determined by
495  * checking the head item from all of these lists.  This value is stored
496  * with the taskq as the lowest id.  It only needs to be recalculated when
497  * either the task with the current lowest id completes or is canceled.
498  *
499  * By blocking until the lowest task id exceeds the passed task id the
500  * taskq_wait_outstanding() function can be easily implemented.  Similarly,
501  * by blocking until the lowest task id matches the next task id taskq_wait()
502  * can be implemented.
503  *
504  * Callers should be aware that when there are multiple worked threads it
505  * is possible for larger task ids to complete before smaller ones.  Also
506  * when the taskq contains delay tasks with small task ids callers may
507  * block for a considerable length of time waiting for them to expire and
508  * execute.
509  */
510 static int
511 taskq_wait_id_check(taskq_t *tq, taskqid_t id)
512 {
513 	int rc;
514 	unsigned long flags;
515 
516 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
517 	rc = (taskq_find(tq, id) == NULL);
518 	spin_unlock_irqrestore(&tq->tq_lock, flags);
519 
520 	return (rc);
521 }
522 
523 /*
524  * The taskq_wait_id() function blocks until the passed task id completes.
525  * This does not guarantee that all lower task ids have completed.
526  */
527 void
528 taskq_wait_id(taskq_t *tq, taskqid_t id)
529 {
530 	wait_event(tq->tq_wait_waitq, taskq_wait_id_check(tq, id));
531 }
532 EXPORT_SYMBOL(taskq_wait_id);
533 
534 static int
535 taskq_wait_outstanding_check(taskq_t *tq, taskqid_t id)
536 {
537 	int rc;
538 	unsigned long flags;
539 
540 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
541 	rc = (id < tq->tq_lowest_id);
542 	spin_unlock_irqrestore(&tq->tq_lock, flags);
543 
544 	return (rc);
545 }
546 
547 /*
548  * The taskq_wait_outstanding() function will block until all tasks with a
549  * lower taskqid than the passed 'id' have been completed.  Note that all
550  * task id's are assigned monotonically at dispatch time.  Zero may be
551  * passed for the id to indicate all tasks dispatch up to this point,
552  * but not after, should be waited for.
553  */
554 void
555 taskq_wait_outstanding(taskq_t *tq, taskqid_t id)
556 {
557 	id = id ? id : tq->tq_next_id - 1;
558 	wait_event(tq->tq_wait_waitq, taskq_wait_outstanding_check(tq, id));
559 }
560 EXPORT_SYMBOL(taskq_wait_outstanding);
561 
562 static int
563 taskq_wait_check(taskq_t *tq)
564 {
565 	int rc;
566 	unsigned long flags;
567 
568 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
569 	rc = (tq->tq_lowest_id == tq->tq_next_id);
570 	spin_unlock_irqrestore(&tq->tq_lock, flags);
571 
572 	return (rc);
573 }
574 
575 /*
576  * The taskq_wait() function will block until the taskq is empty.
577  * This means that if a taskq re-dispatches work to itself taskq_wait()
578  * callers will block indefinitely.
579  */
580 void
581 taskq_wait(taskq_t *tq)
582 {
583 	wait_event(tq->tq_wait_waitq, taskq_wait_check(tq));
584 }
585 EXPORT_SYMBOL(taskq_wait);
586 
587 int
588 taskq_member(taskq_t *tq, kthread_t *t)
589 {
590 	return (tq == (taskq_t *)tsd_get_by_thread(taskq_tsd, t));
591 }
592 EXPORT_SYMBOL(taskq_member);
593 
594 taskq_t *
595 taskq_of_curthread(void)
596 {
597 	return (tsd_get(taskq_tsd));
598 }
599 EXPORT_SYMBOL(taskq_of_curthread);
600 
601 /*
602  * Cancel a dispatched task. Pending tasks are cancelled immediately.
603  * If the task is running, behavior depends on wait parameter:
604  *   - wait=B_TRUE: Block until task completes
605  *   - wait=B_FALSE: Return EBUSY immediately
606  *
607  * Return values:
608  *   0      - Cancelled before execution. Caller must release resources.
609  *   EBUSY  - Task running (wait=B_FALSE only). Will self-cleanup.
610  *   ENOENT - Not found, or completed after waiting. Already cleaned up.
611  *
612  * Note: wait=B_TRUE returns ENOENT (not EBUSY) after waiting because
613  * the task no longer exists. This distinguishes "cancelled before run"
614  * from "completed naturally" for proper resource management.
615  */
616 int
617 taskq_cancel_id(taskq_t *tq, taskqid_t id, boolean_t wait)
618 {
619 	taskq_ent_t *t;
620 	int rc = ENOENT;
621 	unsigned long flags;
622 
623 	ASSERT(tq);
624 
625 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
626 	t = taskq_find(tq, id);
627 	if (t && t != ERR_PTR(-EBUSY)) {
628 		list_del_init(&t->tqent_list);
629 		TQSTAT_DEC_LIST(tq, t);
630 		TQSTAT_DEC(tq, tasks_total);
631 
632 		t->tqent_flags |= TQENT_FLAG_CANCEL;
633 		TQSTAT_INC(tq, tasks_cancelled);
634 
635 		/*
636 		 * When canceling the lowest outstanding task id we
637 		 * must recalculate the new lowest outstanding id.
638 		 */
639 		if (tq->tq_lowest_id == t->tqent_id) {
640 			tq->tq_lowest_id = taskq_lowest_id(tq);
641 			ASSERT3S(tq->tq_lowest_id, >, t->tqent_id);
642 		}
643 
644 		/*
645 		 * The task_expire() function takes the tq->tq_lock so drop
646 		 * the lock before synchronously cancelling the timer.
647 		 *
648 		 * Always call timer_delete_sync() unconditionally. A
649 		 * timer_pending() check would be insufficient and unsafe.
650 		 * When a timer expires, it is immediately dequeued from the
651 		 * timer wheel (timer_pending() returns FALSE), but the
652 		 * callback (task_expire) may not run until later.
653 		 *
654 		 * The race window:
655 		 * 1) Timer expires and is dequeued - timer_pending() now
656 		 *    returns FALSE
657 		 * 2) task_done() is called below, freeing the task, sets
658 		 *    tqent_func = NULL and clears flags including CANCEL
659 		 * 3) Timer callback finally runs, sees no CANCEL flag,
660 		 *    queues task to prio_list
661 		 * 4) Worker thread attempts to execute NULL tqent_func
662 		 *    and panics
663 		 *
664 		 * timer_delete_sync() prevents this by ensuring the timer
665 		 * callback completes before the task is freed.
666 		 */
667 		spin_unlock_irqrestore(&tq->tq_lock, flags);
668 		timer_delete_sync(&t->tqent_timer);
669 		spin_lock_irqsave_nested(&tq->tq_lock, flags,
670 		    tq->tq_lock_class);
671 
672 		if (!(t->tqent_flags & TQENT_FLAG_PREALLOC))
673 			task_done(tq, t);
674 
675 		rc = 0;
676 	}
677 	spin_unlock_irqrestore(&tq->tq_lock, flags);
678 
679 	if (t == ERR_PTR(-EBUSY)) {
680 		if (wait) {
681 			taskq_wait_id(tq, id);
682 			rc = ENOENT;  /* Completed, no longer exists */
683 		} else {
684 			rc = EBUSY;   /* Still running */
685 		}
686 	}
687 
688 	return (rc);
689 }
690 EXPORT_SYMBOL(taskq_cancel_id);
691 
692 static int taskq_thread_spawn(taskq_t *tq);
693 
694 taskqid_t
695 taskq_dispatch(taskq_t *tq, task_func_t func, void *arg, uint_t flags)
696 {
697 	taskq_ent_t *t;
698 	taskqid_t rc = TASKQID_INVALID;
699 	unsigned long irqflags;
700 
701 	ASSERT(tq);
702 	ASSERT(func);
703 
704 	spin_lock_irqsave_nested(&tq->tq_lock, irqflags, tq->tq_lock_class);
705 
706 	/* Taskq being destroyed and all tasks drained */
707 	if (!(tq->tq_flags & TASKQ_ACTIVE))
708 		goto out;
709 
710 	/* Do not queue the task unless there is idle thread for it */
711 	ASSERT(tq->tq_nactive <= tq->tq_nthreads);
712 	if ((flags & TQ_NOQUEUE) && (tq->tq_nactive == tq->tq_nthreads)) {
713 		/* Dynamic taskq may be able to spawn another thread */
714 		if (taskq_thread_spawn(tq) == 0)
715 			goto out;
716 	}
717 
718 	if ((t = task_alloc(tq, flags, &irqflags)) == NULL)
719 		goto out;
720 
721 	spin_lock(&t->tqent_lock);
722 
723 	/* Queue to the front of the list to enforce TQ_NOQUEUE semantics */
724 	if (flags & TQ_NOQUEUE) {
725 		TQENT_SET_LIST(t, TQENT_LIST_PRIORITY);
726 		list_add(&t->tqent_list, &tq->tq_prio_list);
727 	/* Queue to the priority list instead of the pending list */
728 	} else if (flags & TQ_FRONT) {
729 		TQENT_SET_LIST(t, TQENT_LIST_PRIORITY);
730 		list_add_tail(&t->tqent_list, &tq->tq_prio_list);
731 	} else {
732 		TQENT_SET_LIST(t, TQENT_LIST_PENDING);
733 		list_add_tail(&t->tqent_list, &tq->tq_pend_list);
734 	}
735 	TQSTAT_INC_LIST(tq, t);
736 	TQSTAT_INC(tq, tasks_total);
737 
738 	t->tqent_id = rc = tq->tq_next_id;
739 	tq->tq_next_id++;
740 	t->tqent_func = func;
741 	t->tqent_arg = arg;
742 	t->tqent_taskq = tq;
743 	t->tqent_timer.function = NULL;
744 	t->tqent_timer.expires = 0;
745 	t->tqent_birth = jiffies;
746 
747 	ASSERT(!(t->tqent_flags & TQENT_FLAG_PREALLOC));
748 
749 	spin_unlock(&t->tqent_lock);
750 
751 	wake_up(&tq->tq_work_waitq);
752 
753 	TQSTAT_INC(tq, tasks_dispatched);
754 
755 	/* Spawn additional taskq threads if required. */
756 	if (!(flags & TQ_NOQUEUE) && tq->tq_nactive == tq->tq_nthreads)
757 		(void) taskq_thread_spawn(tq);
758 out:
759 	spin_unlock_irqrestore(&tq->tq_lock, irqflags);
760 	return (rc);
761 }
762 EXPORT_SYMBOL(taskq_dispatch);
763 
764 taskqid_t
765 taskq_dispatch_delay(taskq_t *tq, task_func_t func, void *arg,
766     uint_t flags, clock_t expire_time)
767 {
768 	taskqid_t rc = TASKQID_INVALID;
769 	taskq_ent_t *t;
770 	unsigned long irqflags;
771 
772 	ASSERT(tq);
773 	ASSERT(func);
774 
775 	spin_lock_irqsave_nested(&tq->tq_lock, irqflags, tq->tq_lock_class);
776 
777 	/* Taskq being destroyed and all tasks drained */
778 	if (!(tq->tq_flags & TASKQ_ACTIVE))
779 		goto out;
780 
781 	if ((t = task_alloc(tq, flags, &irqflags)) == NULL)
782 		goto out;
783 
784 	spin_lock(&t->tqent_lock);
785 
786 	/* Queue to the delay list for subsequent execution */
787 	list_add_tail(&t->tqent_list, &tq->tq_delay_list);
788 	TQENT_SET_LIST(t, TQENT_LIST_DELAY);
789 	TQSTAT_INC_LIST(tq, t);
790 	TQSTAT_INC(tq, tasks_total);
791 
792 	t->tqent_id = rc = tq->tq_next_id;
793 	tq->tq_next_id++;
794 	t->tqent_func = func;
795 	t->tqent_arg = arg;
796 	t->tqent_taskq = tq;
797 	t->tqent_timer.function = task_expire;
798 	t->tqent_timer.expires = (unsigned long)expire_time;
799 	add_timer(&t->tqent_timer);
800 
801 	ASSERT(!(t->tqent_flags & TQENT_FLAG_PREALLOC));
802 
803 	spin_unlock(&t->tqent_lock);
804 
805 	TQSTAT_INC(tq, tasks_dispatched_delayed);
806 
807 	/* Spawn additional taskq threads if required. */
808 	if (tq->tq_nactive == tq->tq_nthreads)
809 		(void) taskq_thread_spawn(tq);
810 out:
811 	spin_unlock_irqrestore(&tq->tq_lock, irqflags);
812 	return (rc);
813 }
814 EXPORT_SYMBOL(taskq_dispatch_delay);
815 
816 void
817 taskq_dispatch_ent(taskq_t *tq, task_func_t func, void *arg, uint_t flags,
818     taskq_ent_t *t)
819 {
820 	unsigned long irqflags;
821 	ASSERT(tq);
822 	ASSERT(func);
823 
824 	spin_lock_irqsave_nested(&tq->tq_lock, irqflags,
825 	    tq->tq_lock_class);
826 
827 	/* Taskq being destroyed and all tasks drained */
828 	if (!(tq->tq_flags & TASKQ_ACTIVE)) {
829 		t->tqent_id = TASKQID_INVALID;
830 		goto out;
831 	}
832 
833 	if ((flags & TQ_NOQUEUE) && (tq->tq_nactive == tq->tq_nthreads)) {
834 		/* Dynamic taskq may be able to spawn another thread */
835 		if (taskq_thread_spawn(tq) == 0)
836 			goto out;
837 		flags |= TQ_FRONT;
838 	}
839 
840 	spin_lock(&t->tqent_lock);
841 
842 	/*
843 	 * Make sure the entry is not on some other taskq; it is important to
844 	 * ASSERT() under lock
845 	 */
846 	ASSERT(taskq_empty_ent(t));
847 
848 	/*
849 	 * Mark it as a prealloc'd task.  This is important
850 	 * to ensure that we don't free it later.
851 	 */
852 	t->tqent_flags |= TQENT_FLAG_PREALLOC;
853 
854 	/* Queue to the priority list instead of the pending list */
855 	if (flags & TQ_FRONT) {
856 		TQENT_SET_LIST(t, TQENT_LIST_PRIORITY);
857 		list_add_tail(&t->tqent_list, &tq->tq_prio_list);
858 	} else {
859 		TQENT_SET_LIST(t, TQENT_LIST_PENDING);
860 		list_add_tail(&t->tqent_list, &tq->tq_pend_list);
861 	}
862 	TQSTAT_INC_LIST(tq, t);
863 	TQSTAT_INC(tq, tasks_total);
864 
865 	t->tqent_id = tq->tq_next_id;
866 	tq->tq_next_id++;
867 	t->tqent_func = func;
868 	t->tqent_arg = arg;
869 	t->tqent_taskq = tq;
870 	t->tqent_birth = jiffies;
871 
872 	spin_unlock(&t->tqent_lock);
873 
874 	wake_up(&tq->tq_work_waitq);
875 
876 	TQSTAT_INC(tq, tasks_dispatched);
877 
878 	/* Spawn additional taskq threads if required. */
879 	if (tq->tq_nactive == tq->tq_nthreads)
880 		(void) taskq_thread_spawn(tq);
881 out:
882 	spin_unlock_irqrestore(&tq->tq_lock, irqflags);
883 }
884 EXPORT_SYMBOL(taskq_dispatch_ent);
885 
886 int
887 taskq_empty_ent(taskq_ent_t *t)
888 {
889 	return (list_empty(&t->tqent_list));
890 }
891 EXPORT_SYMBOL(taskq_empty_ent);
892 
893 void
894 taskq_init_ent(taskq_ent_t *t)
895 {
896 	spin_lock_init(&t->tqent_lock);
897 	init_waitqueue_head(&t->tqent_waitq);
898 	timer_setup(&t->tqent_timer, NULL, 0);
899 	INIT_LIST_HEAD(&t->tqent_list);
900 	t->tqent_id = 0;
901 	t->tqent_func = NULL;
902 	t->tqent_arg = NULL;
903 	t->tqent_flags = 0;
904 	t->tqent_taskq = NULL;
905 }
906 EXPORT_SYMBOL(taskq_init_ent);
907 
908 /*
909  * Return the next pending task, preference is given to tasks on the
910  * priority list which were dispatched with TQ_FRONT.
911  */
912 static taskq_ent_t *
913 taskq_next_ent(taskq_t *tq)
914 {
915 	struct list_head *list;
916 
917 	if (!list_empty(&tq->tq_prio_list))
918 		list = &tq->tq_prio_list;
919 	else if (!list_empty(&tq->tq_pend_list))
920 		list = &tq->tq_pend_list;
921 	else
922 		return (NULL);
923 
924 	return (list_entry(list->next, taskq_ent_t, tqent_list));
925 }
926 
927 /*
928  * Spawns a new thread for the specified taskq.
929  */
930 static void
931 taskq_thread_spawn_task(void *arg)
932 {
933 	taskq_t *tq = (taskq_t *)arg;
934 	unsigned long flags;
935 
936 	if (taskq_thread_create(tq) == NULL) {
937 		/* restore spawning count if failed */
938 		spin_lock_irqsave_nested(&tq->tq_lock, flags,
939 		    tq->tq_lock_class);
940 		tq->tq_nspawn--;
941 		spin_unlock_irqrestore(&tq->tq_lock, flags);
942 	}
943 }
944 
945 /*
946  * Spawn addition threads for dynamic taskqs (TASKQ_DYNAMIC) the current
947  * number of threads is insufficient to handle the pending tasks.  These
948  * new threads must be created by the dedicated dynamic_taskq to avoid
949  * deadlocks between thread creation and memory reclaim.  The system_taskq
950  * which is also a dynamic taskq cannot be safely used for this.
951  */
952 static int
953 taskq_thread_spawn(taskq_t *tq)
954 {
955 	int spawning = 0;
956 
957 	if (!(tq->tq_flags & TASKQ_DYNAMIC))
958 		return (0);
959 
960 	tq->lastspawnstop = jiffies;
961 	if ((tq->tq_nthreads + tq->tq_nspawn < tq->tq_maxthreads) &&
962 	    (tq->tq_flags & TASKQ_ACTIVE)) {
963 		spawning = (++tq->tq_nspawn);
964 		taskq_dispatch(dynamic_taskq, taskq_thread_spawn_task,
965 		    tq, TQ_NOSLEEP);
966 	}
967 
968 	return (spawning);
969 }
970 
971 /*
972  * Threads in a dynamic taskq may exit once there is no more work to do.
973  * To prevent threads from being created and destroyed too often limit
974  * the exit rate to one per spl_taskq_thread_timeout_ms.
975  *
976  * The first thread is the thread list is treated as the primary thread.
977  * There is nothing special about the primary thread but in order to avoid
978  * all the taskq pids from changing we opt to make it long running.
979  */
980 static int
981 taskq_thread_should_stop(taskq_t *tq, taskq_thread_t *tqt)
982 {
983 	ASSERT(!taskq_next_ent(tq));
984 	if (!(tq->tq_flags & TASKQ_DYNAMIC) || !spl_taskq_thread_dynamic)
985 		return (0);
986 	if (!(tq->tq_flags & TASKQ_ACTIVE))
987 		return (1);
988 	if (list_first_entry(&(tq->tq_thread_list), taskq_thread_t,
989 	    tqt_thread_list) == tqt)
990 		return (0);
991 	ASSERT3U(tq->tq_nthreads, >, 1);
992 	if (tq->tq_nspawn != 0)
993 		return (0);
994 	if (time_before(jiffies, tq->lastspawnstop +
995 	    msecs_to_jiffies(spl_taskq_thread_timeout_ms)))
996 		return (0);
997 	tq->lastspawnstop = jiffies;
998 	return (1);
999 }
1000 
1001 static int
1002 taskq_thread(void *args)
1003 {
1004 	DECLARE_WAITQUEUE(wait, current);
1005 	sigset_t blocked;
1006 	taskq_thread_t *tqt = args;
1007 	taskq_t *tq;
1008 	taskq_ent_t *t;
1009 	int seq_tasks = 0;
1010 	unsigned long flags;
1011 	taskq_ent_t dup_task = {};
1012 
1013 	ASSERT(tqt);
1014 	ASSERT(tqt->tqt_tq);
1015 	tq = tqt->tqt_tq;
1016 	current->flags |= PF_NOFREEZE;
1017 
1018 	(void) spl_fstrans_mark();
1019 
1020 	sigfillset(&blocked);
1021 	sigprocmask(SIG_BLOCK, &blocked, NULL);
1022 	flush_signals(current);
1023 
1024 	tsd_set(taskq_tsd, tq);
1025 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
1026 	/*
1027 	 * If we are dynamically spawned, decrease spawning count. Note that
1028 	 * we could be created during taskq_create, in which case we shouldn't
1029 	 * do the decrement. But it's fine because taskq_create will reset
1030 	 * tq_nspawn later.
1031 	 */
1032 	if (tq->tq_flags & TASKQ_DYNAMIC)
1033 		tq->tq_nspawn--;
1034 
1035 	/* Immediately exit if more threads than allowed were created. */
1036 	if (tq->tq_nthreads >= tq->tq_maxthreads)
1037 		goto error;
1038 
1039 	tq->tq_nthreads++;
1040 	list_add_tail(&tqt->tqt_thread_list, &tq->tq_thread_list);
1041 	wake_up(&tq->tq_wait_waitq);
1042 	set_current_state(TASK_INTERRUPTIBLE);
1043 
1044 	TQSTAT_INC(tq, threads_total);
1045 
1046 	while (!kthread_should_stop()) {
1047 
1048 		if (list_empty(&tq->tq_pend_list) &&
1049 		    list_empty(&tq->tq_prio_list)) {
1050 
1051 			if (taskq_thread_should_stop(tq, tqt))
1052 				break;
1053 
1054 			add_wait_queue_exclusive(&tq->tq_work_waitq, &wait);
1055 			spin_unlock_irqrestore(&tq->tq_lock, flags);
1056 
1057 			TQSTAT_INC(tq, thread_sleeps);
1058 			TQSTAT_INC(tq, threads_idle);
1059 
1060 			schedule();
1061 			seq_tasks = 0;
1062 
1063 			TQSTAT_DEC(tq, threads_idle);
1064 			TQSTAT_INC(tq, thread_wakeups);
1065 
1066 			spin_lock_irqsave_nested(&tq->tq_lock, flags,
1067 			    tq->tq_lock_class);
1068 			remove_wait_queue(&tq->tq_work_waitq, &wait);
1069 		} else {
1070 			__set_current_state(TASK_RUNNING);
1071 		}
1072 
1073 		if ((t = taskq_next_ent(tq)) != NULL) {
1074 			list_del_init(&t->tqent_list);
1075 			TQSTAT_DEC_LIST(tq, t);
1076 			TQSTAT_DEC(tq, tasks_total);
1077 
1078 			/*
1079 			 * A TQENT_FLAG_PREALLOC task may be reused or freed
1080 			 * during the task function call. Store tqent_id and
1081 			 * tqent_flags here.
1082 			 */
1083 			tqt->tqt_id = t->tqent_id;
1084 			tqt->tqt_flags = t->tqent_flags;
1085 
1086 			if (t->tqent_flags & TQENT_FLAG_PREALLOC) {
1087 				dup_task = *t;
1088 				t = &dup_task;
1089 			}
1090 			tqt->tqt_task = t;
1091 
1092 			taskq_insert_in_order(tq, tqt);
1093 			tq->tq_nactive++;
1094 			spin_unlock_irqrestore(&tq->tq_lock, flags);
1095 
1096 			TQSTAT_INC(tq, threads_active);
1097 
1098 			/* Perform the requested task */
1099 			scoped_with_init_fs()
1100 			    t->tqent_func(t->tqent_arg);
1101 
1102 			TQSTAT_DEC(tq, threads_active);
1103 			if ((t->tqent_flags & TQENT_LIST_MASK) ==
1104 			    TQENT_LIST_PENDING)
1105 				TQSTAT_INC(tq, tasks_executed_normal);
1106 			else
1107 				TQSTAT_INC(tq, tasks_executed_priority);
1108 			TQSTAT_INC(tq, tasks_executed);
1109 
1110 			spin_lock_irqsave_nested(&tq->tq_lock, flags,
1111 			    tq->tq_lock_class);
1112 
1113 			tq->tq_nactive--;
1114 			list_del_init(&tqt->tqt_active_list);
1115 			tqt->tqt_task = NULL;
1116 
1117 			/* For prealloc'd tasks, we don't free anything. */
1118 			if (!(tqt->tqt_flags & TQENT_FLAG_PREALLOC))
1119 				task_done(tq, t);
1120 
1121 			/*
1122 			 * When the current lowest outstanding taskqid is
1123 			 * done calculate the new lowest outstanding id
1124 			 */
1125 			if (tq->tq_lowest_id == tqt->tqt_id) {
1126 				tq->tq_lowest_id = taskq_lowest_id(tq);
1127 				ASSERT3S(tq->tq_lowest_id, >, tqt->tqt_id);
1128 			}
1129 
1130 			/* Spawn additional taskq threads if required. */
1131 			if ((++seq_tasks) > spl_taskq_thread_sequential &&
1132 			    taskq_thread_spawn(tq))
1133 				seq_tasks = 0;
1134 
1135 			tqt->tqt_id = TASKQID_INVALID;
1136 			tqt->tqt_flags = 0;
1137 			wake_up_all(&tq->tq_wait_waitq);
1138 		} else
1139 			TQSTAT_INC(tq, thread_wakeups_nowork);
1140 
1141 		set_current_state(TASK_INTERRUPTIBLE);
1142 
1143 	}
1144 
1145 	__set_current_state(TASK_RUNNING);
1146 	tq->tq_nthreads--;
1147 	list_del_init(&tqt->tqt_thread_list);
1148 
1149 	TQSTAT_DEC(tq, threads_total);
1150 	TQSTAT_INC(tq, threads_destroyed);
1151 
1152 error:
1153 	kmem_free(tqt, sizeof (taskq_thread_t));
1154 	spin_unlock_irqrestore(&tq->tq_lock, flags);
1155 
1156 	tsd_set(taskq_tsd, NULL);
1157 	thread_exit();
1158 
1159 	return (0);
1160 }
1161 
1162 static taskq_thread_t *
1163 taskq_thread_create(taskq_t *tq)
1164 {
1165 	static int last_used_cpu = 0;
1166 	taskq_thread_t *tqt;
1167 
1168 	tqt = kmem_alloc(sizeof (*tqt), KM_PUSHPAGE);
1169 	INIT_LIST_HEAD(&tqt->tqt_thread_list);
1170 	INIT_LIST_HEAD(&tqt->tqt_active_list);
1171 	tqt->tqt_tq = tq;
1172 	tqt->tqt_id = TASKQID_INVALID;
1173 
1174 	tqt->tqt_thread = spl_kthread_create(taskq_thread, tqt,
1175 	    "%s", tq->tq_name);
1176 	if (tqt->tqt_thread == NULL) {
1177 		kmem_free(tqt, sizeof (taskq_thread_t));
1178 		return (NULL);
1179 	}
1180 
1181 	if (spl_taskq_thread_bind) {
1182 		last_used_cpu = (last_used_cpu + 1) % num_online_cpus();
1183 		kthread_bind(tqt->tqt_thread, last_used_cpu);
1184 	}
1185 
1186 	if (spl_taskq_thread_priority)
1187 		set_user_nice(tqt->tqt_thread, PRIO_TO_NICE(tq->tq_pri));
1188 
1189 	wake_up_process(tqt->tqt_thread);
1190 
1191 	TQSTAT_INC(tq, threads_created);
1192 
1193 	return (tqt);
1194 }
1195 
1196 static void
1197 taskq_stats_init(taskq_t *tq)
1198 {
1199 	taskq_sums_t *tqs = &tq->tq_sums;
1200 	wmsum_init(&tqs->tqs_threads_active, 0);
1201 	wmsum_init(&tqs->tqs_threads_idle, 0);
1202 	wmsum_init(&tqs->tqs_threads_total, 0);
1203 	wmsum_init(&tqs->tqs_tasks_pending, 0);
1204 	wmsum_init(&tqs->tqs_tasks_priority, 0);
1205 	wmsum_init(&tqs->tqs_tasks_total, 0);
1206 	wmsum_init(&tqs->tqs_tasks_delayed, 0);
1207 	wmsum_init(&tqs->tqs_entries_free, 0);
1208 	wmsum_init(&tqs->tqs_threads_created, 0);
1209 	wmsum_init(&tqs->tqs_threads_destroyed, 0);
1210 	wmsum_init(&tqs->tqs_tasks_dispatched, 0);
1211 	wmsum_init(&tqs->tqs_tasks_dispatched_delayed, 0);
1212 	wmsum_init(&tqs->tqs_tasks_executed_normal, 0);
1213 	wmsum_init(&tqs->tqs_tasks_executed_priority, 0);
1214 	wmsum_init(&tqs->tqs_tasks_executed, 0);
1215 	wmsum_init(&tqs->tqs_tasks_delayed_requeued, 0);
1216 	wmsum_init(&tqs->tqs_tasks_cancelled, 0);
1217 	wmsum_init(&tqs->tqs_thread_wakeups, 0);
1218 	wmsum_init(&tqs->tqs_thread_wakeups_nowork, 0);
1219 	wmsum_init(&tqs->tqs_thread_sleeps, 0);
1220 }
1221 
1222 static void
1223 taskq_stats_fini(taskq_t *tq)
1224 {
1225 	taskq_sums_t *tqs = &tq->tq_sums;
1226 	wmsum_fini(&tqs->tqs_threads_active);
1227 	wmsum_fini(&tqs->tqs_threads_idle);
1228 	wmsum_fini(&tqs->tqs_threads_total);
1229 	wmsum_fini(&tqs->tqs_tasks_pending);
1230 	wmsum_fini(&tqs->tqs_tasks_priority);
1231 	wmsum_fini(&tqs->tqs_tasks_total);
1232 	wmsum_fini(&tqs->tqs_tasks_delayed);
1233 	wmsum_fini(&tqs->tqs_entries_free);
1234 	wmsum_fini(&tqs->tqs_threads_created);
1235 	wmsum_fini(&tqs->tqs_threads_destroyed);
1236 	wmsum_fini(&tqs->tqs_tasks_dispatched);
1237 	wmsum_fini(&tqs->tqs_tasks_dispatched_delayed);
1238 	wmsum_fini(&tqs->tqs_tasks_executed_normal);
1239 	wmsum_fini(&tqs->tqs_tasks_executed_priority);
1240 	wmsum_fini(&tqs->tqs_tasks_executed);
1241 	wmsum_fini(&tqs->tqs_tasks_delayed_requeued);
1242 	wmsum_fini(&tqs->tqs_tasks_cancelled);
1243 	wmsum_fini(&tqs->tqs_thread_wakeups);
1244 	wmsum_fini(&tqs->tqs_thread_wakeups_nowork);
1245 	wmsum_fini(&tqs->tqs_thread_sleeps);
1246 }
1247 
1248 static int
1249 taskq_kstats_update(kstat_t *ksp, int rw)
1250 {
1251 	if (rw == KSTAT_WRITE)
1252 		return (EACCES);
1253 
1254 	taskq_t *tq = ksp->ks_private;
1255 	taskq_kstats_t *tqks = ksp->ks_data;
1256 
1257 	tqks->tqks_threads_max.value.ui64 = tq->tq_maxthreads;
1258 	tqks->tqks_entry_pool_min.value.ui64 = tq->tq_minalloc;
1259 	tqks->tqks_entry_pool_max.value.ui64 = tq->tq_maxalloc;
1260 
1261 	taskq_sums_t *tqs = &tq->tq_sums;
1262 
1263 	tqks->tqks_threads_active.value.ui64 =
1264 	    wmsum_value(&tqs->tqs_threads_active);
1265 	tqks->tqks_threads_idle.value.ui64 =
1266 	    wmsum_value(&tqs->tqs_threads_idle);
1267 	tqks->tqks_threads_total.value.ui64 =
1268 	    wmsum_value(&tqs->tqs_threads_total);
1269 	tqks->tqks_tasks_pending.value.ui64 =
1270 	    wmsum_value(&tqs->tqs_tasks_pending);
1271 	tqks->tqks_tasks_priority.value.ui64 =
1272 	    wmsum_value(&tqs->tqs_tasks_priority);
1273 	tqks->tqks_tasks_total.value.ui64 =
1274 	    wmsum_value(&tqs->tqs_tasks_total);
1275 	tqks->tqks_tasks_delayed.value.ui64 =
1276 	    wmsum_value(&tqs->tqs_tasks_delayed);
1277 	tqks->tqks_entries_free.value.ui64 =
1278 	    wmsum_value(&tqs->tqs_entries_free);
1279 	tqks->tqks_threads_created.value.ui64 =
1280 	    wmsum_value(&tqs->tqs_threads_created);
1281 	tqks->tqks_threads_destroyed.value.ui64 =
1282 	    wmsum_value(&tqs->tqs_threads_destroyed);
1283 	tqks->tqks_tasks_dispatched.value.ui64 =
1284 	    wmsum_value(&tqs->tqs_tasks_dispatched);
1285 	tqks->tqks_tasks_dispatched_delayed.value.ui64 =
1286 	    wmsum_value(&tqs->tqs_tasks_dispatched_delayed);
1287 	tqks->tqks_tasks_executed_normal.value.ui64 =
1288 	    wmsum_value(&tqs->tqs_tasks_executed_normal);
1289 	tqks->tqks_tasks_executed_priority.value.ui64 =
1290 	    wmsum_value(&tqs->tqs_tasks_executed_priority);
1291 	tqks->tqks_tasks_executed.value.ui64 =
1292 	    wmsum_value(&tqs->tqs_tasks_executed);
1293 	tqks->tqks_tasks_delayed_requeued.value.ui64 =
1294 	    wmsum_value(&tqs->tqs_tasks_delayed_requeued);
1295 	tqks->tqks_tasks_cancelled.value.ui64 =
1296 	    wmsum_value(&tqs->tqs_tasks_cancelled);
1297 	tqks->tqks_thread_wakeups.value.ui64 =
1298 	    wmsum_value(&tqs->tqs_thread_wakeups);
1299 	tqks->tqks_thread_wakeups_nowork.value.ui64 =
1300 	    wmsum_value(&tqs->tqs_thread_wakeups_nowork);
1301 	tqks->tqks_thread_sleeps.value.ui64 =
1302 	    wmsum_value(&tqs->tqs_thread_sleeps);
1303 
1304 	return (0);
1305 }
1306 
1307 static void
1308 taskq_kstats_init(taskq_t *tq)
1309 {
1310 	char name[TASKQ_NAMELEN+5]; /* 5 for dot, 3x instance digits, null */
1311 	snprintf(name, sizeof (name), "%s.%d", tq->tq_name, tq->tq_instance);
1312 
1313 	kstat_t *ksp = kstat_create("taskq", 0, name, "misc",
1314 	    KSTAT_TYPE_NAMED, sizeof (taskq_kstats_t) / sizeof (kstat_named_t),
1315 	    KSTAT_FLAG_VIRTUAL);
1316 
1317 	if (ksp == NULL)
1318 		return;
1319 
1320 	ksp->ks_private = tq;
1321 	ksp->ks_update = taskq_kstats_update;
1322 	ksp->ks_data = kmem_alloc(sizeof (taskq_kstats_t), KM_SLEEP);
1323 	memcpy(ksp->ks_data, &taskq_kstats_template, sizeof (taskq_kstats_t));
1324 	kstat_install(ksp);
1325 
1326 	tq->tq_ksp = ksp;
1327 }
1328 
1329 static void
1330 taskq_kstats_fini(taskq_t *tq)
1331 {
1332 	if (tq->tq_ksp == NULL)
1333 		return;
1334 
1335 	kmem_free(tq->tq_ksp->ks_data, sizeof (taskq_kstats_t));
1336 	kstat_delete(tq->tq_ksp);
1337 
1338 	tq->tq_ksp = NULL;
1339 }
1340 
1341 taskq_t *
1342 taskq_create(const char *name, int threads_arg, pri_t pri,
1343     int minalloc, int maxalloc, uint_t flags)
1344 {
1345 	taskq_t *tq;
1346 	taskq_thread_t *tqt;
1347 	int count = 0, rc = 0, i;
1348 	unsigned long irqflags;
1349 	int nthreads = threads_arg;
1350 
1351 	ASSERT(name != NULL);
1352 	ASSERT(minalloc >= 0);
1353 	ASSERT(!(flags & (TASKQ_CPR_SAFE))); /* Unsupported */
1354 
1355 	/* Scale the number of threads using nthreads as a percentage */
1356 	if (flags & TASKQ_THREADS_CPU_PCT) {
1357 		ASSERT(nthreads <= 100);
1358 		ASSERT(nthreads >= 0);
1359 		nthreads = MIN(threads_arg, 100);
1360 		nthreads = MAX(nthreads, 0);
1361 		nthreads = MAX((num_online_cpus() * nthreads) /100, 1);
1362 	}
1363 
1364 	tq = kmem_alloc(sizeof (*tq), KM_PUSHPAGE);
1365 	if (tq == NULL)
1366 		return (NULL);
1367 
1368 	tq->tq_hp_support = B_FALSE;
1369 
1370 	if (flags & TASKQ_THREADS_CPU_PCT) {
1371 		tq->tq_hp_support = B_TRUE;
1372 		if (cpuhp_state_add_instance_nocalls(spl_taskq_cpuhp_state,
1373 		    &tq->tq_hp_cb_node) != 0) {
1374 			kmem_free(tq, sizeof (*tq));
1375 			return (NULL);
1376 		}
1377 	}
1378 
1379 	spin_lock_init(&tq->tq_lock);
1380 	INIT_LIST_HEAD(&tq->tq_thread_list);
1381 	INIT_LIST_HEAD(&tq->tq_active_list);
1382 	tq->tq_name = kmem_strdup(name);
1383 	tq->tq_nactive = 0;
1384 	tq->tq_nthreads = 0;
1385 	tq->tq_nspawn = 0;
1386 	tq->tq_maxthreads = nthreads;
1387 	tq->tq_cpu_pct = threads_arg;
1388 	tq->tq_pri = pri;
1389 	tq->tq_minalloc = minalloc;
1390 	tq->tq_maxalloc = maxalloc;
1391 	tq->tq_nalloc = 0;
1392 	tq->tq_flags = (flags | TASKQ_ACTIVE);
1393 	tq->tq_next_id = TASKQID_INITIAL;
1394 	tq->tq_lowest_id = TASKQID_INITIAL;
1395 	tq->lastspawnstop = jiffies;
1396 	INIT_LIST_HEAD(&tq->tq_free_list);
1397 	INIT_LIST_HEAD(&tq->tq_pend_list);
1398 	INIT_LIST_HEAD(&tq->tq_prio_list);
1399 	INIT_LIST_HEAD(&tq->tq_delay_list);
1400 	init_waitqueue_head(&tq->tq_work_waitq);
1401 	init_waitqueue_head(&tq->tq_wait_waitq);
1402 	tq->tq_lock_class = TQ_LOCK_GENERAL;
1403 	INIT_LIST_HEAD(&tq->tq_taskqs);
1404 	taskq_stats_init(tq);
1405 
1406 	if (flags & TASKQ_PREPOPULATE) {
1407 		spin_lock_irqsave_nested(&tq->tq_lock, irqflags,
1408 		    tq->tq_lock_class);
1409 
1410 		for (i = 0; i < minalloc; i++)
1411 			task_done(tq, task_alloc(tq, TQ_PUSHPAGE | TQ_NEW,
1412 			    &irqflags));
1413 
1414 		spin_unlock_irqrestore(&tq->tq_lock, irqflags);
1415 	}
1416 
1417 	if ((flags & TASKQ_DYNAMIC) && spl_taskq_thread_dynamic)
1418 		nthreads = 1;
1419 
1420 	for (i = 0; i < nthreads; i++) {
1421 		tqt = taskq_thread_create(tq);
1422 		if (tqt == NULL)
1423 			rc = 1;
1424 		else
1425 			count++;
1426 	}
1427 
1428 	/* Wait for all threads to be started before potential destroy */
1429 	wait_event(tq->tq_wait_waitq, tq->tq_nthreads == count);
1430 	/*
1431 	 * taskq_thread might have touched nspawn, but we don't want them to
1432 	 * because they're not dynamically spawned. So we reset it to 0
1433 	 */
1434 	tq->tq_nspawn = 0;
1435 
1436 	if (rc) {
1437 		taskq_destroy(tq);
1438 		return (NULL);
1439 	}
1440 
1441 	down_write(&tq_list_sem);
1442 	tq->tq_instance = taskq_find_by_name(name) + 1;
1443 	list_add_tail(&tq->tq_taskqs, &tq_list);
1444 	up_write(&tq_list_sem);
1445 
1446 	/* Install kstats late, because the name includes tq_instance */
1447 	taskq_kstats_init(tq);
1448 
1449 	return (tq);
1450 }
1451 EXPORT_SYMBOL(taskq_create);
1452 
1453 void
1454 taskq_destroy(taskq_t *tq)
1455 {
1456 	struct task_struct *thread;
1457 	taskq_thread_t *tqt;
1458 	taskq_ent_t *t;
1459 	unsigned long flags;
1460 
1461 	ASSERT(tq);
1462 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
1463 	tq->tq_flags &= ~TASKQ_ACTIVE;
1464 	spin_unlock_irqrestore(&tq->tq_lock, flags);
1465 
1466 	if (tq->tq_hp_support) {
1467 		VERIFY0(cpuhp_state_remove_instance_nocalls(
1468 		    spl_taskq_cpuhp_state, &tq->tq_hp_cb_node));
1469 	}
1470 
1471 	/*
1472 	 * When TASKQ_ACTIVE is clear new tasks may not be added nor may
1473 	 * new worker threads be spawned for dynamic taskq.
1474 	 */
1475 	if (dynamic_taskq != NULL)
1476 		taskq_wait_outstanding(dynamic_taskq, 0);
1477 
1478 	taskq_wait(tq);
1479 
1480 	taskq_kstats_fini(tq);
1481 
1482 	/* remove taskq from global list used by the kstats */
1483 	down_write(&tq_list_sem);
1484 	list_del(&tq->tq_taskqs);
1485 	up_write(&tq_list_sem);
1486 
1487 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
1488 	/* wait for spawning threads to insert themselves to the list */
1489 	while (tq->tq_nspawn) {
1490 		spin_unlock_irqrestore(&tq->tq_lock, flags);
1491 		schedule_timeout_interruptible(1);
1492 		spin_lock_irqsave_nested(&tq->tq_lock, flags,
1493 		    tq->tq_lock_class);
1494 	}
1495 
1496 	/*
1497 	 * Signal each thread to exit and block until it does.  Each thread
1498 	 * is responsible for removing itself from the list and freeing its
1499 	 * taskq_thread_t.  This allows for idle threads to opt to remove
1500 	 * themselves from the taskq.  They can be recreated as needed.
1501 	 */
1502 	while (!list_empty(&tq->tq_thread_list)) {
1503 		tqt = list_entry(tq->tq_thread_list.next,
1504 		    taskq_thread_t, tqt_thread_list);
1505 		thread = tqt->tqt_thread;
1506 		spin_unlock_irqrestore(&tq->tq_lock, flags);
1507 
1508 		kthread_stop(thread);
1509 
1510 		spin_lock_irqsave_nested(&tq->tq_lock, flags,
1511 		    tq->tq_lock_class);
1512 	}
1513 
1514 	while (!list_empty(&tq->tq_free_list)) {
1515 		t = list_entry(tq->tq_free_list.next, taskq_ent_t, tqent_list);
1516 
1517 		ASSERT(!(t->tqent_flags & TQENT_FLAG_PREALLOC));
1518 
1519 		list_del_init(&t->tqent_list);
1520 		task_free(tq, t);
1521 	}
1522 
1523 	ASSERT0(tq->tq_nthreads);
1524 	ASSERT0(tq->tq_nalloc);
1525 	ASSERT0(tq->tq_nspawn);
1526 	ASSERT(list_empty(&tq->tq_thread_list));
1527 	ASSERT(list_empty(&tq->tq_active_list));
1528 	ASSERT(list_empty(&tq->tq_free_list));
1529 	ASSERT(list_empty(&tq->tq_pend_list));
1530 	ASSERT(list_empty(&tq->tq_prio_list));
1531 	ASSERT(list_empty(&tq->tq_delay_list));
1532 
1533 	spin_unlock_irqrestore(&tq->tq_lock, flags);
1534 
1535 	taskq_stats_fini(tq);
1536 	kmem_strfree(tq->tq_name);
1537 	kmem_free(tq, sizeof (taskq_t));
1538 }
1539 EXPORT_SYMBOL(taskq_destroy);
1540 
1541 /*
1542  * Create a taskq with a specified number of pool threads. Allocate
1543  * and return an array of nthreads kthread_t pointers, one for each
1544  * thread in the pool. The array is not ordered and must be freed
1545  * by the caller.
1546  */
1547 taskq_t *
1548 taskq_create_synced(const char *name, int nthreads, pri_t pri,
1549     int minalloc, int maxalloc, uint_t flags, kthread_t ***ktpp)
1550 {
1551 	taskq_t *tq;
1552 	taskq_thread_t *tqt;
1553 	int i = 0;
1554 	kthread_t **kthreads = kmem_zalloc(sizeof (*kthreads) * nthreads,
1555 	    KM_SLEEP);
1556 
1557 	flags &= ~(TASKQ_DYNAMIC | TASKQ_THREADS_CPU_PCT | TASKQ_DC_BATCH);
1558 
1559 	/* taskq_create spawns all the threads before returning */
1560 	tq = taskq_create(name, nthreads, minclsyspri, nthreads, INT_MAX,
1561 	    flags | TASKQ_PREPOPULATE);
1562 	VERIFY(tq != NULL);
1563 	VERIFY(tq->tq_nthreads == nthreads);
1564 
1565 	list_for_each_entry(tqt, &tq->tq_thread_list, tqt_thread_list) {
1566 		kthreads[i] = tqt->tqt_thread;
1567 		i++;
1568 	}
1569 
1570 	ASSERT3S(i, ==, nthreads);
1571 	*ktpp = kthreads;
1572 
1573 	return (tq);
1574 }
1575 EXPORT_SYMBOL(taskq_create_synced);
1576 
1577 static kstat_t *taskq_summary_ksp = NULL;
1578 
1579 static int
1580 spl_taskq_kstat_headers(char *buf, size_t size)
1581 {
1582 	size_t n = snprintf(buf, size,
1583 	    "%-20s | %-17s | %-23s\n"
1584 	    "%-20s | %-17s | %-23s\n"
1585 	    "%-20s | %-17s | %-23s\n",
1586 	    "", "threads", "tasks on queue",
1587 	    "taskq name", "tot [act idl] max", " pend [ norm  high] dly",
1588 	    "--------------------", "-----------------",
1589 	    "-----------------------");
1590 	return (n >= size ? ENOMEM : 0);
1591 }
1592 
1593 static int
1594 spl_taskq_kstat_data(char *buf, size_t size, void *data)
1595 {
1596 	struct list_head *tql = NULL;
1597 	taskq_t *tq;
1598 	char name[TASKQ_NAMELEN+5]; /* 5 for dot, 3x instance digits, null */
1599 	char threads[25];
1600 	char tasks[30];
1601 	size_t n;
1602 	int err = 0;
1603 
1604 	down_read(&tq_list_sem);
1605 	list_for_each_prev(tql, &tq_list) {
1606 		tq = list_entry(tql, taskq_t, tq_taskqs);
1607 
1608 		mutex_enter(tq->tq_ksp->ks_lock);
1609 		taskq_kstats_update(tq->tq_ksp, KSTAT_READ);
1610 		taskq_kstats_t *tqks = tq->tq_ksp->ks_data;
1611 
1612 		snprintf(name, sizeof (name), "%s.%d", tq->tq_name,
1613 		    tq->tq_instance);
1614 		snprintf(threads, sizeof (threads), "%3llu [%3llu %3llu] %3llu",
1615 		    tqks->tqks_threads_total.value.ui64,
1616 		    tqks->tqks_threads_active.value.ui64,
1617 		    tqks->tqks_threads_idle.value.ui64,
1618 		    tqks->tqks_threads_max.value.ui64);
1619 		snprintf(tasks, sizeof (tasks), "%5llu [%5llu %5llu] %3llu",
1620 		    tqks->tqks_tasks_total.value.ui64,
1621 		    tqks->tqks_tasks_pending.value.ui64,
1622 		    tqks->tqks_tasks_priority.value.ui64,
1623 		    tqks->tqks_tasks_delayed.value.ui64);
1624 
1625 		mutex_exit(tq->tq_ksp->ks_lock);
1626 
1627 		n = snprintf(buf, size, "%-20s | %-17s | %-23s\n",
1628 		    name, threads, tasks);
1629 		if (n >= size) {
1630 			err = ENOMEM;
1631 			break;
1632 		}
1633 
1634 		buf = &buf[n];
1635 		size -= n;
1636 	}
1637 
1638 	up_read(&tq_list_sem);
1639 
1640 	return (err);
1641 }
1642 
1643 static void
1644 spl_taskq_kstat_init(void)
1645 {
1646 	kstat_t *ksp = kstat_create("taskq", 0, "summary", "misc",
1647 	    KSTAT_TYPE_RAW, 0, KSTAT_FLAG_VIRTUAL);
1648 
1649 	if (ksp == NULL)
1650 		return;
1651 
1652 	ksp->ks_data = (void *)(uintptr_t)1;
1653 	ksp->ks_ndata = 1;
1654 	kstat_set_raw_ops(ksp, spl_taskq_kstat_headers,
1655 	    spl_taskq_kstat_data, NULL);
1656 	kstat_install(ksp);
1657 
1658 	taskq_summary_ksp = ksp;
1659 }
1660 
1661 static void
1662 spl_taskq_kstat_fini(void)
1663 {
1664 	if (taskq_summary_ksp == NULL)
1665 		return;
1666 
1667 	kstat_delete(taskq_summary_ksp);
1668 	taskq_summary_ksp = NULL;
1669 }
1670 
1671 static unsigned int spl_taskq_kick = 0;
1672 
1673 static int
1674 param_set_taskq_kick(const char *val, zfs_kernel_param_t *kp)
1675 {
1676 	int ret;
1677 	taskq_t *tq = NULL;
1678 	taskq_ent_t *t;
1679 	unsigned long flags;
1680 
1681 	ret = param_set_uint(val, kp);
1682 	if (ret < 0 || !spl_taskq_kick)
1683 		return (ret);
1684 	/* reset value */
1685 	spl_taskq_kick = 0;
1686 
1687 	down_read(&tq_list_sem);
1688 	list_for_each_entry(tq, &tq_list, tq_taskqs) {
1689 		spin_lock_irqsave_nested(&tq->tq_lock, flags,
1690 		    tq->tq_lock_class);
1691 		/* Check if the first pending is older than 5 seconds */
1692 		t = taskq_next_ent(tq);
1693 		if (t && time_after(jiffies, t->tqent_birth + 5*HZ)) {
1694 			(void) taskq_thread_spawn(tq);
1695 			printk(KERN_INFO "spl: Kicked taskq %s/%d\n",
1696 			    tq->tq_name, tq->tq_instance);
1697 		}
1698 		spin_unlock_irqrestore(&tq->tq_lock, flags);
1699 	}
1700 	up_read(&tq_list_sem);
1701 	return (ret);
1702 }
1703 
1704 module_param_call(spl_taskq_kick, param_set_taskq_kick, param_get_uint,
1705 	&spl_taskq_kick, 0644);
1706 MODULE_PARM_DESC(spl_taskq_kick,
1707 	"Write nonzero to kick stuck taskqs to spawn more threads");
1708 
1709 /*
1710  * This callback will be called exactly once for each core that comes online,
1711  * for each dynamic taskq. We attempt to expand taskqs that have
1712  * TASKQ_THREADS_CPU_PCT set. We need to redo the percentage calculation every
1713  * time, to correctly determine whether or not to add a thread.
1714  */
1715 static int
1716 spl_taskq_expand(unsigned int cpu, struct hlist_node *node)
1717 {
1718 	taskq_t *tq = list_entry(node, taskq_t, tq_hp_cb_node);
1719 	unsigned long flags;
1720 	int err = 0;
1721 
1722 	ASSERT(tq);
1723 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
1724 
1725 	if (!(tq->tq_flags & TASKQ_ACTIVE)) {
1726 		spin_unlock_irqrestore(&tq->tq_lock, flags);
1727 		return (err);
1728 	}
1729 
1730 	ASSERT(tq->tq_flags & TASKQ_THREADS_CPU_PCT);
1731 	int nthreads = MIN(tq->tq_cpu_pct, 100);
1732 	nthreads = MAX(((num_online_cpus() + 1) * nthreads) / 100, 1);
1733 	tq->tq_maxthreads = nthreads;
1734 
1735 	if (!((tq->tq_flags & TASKQ_DYNAMIC) && spl_taskq_thread_dynamic) &&
1736 	    tq->tq_maxthreads > tq->tq_nthreads) {
1737 		spin_unlock_irqrestore(&tq->tq_lock, flags);
1738 		taskq_thread_t *tqt = taskq_thread_create(tq);
1739 		if (tqt == NULL)
1740 			err = -1;
1741 		return (err);
1742 	}
1743 	spin_unlock_irqrestore(&tq->tq_lock, flags);
1744 	return (err);
1745 }
1746 
1747 /*
1748  * While we don't support offlining CPUs, it is possible that CPUs will fail
1749  * to online successfully. We do need to be able to handle this case
1750  * gracefully.
1751  */
1752 static int
1753 spl_taskq_prepare_down(unsigned int cpu, struct hlist_node *node)
1754 {
1755 	taskq_t *tq = list_entry(node, taskq_t, tq_hp_cb_node);
1756 	unsigned long flags;
1757 
1758 	ASSERT(tq);
1759 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
1760 
1761 	if (!(tq->tq_flags & TASKQ_ACTIVE))
1762 		goto out;
1763 
1764 	ASSERT(tq->tq_flags & TASKQ_THREADS_CPU_PCT);
1765 	int nthreads = MIN(tq->tq_cpu_pct, 100);
1766 	nthreads = MAX(((num_online_cpus()) * nthreads) / 100, 1);
1767 	tq->tq_maxthreads = nthreads;
1768 
1769 	if (!((tq->tq_flags & TASKQ_DYNAMIC) && spl_taskq_thread_dynamic) &&
1770 	    tq->tq_maxthreads < tq->tq_nthreads) {
1771 		ASSERT3U(tq->tq_maxthreads, ==, tq->tq_nthreads - 1);
1772 		taskq_thread_t *tqt = list_entry(tq->tq_thread_list.next,
1773 		    taskq_thread_t, tqt_thread_list);
1774 		struct task_struct *thread = tqt->tqt_thread;
1775 		spin_unlock_irqrestore(&tq->tq_lock, flags);
1776 
1777 		kthread_stop(thread);
1778 
1779 		return (0);
1780 	}
1781 
1782 out:
1783 	spin_unlock_irqrestore(&tq->tq_lock, flags);
1784 	return (0);
1785 }
1786 
1787 int
1788 spl_taskq_init(void)
1789 {
1790 	init_rwsem(&tq_list_sem);
1791 	tsd_create(&taskq_tsd, NULL);
1792 
1793 	spl_taskq_cpuhp_state = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
1794 	    "fs/spl_taskq:online", spl_taskq_expand, spl_taskq_prepare_down);
1795 
1796 	system_taskq = taskq_create("spl_system_taskq", MAX(boot_ncpus, 64),
1797 	    maxclsyspri, boot_ncpus, INT_MAX, TASKQ_PREPOPULATE|TASKQ_DYNAMIC);
1798 	if (system_taskq == NULL)
1799 		return (-ENOMEM);
1800 
1801 	system_delay_taskq = taskq_create("spl_delay_taskq", MAX(boot_ncpus, 4),
1802 	    maxclsyspri, boot_ncpus, INT_MAX, TASKQ_PREPOPULATE|TASKQ_DYNAMIC);
1803 	if (system_delay_taskq == NULL) {
1804 		cpuhp_remove_multi_state(spl_taskq_cpuhp_state);
1805 		taskq_destroy(system_taskq);
1806 		return (-ENOMEM);
1807 	}
1808 
1809 	dynamic_taskq = taskq_create("spl_dynamic_taskq", 1,
1810 	    maxclsyspri, boot_ncpus, INT_MAX, TASKQ_PREPOPULATE);
1811 	if (dynamic_taskq == NULL) {
1812 		cpuhp_remove_multi_state(spl_taskq_cpuhp_state);
1813 		taskq_destroy(system_taskq);
1814 		taskq_destroy(system_delay_taskq);
1815 		return (-ENOMEM);
1816 	}
1817 
1818 	/*
1819 	 * This is used to annotate tq_lock, so
1820 	 *   taskq_dispatch -> taskq_thread_spawn -> taskq_dispatch
1821 	 * does not trigger a lockdep warning re: possible recursive locking
1822 	 */
1823 	dynamic_taskq->tq_lock_class = TQ_LOCK_DYNAMIC;
1824 
1825 	spl_taskq_kstat_init();
1826 
1827 	return (0);
1828 }
1829 
1830 void
1831 spl_taskq_fini(void)
1832 {
1833 	spl_taskq_kstat_fini();
1834 
1835 	taskq_destroy(dynamic_taskq);
1836 	dynamic_taskq = NULL;
1837 
1838 	taskq_destroy(system_delay_taskq);
1839 	system_delay_taskq = NULL;
1840 
1841 	taskq_destroy(system_taskq);
1842 	system_taskq = NULL;
1843 
1844 	tsd_destroy(&taskq_tsd);
1845 
1846 	cpuhp_remove_multi_state(spl_taskq_cpuhp_state);
1847 	spl_taskq_cpuhp_state = 0;
1848 }
1849