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