2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2000 Doug Rabson
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/param.h>
33 #include <sys/systm.h>
35 #include <sys/cpuset.h>
36 #include <sys/interrupt.h>
37 #include <sys/kernel.h>
38 #include <sys/kthread.h>
39 #include <sys/libkern.h>
40 #include <sys/limits.h>
42 #include <sys/malloc.h>
43 #include <sys/mutex.h>
45 #include <sys/sched.h>
47 #include <sys/taskqueue.h>
48 #include <sys/unistd.h>
49 #include <machine/stdarg.h>
51 static MALLOC_DEFINE(M_TASKQUEUE, "taskqueue", "Task Queues");
52 static void *taskqueue_giant_ih;
53 static void *taskqueue_ih;
54 static void taskqueue_fast_enqueue(void *);
55 static void taskqueue_swi_enqueue(void *);
56 static void taskqueue_swi_giant_enqueue(void *);
58 struct taskqueue_busy {
59 struct task *tb_running;
61 LIST_ENTRY(taskqueue_busy) tb_link;
65 STAILQ_HEAD(, task) tq_queue;
66 LIST_HEAD(, taskqueue_busy) tq_active;
70 struct mtx_padalign tq_mutex;
71 taskqueue_enqueue_fn tq_enqueue;
74 struct thread **tq_threads;
78 taskqueue_callback_fn tq_callbacks[TASKQUEUE_NUM_CALLBACKS];
79 void *tq_cb_contexts[TASKQUEUE_NUM_CALLBACKS];
82 #define TQ_FLAGS_ACTIVE (1 << 0)
83 #define TQ_FLAGS_BLOCKED (1 << 1)
84 #define TQ_FLAGS_UNLOCKED_ENQUEUE (1 << 2)
86 #define DT_CALLOUT_ARMED (1 << 0)
87 #define DT_DRAIN_IN_PROGRESS (1 << 1)
92 mtx_lock_spin(&(tq)->tq_mutex); \
94 mtx_lock(&(tq)->tq_mutex); \
96 #define TQ_ASSERT_LOCKED(tq) mtx_assert(&(tq)->tq_mutex, MA_OWNED)
98 #define TQ_UNLOCK(tq) \
101 mtx_unlock_spin(&(tq)->tq_mutex); \
103 mtx_unlock(&(tq)->tq_mutex); \
105 #define TQ_ASSERT_UNLOCKED(tq) mtx_assert(&(tq)->tq_mutex, MA_NOTOWNED)
108 _timeout_task_init(struct taskqueue *queue, struct timeout_task *timeout_task,
109 int priority, task_fn_t func, void *context)
112 TASK_INIT(&timeout_task->t, priority, func, context);
113 callout_init_mtx(&timeout_task->c, &queue->tq_mutex,
114 CALLOUT_RETURNUNLOCKED);
115 timeout_task->q = queue;
120 TQ_SLEEP(struct taskqueue *tq, void *p, const char *wm)
123 return (msleep_spin(p, (struct mtx *)&tq->tq_mutex, wm, 0));
124 return (msleep(p, &tq->tq_mutex, 0, wm, 0));
127 static struct taskqueue *
128 _taskqueue_create(const char *name, int mflags,
129 taskqueue_enqueue_fn enqueue, void *context,
130 int mtxflags, const char *mtxname __unused)
132 struct taskqueue *queue;
135 tq_name = malloc(TASKQUEUE_NAMELEN, M_TASKQUEUE, mflags | M_ZERO);
139 queue = malloc(sizeof(struct taskqueue), M_TASKQUEUE, mflags | M_ZERO);
141 free(tq_name, M_TASKQUEUE);
145 snprintf(tq_name, TASKQUEUE_NAMELEN, "%s", (name) ? name : "taskqueue");
147 STAILQ_INIT(&queue->tq_queue);
148 LIST_INIT(&queue->tq_active);
149 queue->tq_enqueue = enqueue;
150 queue->tq_context = context;
151 queue->tq_name = tq_name;
152 queue->tq_spin = (mtxflags & MTX_SPIN) != 0;
153 queue->tq_flags |= TQ_FLAGS_ACTIVE;
154 if (enqueue == taskqueue_fast_enqueue ||
155 enqueue == taskqueue_swi_enqueue ||
156 enqueue == taskqueue_swi_giant_enqueue ||
157 enqueue == taskqueue_thread_enqueue)
158 queue->tq_flags |= TQ_FLAGS_UNLOCKED_ENQUEUE;
159 mtx_init(&queue->tq_mutex, tq_name, NULL, mtxflags);
165 taskqueue_create(const char *name, int mflags,
166 taskqueue_enqueue_fn enqueue, void *context)
169 return _taskqueue_create(name, mflags, enqueue, context,
174 taskqueue_set_callback(struct taskqueue *queue,
175 enum taskqueue_callback_type cb_type, taskqueue_callback_fn callback,
179 KASSERT(((cb_type >= TASKQUEUE_CALLBACK_TYPE_MIN) &&
180 (cb_type <= TASKQUEUE_CALLBACK_TYPE_MAX)),
181 ("Callback type %d not valid, must be %d-%d", cb_type,
182 TASKQUEUE_CALLBACK_TYPE_MIN, TASKQUEUE_CALLBACK_TYPE_MAX));
183 KASSERT((queue->tq_callbacks[cb_type] == NULL),
184 ("Re-initialization of taskqueue callback?"));
186 queue->tq_callbacks[cb_type] = callback;
187 queue->tq_cb_contexts[cb_type] = context;
191 * Signal a taskqueue thread to terminate.
194 taskqueue_terminate(struct thread **pp, struct taskqueue *tq)
197 while (tq->tq_tcount > 0 || tq->tq_callouts > 0) {
199 TQ_SLEEP(tq, pp, "tq_destroy");
204 taskqueue_free(struct taskqueue *queue)
208 queue->tq_flags &= ~TQ_FLAGS_ACTIVE;
209 taskqueue_terminate(queue->tq_threads, queue);
210 KASSERT(LIST_EMPTY(&queue->tq_active), ("Tasks still running?"));
211 KASSERT(queue->tq_callouts == 0, ("Armed timeout tasks"));
212 mtx_destroy(&queue->tq_mutex);
213 free(queue->tq_threads, M_TASKQUEUE);
214 free(queue->tq_name, M_TASKQUEUE);
215 free(queue, M_TASKQUEUE);
219 taskqueue_enqueue_locked(struct taskqueue *queue, struct task *task)
224 KASSERT(task->ta_func != NULL, ("enqueueing task with NULL func"));
226 * Count multiple enqueues.
228 if (task->ta_pending) {
229 if (task->ta_pending < USHRT_MAX)
236 * Optimise cases when all tasks use small set of priorities.
237 * In case of only one priority we always insert at the end.
238 * In case of two tq_hint typically gives the insertion point.
239 * In case of more then two tq_hint should halve the search.
241 prev = STAILQ_LAST(&queue->tq_queue, task, ta_link);
242 if (!prev || prev->ta_priority >= task->ta_priority) {
243 STAILQ_INSERT_TAIL(&queue->tq_queue, task, ta_link);
245 prev = queue->tq_hint;
246 if (prev && prev->ta_priority >= task->ta_priority) {
247 ins = STAILQ_NEXT(prev, ta_link);
250 ins = STAILQ_FIRST(&queue->tq_queue);
252 for (; ins; prev = ins, ins = STAILQ_NEXT(ins, ta_link))
253 if (ins->ta_priority < task->ta_priority)
257 STAILQ_INSERT_AFTER(&queue->tq_queue, prev, task, ta_link);
258 queue->tq_hint = task;
260 STAILQ_INSERT_HEAD(&queue->tq_queue, task, ta_link);
263 task->ta_pending = 1;
264 if ((queue->tq_flags & TQ_FLAGS_UNLOCKED_ENQUEUE) != 0)
266 if ((queue->tq_flags & TQ_FLAGS_BLOCKED) == 0)
267 queue->tq_enqueue(queue->tq_context);
268 if ((queue->tq_flags & TQ_FLAGS_UNLOCKED_ENQUEUE) == 0)
271 /* Return with lock released. */
276 taskqueue_enqueue(struct taskqueue *queue, struct task *task)
281 res = taskqueue_enqueue_locked(queue, task);
282 /* The lock is released inside. */
288 taskqueue_timeout_func(void *arg)
290 struct taskqueue *queue;
291 struct timeout_task *timeout_task;
294 queue = timeout_task->q;
295 KASSERT((timeout_task->f & DT_CALLOUT_ARMED) != 0, ("Stray timeout"));
296 timeout_task->f &= ~DT_CALLOUT_ARMED;
297 queue->tq_callouts--;
298 taskqueue_enqueue_locked(timeout_task->q, &timeout_task->t);
299 /* The lock is released inside. */
303 taskqueue_enqueue_timeout_sbt(struct taskqueue *queue,
304 struct timeout_task *timeout_task, sbintime_t sbt, sbintime_t pr, int flags)
309 KASSERT(timeout_task->q == NULL || timeout_task->q == queue,
311 KASSERT(!queue->tq_spin, ("Timeout for spin-queue"));
312 timeout_task->q = queue;
313 res = timeout_task->t.ta_pending;
314 if (timeout_task->f & DT_DRAIN_IN_PROGRESS) {
318 } else if (sbt == 0) {
319 taskqueue_enqueue_locked(queue, &timeout_task->t);
320 /* The lock is released inside. */
322 if ((timeout_task->f & DT_CALLOUT_ARMED) != 0) {
325 queue->tq_callouts++;
326 timeout_task->f |= DT_CALLOUT_ARMED;
328 sbt = -sbt; /* Ignore overflow. */
331 callout_reset_sbt(&timeout_task->c, sbt, pr,
332 taskqueue_timeout_func, timeout_task, flags);
340 taskqueue_enqueue_timeout(struct taskqueue *queue,
341 struct timeout_task *ttask, int ticks)
344 return (taskqueue_enqueue_timeout_sbt(queue, ttask, ticks * tick_sbt,
349 taskqueue_task_nop_fn(void *context, int pending)
354 * Block until all currently queued tasks in this taskqueue
355 * have begun execution. Tasks queued during execution of
356 * this function are ignored.
359 taskqueue_drain_tq_queue(struct taskqueue *queue)
361 struct task t_barrier;
363 if (STAILQ_EMPTY(&queue->tq_queue))
367 * Enqueue our barrier after all current tasks, but with
368 * the highest priority so that newly queued tasks cannot
369 * pass it. Because of the high priority, we can not use
370 * taskqueue_enqueue_locked directly (which drops the lock
371 * anyway) so just insert it at tail while we have the
374 TASK_INIT(&t_barrier, USHRT_MAX, taskqueue_task_nop_fn, &t_barrier);
375 STAILQ_INSERT_TAIL(&queue->tq_queue, &t_barrier, ta_link);
376 queue->tq_hint = &t_barrier;
377 t_barrier.ta_pending = 1;
380 * Once the barrier has executed, all previously queued tasks
381 * have completed or are currently executing.
383 while (t_barrier.ta_pending != 0)
384 TQ_SLEEP(queue, &t_barrier, "tq_qdrain");
389 * Block until all currently executing tasks for this taskqueue
390 * complete. Tasks that begin execution during the execution
391 * of this function are ignored.
394 taskqueue_drain_tq_active(struct taskqueue *queue)
396 struct taskqueue_busy *tb;
399 if (LIST_EMPTY(&queue->tq_active))
402 /* Block taskq_terminate().*/
403 queue->tq_callouts++;
405 /* Wait for any active task with sequence from the past. */
408 LIST_FOREACH(tb, &queue->tq_active, tb_link) {
409 if ((int)(tb->tb_seq - seq) <= 0) {
410 TQ_SLEEP(queue, tb->tb_running, "tq_adrain");
415 /* Release taskqueue_terminate(). */
416 queue->tq_callouts--;
417 if ((queue->tq_flags & TQ_FLAGS_ACTIVE) == 0)
418 wakeup_one(queue->tq_threads);
423 taskqueue_block(struct taskqueue *queue)
427 queue->tq_flags |= TQ_FLAGS_BLOCKED;
432 taskqueue_unblock(struct taskqueue *queue)
436 queue->tq_flags &= ~TQ_FLAGS_BLOCKED;
437 if (!STAILQ_EMPTY(&queue->tq_queue))
438 queue->tq_enqueue(queue->tq_context);
443 taskqueue_run_locked(struct taskqueue *queue)
445 struct taskqueue_busy tb;
449 KASSERT(queue != NULL, ("tq is NULL"));
450 TQ_ASSERT_LOCKED(queue);
451 tb.tb_running = NULL;
452 LIST_INSERT_HEAD(&queue->tq_active, &tb, tb_link);
454 while ((task = STAILQ_FIRST(&queue->tq_queue)) != NULL) {
455 STAILQ_REMOVE_HEAD(&queue->tq_queue, ta_link);
456 if (queue->tq_hint == task)
457 queue->tq_hint = NULL;
458 pending = task->ta_pending;
459 task->ta_pending = 0;
460 tb.tb_running = task;
461 tb.tb_seq = ++queue->tq_seq;
464 KASSERT(task->ta_func != NULL, ("task->ta_func is NULL"));
465 task->ta_func(task->ta_context, pending);
470 LIST_REMOVE(&tb, tb_link);
474 taskqueue_run(struct taskqueue *queue)
478 taskqueue_run_locked(queue);
483 task_is_running(struct taskqueue *queue, struct task *task)
485 struct taskqueue_busy *tb;
487 TQ_ASSERT_LOCKED(queue);
488 LIST_FOREACH(tb, &queue->tq_active, tb_link) {
489 if (tb->tb_running == task)
496 * Only use this function in single threaded contexts. It returns
497 * non-zero if the given task is either pending or running. Else the
498 * task is idle and can be queued again or freed.
501 taskqueue_poll_is_busy(struct taskqueue *queue, struct task *task)
506 retval = task->ta_pending > 0 || task_is_running(queue, task);
513 taskqueue_cancel_locked(struct taskqueue *queue, struct task *task,
517 if (task->ta_pending > 0) {
518 STAILQ_REMOVE(&queue->tq_queue, task, task, ta_link);
519 if (queue->tq_hint == task)
520 queue->tq_hint = NULL;
523 *pendp = task->ta_pending;
524 task->ta_pending = 0;
525 return (task_is_running(queue, task) ? EBUSY : 0);
529 taskqueue_cancel(struct taskqueue *queue, struct task *task, u_int *pendp)
534 error = taskqueue_cancel_locked(queue, task, pendp);
541 taskqueue_cancel_timeout(struct taskqueue *queue,
542 struct timeout_task *timeout_task, u_int *pendp)
544 u_int pending, pending1;
548 pending = !!(callout_stop(&timeout_task->c) > 0);
549 error = taskqueue_cancel_locked(queue, &timeout_task->t, &pending1);
550 if ((timeout_task->f & DT_CALLOUT_ARMED) != 0) {
551 timeout_task->f &= ~DT_CALLOUT_ARMED;
552 queue->tq_callouts--;
557 *pendp = pending + pending1;
562 taskqueue_drain(struct taskqueue *queue, struct task *task)
566 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, __func__);
569 while (task->ta_pending != 0 || task_is_running(queue, task))
570 TQ_SLEEP(queue, task, "tq_drain");
575 taskqueue_drain_all(struct taskqueue *queue)
579 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, __func__);
582 (void)taskqueue_drain_tq_queue(queue);
583 (void)taskqueue_drain_tq_active(queue);
588 taskqueue_drain_timeout(struct taskqueue *queue,
589 struct timeout_task *timeout_task)
593 * Set flag to prevent timer from re-starting during drain:
596 KASSERT((timeout_task->f & DT_DRAIN_IN_PROGRESS) == 0,
597 ("Drain already in progress"));
598 timeout_task->f |= DT_DRAIN_IN_PROGRESS;
601 callout_drain(&timeout_task->c);
602 taskqueue_drain(queue, &timeout_task->t);
605 * Clear flag to allow timer to re-start:
608 timeout_task->f &= ~DT_DRAIN_IN_PROGRESS;
613 taskqueue_quiesce(struct taskqueue *queue)
619 ret = taskqueue_drain_tq_queue(queue);
621 ret = taskqueue_drain_tq_active(queue);
627 taskqueue_swi_enqueue(void *context)
629 swi_sched(taskqueue_ih, 0);
633 taskqueue_swi_run(void *dummy)
635 taskqueue_run(taskqueue_swi);
639 taskqueue_swi_giant_enqueue(void *context)
641 swi_sched(taskqueue_giant_ih, 0);
645 taskqueue_swi_giant_run(void *dummy)
647 taskqueue_run(taskqueue_swi_giant);
651 _taskqueue_start_threads(struct taskqueue **tqp, int count, int pri,
652 cpuset_t *mask, struct proc *p, const char *name, va_list ap)
654 char ktname[MAXCOMLEN + 1];
656 struct taskqueue *tq;
662 vsnprintf(ktname, sizeof(ktname), name, ap);
665 tq->tq_threads = malloc(sizeof(struct thread *) * count, M_TASKQUEUE,
667 if (tq->tq_threads == NULL) {
668 printf("%s: no memory for %s threads\n", __func__, ktname);
672 for (i = 0; i < count; i++) {
674 error = kthread_add(taskqueue_thread_loop, tqp, p,
675 &tq->tq_threads[i], RFSTOPPED, 0, "%s", ktname);
677 error = kthread_add(taskqueue_thread_loop, tqp, p,
678 &tq->tq_threads[i], RFSTOPPED, 0,
681 /* should be ok to continue, taskqueue_free will dtrt */
682 printf("%s: kthread_add(%s): error %d", __func__,
684 tq->tq_threads[i] = NULL; /* paranoid */
688 if (tq->tq_tcount == 0) {
689 free(tq->tq_threads, M_TASKQUEUE);
690 tq->tq_threads = NULL;
693 for (i = 0; i < count; i++) {
694 if (tq->tq_threads[i] == NULL)
696 td = tq->tq_threads[i];
698 error = cpuset_setthread(td->td_tid, mask);
700 * Failing to pin is rarely an actual fatal error;
701 * it'll just affect performance.
704 printf("%s: curthread=%llu: can't pin; "
707 (unsigned long long) td->td_tid,
712 sched_add(td, SRQ_BORING);
720 taskqueue_start_threads(struct taskqueue **tqp, int count, int pri,
721 const char *name, ...)
727 error = _taskqueue_start_threads(tqp, count, pri, NULL, NULL, name, ap);
733 taskqueue_start_threads_in_proc(struct taskqueue **tqp, int count, int pri,
734 struct proc *proc, const char *name, ...)
740 error = _taskqueue_start_threads(tqp, count, pri, NULL, proc, name, ap);
746 taskqueue_start_threads_cpuset(struct taskqueue **tqp, int count, int pri,
747 cpuset_t *mask, const char *name, ...)
753 error = _taskqueue_start_threads(tqp, count, pri, mask, NULL, name, ap);
759 taskqueue_run_callback(struct taskqueue *tq,
760 enum taskqueue_callback_type cb_type)
762 taskqueue_callback_fn tq_callback;
764 TQ_ASSERT_UNLOCKED(tq);
765 tq_callback = tq->tq_callbacks[cb_type];
766 if (tq_callback != NULL)
767 tq_callback(tq->tq_cb_contexts[cb_type]);
771 taskqueue_thread_loop(void *arg)
773 struct taskqueue **tqp, *tq;
777 taskqueue_run_callback(tq, TASKQUEUE_CALLBACK_TYPE_INIT);
779 while ((tq->tq_flags & TQ_FLAGS_ACTIVE) != 0) {
781 taskqueue_run_locked(tq);
783 * Because taskqueue_run() can drop tq_mutex, we need to
784 * check if the TQ_FLAGS_ACTIVE flag wasn't removed in the
785 * meantime, which means we missed a wakeup.
787 if ((tq->tq_flags & TQ_FLAGS_ACTIVE) == 0)
789 TQ_SLEEP(tq, tq, "-");
791 taskqueue_run_locked(tq);
793 * This thread is on its way out, so just drop the lock temporarily
794 * in order to call the shutdown callback. This allows the callback
795 * to look at the taskqueue, even just before it dies.
798 taskqueue_run_callback(tq, TASKQUEUE_CALLBACK_TYPE_SHUTDOWN);
801 /* rendezvous with thread that asked us to terminate */
803 wakeup_one(tq->tq_threads);
809 taskqueue_thread_enqueue(void *context)
811 struct taskqueue **tqp, *tq;
818 TASKQUEUE_DEFINE(swi, taskqueue_swi_enqueue, NULL,
819 swi_add(NULL, "task queue", taskqueue_swi_run, NULL, SWI_TQ,
820 INTR_MPSAFE, &taskqueue_ih));
822 TASKQUEUE_DEFINE(swi_giant, taskqueue_swi_giant_enqueue, NULL,
823 swi_add(NULL, "Giant taskq", taskqueue_swi_giant_run,
824 NULL, SWI_TQ_GIANT, 0, &taskqueue_giant_ih));
826 TASKQUEUE_DEFINE_THREAD(thread);
829 taskqueue_create_fast(const char *name, int mflags,
830 taskqueue_enqueue_fn enqueue, void *context)
832 return _taskqueue_create(name, mflags, enqueue, context,
833 MTX_SPIN, "fast_taskqueue");
836 static void *taskqueue_fast_ih;
839 taskqueue_fast_enqueue(void *context)
841 swi_sched(taskqueue_fast_ih, 0);
845 taskqueue_fast_run(void *dummy)
847 taskqueue_run(taskqueue_fast);
850 TASKQUEUE_FAST_DEFINE(fast, taskqueue_fast_enqueue, NULL,
851 swi_add(NULL, "fast taskq", taskqueue_fast_run, NULL,
852 SWI_TQ_FAST, INTR_MPSAFE, &taskqueue_fast_ih));
855 taskqueue_member(struct taskqueue *queue, struct thread *td)
859 for (i = 0, j = 0; ; i++) {
860 if (queue->tq_threads[i] == NULL)
862 if (queue->tq_threads[i] == td) {
866 if (++j >= queue->tq_tcount)