xref: /freebsd/sys/kern/subr_taskqueue.c (revision 4b9d6057)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2000 Doug Rabson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/bus.h>
32 #include <sys/cpuset.h>
33 #include <sys/interrupt.h>
34 #include <sys/kernel.h>
35 #include <sys/kthread.h>
36 #include <sys/libkern.h>
37 #include <sys/limits.h>
38 #include <sys/lock.h>
39 #include <sys/malloc.h>
40 #include <sys/mutex.h>
41 #include <sys/proc.h>
42 #include <sys/epoch.h>
43 #include <sys/sched.h>
44 #include <sys/smp.h>
45 #include <sys/taskqueue.h>
46 #include <sys/unistd.h>
47 #include <machine/stdarg.h>
48 
49 static MALLOC_DEFINE(M_TASKQUEUE, "taskqueue", "Task Queues");
50 static void	*taskqueue_giant_ih;
51 static void	*taskqueue_ih;
52 static void	 taskqueue_fast_enqueue(void *);
53 static void	 taskqueue_swi_enqueue(void *);
54 static void	 taskqueue_swi_giant_enqueue(void *);
55 
56 struct taskqueue_busy {
57 	struct task		*tb_running;
58 	u_int			 tb_seq;
59 	bool			 tb_canceling;
60 	LIST_ENTRY(taskqueue_busy) tb_link;
61 };
62 
63 struct taskqueue {
64 	STAILQ_HEAD(, task)	tq_queue;
65 	LIST_HEAD(, taskqueue_busy) tq_active;
66 	struct task		*tq_hint;
67 	u_int			tq_seq;
68 	int			tq_callouts;
69 	struct mtx_padalign	tq_mutex;
70 	taskqueue_enqueue_fn	tq_enqueue;
71 	void			*tq_context;
72 	char			*tq_name;
73 	struct thread		**tq_threads;
74 	int			tq_tcount;
75 	int			tq_spin;
76 	int			tq_flags;
77 	taskqueue_callback_fn	tq_callbacks[TASKQUEUE_NUM_CALLBACKS];
78 	void			*tq_cb_contexts[TASKQUEUE_NUM_CALLBACKS];
79 };
80 
81 #define	TQ_FLAGS_ACTIVE		(1 << 0)
82 #define	TQ_FLAGS_BLOCKED	(1 << 1)
83 #define	TQ_FLAGS_UNLOCKED_ENQUEUE	(1 << 2)
84 
85 #define	DT_CALLOUT_ARMED	(1 << 0)
86 #define	DT_DRAIN_IN_PROGRESS	(1 << 1)
87 
88 #define	TQ_LOCK(tq)							\
89 	do {								\
90 		if ((tq)->tq_spin)					\
91 			mtx_lock_spin(&(tq)->tq_mutex);			\
92 		else							\
93 			mtx_lock(&(tq)->tq_mutex);			\
94 	} while (0)
95 #define	TQ_ASSERT_LOCKED(tq)	mtx_assert(&(tq)->tq_mutex, MA_OWNED)
96 
97 #define	TQ_UNLOCK(tq)							\
98 	do {								\
99 		if ((tq)->tq_spin)					\
100 			mtx_unlock_spin(&(tq)->tq_mutex);		\
101 		else							\
102 			mtx_unlock(&(tq)->tq_mutex);			\
103 	} while (0)
104 #define	TQ_ASSERT_UNLOCKED(tq)	mtx_assert(&(tq)->tq_mutex, MA_NOTOWNED)
105 
106 void
107 _timeout_task_init(struct taskqueue *queue, struct timeout_task *timeout_task,
108     int priority, task_fn_t func, void *context)
109 {
110 
111 	TASK_INIT(&timeout_task->t, priority, func, context);
112 	callout_init_mtx(&timeout_task->c, &queue->tq_mutex,
113 	    CALLOUT_RETURNUNLOCKED);
114 	timeout_task->q = queue;
115 	timeout_task->f = 0;
116 }
117 
118 static __inline int
119 TQ_SLEEP(struct taskqueue *tq, void *p, const char *wm)
120 {
121 	if (tq->tq_spin)
122 		return (msleep_spin(p, (struct mtx *)&tq->tq_mutex, wm, 0));
123 	return (msleep(p, &tq->tq_mutex, 0, wm, 0));
124 }
125 
126 static struct taskqueue_busy *
127 task_get_busy(struct taskqueue *queue, struct task *task)
128 {
129 	struct taskqueue_busy *tb;
130 
131 	TQ_ASSERT_LOCKED(queue);
132 	LIST_FOREACH(tb, &queue->tq_active, tb_link) {
133 		if (tb->tb_running == task)
134 			return (tb);
135 	}
136 	return (NULL);
137 }
138 
139 static struct taskqueue *
140 _taskqueue_create(const char *name, int mflags,
141 		 taskqueue_enqueue_fn enqueue, void *context,
142 		 int mtxflags, const char *mtxname __unused)
143 {
144 	struct taskqueue *queue;
145 	char *tq_name;
146 
147 	tq_name = malloc(TASKQUEUE_NAMELEN, M_TASKQUEUE, mflags | M_ZERO);
148 	if (tq_name == NULL)
149 		return (NULL);
150 
151 	queue = malloc(sizeof(struct taskqueue), M_TASKQUEUE, mflags | M_ZERO);
152 	if (queue == NULL) {
153 		free(tq_name, M_TASKQUEUE);
154 		return (NULL);
155 	}
156 
157 	snprintf(tq_name, TASKQUEUE_NAMELEN, "%s", (name) ? name : "taskqueue");
158 
159 	STAILQ_INIT(&queue->tq_queue);
160 	LIST_INIT(&queue->tq_active);
161 	queue->tq_enqueue = enqueue;
162 	queue->tq_context = context;
163 	queue->tq_name = tq_name;
164 	queue->tq_spin = (mtxflags & MTX_SPIN) != 0;
165 	queue->tq_flags |= TQ_FLAGS_ACTIVE;
166 	if (enqueue == taskqueue_fast_enqueue ||
167 	    enqueue == taskqueue_swi_enqueue ||
168 	    enqueue == taskqueue_swi_giant_enqueue ||
169 	    enqueue == taskqueue_thread_enqueue)
170 		queue->tq_flags |= TQ_FLAGS_UNLOCKED_ENQUEUE;
171 	mtx_init(&queue->tq_mutex, tq_name, NULL, mtxflags);
172 
173 	return (queue);
174 }
175 
176 struct taskqueue *
177 taskqueue_create(const char *name, int mflags,
178 		 taskqueue_enqueue_fn enqueue, void *context)
179 {
180 
181 	return _taskqueue_create(name, mflags, enqueue, context,
182 			MTX_DEF, name);
183 }
184 
185 void
186 taskqueue_set_callback(struct taskqueue *queue,
187     enum taskqueue_callback_type cb_type, taskqueue_callback_fn callback,
188     void *context)
189 {
190 
191 	KASSERT(((cb_type >= TASKQUEUE_CALLBACK_TYPE_MIN) &&
192 	    (cb_type <= TASKQUEUE_CALLBACK_TYPE_MAX)),
193 	    ("Callback type %d not valid, must be %d-%d", cb_type,
194 	    TASKQUEUE_CALLBACK_TYPE_MIN, TASKQUEUE_CALLBACK_TYPE_MAX));
195 	KASSERT((queue->tq_callbacks[cb_type] == NULL),
196 	    ("Re-initialization of taskqueue callback?"));
197 
198 	queue->tq_callbacks[cb_type] = callback;
199 	queue->tq_cb_contexts[cb_type] = context;
200 }
201 
202 /*
203  * Signal a taskqueue thread to terminate.
204  */
205 static void
206 taskqueue_terminate(struct thread **pp, struct taskqueue *tq)
207 {
208 
209 	while (tq->tq_tcount > 0 || tq->tq_callouts > 0) {
210 		wakeup(tq);
211 		TQ_SLEEP(tq, pp, "tq_destroy");
212 	}
213 }
214 
215 void
216 taskqueue_free(struct taskqueue *queue)
217 {
218 
219 	TQ_LOCK(queue);
220 	queue->tq_flags &= ~TQ_FLAGS_ACTIVE;
221 	taskqueue_terminate(queue->tq_threads, queue);
222 	KASSERT(LIST_EMPTY(&queue->tq_active), ("Tasks still running?"));
223 	KASSERT(queue->tq_callouts == 0, ("Armed timeout tasks"));
224 	mtx_destroy(&queue->tq_mutex);
225 	free(queue->tq_threads, M_TASKQUEUE);
226 	free(queue->tq_name, M_TASKQUEUE);
227 	free(queue, M_TASKQUEUE);
228 }
229 
230 static int
231 taskqueue_enqueue_locked(struct taskqueue *queue, struct task *task, int flags)
232 {
233 	struct task *ins;
234 	struct task *prev;
235 	struct taskqueue_busy *tb;
236 
237 	KASSERT(task->ta_func != NULL, ("enqueueing task with NULL func"));
238 	/*
239 	 * Ignore canceling task if requested.
240 	 */
241 	if (__predict_false((flags & TASKQUEUE_FAIL_IF_CANCELING) != 0)) {
242 		tb = task_get_busy(queue, task);
243 		if (tb != NULL && tb->tb_canceling) {
244 			TQ_UNLOCK(queue);
245 			return (ECANCELED);
246 		}
247 	}
248 
249 	/*
250 	 * Count multiple enqueues.
251 	 */
252 	if (task->ta_pending) {
253 		if (__predict_false((flags & TASKQUEUE_FAIL_IF_PENDING) != 0)) {
254 			TQ_UNLOCK(queue);
255 			return (EEXIST);
256 		}
257 		if (task->ta_pending < USHRT_MAX)
258 			task->ta_pending++;
259 		TQ_UNLOCK(queue);
260 		return (0);
261 	}
262 
263 	/*
264 	 * Optimise cases when all tasks use small set of priorities.
265 	 * In case of only one priority we always insert at the end.
266 	 * In case of two tq_hint typically gives the insertion point.
267 	 * In case of more then two tq_hint should halve the search.
268 	 */
269 	prev = STAILQ_LAST(&queue->tq_queue, task, ta_link);
270 	if (!prev || prev->ta_priority >= task->ta_priority) {
271 		STAILQ_INSERT_TAIL(&queue->tq_queue, task, ta_link);
272 	} else {
273 		prev = queue->tq_hint;
274 		if (prev && prev->ta_priority >= task->ta_priority) {
275 			ins = STAILQ_NEXT(prev, ta_link);
276 		} else {
277 			prev = NULL;
278 			ins = STAILQ_FIRST(&queue->tq_queue);
279 		}
280 		for (; ins; prev = ins, ins = STAILQ_NEXT(ins, ta_link))
281 			if (ins->ta_priority < task->ta_priority)
282 				break;
283 
284 		if (prev) {
285 			STAILQ_INSERT_AFTER(&queue->tq_queue, prev, task, ta_link);
286 			queue->tq_hint = task;
287 		} else
288 			STAILQ_INSERT_HEAD(&queue->tq_queue, task, ta_link);
289 	}
290 
291 	task->ta_pending = 1;
292 	if ((queue->tq_flags & TQ_FLAGS_UNLOCKED_ENQUEUE) != 0)
293 		TQ_UNLOCK(queue);
294 	if ((queue->tq_flags & TQ_FLAGS_BLOCKED) == 0)
295 		queue->tq_enqueue(queue->tq_context);
296 	if ((queue->tq_flags & TQ_FLAGS_UNLOCKED_ENQUEUE) == 0)
297 		TQ_UNLOCK(queue);
298 
299 	/* Return with lock released. */
300 	return (0);
301 }
302 
303 int
304 taskqueue_enqueue_flags(struct taskqueue *queue, struct task *task, int flags)
305 {
306 	int res;
307 
308 	TQ_LOCK(queue);
309 	res = taskqueue_enqueue_locked(queue, task, flags);
310 	/* The lock is released inside. */
311 
312 	return (res);
313 }
314 
315 int
316 taskqueue_enqueue(struct taskqueue *queue, struct task *task)
317 {
318 	return (taskqueue_enqueue_flags(queue, task, 0));
319 }
320 
321 static void
322 taskqueue_timeout_func(void *arg)
323 {
324 	struct taskqueue *queue;
325 	struct timeout_task *timeout_task;
326 
327 	timeout_task = arg;
328 	queue = timeout_task->q;
329 	KASSERT((timeout_task->f & DT_CALLOUT_ARMED) != 0, ("Stray timeout"));
330 	timeout_task->f &= ~DT_CALLOUT_ARMED;
331 	queue->tq_callouts--;
332 	taskqueue_enqueue_locked(timeout_task->q, &timeout_task->t, 0);
333 	/* The lock is released inside. */
334 }
335 
336 int
337 taskqueue_enqueue_timeout_sbt(struct taskqueue *queue,
338     struct timeout_task *timeout_task, sbintime_t sbt, sbintime_t pr, int flags)
339 {
340 	int res;
341 
342 	TQ_LOCK(queue);
343 	KASSERT(timeout_task->q == NULL || timeout_task->q == queue,
344 	    ("Migrated queue"));
345 	timeout_task->q = queue;
346 	res = timeout_task->t.ta_pending;
347 	if (timeout_task->f & DT_DRAIN_IN_PROGRESS) {
348 		/* Do nothing */
349 		TQ_UNLOCK(queue);
350 		res = -1;
351 	} else if (sbt == 0) {
352 		taskqueue_enqueue_locked(queue, &timeout_task->t, 0);
353 		/* The lock is released inside. */
354 	} else {
355 		if ((timeout_task->f & DT_CALLOUT_ARMED) != 0) {
356 			res++;
357 		} else {
358 			queue->tq_callouts++;
359 			timeout_task->f |= DT_CALLOUT_ARMED;
360 			if (sbt < 0)
361 				sbt = -sbt; /* Ignore overflow. */
362 		}
363 		if (sbt > 0) {
364 			if (queue->tq_spin)
365 				flags |= C_DIRECT_EXEC;
366 			callout_reset_sbt(&timeout_task->c, sbt, pr,
367 			    taskqueue_timeout_func, timeout_task, flags);
368 		}
369 		TQ_UNLOCK(queue);
370 	}
371 	return (res);
372 }
373 
374 int
375 taskqueue_enqueue_timeout(struct taskqueue *queue,
376     struct timeout_task *ttask, int ticks)
377 {
378 
379 	return (taskqueue_enqueue_timeout_sbt(queue, ttask, ticks * tick_sbt,
380 	    0, C_HARDCLOCK));
381 }
382 
383 static void
384 taskqueue_task_nop_fn(void *context, int pending)
385 {
386 }
387 
388 /*
389  * Block until all currently queued tasks in this taskqueue
390  * have begun execution.  Tasks queued during execution of
391  * this function are ignored.
392  */
393 static int
394 taskqueue_drain_tq_queue(struct taskqueue *queue)
395 {
396 	struct task t_barrier;
397 
398 	if (STAILQ_EMPTY(&queue->tq_queue))
399 		return (0);
400 
401 	/*
402 	 * Enqueue our barrier after all current tasks, but with
403 	 * the highest priority so that newly queued tasks cannot
404 	 * pass it.  Because of the high priority, we can not use
405 	 * taskqueue_enqueue_locked directly (which drops the lock
406 	 * anyway) so just insert it at tail while we have the
407 	 * queue lock.
408 	 */
409 	TASK_INIT(&t_barrier, UCHAR_MAX, taskqueue_task_nop_fn, &t_barrier);
410 	STAILQ_INSERT_TAIL(&queue->tq_queue, &t_barrier, ta_link);
411 	queue->tq_hint = &t_barrier;
412 	t_barrier.ta_pending = 1;
413 
414 	/*
415 	 * Once the barrier has executed, all previously queued tasks
416 	 * have completed or are currently executing.
417 	 */
418 	while (t_barrier.ta_pending != 0)
419 		TQ_SLEEP(queue, &t_barrier, "tq_qdrain");
420 	return (1);
421 }
422 
423 /*
424  * Block until all currently executing tasks for this taskqueue
425  * complete.  Tasks that begin execution during the execution
426  * of this function are ignored.
427  */
428 static int
429 taskqueue_drain_tq_active(struct taskqueue *queue)
430 {
431 	struct taskqueue_busy *tb;
432 	u_int seq;
433 
434 	if (LIST_EMPTY(&queue->tq_active))
435 		return (0);
436 
437 	/* Block taskq_terminate().*/
438 	queue->tq_callouts++;
439 
440 	/* Wait for any active task with sequence from the past. */
441 	seq = queue->tq_seq;
442 restart:
443 	LIST_FOREACH(tb, &queue->tq_active, tb_link) {
444 		if ((int)(tb->tb_seq - seq) <= 0) {
445 			TQ_SLEEP(queue, tb->tb_running, "tq_adrain");
446 			goto restart;
447 		}
448 	}
449 
450 	/* Release taskqueue_terminate(). */
451 	queue->tq_callouts--;
452 	if ((queue->tq_flags & TQ_FLAGS_ACTIVE) == 0)
453 		wakeup_one(queue->tq_threads);
454 	return (1);
455 }
456 
457 void
458 taskqueue_block(struct taskqueue *queue)
459 {
460 
461 	TQ_LOCK(queue);
462 	queue->tq_flags |= TQ_FLAGS_BLOCKED;
463 	TQ_UNLOCK(queue);
464 }
465 
466 void
467 taskqueue_unblock(struct taskqueue *queue)
468 {
469 
470 	TQ_LOCK(queue);
471 	queue->tq_flags &= ~TQ_FLAGS_BLOCKED;
472 	if (!STAILQ_EMPTY(&queue->tq_queue))
473 		queue->tq_enqueue(queue->tq_context);
474 	TQ_UNLOCK(queue);
475 }
476 
477 static void
478 taskqueue_run_locked(struct taskqueue *queue)
479 {
480 	struct epoch_tracker et;
481 	struct taskqueue_busy tb;
482 	struct task *task;
483 	bool in_net_epoch;
484 	int pending;
485 
486 	KASSERT(queue != NULL, ("tq is NULL"));
487 	TQ_ASSERT_LOCKED(queue);
488 	tb.tb_running = NULL;
489 	LIST_INSERT_HEAD(&queue->tq_active, &tb, tb_link);
490 	in_net_epoch = false;
491 
492 	while ((task = STAILQ_FIRST(&queue->tq_queue)) != NULL) {
493 		STAILQ_REMOVE_HEAD(&queue->tq_queue, ta_link);
494 		if (queue->tq_hint == task)
495 			queue->tq_hint = NULL;
496 		pending = task->ta_pending;
497 		task->ta_pending = 0;
498 		tb.tb_running = task;
499 		tb.tb_seq = ++queue->tq_seq;
500 		tb.tb_canceling = false;
501 		TQ_UNLOCK(queue);
502 
503 		KASSERT(task->ta_func != NULL, ("task->ta_func is NULL"));
504 		if (!in_net_epoch && TASK_IS_NET(task)) {
505 			in_net_epoch = true;
506 			NET_EPOCH_ENTER(et);
507 		} else if (in_net_epoch && !TASK_IS_NET(task)) {
508 			NET_EPOCH_EXIT(et);
509 			in_net_epoch = false;
510 		}
511 		task->ta_func(task->ta_context, pending);
512 
513 		TQ_LOCK(queue);
514 		wakeup(task);
515 	}
516 	if (in_net_epoch)
517 		NET_EPOCH_EXIT(et);
518 	LIST_REMOVE(&tb, tb_link);
519 }
520 
521 void
522 taskqueue_run(struct taskqueue *queue)
523 {
524 
525 	TQ_LOCK(queue);
526 	taskqueue_run_locked(queue);
527 	TQ_UNLOCK(queue);
528 }
529 
530 /*
531  * Only use this function in single threaded contexts. It returns
532  * non-zero if the given task is either pending or running. Else the
533  * task is idle and can be queued again or freed.
534  */
535 int
536 taskqueue_poll_is_busy(struct taskqueue *queue, struct task *task)
537 {
538 	int retval;
539 
540 	TQ_LOCK(queue);
541 	retval = task->ta_pending > 0 || task_get_busy(queue, task) != NULL;
542 	TQ_UNLOCK(queue);
543 
544 	return (retval);
545 }
546 
547 static int
548 taskqueue_cancel_locked(struct taskqueue *queue, struct task *task,
549     u_int *pendp)
550 {
551 	struct taskqueue_busy *tb;
552 	int retval = 0;
553 
554 	if (task->ta_pending > 0) {
555 		STAILQ_REMOVE(&queue->tq_queue, task, task, ta_link);
556 		if (queue->tq_hint == task)
557 			queue->tq_hint = NULL;
558 	}
559 	if (pendp != NULL)
560 		*pendp = task->ta_pending;
561 	task->ta_pending = 0;
562 	tb = task_get_busy(queue, task);
563 	if (tb != NULL) {
564 		tb->tb_canceling = true;
565 		retval = EBUSY;
566 	}
567 
568 	return (retval);
569 }
570 
571 int
572 taskqueue_cancel(struct taskqueue *queue, struct task *task, u_int *pendp)
573 {
574 	int error;
575 
576 	TQ_LOCK(queue);
577 	error = taskqueue_cancel_locked(queue, task, pendp);
578 	TQ_UNLOCK(queue);
579 
580 	return (error);
581 }
582 
583 int
584 taskqueue_cancel_timeout(struct taskqueue *queue,
585     struct timeout_task *timeout_task, u_int *pendp)
586 {
587 	u_int pending, pending1;
588 	int error;
589 
590 	TQ_LOCK(queue);
591 	pending = !!(callout_stop(&timeout_task->c) > 0);
592 	error = taskqueue_cancel_locked(queue, &timeout_task->t, &pending1);
593 	if ((timeout_task->f & DT_CALLOUT_ARMED) != 0) {
594 		timeout_task->f &= ~DT_CALLOUT_ARMED;
595 		queue->tq_callouts--;
596 	}
597 	TQ_UNLOCK(queue);
598 
599 	if (pendp != NULL)
600 		*pendp = pending + pending1;
601 	return (error);
602 }
603 
604 void
605 taskqueue_drain(struct taskqueue *queue, struct task *task)
606 {
607 
608 	if (!queue->tq_spin)
609 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, __func__);
610 
611 	TQ_LOCK(queue);
612 	while (task->ta_pending != 0 || task_get_busy(queue, task) != NULL)
613 		TQ_SLEEP(queue, task, "tq_drain");
614 	TQ_UNLOCK(queue);
615 }
616 
617 void
618 taskqueue_drain_all(struct taskqueue *queue)
619 {
620 
621 	if (!queue->tq_spin)
622 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, __func__);
623 
624 	TQ_LOCK(queue);
625 	(void)taskqueue_drain_tq_queue(queue);
626 	(void)taskqueue_drain_tq_active(queue);
627 	TQ_UNLOCK(queue);
628 }
629 
630 void
631 taskqueue_drain_timeout(struct taskqueue *queue,
632     struct timeout_task *timeout_task)
633 {
634 
635 	/*
636 	 * Set flag to prevent timer from re-starting during drain:
637 	 */
638 	TQ_LOCK(queue);
639 	KASSERT((timeout_task->f & DT_DRAIN_IN_PROGRESS) == 0,
640 	    ("Drain already in progress"));
641 	timeout_task->f |= DT_DRAIN_IN_PROGRESS;
642 	TQ_UNLOCK(queue);
643 
644 	callout_drain(&timeout_task->c);
645 	taskqueue_drain(queue, &timeout_task->t);
646 
647 	/*
648 	 * Clear flag to allow timer to re-start:
649 	 */
650 	TQ_LOCK(queue);
651 	timeout_task->f &= ~DT_DRAIN_IN_PROGRESS;
652 	TQ_UNLOCK(queue);
653 }
654 
655 void
656 taskqueue_quiesce(struct taskqueue *queue)
657 {
658 	int ret;
659 
660 	TQ_LOCK(queue);
661 	do {
662 		ret = taskqueue_drain_tq_queue(queue);
663 		if (ret == 0)
664 			ret = taskqueue_drain_tq_active(queue);
665 	} while (ret != 0);
666 	TQ_UNLOCK(queue);
667 }
668 
669 static void
670 taskqueue_swi_enqueue(void *context)
671 {
672 	swi_sched(taskqueue_ih, 0);
673 }
674 
675 static void
676 taskqueue_swi_run(void *dummy)
677 {
678 	taskqueue_run(taskqueue_swi);
679 }
680 
681 static void
682 taskqueue_swi_giant_enqueue(void *context)
683 {
684 	swi_sched(taskqueue_giant_ih, 0);
685 }
686 
687 static void
688 taskqueue_swi_giant_run(void *dummy)
689 {
690 	taskqueue_run(taskqueue_swi_giant);
691 }
692 
693 static int
694 _taskqueue_start_threads(struct taskqueue **tqp, int count, int pri,
695     cpuset_t *mask, struct proc *p, const char *name, va_list ap)
696 {
697 	char ktname[MAXCOMLEN + 1];
698 	struct thread *td;
699 	struct taskqueue *tq;
700 	int i, error;
701 
702 	if (count <= 0)
703 		return (EINVAL);
704 
705 	vsnprintf(ktname, sizeof(ktname), name, ap);
706 	tq = *tqp;
707 
708 	tq->tq_threads = malloc(sizeof(struct thread *) * count, M_TASKQUEUE,
709 	    M_NOWAIT | M_ZERO);
710 	if (tq->tq_threads == NULL) {
711 		printf("%s: no memory for %s threads\n", __func__, ktname);
712 		return (ENOMEM);
713 	}
714 
715 	for (i = 0; i < count; i++) {
716 		if (count == 1)
717 			error = kthread_add(taskqueue_thread_loop, tqp, p,
718 			    &tq->tq_threads[i], RFSTOPPED, 0, "%s", ktname);
719 		else
720 			error = kthread_add(taskqueue_thread_loop, tqp, p,
721 			    &tq->tq_threads[i], RFSTOPPED, 0,
722 			    "%s_%d", ktname, i);
723 		if (error) {
724 			/* should be ok to continue, taskqueue_free will dtrt */
725 			printf("%s: kthread_add(%s): error %d", __func__,
726 			    ktname, error);
727 			tq->tq_threads[i] = NULL;		/* paranoid */
728 		} else
729 			tq->tq_tcount++;
730 	}
731 	if (tq->tq_tcount == 0) {
732 		free(tq->tq_threads, M_TASKQUEUE);
733 		tq->tq_threads = NULL;
734 		return (ENOMEM);
735 	}
736 	for (i = 0; i < count; i++) {
737 		if (tq->tq_threads[i] == NULL)
738 			continue;
739 		td = tq->tq_threads[i];
740 		if (mask) {
741 			error = cpuset_setthread(td->td_tid, mask);
742 			/*
743 			 * Failing to pin is rarely an actual fatal error;
744 			 * it'll just affect performance.
745 			 */
746 			if (error)
747 				printf("%s: curthread=%llu: can't pin; "
748 				    "error=%d\n",
749 				    __func__,
750 				    (unsigned long long) td->td_tid,
751 				    error);
752 		}
753 		thread_lock(td);
754 		sched_prio(td, pri);
755 		sched_add(td, SRQ_BORING);
756 	}
757 
758 	return (0);
759 }
760 
761 int
762 taskqueue_start_threads(struct taskqueue **tqp, int count, int pri,
763     const char *name, ...)
764 {
765 	va_list ap;
766 	int error;
767 
768 	va_start(ap, name);
769 	error = _taskqueue_start_threads(tqp, count, pri, NULL, NULL, name, ap);
770 	va_end(ap);
771 	return (error);
772 }
773 
774 int
775 taskqueue_start_threads_in_proc(struct taskqueue **tqp, int count, int pri,
776     struct proc *proc, const char *name, ...)
777 {
778 	va_list ap;
779 	int error;
780 
781 	va_start(ap, name);
782 	error = _taskqueue_start_threads(tqp, count, pri, NULL, proc, name, ap);
783 	va_end(ap);
784 	return (error);
785 }
786 
787 int
788 taskqueue_start_threads_cpuset(struct taskqueue **tqp, int count, int pri,
789     cpuset_t *mask, const char *name, ...)
790 {
791 	va_list ap;
792 	int error;
793 
794 	va_start(ap, name);
795 	error = _taskqueue_start_threads(tqp, count, pri, mask, NULL, name, ap);
796 	va_end(ap);
797 	return (error);
798 }
799 
800 static inline void
801 taskqueue_run_callback(struct taskqueue *tq,
802     enum taskqueue_callback_type cb_type)
803 {
804 	taskqueue_callback_fn tq_callback;
805 
806 	TQ_ASSERT_UNLOCKED(tq);
807 	tq_callback = tq->tq_callbacks[cb_type];
808 	if (tq_callback != NULL)
809 		tq_callback(tq->tq_cb_contexts[cb_type]);
810 }
811 
812 void
813 taskqueue_thread_loop(void *arg)
814 {
815 	struct taskqueue **tqp, *tq;
816 
817 	tqp = arg;
818 	tq = *tqp;
819 	taskqueue_run_callback(tq, TASKQUEUE_CALLBACK_TYPE_INIT);
820 	TQ_LOCK(tq);
821 	while ((tq->tq_flags & TQ_FLAGS_ACTIVE) != 0) {
822 		/* XXX ? */
823 		taskqueue_run_locked(tq);
824 		/*
825 		 * Because taskqueue_run() can drop tq_mutex, we need to
826 		 * check if the TQ_FLAGS_ACTIVE flag wasn't removed in the
827 		 * meantime, which means we missed a wakeup.
828 		 */
829 		if ((tq->tq_flags & TQ_FLAGS_ACTIVE) == 0)
830 			break;
831 		TQ_SLEEP(tq, tq, "-");
832 	}
833 	taskqueue_run_locked(tq);
834 	/*
835 	 * This thread is on its way out, so just drop the lock temporarily
836 	 * in order to call the shutdown callback.  This allows the callback
837 	 * to look at the taskqueue, even just before it dies.
838 	 */
839 	TQ_UNLOCK(tq);
840 	taskqueue_run_callback(tq, TASKQUEUE_CALLBACK_TYPE_SHUTDOWN);
841 	TQ_LOCK(tq);
842 
843 	/* rendezvous with thread that asked us to terminate */
844 	tq->tq_tcount--;
845 	wakeup_one(tq->tq_threads);
846 	TQ_UNLOCK(tq);
847 	kthread_exit();
848 }
849 
850 void
851 taskqueue_thread_enqueue(void *context)
852 {
853 	struct taskqueue **tqp, *tq;
854 
855 	tqp = context;
856 	tq = *tqp;
857 	wakeup_any(tq);
858 }
859 
860 TASKQUEUE_DEFINE(swi, taskqueue_swi_enqueue, NULL,
861 		 swi_add(NULL, "task queue", taskqueue_swi_run, NULL, SWI_TQ,
862 		     INTR_MPSAFE, &taskqueue_ih));
863 
864 TASKQUEUE_DEFINE(swi_giant, taskqueue_swi_giant_enqueue, NULL,
865 		 swi_add(NULL, "Giant taskq", taskqueue_swi_giant_run,
866 		     NULL, SWI_TQ_GIANT, 0, &taskqueue_giant_ih));
867 
868 TASKQUEUE_DEFINE_THREAD(thread);
869 
870 struct taskqueue *
871 taskqueue_create_fast(const char *name, int mflags,
872 		 taskqueue_enqueue_fn enqueue, void *context)
873 {
874 	return _taskqueue_create(name, mflags, enqueue, context,
875 			MTX_SPIN, "fast_taskqueue");
876 }
877 
878 static void	*taskqueue_fast_ih;
879 
880 static void
881 taskqueue_fast_enqueue(void *context)
882 {
883 	swi_sched(taskqueue_fast_ih, 0);
884 }
885 
886 static void
887 taskqueue_fast_run(void *dummy)
888 {
889 	taskqueue_run(taskqueue_fast);
890 }
891 
892 TASKQUEUE_FAST_DEFINE(fast, taskqueue_fast_enqueue, NULL,
893 	swi_add(NULL, "fast taskq", taskqueue_fast_run, NULL,
894 	SWI_TQ_FAST, INTR_MPSAFE, &taskqueue_fast_ih));
895 
896 int
897 taskqueue_member(struct taskqueue *queue, struct thread *td)
898 {
899 	int i, j, ret = 0;
900 
901 	for (i = 0, j = 0; ; i++) {
902 		if (queue->tq_threads[i] == NULL)
903 			continue;
904 		if (queue->tq_threads[i] == td) {
905 			ret = 1;
906 			break;
907 		}
908 		if (++j >= queue->tq_tcount)
909 			break;
910 	}
911 	return (ret);
912 }
913