xref: /freebsd/sys/contrib/openzfs/module/os/linux/spl/spl-taskq.c (revision 7c43148a974877188a930e4078a164f83da8e652)
1 /*
2  *  Copyright (C) 2007-2010 Lawrence Livermore National Security, LLC.
3  *  Copyright (C) 2007 The Regents of the University of California.
4  *  Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
5  *  Written by Brian Behlendorf <behlendorf1@llnl.gov>.
6  *  UCRL-CODE-235197
7  *
8  *  This file is part of the SPL, Solaris Porting Layer.
9  *
10  *  The SPL is free software; you can redistribute it and/or modify it
11  *  under the terms of the GNU General Public License as published by the
12  *  Free Software Foundation; either version 2 of the License, or (at your
13  *  option) any later version.
14  *
15  *  The SPL is distributed in the hope that it will be useful, but WITHOUT
16  *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17  *  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
18  *  for more details.
19  *
20  *  You should have received a copy of the GNU General Public License along
21  *  with the SPL.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  *  Solaris Porting Layer (SPL) Task Queue Implementation.
24  */
25 
26 #include <sys/timer.h>
27 #include <sys/taskq.h>
28 #include <sys/kmem.h>
29 #include <sys/tsd.h>
30 #include <sys/trace_spl.h>
31 #ifdef HAVE_CPU_HOTPLUG
32 #include <linux/cpuhotplug.h>
33 #endif
34 
35 static int spl_taskq_thread_bind = 0;
36 module_param(spl_taskq_thread_bind, int, 0644);
37 MODULE_PARM_DESC(spl_taskq_thread_bind, "Bind taskq thread to CPU by default");
38 
39 static uint_t spl_taskq_thread_timeout_ms = 10000;
40 /* BEGIN CSTYLED */
41 module_param(spl_taskq_thread_timeout_ms, uint, 0644);
42 /* END CSTYLED */
43 MODULE_PARM_DESC(spl_taskq_thread_timeout_ms,
44 	"Time to require a dynamic thread be idle before it gets cleaned up");
45 
46 static int spl_taskq_thread_dynamic = 1;
47 module_param(spl_taskq_thread_dynamic, int, 0444);
48 MODULE_PARM_DESC(spl_taskq_thread_dynamic, "Allow dynamic taskq threads");
49 
50 static int spl_taskq_thread_priority = 1;
51 module_param(spl_taskq_thread_priority, int, 0644);
52 MODULE_PARM_DESC(spl_taskq_thread_priority,
53 	"Allow non-default priority for taskq threads");
54 
55 static uint_t spl_taskq_thread_sequential = 4;
56 /* BEGIN CSTYLED */
57 module_param(spl_taskq_thread_sequential, uint, 0644);
58 /* END CSTYLED */
59 MODULE_PARM_DESC(spl_taskq_thread_sequential,
60 	"Create new taskq threads after N sequential tasks");
61 
62 /*
63  * Global system-wide dynamic task queue available for all consumers. This
64  * taskq is not intended for long-running tasks; instead, a dedicated taskq
65  * should be created.
66  */
67 taskq_t *system_taskq;
68 EXPORT_SYMBOL(system_taskq);
69 /* Global dynamic task queue for long delay */
70 taskq_t *system_delay_taskq;
71 EXPORT_SYMBOL(system_delay_taskq);
72 
73 /* Private dedicated taskq for creating new taskq threads on demand. */
74 static taskq_t *dynamic_taskq;
75 static taskq_thread_t *taskq_thread_create(taskq_t *);
76 
77 #ifdef HAVE_CPU_HOTPLUG
78 /* Multi-callback id for cpu hotplugging. */
79 static int spl_taskq_cpuhp_state;
80 #endif
81 
82 /* List of all taskqs */
83 LIST_HEAD(tq_list);
84 struct rw_semaphore tq_list_sem;
85 static uint_t taskq_tsd;
86 
87 static int
88 task_km_flags(uint_t flags)
89 {
90 	if (flags & TQ_NOSLEEP)
91 		return (KM_NOSLEEP);
92 
93 	if (flags & TQ_PUSHPAGE)
94 		return (KM_PUSHPAGE);
95 
96 	return (KM_SLEEP);
97 }
98 
99 /*
100  * taskq_find_by_name - Find the largest instance number of a named taskq.
101  */
102 static int
103 taskq_find_by_name(const char *name)
104 {
105 	struct list_head *tql = NULL;
106 	taskq_t *tq;
107 
108 	list_for_each_prev(tql, &tq_list) {
109 		tq = list_entry(tql, taskq_t, tq_taskqs);
110 		if (strcmp(name, tq->tq_name) == 0)
111 			return (tq->tq_instance);
112 	}
113 	return (-1);
114 }
115 
116 /*
117  * NOTE: Must be called with tq->tq_lock held, returns a list_t which
118  * is not attached to the free, work, or pending taskq lists.
119  */
120 static taskq_ent_t *
121 task_alloc(taskq_t *tq, uint_t flags, unsigned long *irqflags)
122 {
123 	taskq_ent_t *t;
124 	int count = 0;
125 
126 	ASSERT(tq);
127 retry:
128 	/* Acquire taskq_ent_t's from free list if available */
129 	if (!list_empty(&tq->tq_free_list) && !(flags & TQ_NEW)) {
130 		t = list_entry(tq->tq_free_list.next, taskq_ent_t, tqent_list);
131 
132 		ASSERT(!(t->tqent_flags & TQENT_FLAG_PREALLOC));
133 		ASSERT(!(t->tqent_flags & TQENT_FLAG_CANCEL));
134 		ASSERT(!timer_pending(&t->tqent_timer));
135 
136 		list_del_init(&t->tqent_list);
137 		return (t);
138 	}
139 
140 	/* Free list is empty and memory allocations are prohibited */
141 	if (flags & TQ_NOALLOC)
142 		return (NULL);
143 
144 	/* Hit maximum taskq_ent_t pool size */
145 	if (tq->tq_nalloc >= tq->tq_maxalloc) {
146 		if (flags & TQ_NOSLEEP)
147 			return (NULL);
148 
149 		/*
150 		 * Sleep periodically polling the free list for an available
151 		 * taskq_ent_t. Dispatching with TQ_SLEEP should always succeed
152 		 * but we cannot block forever waiting for an taskq_ent_t to
153 		 * show up in the free list, otherwise a deadlock can happen.
154 		 *
155 		 * Therefore, we need to allocate a new task even if the number
156 		 * of allocated tasks is above tq->tq_maxalloc, but we still
157 		 * end up delaying the task allocation by one second, thereby
158 		 * throttling the task dispatch rate.
159 		 */
160 		spin_unlock_irqrestore(&tq->tq_lock, *irqflags);
161 		schedule_timeout(HZ / 100);
162 		spin_lock_irqsave_nested(&tq->tq_lock, *irqflags,
163 		    tq->tq_lock_class);
164 		if (count < 100) {
165 			count++;
166 			goto retry;
167 		}
168 	}
169 
170 	spin_unlock_irqrestore(&tq->tq_lock, *irqflags);
171 	t = kmem_alloc(sizeof (taskq_ent_t), task_km_flags(flags));
172 	spin_lock_irqsave_nested(&tq->tq_lock, *irqflags, tq->tq_lock_class);
173 
174 	if (t) {
175 		taskq_init_ent(t);
176 		tq->tq_nalloc++;
177 	}
178 
179 	return (t);
180 }
181 
182 /*
183  * NOTE: Must be called with tq->tq_lock held, expects the taskq_ent_t
184  * to already be removed from the free, work, or pending taskq lists.
185  */
186 static void
187 task_free(taskq_t *tq, taskq_ent_t *t)
188 {
189 	ASSERT(tq);
190 	ASSERT(t);
191 	ASSERT(list_empty(&t->tqent_list));
192 	ASSERT(!timer_pending(&t->tqent_timer));
193 
194 	kmem_free(t, sizeof (taskq_ent_t));
195 	tq->tq_nalloc--;
196 }
197 
198 /*
199  * NOTE: Must be called with tq->tq_lock held, either destroys the
200  * taskq_ent_t if too many exist or moves it to the free list for later use.
201  */
202 static void
203 task_done(taskq_t *tq, taskq_ent_t *t)
204 {
205 	ASSERT(tq);
206 	ASSERT(t);
207 
208 	/* Wake tasks blocked in taskq_wait_id() */
209 	wake_up_all(&t->tqent_waitq);
210 
211 	list_del_init(&t->tqent_list);
212 
213 	if (tq->tq_nalloc <= tq->tq_minalloc) {
214 		t->tqent_id = TASKQID_INVALID;
215 		t->tqent_func = NULL;
216 		t->tqent_arg = NULL;
217 		t->tqent_flags = 0;
218 
219 		list_add_tail(&t->tqent_list, &tq->tq_free_list);
220 	} else {
221 		task_free(tq, t);
222 	}
223 }
224 
225 /*
226  * When a delayed task timer expires remove it from the delay list and
227  * add it to the priority list in order for immediate processing.
228  */
229 static void
230 task_expire_impl(taskq_ent_t *t)
231 {
232 	taskq_ent_t *w;
233 	taskq_t *tq = t->tqent_taskq;
234 	struct list_head *l = NULL;
235 	unsigned long flags;
236 
237 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
238 
239 	if (t->tqent_flags & TQENT_FLAG_CANCEL) {
240 		ASSERT(list_empty(&t->tqent_list));
241 		spin_unlock_irqrestore(&tq->tq_lock, flags);
242 		return;
243 	}
244 
245 	t->tqent_birth = jiffies;
246 	DTRACE_PROBE1(taskq_ent__birth, taskq_ent_t *, t);
247 
248 	/*
249 	 * The priority list must be maintained in strict task id order
250 	 * from lowest to highest for lowest_id to be easily calculable.
251 	 */
252 	list_del(&t->tqent_list);
253 	list_for_each_prev(l, &tq->tq_prio_list) {
254 		w = list_entry(l, taskq_ent_t, tqent_list);
255 		if (w->tqent_id < t->tqent_id) {
256 			list_add(&t->tqent_list, l);
257 			break;
258 		}
259 	}
260 	if (l == &tq->tq_prio_list)
261 		list_add(&t->tqent_list, &tq->tq_prio_list);
262 
263 	spin_unlock_irqrestore(&tq->tq_lock, flags);
264 
265 	wake_up(&tq->tq_work_waitq);
266 }
267 
268 static void
269 task_expire(spl_timer_list_t tl)
270 {
271 	struct timer_list *tmr = (struct timer_list *)tl;
272 	taskq_ent_t *t = from_timer(t, tmr, tqent_timer);
273 	task_expire_impl(t);
274 }
275 
276 /*
277  * Returns the lowest incomplete taskqid_t.  The taskqid_t may
278  * be queued on the pending list, on the priority list, on the
279  * delay list, or on the work list currently being handled, but
280  * it is not 100% complete yet.
281  */
282 static taskqid_t
283 taskq_lowest_id(taskq_t *tq)
284 {
285 	taskqid_t lowest_id = tq->tq_next_id;
286 	taskq_ent_t *t;
287 	taskq_thread_t *tqt;
288 
289 	if (!list_empty(&tq->tq_pend_list)) {
290 		t = list_entry(tq->tq_pend_list.next, taskq_ent_t, tqent_list);
291 		lowest_id = MIN(lowest_id, t->tqent_id);
292 	}
293 
294 	if (!list_empty(&tq->tq_prio_list)) {
295 		t = list_entry(tq->tq_prio_list.next, taskq_ent_t, tqent_list);
296 		lowest_id = MIN(lowest_id, t->tqent_id);
297 	}
298 
299 	if (!list_empty(&tq->tq_delay_list)) {
300 		t = list_entry(tq->tq_delay_list.next, taskq_ent_t, tqent_list);
301 		lowest_id = MIN(lowest_id, t->tqent_id);
302 	}
303 
304 	if (!list_empty(&tq->tq_active_list)) {
305 		tqt = list_entry(tq->tq_active_list.next, taskq_thread_t,
306 		    tqt_active_list);
307 		ASSERT(tqt->tqt_id != TASKQID_INVALID);
308 		lowest_id = MIN(lowest_id, tqt->tqt_id);
309 	}
310 
311 	return (lowest_id);
312 }
313 
314 /*
315  * Insert a task into a list keeping the list sorted by increasing taskqid.
316  */
317 static void
318 taskq_insert_in_order(taskq_t *tq, taskq_thread_t *tqt)
319 {
320 	taskq_thread_t *w;
321 	struct list_head *l = NULL;
322 
323 	ASSERT(tq);
324 	ASSERT(tqt);
325 
326 	list_for_each_prev(l, &tq->tq_active_list) {
327 		w = list_entry(l, taskq_thread_t, tqt_active_list);
328 		if (w->tqt_id < tqt->tqt_id) {
329 			list_add(&tqt->tqt_active_list, l);
330 			break;
331 		}
332 	}
333 	if (l == &tq->tq_active_list)
334 		list_add(&tqt->tqt_active_list, &tq->tq_active_list);
335 }
336 
337 /*
338  * Find and return a task from the given list if it exists.  The list
339  * must be in lowest to highest task id order.
340  */
341 static taskq_ent_t *
342 taskq_find_list(taskq_t *tq, struct list_head *lh, taskqid_t id)
343 {
344 	struct list_head *l = NULL;
345 	taskq_ent_t *t;
346 
347 	list_for_each(l, lh) {
348 		t = list_entry(l, taskq_ent_t, tqent_list);
349 
350 		if (t->tqent_id == id)
351 			return (t);
352 
353 		if (t->tqent_id > id)
354 			break;
355 	}
356 
357 	return (NULL);
358 }
359 
360 /*
361  * Find an already dispatched task given the task id regardless of what
362  * state it is in.  If a task is still pending it will be returned.
363  * If a task is executing, then -EBUSY will be returned instead.
364  * If the task has already been run then NULL is returned.
365  */
366 static taskq_ent_t *
367 taskq_find(taskq_t *tq, taskqid_t id)
368 {
369 	taskq_thread_t *tqt;
370 	struct list_head *l = NULL;
371 	taskq_ent_t *t;
372 
373 	t = taskq_find_list(tq, &tq->tq_delay_list, id);
374 	if (t)
375 		return (t);
376 
377 	t = taskq_find_list(tq, &tq->tq_prio_list, id);
378 	if (t)
379 		return (t);
380 
381 	t = taskq_find_list(tq, &tq->tq_pend_list, id);
382 	if (t)
383 		return (t);
384 
385 	list_for_each(l, &tq->tq_active_list) {
386 		tqt = list_entry(l, taskq_thread_t, tqt_active_list);
387 		if (tqt->tqt_id == id) {
388 			/*
389 			 * Instead of returning tqt_task, we just return a non
390 			 * NULL value to prevent misuse, since tqt_task only
391 			 * has two valid fields.
392 			 */
393 			return (ERR_PTR(-EBUSY));
394 		}
395 	}
396 
397 	return (NULL);
398 }
399 
400 /*
401  * Theory for the taskq_wait_id(), taskq_wait_outstanding(), and
402  * taskq_wait() functions below.
403  *
404  * Taskq waiting is accomplished by tracking the lowest outstanding task
405  * id and the next available task id.  As tasks are dispatched they are
406  * added to the tail of the pending, priority, or delay lists.  As worker
407  * threads become available the tasks are removed from the heads of these
408  * lists and linked to the worker threads.  This ensures the lists are
409  * kept sorted by lowest to highest task id.
410  *
411  * Therefore the lowest outstanding task id can be quickly determined by
412  * checking the head item from all of these lists.  This value is stored
413  * with the taskq as the lowest id.  It only needs to be recalculated when
414  * either the task with the current lowest id completes or is canceled.
415  *
416  * By blocking until the lowest task id exceeds the passed task id the
417  * taskq_wait_outstanding() function can be easily implemented.  Similarly,
418  * by blocking until the lowest task id matches the next task id taskq_wait()
419  * can be implemented.
420  *
421  * Callers should be aware that when there are multiple worked threads it
422  * is possible for larger task ids to complete before smaller ones.  Also
423  * when the taskq contains delay tasks with small task ids callers may
424  * block for a considerable length of time waiting for them to expire and
425  * execute.
426  */
427 static int
428 taskq_wait_id_check(taskq_t *tq, taskqid_t id)
429 {
430 	int rc;
431 	unsigned long flags;
432 
433 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
434 	rc = (taskq_find(tq, id) == NULL);
435 	spin_unlock_irqrestore(&tq->tq_lock, flags);
436 
437 	return (rc);
438 }
439 
440 /*
441  * The taskq_wait_id() function blocks until the passed task id completes.
442  * This does not guarantee that all lower task ids have completed.
443  */
444 void
445 taskq_wait_id(taskq_t *tq, taskqid_t id)
446 {
447 	wait_event(tq->tq_wait_waitq, taskq_wait_id_check(tq, id));
448 }
449 EXPORT_SYMBOL(taskq_wait_id);
450 
451 static int
452 taskq_wait_outstanding_check(taskq_t *tq, taskqid_t id)
453 {
454 	int rc;
455 	unsigned long flags;
456 
457 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
458 	rc = (id < tq->tq_lowest_id);
459 	spin_unlock_irqrestore(&tq->tq_lock, flags);
460 
461 	return (rc);
462 }
463 
464 /*
465  * The taskq_wait_outstanding() function will block until all tasks with a
466  * lower taskqid than the passed 'id' have been completed.  Note that all
467  * task id's are assigned monotonically at dispatch time.  Zero may be
468  * passed for the id to indicate all tasks dispatch up to this point,
469  * but not after, should be waited for.
470  */
471 void
472 taskq_wait_outstanding(taskq_t *tq, taskqid_t id)
473 {
474 	id = id ? id : tq->tq_next_id - 1;
475 	wait_event(tq->tq_wait_waitq, taskq_wait_outstanding_check(tq, id));
476 }
477 EXPORT_SYMBOL(taskq_wait_outstanding);
478 
479 static int
480 taskq_wait_check(taskq_t *tq)
481 {
482 	int rc;
483 	unsigned long flags;
484 
485 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
486 	rc = (tq->tq_lowest_id == tq->tq_next_id);
487 	spin_unlock_irqrestore(&tq->tq_lock, flags);
488 
489 	return (rc);
490 }
491 
492 /*
493  * The taskq_wait() function will block until the taskq is empty.
494  * This means that if a taskq re-dispatches work to itself taskq_wait()
495  * callers will block indefinitely.
496  */
497 void
498 taskq_wait(taskq_t *tq)
499 {
500 	wait_event(tq->tq_wait_waitq, taskq_wait_check(tq));
501 }
502 EXPORT_SYMBOL(taskq_wait);
503 
504 int
505 taskq_member(taskq_t *tq, kthread_t *t)
506 {
507 	return (tq == (taskq_t *)tsd_get_by_thread(taskq_tsd, t));
508 }
509 EXPORT_SYMBOL(taskq_member);
510 
511 taskq_t *
512 taskq_of_curthread(void)
513 {
514 	return (tsd_get(taskq_tsd));
515 }
516 EXPORT_SYMBOL(taskq_of_curthread);
517 
518 /*
519  * Cancel an already dispatched task given the task id.  Still pending tasks
520  * will be immediately canceled, and if the task is active the function will
521  * block until it completes.  Preallocated tasks which are canceled must be
522  * freed by the caller.
523  */
524 int
525 taskq_cancel_id(taskq_t *tq, taskqid_t id)
526 {
527 	taskq_ent_t *t;
528 	int rc = ENOENT;
529 	unsigned long flags;
530 
531 	ASSERT(tq);
532 
533 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
534 	t = taskq_find(tq, id);
535 	if (t && t != ERR_PTR(-EBUSY)) {
536 		list_del_init(&t->tqent_list);
537 		t->tqent_flags |= TQENT_FLAG_CANCEL;
538 
539 		/*
540 		 * When canceling the lowest outstanding task id we
541 		 * must recalculate the new lowest outstanding id.
542 		 */
543 		if (tq->tq_lowest_id == t->tqent_id) {
544 			tq->tq_lowest_id = taskq_lowest_id(tq);
545 			ASSERT3S(tq->tq_lowest_id, >, t->tqent_id);
546 		}
547 
548 		/*
549 		 * The task_expire() function takes the tq->tq_lock so drop
550 		 * drop the lock before synchronously cancelling the timer.
551 		 */
552 		if (timer_pending(&t->tqent_timer)) {
553 			spin_unlock_irqrestore(&tq->tq_lock, flags);
554 			del_timer_sync(&t->tqent_timer);
555 			spin_lock_irqsave_nested(&tq->tq_lock, flags,
556 			    tq->tq_lock_class);
557 		}
558 
559 		if (!(t->tqent_flags & TQENT_FLAG_PREALLOC))
560 			task_done(tq, t);
561 
562 		rc = 0;
563 	}
564 	spin_unlock_irqrestore(&tq->tq_lock, flags);
565 
566 	if (t == ERR_PTR(-EBUSY)) {
567 		taskq_wait_id(tq, id);
568 		rc = EBUSY;
569 	}
570 
571 	return (rc);
572 }
573 EXPORT_SYMBOL(taskq_cancel_id);
574 
575 static int taskq_thread_spawn(taskq_t *tq);
576 
577 taskqid_t
578 taskq_dispatch(taskq_t *tq, task_func_t func, void *arg, uint_t flags)
579 {
580 	taskq_ent_t *t;
581 	taskqid_t rc = TASKQID_INVALID;
582 	unsigned long irqflags;
583 
584 	ASSERT(tq);
585 	ASSERT(func);
586 
587 	spin_lock_irqsave_nested(&tq->tq_lock, irqflags, tq->tq_lock_class);
588 
589 	/* Taskq being destroyed and all tasks drained */
590 	if (!(tq->tq_flags & TASKQ_ACTIVE))
591 		goto out;
592 
593 	/* Do not queue the task unless there is idle thread for it */
594 	ASSERT(tq->tq_nactive <= tq->tq_nthreads);
595 	if ((flags & TQ_NOQUEUE) && (tq->tq_nactive == tq->tq_nthreads)) {
596 		/* Dynamic taskq may be able to spawn another thread */
597 		if (!(tq->tq_flags & TASKQ_DYNAMIC) ||
598 		    taskq_thread_spawn(tq) == 0)
599 			goto out;
600 	}
601 
602 	if ((t = task_alloc(tq, flags, &irqflags)) == NULL)
603 		goto out;
604 
605 	spin_lock(&t->tqent_lock);
606 
607 	/* Queue to the front of the list to enforce TQ_NOQUEUE semantics */
608 	if (flags & TQ_NOQUEUE)
609 		list_add(&t->tqent_list, &tq->tq_prio_list);
610 	/* Queue to the priority list instead of the pending list */
611 	else if (flags & TQ_FRONT)
612 		list_add_tail(&t->tqent_list, &tq->tq_prio_list);
613 	else
614 		list_add_tail(&t->tqent_list, &tq->tq_pend_list);
615 
616 	t->tqent_id = rc = tq->tq_next_id;
617 	tq->tq_next_id++;
618 	t->tqent_func = func;
619 	t->tqent_arg = arg;
620 	t->tqent_taskq = tq;
621 	t->tqent_timer.function = NULL;
622 	t->tqent_timer.expires = 0;
623 
624 	t->tqent_birth = jiffies;
625 	DTRACE_PROBE1(taskq_ent__birth, taskq_ent_t *, t);
626 
627 	ASSERT(!(t->tqent_flags & TQENT_FLAG_PREALLOC));
628 
629 	spin_unlock(&t->tqent_lock);
630 
631 	wake_up(&tq->tq_work_waitq);
632 out:
633 	/* Spawn additional taskq threads if required. */
634 	if (!(flags & TQ_NOQUEUE) && tq->tq_nactive == tq->tq_nthreads)
635 		(void) taskq_thread_spawn(tq);
636 
637 	spin_unlock_irqrestore(&tq->tq_lock, irqflags);
638 	return (rc);
639 }
640 EXPORT_SYMBOL(taskq_dispatch);
641 
642 taskqid_t
643 taskq_dispatch_delay(taskq_t *tq, task_func_t func, void *arg,
644     uint_t flags, clock_t expire_time)
645 {
646 	taskqid_t rc = TASKQID_INVALID;
647 	taskq_ent_t *t;
648 	unsigned long irqflags;
649 
650 	ASSERT(tq);
651 	ASSERT(func);
652 
653 	spin_lock_irqsave_nested(&tq->tq_lock, irqflags, tq->tq_lock_class);
654 
655 	/* Taskq being destroyed and all tasks drained */
656 	if (!(tq->tq_flags & TASKQ_ACTIVE))
657 		goto out;
658 
659 	if ((t = task_alloc(tq, flags, &irqflags)) == NULL)
660 		goto out;
661 
662 	spin_lock(&t->tqent_lock);
663 
664 	/* Queue to the delay list for subsequent execution */
665 	list_add_tail(&t->tqent_list, &tq->tq_delay_list);
666 
667 	t->tqent_id = rc = tq->tq_next_id;
668 	tq->tq_next_id++;
669 	t->tqent_func = func;
670 	t->tqent_arg = arg;
671 	t->tqent_taskq = tq;
672 	t->tqent_timer.function = task_expire;
673 	t->tqent_timer.expires = (unsigned long)expire_time;
674 	add_timer(&t->tqent_timer);
675 
676 	ASSERT(!(t->tqent_flags & TQENT_FLAG_PREALLOC));
677 
678 	spin_unlock(&t->tqent_lock);
679 out:
680 	/* Spawn additional taskq threads if required. */
681 	if (tq->tq_nactive == tq->tq_nthreads)
682 		(void) taskq_thread_spawn(tq);
683 	spin_unlock_irqrestore(&tq->tq_lock, irqflags);
684 	return (rc);
685 }
686 EXPORT_SYMBOL(taskq_dispatch_delay);
687 
688 void
689 taskq_dispatch_ent(taskq_t *tq, task_func_t func, void *arg, uint_t flags,
690     taskq_ent_t *t)
691 {
692 	unsigned long irqflags;
693 	ASSERT(tq);
694 	ASSERT(func);
695 
696 	spin_lock_irqsave_nested(&tq->tq_lock, irqflags,
697 	    tq->tq_lock_class);
698 
699 	/* Taskq being destroyed and all tasks drained */
700 	if (!(tq->tq_flags & TASKQ_ACTIVE)) {
701 		t->tqent_id = TASKQID_INVALID;
702 		goto out;
703 	}
704 
705 	if ((flags & TQ_NOQUEUE) && (tq->tq_nactive == tq->tq_nthreads)) {
706 		/* Dynamic taskq may be able to spawn another thread */
707 		if (!(tq->tq_flags & TASKQ_DYNAMIC) ||
708 		    taskq_thread_spawn(tq) == 0)
709 			goto out2;
710 		flags |= TQ_FRONT;
711 	}
712 
713 	spin_lock(&t->tqent_lock);
714 
715 	/*
716 	 * Make sure the entry is not on some other taskq; it is important to
717 	 * ASSERT() under lock
718 	 */
719 	ASSERT(taskq_empty_ent(t));
720 
721 	/*
722 	 * Mark it as a prealloc'd task.  This is important
723 	 * to ensure that we don't free it later.
724 	 */
725 	t->tqent_flags |= TQENT_FLAG_PREALLOC;
726 
727 	/* Queue to the priority list instead of the pending list */
728 	if (flags & TQ_FRONT)
729 		list_add_tail(&t->tqent_list, &tq->tq_prio_list);
730 	else
731 		list_add_tail(&t->tqent_list, &tq->tq_pend_list);
732 
733 	t->tqent_id = tq->tq_next_id;
734 	tq->tq_next_id++;
735 	t->tqent_func = func;
736 	t->tqent_arg = arg;
737 	t->tqent_taskq = tq;
738 
739 	t->tqent_birth = jiffies;
740 	DTRACE_PROBE1(taskq_ent__birth, taskq_ent_t *, t);
741 
742 	spin_unlock(&t->tqent_lock);
743 
744 	wake_up(&tq->tq_work_waitq);
745 out:
746 	/* Spawn additional taskq threads if required. */
747 	if (tq->tq_nactive == tq->tq_nthreads)
748 		(void) taskq_thread_spawn(tq);
749 out2:
750 	spin_unlock_irqrestore(&tq->tq_lock, irqflags);
751 }
752 EXPORT_SYMBOL(taskq_dispatch_ent);
753 
754 int
755 taskq_empty_ent(taskq_ent_t *t)
756 {
757 	return (list_empty(&t->tqent_list));
758 }
759 EXPORT_SYMBOL(taskq_empty_ent);
760 
761 void
762 taskq_init_ent(taskq_ent_t *t)
763 {
764 	spin_lock_init(&t->tqent_lock);
765 	init_waitqueue_head(&t->tqent_waitq);
766 	timer_setup(&t->tqent_timer, NULL, 0);
767 	INIT_LIST_HEAD(&t->tqent_list);
768 	t->tqent_id = 0;
769 	t->tqent_func = NULL;
770 	t->tqent_arg = NULL;
771 	t->tqent_flags = 0;
772 	t->tqent_taskq = NULL;
773 }
774 EXPORT_SYMBOL(taskq_init_ent);
775 
776 /*
777  * Return the next pending task, preference is given to tasks on the
778  * priority list which were dispatched with TQ_FRONT.
779  */
780 static taskq_ent_t *
781 taskq_next_ent(taskq_t *tq)
782 {
783 	struct list_head *list;
784 
785 	if (!list_empty(&tq->tq_prio_list))
786 		list = &tq->tq_prio_list;
787 	else if (!list_empty(&tq->tq_pend_list))
788 		list = &tq->tq_pend_list;
789 	else
790 		return (NULL);
791 
792 	return (list_entry(list->next, taskq_ent_t, tqent_list));
793 }
794 
795 /*
796  * Spawns a new thread for the specified taskq.
797  */
798 static void
799 taskq_thread_spawn_task(void *arg)
800 {
801 	taskq_t *tq = (taskq_t *)arg;
802 	unsigned long flags;
803 
804 	if (taskq_thread_create(tq) == NULL) {
805 		/* restore spawning count if failed */
806 		spin_lock_irqsave_nested(&tq->tq_lock, flags,
807 		    tq->tq_lock_class);
808 		tq->tq_nspawn--;
809 		spin_unlock_irqrestore(&tq->tq_lock, flags);
810 	}
811 }
812 
813 /*
814  * Spawn addition threads for dynamic taskqs (TASKQ_DYNAMIC) the current
815  * number of threads is insufficient to handle the pending tasks.  These
816  * new threads must be created by the dedicated dynamic_taskq to avoid
817  * deadlocks between thread creation and memory reclaim.  The system_taskq
818  * which is also a dynamic taskq cannot be safely used for this.
819  */
820 static int
821 taskq_thread_spawn(taskq_t *tq)
822 {
823 	int spawning = 0;
824 
825 	if (!(tq->tq_flags & TASKQ_DYNAMIC))
826 		return (0);
827 
828 	if ((tq->tq_nthreads + tq->tq_nspawn < tq->tq_maxthreads) &&
829 	    (tq->tq_flags & TASKQ_ACTIVE)) {
830 		spawning = (++tq->tq_nspawn);
831 		taskq_dispatch(dynamic_taskq, taskq_thread_spawn_task,
832 		    tq, TQ_NOSLEEP);
833 	}
834 
835 	return (spawning);
836 }
837 
838 /*
839  * Threads in a dynamic taskq should only exit once it has been completely
840  * drained and no other threads are actively servicing tasks.  This prevents
841  * threads from being created and destroyed more than is required.
842  *
843  * The first thread is the thread list is treated as the primary thread.
844  * There is nothing special about the primary thread but in order to avoid
845  * all the taskq pids from changing we opt to make it long running.
846  */
847 static int
848 taskq_thread_should_stop(taskq_t *tq, taskq_thread_t *tqt)
849 {
850 	if (!(tq->tq_flags & TASKQ_DYNAMIC))
851 		return (0);
852 
853 	if (list_first_entry(&(tq->tq_thread_list), taskq_thread_t,
854 	    tqt_thread_list) == tqt)
855 		return (0);
856 
857 	int no_work =
858 	    ((tq->tq_nspawn == 0) &&	/* No threads are being spawned */
859 	    (tq->tq_nactive == 0) &&	/* No threads are handling tasks */
860 	    (tq->tq_nthreads > 1) &&	/* More than 1 thread is running */
861 	    (!taskq_next_ent(tq)) &&	/* There are no pending tasks */
862 	    (spl_taskq_thread_dynamic)); /* Dynamic taskqs are allowed */
863 
864 	/*
865 	 * If we would have said stop before, let's instead wait a bit, maybe
866 	 * we'll see more work come our way soon...
867 	 */
868 	if (no_work) {
869 		/* if it's 0, we want the old behavior. */
870 		/* if the taskq is being torn down, we also want to go away. */
871 		if (spl_taskq_thread_timeout_ms == 0 ||
872 		    !(tq->tq_flags & TASKQ_ACTIVE))
873 			return (1);
874 		unsigned long lasttime = tq->lastshouldstop;
875 		if (lasttime > 0) {
876 			if (time_after(jiffies, lasttime +
877 			    msecs_to_jiffies(spl_taskq_thread_timeout_ms)))
878 				return (1);
879 			else
880 				return (0);
881 		} else {
882 			tq->lastshouldstop = jiffies;
883 		}
884 	} else {
885 		tq->lastshouldstop = 0;
886 	}
887 	return (0);
888 }
889 
890 static int
891 taskq_thread(void *args)
892 {
893 	DECLARE_WAITQUEUE(wait, current);
894 	sigset_t blocked;
895 	taskq_thread_t *tqt = args;
896 	taskq_t *tq;
897 	taskq_ent_t *t;
898 	int seq_tasks = 0;
899 	unsigned long flags;
900 	taskq_ent_t dup_task = {};
901 
902 	ASSERT(tqt);
903 	ASSERT(tqt->tqt_tq);
904 	tq = tqt->tqt_tq;
905 	current->flags |= PF_NOFREEZE;
906 
907 	(void) spl_fstrans_mark();
908 
909 	sigfillset(&blocked);
910 	sigprocmask(SIG_BLOCK, &blocked, NULL);
911 	flush_signals(current);
912 
913 	tsd_set(taskq_tsd, tq);
914 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
915 	/*
916 	 * If we are dynamically spawned, decrease spawning count. Note that
917 	 * we could be created during taskq_create, in which case we shouldn't
918 	 * do the decrement. But it's fine because taskq_create will reset
919 	 * tq_nspawn later.
920 	 */
921 	if (tq->tq_flags & TASKQ_DYNAMIC)
922 		tq->tq_nspawn--;
923 
924 	/* Immediately exit if more threads than allowed were created. */
925 	if (tq->tq_nthreads >= tq->tq_maxthreads)
926 		goto error;
927 
928 	tq->tq_nthreads++;
929 	list_add_tail(&tqt->tqt_thread_list, &tq->tq_thread_list);
930 	wake_up(&tq->tq_wait_waitq);
931 	set_current_state(TASK_INTERRUPTIBLE);
932 
933 	while (!kthread_should_stop()) {
934 
935 		if (list_empty(&tq->tq_pend_list) &&
936 		    list_empty(&tq->tq_prio_list)) {
937 
938 			if (taskq_thread_should_stop(tq, tqt)) {
939 				wake_up_all(&tq->tq_wait_waitq);
940 				break;
941 			}
942 
943 			add_wait_queue_exclusive(&tq->tq_work_waitq, &wait);
944 			spin_unlock_irqrestore(&tq->tq_lock, flags);
945 
946 			schedule();
947 			seq_tasks = 0;
948 
949 			spin_lock_irqsave_nested(&tq->tq_lock, flags,
950 			    tq->tq_lock_class);
951 			remove_wait_queue(&tq->tq_work_waitq, &wait);
952 		} else {
953 			__set_current_state(TASK_RUNNING);
954 		}
955 
956 		if ((t = taskq_next_ent(tq)) != NULL) {
957 			list_del_init(&t->tqent_list);
958 
959 			/*
960 			 * A TQENT_FLAG_PREALLOC task may be reused or freed
961 			 * during the task function call. Store tqent_id and
962 			 * tqent_flags here.
963 			 *
964 			 * Also use an on stack taskq_ent_t for tqt_task
965 			 * assignment in this case; we want to make sure
966 			 * to duplicate all fields, so the values are
967 			 * correct when it's accessed via DTRACE_PROBE*.
968 			 */
969 			tqt->tqt_id = t->tqent_id;
970 			tqt->tqt_flags = t->tqent_flags;
971 
972 			if (t->tqent_flags & TQENT_FLAG_PREALLOC) {
973 				dup_task = *t;
974 				t = &dup_task;
975 			}
976 			tqt->tqt_task = t;
977 
978 			taskq_insert_in_order(tq, tqt);
979 			tq->tq_nactive++;
980 			spin_unlock_irqrestore(&tq->tq_lock, flags);
981 
982 			DTRACE_PROBE1(taskq_ent__start, taskq_ent_t *, t);
983 
984 			/* Perform the requested task */
985 			t->tqent_func(t->tqent_arg);
986 
987 			DTRACE_PROBE1(taskq_ent__finish, taskq_ent_t *, t);
988 
989 			spin_lock_irqsave_nested(&tq->tq_lock, flags,
990 			    tq->tq_lock_class);
991 			tq->tq_nactive--;
992 			list_del_init(&tqt->tqt_active_list);
993 			tqt->tqt_task = NULL;
994 
995 			/* For prealloc'd tasks, we don't free anything. */
996 			if (!(tqt->tqt_flags & TQENT_FLAG_PREALLOC))
997 				task_done(tq, t);
998 
999 			/*
1000 			 * When the current lowest outstanding taskqid is
1001 			 * done calculate the new lowest outstanding id
1002 			 */
1003 			if (tq->tq_lowest_id == tqt->tqt_id) {
1004 				tq->tq_lowest_id = taskq_lowest_id(tq);
1005 				ASSERT3S(tq->tq_lowest_id, >, tqt->tqt_id);
1006 			}
1007 
1008 			/* Spawn additional taskq threads if required. */
1009 			if ((++seq_tasks) > spl_taskq_thread_sequential &&
1010 			    taskq_thread_spawn(tq))
1011 				seq_tasks = 0;
1012 
1013 			tqt->tqt_id = TASKQID_INVALID;
1014 			tqt->tqt_flags = 0;
1015 			wake_up_all(&tq->tq_wait_waitq);
1016 		} else {
1017 			if (taskq_thread_should_stop(tq, tqt))
1018 				break;
1019 		}
1020 
1021 		set_current_state(TASK_INTERRUPTIBLE);
1022 
1023 	}
1024 
1025 	__set_current_state(TASK_RUNNING);
1026 	tq->tq_nthreads--;
1027 	list_del_init(&tqt->tqt_thread_list);
1028 error:
1029 	kmem_free(tqt, sizeof (taskq_thread_t));
1030 	spin_unlock_irqrestore(&tq->tq_lock, flags);
1031 
1032 	tsd_set(taskq_tsd, NULL);
1033 	thread_exit();
1034 
1035 	return (0);
1036 }
1037 
1038 static taskq_thread_t *
1039 taskq_thread_create(taskq_t *tq)
1040 {
1041 	static int last_used_cpu = 0;
1042 	taskq_thread_t *tqt;
1043 
1044 	tqt = kmem_alloc(sizeof (*tqt), KM_PUSHPAGE);
1045 	INIT_LIST_HEAD(&tqt->tqt_thread_list);
1046 	INIT_LIST_HEAD(&tqt->tqt_active_list);
1047 	tqt->tqt_tq = tq;
1048 	tqt->tqt_id = TASKQID_INVALID;
1049 
1050 	tqt->tqt_thread = spl_kthread_create(taskq_thread, tqt,
1051 	    "%s", tq->tq_name);
1052 	if (tqt->tqt_thread == NULL) {
1053 		kmem_free(tqt, sizeof (taskq_thread_t));
1054 		return (NULL);
1055 	}
1056 
1057 	if (spl_taskq_thread_bind) {
1058 		last_used_cpu = (last_used_cpu + 1) % num_online_cpus();
1059 		kthread_bind(tqt->tqt_thread, last_used_cpu);
1060 	}
1061 
1062 	if (spl_taskq_thread_priority)
1063 		set_user_nice(tqt->tqt_thread, PRIO_TO_NICE(tq->tq_pri));
1064 
1065 	wake_up_process(tqt->tqt_thread);
1066 
1067 	return (tqt);
1068 }
1069 
1070 taskq_t *
1071 taskq_create(const char *name, int threads_arg, pri_t pri,
1072     int minalloc, int maxalloc, uint_t flags)
1073 {
1074 	taskq_t *tq;
1075 	taskq_thread_t *tqt;
1076 	int count = 0, rc = 0, i;
1077 	unsigned long irqflags;
1078 	int nthreads = threads_arg;
1079 
1080 	ASSERT(name != NULL);
1081 	ASSERT(minalloc >= 0);
1082 	ASSERT(!(flags & (TASKQ_CPR_SAFE))); /* Unsupported */
1083 
1084 	/* Scale the number of threads using nthreads as a percentage */
1085 	if (flags & TASKQ_THREADS_CPU_PCT) {
1086 		ASSERT(nthreads <= 100);
1087 		ASSERT(nthreads >= 0);
1088 		nthreads = MIN(threads_arg, 100);
1089 		nthreads = MAX(nthreads, 0);
1090 		nthreads = MAX((num_online_cpus() * nthreads) /100, 1);
1091 	}
1092 
1093 	tq = kmem_alloc(sizeof (*tq), KM_PUSHPAGE);
1094 	if (tq == NULL)
1095 		return (NULL);
1096 
1097 	tq->tq_hp_support = B_FALSE;
1098 #ifdef HAVE_CPU_HOTPLUG
1099 	if (flags & TASKQ_THREADS_CPU_PCT) {
1100 		tq->tq_hp_support = B_TRUE;
1101 		if (cpuhp_state_add_instance_nocalls(spl_taskq_cpuhp_state,
1102 		    &tq->tq_hp_cb_node) != 0) {
1103 			kmem_free(tq, sizeof (*tq));
1104 			return (NULL);
1105 		}
1106 	}
1107 #endif
1108 
1109 	spin_lock_init(&tq->tq_lock);
1110 	INIT_LIST_HEAD(&tq->tq_thread_list);
1111 	INIT_LIST_HEAD(&tq->tq_active_list);
1112 	tq->tq_name = kmem_strdup(name);
1113 	tq->tq_nactive = 0;
1114 	tq->tq_nthreads = 0;
1115 	tq->tq_nspawn = 0;
1116 	tq->tq_maxthreads = nthreads;
1117 	tq->tq_cpu_pct = threads_arg;
1118 	tq->tq_pri = pri;
1119 	tq->tq_minalloc = minalloc;
1120 	tq->tq_maxalloc = maxalloc;
1121 	tq->tq_nalloc = 0;
1122 	tq->tq_flags = (flags | TASKQ_ACTIVE);
1123 	tq->tq_next_id = TASKQID_INITIAL;
1124 	tq->tq_lowest_id = TASKQID_INITIAL;
1125 	tq->lastshouldstop = 0;
1126 	INIT_LIST_HEAD(&tq->tq_free_list);
1127 	INIT_LIST_HEAD(&tq->tq_pend_list);
1128 	INIT_LIST_HEAD(&tq->tq_prio_list);
1129 	INIT_LIST_HEAD(&tq->tq_delay_list);
1130 	init_waitqueue_head(&tq->tq_work_waitq);
1131 	init_waitqueue_head(&tq->tq_wait_waitq);
1132 	tq->tq_lock_class = TQ_LOCK_GENERAL;
1133 	INIT_LIST_HEAD(&tq->tq_taskqs);
1134 
1135 	if (flags & TASKQ_PREPOPULATE) {
1136 		spin_lock_irqsave_nested(&tq->tq_lock, irqflags,
1137 		    tq->tq_lock_class);
1138 
1139 		for (i = 0; i < minalloc; i++)
1140 			task_done(tq, task_alloc(tq, TQ_PUSHPAGE | TQ_NEW,
1141 			    &irqflags));
1142 
1143 		spin_unlock_irqrestore(&tq->tq_lock, irqflags);
1144 	}
1145 
1146 	if ((flags & TASKQ_DYNAMIC) && spl_taskq_thread_dynamic)
1147 		nthreads = 1;
1148 
1149 	for (i = 0; i < nthreads; i++) {
1150 		tqt = taskq_thread_create(tq);
1151 		if (tqt == NULL)
1152 			rc = 1;
1153 		else
1154 			count++;
1155 	}
1156 
1157 	/* Wait for all threads to be started before potential destroy */
1158 	wait_event(tq->tq_wait_waitq, tq->tq_nthreads == count);
1159 	/*
1160 	 * taskq_thread might have touched nspawn, but we don't want them to
1161 	 * because they're not dynamically spawned. So we reset it to 0
1162 	 */
1163 	tq->tq_nspawn = 0;
1164 
1165 	if (rc) {
1166 		taskq_destroy(tq);
1167 		tq = NULL;
1168 	} else {
1169 		down_write(&tq_list_sem);
1170 		tq->tq_instance = taskq_find_by_name(name) + 1;
1171 		list_add_tail(&tq->tq_taskqs, &tq_list);
1172 		up_write(&tq_list_sem);
1173 	}
1174 
1175 	return (tq);
1176 }
1177 EXPORT_SYMBOL(taskq_create);
1178 
1179 void
1180 taskq_destroy(taskq_t *tq)
1181 {
1182 	struct task_struct *thread;
1183 	taskq_thread_t *tqt;
1184 	taskq_ent_t *t;
1185 	unsigned long flags;
1186 
1187 	ASSERT(tq);
1188 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
1189 	tq->tq_flags &= ~TASKQ_ACTIVE;
1190 	spin_unlock_irqrestore(&tq->tq_lock, flags);
1191 
1192 #ifdef HAVE_CPU_HOTPLUG
1193 	if (tq->tq_hp_support) {
1194 		VERIFY0(cpuhp_state_remove_instance_nocalls(
1195 		    spl_taskq_cpuhp_state, &tq->tq_hp_cb_node));
1196 	}
1197 #endif
1198 	/*
1199 	 * When TASKQ_ACTIVE is clear new tasks may not be added nor may
1200 	 * new worker threads be spawned for dynamic taskq.
1201 	 */
1202 	if (dynamic_taskq != NULL)
1203 		taskq_wait_outstanding(dynamic_taskq, 0);
1204 
1205 	taskq_wait(tq);
1206 
1207 	/* remove taskq from global list used by the kstats */
1208 	down_write(&tq_list_sem);
1209 	list_del(&tq->tq_taskqs);
1210 	up_write(&tq_list_sem);
1211 
1212 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
1213 	/* wait for spawning threads to insert themselves to the list */
1214 	while (tq->tq_nspawn) {
1215 		spin_unlock_irqrestore(&tq->tq_lock, flags);
1216 		schedule_timeout_interruptible(1);
1217 		spin_lock_irqsave_nested(&tq->tq_lock, flags,
1218 		    tq->tq_lock_class);
1219 	}
1220 
1221 	/*
1222 	 * Signal each thread to exit and block until it does.  Each thread
1223 	 * is responsible for removing itself from the list and freeing its
1224 	 * taskq_thread_t.  This allows for idle threads to opt to remove
1225 	 * themselves from the taskq.  They can be recreated as needed.
1226 	 */
1227 	while (!list_empty(&tq->tq_thread_list)) {
1228 		tqt = list_entry(tq->tq_thread_list.next,
1229 		    taskq_thread_t, tqt_thread_list);
1230 		thread = tqt->tqt_thread;
1231 		spin_unlock_irqrestore(&tq->tq_lock, flags);
1232 
1233 		kthread_stop(thread);
1234 
1235 		spin_lock_irqsave_nested(&tq->tq_lock, flags,
1236 		    tq->tq_lock_class);
1237 	}
1238 
1239 	while (!list_empty(&tq->tq_free_list)) {
1240 		t = list_entry(tq->tq_free_list.next, taskq_ent_t, tqent_list);
1241 
1242 		ASSERT(!(t->tqent_flags & TQENT_FLAG_PREALLOC));
1243 
1244 		list_del_init(&t->tqent_list);
1245 		task_free(tq, t);
1246 	}
1247 
1248 	ASSERT0(tq->tq_nthreads);
1249 	ASSERT0(tq->tq_nalloc);
1250 	ASSERT0(tq->tq_nspawn);
1251 	ASSERT(list_empty(&tq->tq_thread_list));
1252 	ASSERT(list_empty(&tq->tq_active_list));
1253 	ASSERT(list_empty(&tq->tq_free_list));
1254 	ASSERT(list_empty(&tq->tq_pend_list));
1255 	ASSERT(list_empty(&tq->tq_prio_list));
1256 	ASSERT(list_empty(&tq->tq_delay_list));
1257 
1258 	spin_unlock_irqrestore(&tq->tq_lock, flags);
1259 
1260 	kmem_strfree(tq->tq_name);
1261 	kmem_free(tq, sizeof (taskq_t));
1262 }
1263 EXPORT_SYMBOL(taskq_destroy);
1264 
1265 /*
1266  * Create a taskq with a specified number of pool threads. Allocate
1267  * and return an array of nthreads kthread_t pointers, one for each
1268  * thread in the pool. The array is not ordered and must be freed
1269  * by the caller.
1270  */
1271 taskq_t *
1272 taskq_create_synced(const char *name, int nthreads, pri_t pri,
1273     int minalloc, int maxalloc, uint_t flags, kthread_t ***ktpp)
1274 {
1275 	taskq_t *tq;
1276 	taskq_thread_t *tqt;
1277 	int i = 0;
1278 	kthread_t **kthreads = kmem_zalloc(sizeof (*kthreads) * nthreads,
1279 	    KM_SLEEP);
1280 
1281 	flags &= ~(TASKQ_DYNAMIC | TASKQ_THREADS_CPU_PCT | TASKQ_DC_BATCH);
1282 
1283 	/* taskq_create spawns all the threads before returning */
1284 	tq = taskq_create(name, nthreads, minclsyspri, nthreads, INT_MAX,
1285 	    flags | TASKQ_PREPOPULATE);
1286 	VERIFY(tq != NULL);
1287 	VERIFY(tq->tq_nthreads == nthreads);
1288 
1289 	list_for_each_entry(tqt, &tq->tq_thread_list, tqt_thread_list) {
1290 		kthreads[i] = tqt->tqt_thread;
1291 		i++;
1292 	}
1293 
1294 	ASSERT3S(i, ==, nthreads);
1295 	*ktpp = kthreads;
1296 
1297 	return (tq);
1298 }
1299 EXPORT_SYMBOL(taskq_create_synced);
1300 
1301 static unsigned int spl_taskq_kick = 0;
1302 
1303 /*
1304  * 2.6.36 API Change
1305  * module_param_cb is introduced to take kernel_param_ops and
1306  * module_param_call is marked as obsolete. Also set and get operations
1307  * were changed to take a 'const struct kernel_param *'.
1308  */
1309 static int
1310 #ifdef module_param_cb
1311 param_set_taskq_kick(const char *val, const struct kernel_param *kp)
1312 #else
1313 param_set_taskq_kick(const char *val, struct kernel_param *kp)
1314 #endif
1315 {
1316 	int ret;
1317 	taskq_t *tq = NULL;
1318 	taskq_ent_t *t;
1319 	unsigned long flags;
1320 
1321 	ret = param_set_uint(val, kp);
1322 	if (ret < 0 || !spl_taskq_kick)
1323 		return (ret);
1324 	/* reset value */
1325 	spl_taskq_kick = 0;
1326 
1327 	down_read(&tq_list_sem);
1328 	list_for_each_entry(tq, &tq_list, tq_taskqs) {
1329 		spin_lock_irqsave_nested(&tq->tq_lock, flags,
1330 		    tq->tq_lock_class);
1331 		/* Check if the first pending is older than 5 seconds */
1332 		t = taskq_next_ent(tq);
1333 		if (t && time_after(jiffies, t->tqent_birth + 5*HZ)) {
1334 			(void) taskq_thread_spawn(tq);
1335 			printk(KERN_INFO "spl: Kicked taskq %s/%d\n",
1336 			    tq->tq_name, tq->tq_instance);
1337 		}
1338 		spin_unlock_irqrestore(&tq->tq_lock, flags);
1339 	}
1340 	up_read(&tq_list_sem);
1341 	return (ret);
1342 }
1343 
1344 #ifdef module_param_cb
1345 static const struct kernel_param_ops param_ops_taskq_kick = {
1346 	.set = param_set_taskq_kick,
1347 	.get = param_get_uint,
1348 };
1349 module_param_cb(spl_taskq_kick, &param_ops_taskq_kick, &spl_taskq_kick, 0644);
1350 #else
1351 module_param_call(spl_taskq_kick, param_set_taskq_kick, param_get_uint,
1352 	&spl_taskq_kick, 0644);
1353 #endif
1354 MODULE_PARM_DESC(spl_taskq_kick,
1355 	"Write nonzero to kick stuck taskqs to spawn more threads");
1356 
1357 #ifdef HAVE_CPU_HOTPLUG
1358 /*
1359  * This callback will be called exactly once for each core that comes online,
1360  * for each dynamic taskq. We attempt to expand taskqs that have
1361  * TASKQ_THREADS_CPU_PCT set. We need to redo the percentage calculation every
1362  * time, to correctly determine whether or not to add a thread.
1363  */
1364 static int
1365 spl_taskq_expand(unsigned int cpu, struct hlist_node *node)
1366 {
1367 	taskq_t *tq = list_entry(node, taskq_t, tq_hp_cb_node);
1368 	unsigned long flags;
1369 	int err = 0;
1370 
1371 	ASSERT(tq);
1372 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
1373 
1374 	if (!(tq->tq_flags & TASKQ_ACTIVE)) {
1375 		spin_unlock_irqrestore(&tq->tq_lock, flags);
1376 		return (err);
1377 	}
1378 
1379 	ASSERT(tq->tq_flags & TASKQ_THREADS_CPU_PCT);
1380 	int nthreads = MIN(tq->tq_cpu_pct, 100);
1381 	nthreads = MAX(((num_online_cpus() + 1) * nthreads) / 100, 1);
1382 	tq->tq_maxthreads = nthreads;
1383 
1384 	if (!((tq->tq_flags & TASKQ_DYNAMIC) && spl_taskq_thread_dynamic) &&
1385 	    tq->tq_maxthreads > tq->tq_nthreads) {
1386 		spin_unlock_irqrestore(&tq->tq_lock, flags);
1387 		taskq_thread_t *tqt = taskq_thread_create(tq);
1388 		if (tqt == NULL)
1389 			err = -1;
1390 		return (err);
1391 	}
1392 	spin_unlock_irqrestore(&tq->tq_lock, flags);
1393 	return (err);
1394 }
1395 
1396 /*
1397  * While we don't support offlining CPUs, it is possible that CPUs will fail
1398  * to online successfully. We do need to be able to handle this case
1399  * gracefully.
1400  */
1401 static int
1402 spl_taskq_prepare_down(unsigned int cpu, struct hlist_node *node)
1403 {
1404 	taskq_t *tq = list_entry(node, taskq_t, tq_hp_cb_node);
1405 	unsigned long flags;
1406 
1407 	ASSERT(tq);
1408 	spin_lock_irqsave_nested(&tq->tq_lock, flags, tq->tq_lock_class);
1409 
1410 	if (!(tq->tq_flags & TASKQ_ACTIVE))
1411 		goto out;
1412 
1413 	ASSERT(tq->tq_flags & TASKQ_THREADS_CPU_PCT);
1414 	int nthreads = MIN(tq->tq_cpu_pct, 100);
1415 	nthreads = MAX(((num_online_cpus()) * nthreads) / 100, 1);
1416 	tq->tq_maxthreads = nthreads;
1417 
1418 	if (!((tq->tq_flags & TASKQ_DYNAMIC) && spl_taskq_thread_dynamic) &&
1419 	    tq->tq_maxthreads < tq->tq_nthreads) {
1420 		ASSERT3U(tq->tq_maxthreads, ==, tq->tq_nthreads - 1);
1421 		taskq_thread_t *tqt = list_entry(tq->tq_thread_list.next,
1422 		    taskq_thread_t, tqt_thread_list);
1423 		struct task_struct *thread = tqt->tqt_thread;
1424 		spin_unlock_irqrestore(&tq->tq_lock, flags);
1425 
1426 		kthread_stop(thread);
1427 
1428 		return (0);
1429 	}
1430 
1431 out:
1432 	spin_unlock_irqrestore(&tq->tq_lock, flags);
1433 	return (0);
1434 }
1435 #endif
1436 
1437 int
1438 spl_taskq_init(void)
1439 {
1440 	init_rwsem(&tq_list_sem);
1441 	tsd_create(&taskq_tsd, NULL);
1442 
1443 #ifdef HAVE_CPU_HOTPLUG
1444 	spl_taskq_cpuhp_state = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
1445 	    "fs/spl_taskq:online", spl_taskq_expand, spl_taskq_prepare_down);
1446 #endif
1447 
1448 	system_taskq = taskq_create("spl_system_taskq", MAX(boot_ncpus, 64),
1449 	    maxclsyspri, boot_ncpus, INT_MAX, TASKQ_PREPOPULATE|TASKQ_DYNAMIC);
1450 	if (system_taskq == NULL)
1451 		return (-ENOMEM);
1452 
1453 	system_delay_taskq = taskq_create("spl_delay_taskq", MAX(boot_ncpus, 4),
1454 	    maxclsyspri, boot_ncpus, INT_MAX, TASKQ_PREPOPULATE|TASKQ_DYNAMIC);
1455 	if (system_delay_taskq == NULL) {
1456 #ifdef HAVE_CPU_HOTPLUG
1457 		cpuhp_remove_multi_state(spl_taskq_cpuhp_state);
1458 #endif
1459 		taskq_destroy(system_taskq);
1460 		return (-ENOMEM);
1461 	}
1462 
1463 	dynamic_taskq = taskq_create("spl_dynamic_taskq", 1,
1464 	    maxclsyspri, boot_ncpus, INT_MAX, TASKQ_PREPOPULATE);
1465 	if (dynamic_taskq == NULL) {
1466 #ifdef HAVE_CPU_HOTPLUG
1467 		cpuhp_remove_multi_state(spl_taskq_cpuhp_state);
1468 #endif
1469 		taskq_destroy(system_taskq);
1470 		taskq_destroy(system_delay_taskq);
1471 		return (-ENOMEM);
1472 	}
1473 
1474 	/*
1475 	 * This is used to annotate tq_lock, so
1476 	 *   taskq_dispatch -> taskq_thread_spawn -> taskq_dispatch
1477 	 * does not trigger a lockdep warning re: possible recursive locking
1478 	 */
1479 	dynamic_taskq->tq_lock_class = TQ_LOCK_DYNAMIC;
1480 
1481 	return (0);
1482 }
1483 
1484 void
1485 spl_taskq_fini(void)
1486 {
1487 	taskq_destroy(dynamic_taskq);
1488 	dynamic_taskq = NULL;
1489 
1490 	taskq_destroy(system_delay_taskq);
1491 	system_delay_taskq = NULL;
1492 
1493 	taskq_destroy(system_taskq);
1494 	system_taskq = NULL;
1495 
1496 	tsd_destroy(&taskq_tsd);
1497 
1498 #ifdef HAVE_CPU_HOTPLUG
1499 	cpuhp_remove_multi_state(spl_taskq_cpuhp_state);
1500 	spl_taskq_cpuhp_state = 0;
1501 #endif
1502 }
1503