subr_taskqueue.c revision 256612
1/*-
2 * Copyright (c) 2000 Doug Rabson
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 */
26
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: head/sys/kern/subr_taskqueue.c 256612 2013-10-16 09:48:23Z mav $");
29
30#include <sys/param.h>
31#include <sys/systm.h>
32#include <sys/bus.h>
33#include <sys/interrupt.h>
34#include <sys/kernel.h>
35#include <sys/kthread.h>
36#include <sys/limits.h>
37#include <sys/lock.h>
38#include <sys/malloc.h>
39#include <sys/mutex.h>
40#include <sys/proc.h>
41#include <sys/sched.h>
42#include <sys/taskqueue.h>
43#include <sys/unistd.h>
44#include <machine/stdarg.h>
45#include <net/vnet.h>
46
47static MALLOC_DEFINE(M_TASKQUEUE, "taskqueue", "Task Queues");
48static void	*taskqueue_giant_ih;
49static void	*taskqueue_ih;
50
51struct taskqueue_busy {
52	struct task	*tb_running;
53	TAILQ_ENTRY(taskqueue_busy) tb_link;
54};
55
56struct taskqueue {
57	STAILQ_HEAD(, task)	tq_queue;
58	taskqueue_enqueue_fn	tq_enqueue;
59	void			*tq_context;
60	TAILQ_HEAD(, taskqueue_busy) tq_active;
61	struct mtx		tq_mutex;
62	struct thread		**tq_threads;
63	int			tq_tcount;
64	int			tq_spin;
65	int			tq_flags;
66	int			tq_callouts;
67	taskqueue_callback_fn	tq_callbacks[TASKQUEUE_NUM_CALLBACKS];
68	void			*tq_cb_contexts[TASKQUEUE_NUM_CALLBACKS];
69};
70
71#define	TQ_FLAGS_ACTIVE		(1 << 0)
72#define	TQ_FLAGS_BLOCKED	(1 << 1)
73
74#define	DT_CALLOUT_ARMED	(1 << 0)
75
76#define	TQ_LOCK(tq)							\
77	do {								\
78		if ((tq)->tq_spin)					\
79			mtx_lock_spin(&(tq)->tq_mutex);			\
80		else							\
81			mtx_lock(&(tq)->tq_mutex);			\
82	} while (0)
83#define	TQ_ASSERT_LOCKED(tq)	mtx_assert(&(tq)->tq_mutex, MA_OWNED)
84
85#define	TQ_UNLOCK(tq)							\
86	do {								\
87		if ((tq)->tq_spin)					\
88			mtx_unlock_spin(&(tq)->tq_mutex);		\
89		else							\
90			mtx_unlock(&(tq)->tq_mutex);			\
91	} while (0)
92#define	TQ_ASSERT_UNLOCKED(tq)	mtx_assert(&(tq)->tq_mutex, MA_NOTOWNED)
93
94void
95_timeout_task_init(struct taskqueue *queue, struct timeout_task *timeout_task,
96    int priority, task_fn_t func, void *context)
97{
98
99	TASK_INIT(&timeout_task->t, priority, func, context);
100	callout_init_mtx(&timeout_task->c, &queue->tq_mutex, 0);
101	timeout_task->q = queue;
102	timeout_task->f = 0;
103}
104
105static __inline int
106TQ_SLEEP(struct taskqueue *tq, void *p, struct mtx *m, int pri, const char *wm,
107    int t)
108{
109	if (tq->tq_spin)
110		return (msleep_spin(p, m, wm, t));
111	return (msleep(p, m, pri, wm, t));
112}
113
114static struct taskqueue *
115_taskqueue_create(const char *name __unused, int mflags,
116		 taskqueue_enqueue_fn enqueue, void *context,
117		 int mtxflags, const char *mtxname)
118{
119	struct taskqueue *queue;
120
121	queue = malloc(sizeof(struct taskqueue), M_TASKQUEUE, mflags | M_ZERO);
122	if (!queue)
123		return NULL;
124
125	STAILQ_INIT(&queue->tq_queue);
126	TAILQ_INIT(&queue->tq_active);
127	queue->tq_enqueue = enqueue;
128	queue->tq_context = context;
129	queue->tq_spin = (mtxflags & MTX_SPIN) != 0;
130	queue->tq_flags |= TQ_FLAGS_ACTIVE;
131	mtx_init(&queue->tq_mutex, mtxname, NULL, mtxflags);
132
133	return queue;
134}
135
136struct taskqueue *
137taskqueue_create(const char *name, int mflags,
138		 taskqueue_enqueue_fn enqueue, void *context)
139{
140	return _taskqueue_create(name, mflags, enqueue, context,
141			MTX_DEF, "taskqueue");
142}
143
144void
145taskqueue_set_callback(struct taskqueue *queue,
146    enum taskqueue_callback_type cb_type, taskqueue_callback_fn callback,
147    void *context)
148{
149
150	KASSERT(((cb_type >= TASKQUEUE_CALLBACK_TYPE_MIN) &&
151	    (cb_type <= TASKQUEUE_CALLBACK_TYPE_MAX)),
152	    ("Callback type %d not valid, must be %d-%d", cb_type,
153	    TASKQUEUE_CALLBACK_TYPE_MIN, TASKQUEUE_CALLBACK_TYPE_MAX));
154	KASSERT((queue->tq_callbacks[cb_type] == NULL),
155	    ("Re-initialization of taskqueue callback?"));
156
157	queue->tq_callbacks[cb_type] = callback;
158	queue->tq_cb_contexts[cb_type] = context;
159}
160
161/*
162 * Signal a taskqueue thread to terminate.
163 */
164static void
165taskqueue_terminate(struct thread **pp, struct taskqueue *tq)
166{
167
168	while (tq->tq_tcount > 0 || tq->tq_callouts > 0) {
169		wakeup(tq);
170		TQ_SLEEP(tq, pp, &tq->tq_mutex, PWAIT, "taskqueue_destroy", 0);
171	}
172}
173
174void
175taskqueue_free(struct taskqueue *queue)
176{
177
178	TQ_LOCK(queue);
179	queue->tq_flags &= ~TQ_FLAGS_ACTIVE;
180	taskqueue_terminate(queue->tq_threads, queue);
181	KASSERT(TAILQ_EMPTY(&queue->tq_active), ("Tasks still running?"));
182	KASSERT(queue->tq_callouts == 0, ("Armed timeout tasks"));
183	mtx_destroy(&queue->tq_mutex);
184	free(queue->tq_threads, M_TASKQUEUE);
185	free(queue, M_TASKQUEUE);
186}
187
188static int
189taskqueue_enqueue_locked(struct taskqueue *queue, struct task *task)
190{
191	struct task *ins;
192	struct task *prev;
193
194	/*
195	 * Count multiple enqueues.
196	 */
197	if (task->ta_pending) {
198		if (task->ta_pending < USHRT_MAX)
199			task->ta_pending++;
200		return (0);
201	}
202
203	/*
204	 * Optimise the case when all tasks have the same priority.
205	 */
206	prev = STAILQ_LAST(&queue->tq_queue, task, ta_link);
207	if (!prev || prev->ta_priority >= task->ta_priority) {
208		STAILQ_INSERT_TAIL(&queue->tq_queue, task, ta_link);
209	} else {
210		prev = NULL;
211		for (ins = STAILQ_FIRST(&queue->tq_queue); ins;
212		     prev = ins, ins = STAILQ_NEXT(ins, ta_link))
213			if (ins->ta_priority < task->ta_priority)
214				break;
215
216		if (prev)
217			STAILQ_INSERT_AFTER(&queue->tq_queue, prev, task, ta_link);
218		else
219			STAILQ_INSERT_HEAD(&queue->tq_queue, task, ta_link);
220	}
221
222	task->ta_pending = 1;
223	if ((queue->tq_flags & TQ_FLAGS_BLOCKED) == 0)
224		queue->tq_enqueue(queue->tq_context);
225
226	return (0);
227}
228int
229taskqueue_enqueue(struct taskqueue *queue, struct task *task)
230{
231	int res;
232
233	TQ_LOCK(queue);
234	res = taskqueue_enqueue_locked(queue, task);
235	TQ_UNLOCK(queue);
236
237	return (res);
238}
239
240static void
241taskqueue_timeout_func(void *arg)
242{
243	struct taskqueue *queue;
244	struct timeout_task *timeout_task;
245
246	timeout_task = arg;
247	queue = timeout_task->q;
248	KASSERT((timeout_task->f & DT_CALLOUT_ARMED) != 0, ("Stray timeout"));
249	timeout_task->f &= ~DT_CALLOUT_ARMED;
250	queue->tq_callouts--;
251	taskqueue_enqueue_locked(timeout_task->q, &timeout_task->t);
252}
253
254int
255taskqueue_enqueue_timeout(struct taskqueue *queue,
256    struct timeout_task *timeout_task, int ticks)
257{
258	int res;
259
260	TQ_LOCK(queue);
261	KASSERT(timeout_task->q == NULL || timeout_task->q == queue,
262	    ("Migrated queue"));
263	KASSERT(!queue->tq_spin, ("Timeout for spin-queue"));
264	timeout_task->q = queue;
265	res = timeout_task->t.ta_pending;
266	if (ticks == 0) {
267		taskqueue_enqueue_locked(queue, &timeout_task->t);
268	} else {
269		if ((timeout_task->f & DT_CALLOUT_ARMED) != 0) {
270			res++;
271		} else {
272			queue->tq_callouts++;
273			timeout_task->f |= DT_CALLOUT_ARMED;
274			if (ticks < 0)
275				ticks = -ticks; /* Ignore overflow. */
276		}
277		if (ticks > 0) {
278			callout_reset(&timeout_task->c, ticks,
279			    taskqueue_timeout_func, timeout_task);
280		}
281	}
282	TQ_UNLOCK(queue);
283	return (res);
284}
285
286void
287taskqueue_block(struct taskqueue *queue)
288{
289
290	TQ_LOCK(queue);
291	queue->tq_flags |= TQ_FLAGS_BLOCKED;
292	TQ_UNLOCK(queue);
293}
294
295void
296taskqueue_unblock(struct taskqueue *queue)
297{
298
299	TQ_LOCK(queue);
300	queue->tq_flags &= ~TQ_FLAGS_BLOCKED;
301	if (!STAILQ_EMPTY(&queue->tq_queue))
302		queue->tq_enqueue(queue->tq_context);
303	TQ_UNLOCK(queue);
304}
305
306static void
307taskqueue_run_locked(struct taskqueue *queue)
308{
309	struct taskqueue_busy tb;
310	struct task *task;
311	int pending;
312
313	TQ_ASSERT_LOCKED(queue);
314	tb.tb_running = NULL;
315	TAILQ_INSERT_TAIL(&queue->tq_active, &tb, tb_link);
316
317	while (STAILQ_FIRST(&queue->tq_queue)) {
318		/*
319		 * Carefully remove the first task from the queue and
320		 * zero its pending count.
321		 */
322		task = STAILQ_FIRST(&queue->tq_queue);
323		STAILQ_REMOVE_HEAD(&queue->tq_queue, ta_link);
324		pending = task->ta_pending;
325		task->ta_pending = 0;
326		tb.tb_running = task;
327		TQ_UNLOCK(queue);
328
329		CURVNET_SET(task->ta_vnet);
330		task->ta_func(task->ta_context, pending);
331		CURVNET_RESTORE();
332
333		TQ_LOCK(queue);
334		tb.tb_running = NULL;
335		wakeup(task);
336	}
337	TAILQ_REMOVE(&queue->tq_active, &tb, tb_link);
338}
339
340void
341taskqueue_run(struct taskqueue *queue)
342{
343
344	TQ_LOCK(queue);
345	taskqueue_run_locked(queue);
346	TQ_UNLOCK(queue);
347}
348
349static int
350task_is_running(struct taskqueue *queue, struct task *task)
351{
352	struct taskqueue_busy *tb;
353
354	TQ_ASSERT_LOCKED(queue);
355	TAILQ_FOREACH(tb, &queue->tq_active, tb_link) {
356		if (tb->tb_running == task)
357			return (1);
358	}
359	return (0);
360}
361
362static int
363taskqueue_cancel_locked(struct taskqueue *queue, struct task *task,
364    u_int *pendp)
365{
366
367	if (task->ta_pending > 0)
368		STAILQ_REMOVE(&queue->tq_queue, task, task, ta_link);
369	if (pendp != NULL)
370		*pendp = task->ta_pending;
371	task->ta_pending = 0;
372	return (task_is_running(queue, task) ? EBUSY : 0);
373}
374
375int
376taskqueue_cancel(struct taskqueue *queue, struct task *task, u_int *pendp)
377{
378	u_int pending;
379	int error;
380
381	TQ_LOCK(queue);
382	pending = task->ta_pending;
383	error = taskqueue_cancel_locked(queue, task, pendp);
384	TQ_UNLOCK(queue);
385
386	return (error);
387}
388
389int
390taskqueue_cancel_timeout(struct taskqueue *queue,
391    struct timeout_task *timeout_task, u_int *pendp)
392{
393	u_int pending, pending1;
394	int error;
395
396	TQ_LOCK(queue);
397	pending = !!callout_stop(&timeout_task->c);
398	error = taskqueue_cancel_locked(queue, &timeout_task->t, &pending1);
399	if ((timeout_task->f & DT_CALLOUT_ARMED) != 0) {
400		timeout_task->f &= ~DT_CALLOUT_ARMED;
401		queue->tq_callouts--;
402	}
403	TQ_UNLOCK(queue);
404
405	if (pendp != NULL)
406		*pendp = pending + pending1;
407	return (error);
408}
409
410void
411taskqueue_drain(struct taskqueue *queue, struct task *task)
412{
413
414	if (!queue->tq_spin)
415		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, __func__);
416
417	TQ_LOCK(queue);
418	while (task->ta_pending != 0 || task_is_running(queue, task))
419		TQ_SLEEP(queue, task, &queue->tq_mutex, PWAIT, "-", 0);
420	TQ_UNLOCK(queue);
421}
422
423void
424taskqueue_drain_timeout(struct taskqueue *queue,
425    struct timeout_task *timeout_task)
426{
427
428	callout_drain(&timeout_task->c);
429	taskqueue_drain(queue, &timeout_task->t);
430}
431
432static void
433taskqueue_swi_enqueue(void *context)
434{
435	swi_sched(taskqueue_ih, 0);
436}
437
438static void
439taskqueue_swi_run(void *dummy)
440{
441	taskqueue_run(taskqueue_swi);
442}
443
444static void
445taskqueue_swi_giant_enqueue(void *context)
446{
447	swi_sched(taskqueue_giant_ih, 0);
448}
449
450static void
451taskqueue_swi_giant_run(void *dummy)
452{
453	taskqueue_run(taskqueue_swi_giant);
454}
455
456int
457taskqueue_start_threads(struct taskqueue **tqp, int count, int pri,
458			const char *name, ...)
459{
460	va_list ap;
461	struct thread *td;
462	struct taskqueue *tq;
463	int i, error;
464	char ktname[MAXCOMLEN + 1];
465
466	if (count <= 0)
467		return (EINVAL);
468
469	tq = *tqp;
470
471	va_start(ap, name);
472	vsnprintf(ktname, sizeof(ktname), name, ap);
473	va_end(ap);
474
475	tq->tq_threads = malloc(sizeof(struct thread *) * count, M_TASKQUEUE,
476	    M_NOWAIT | M_ZERO);
477	if (tq->tq_threads == NULL) {
478		printf("%s: no memory for %s threads\n", __func__, ktname);
479		return (ENOMEM);
480	}
481
482	for (i = 0; i < count; i++) {
483		if (count == 1)
484			error = kthread_add(taskqueue_thread_loop, tqp, NULL,
485			    &tq->tq_threads[i], RFSTOPPED, 0, "%s", ktname);
486		else
487			error = kthread_add(taskqueue_thread_loop, tqp, NULL,
488			    &tq->tq_threads[i], RFSTOPPED, 0,
489			    "%s_%d", ktname, i);
490		if (error) {
491			/* should be ok to continue, taskqueue_free will dtrt */
492			printf("%s: kthread_add(%s): error %d", __func__,
493			    ktname, error);
494			tq->tq_threads[i] = NULL;		/* paranoid */
495		} else
496			tq->tq_tcount++;
497	}
498	for (i = 0; i < count; i++) {
499		if (tq->tq_threads[i] == NULL)
500			continue;
501		td = tq->tq_threads[i];
502		thread_lock(td);
503		sched_prio(td, pri);
504		sched_add(td, SRQ_BORING);
505		thread_unlock(td);
506	}
507
508	return (0);
509}
510
511static inline void
512taskqueue_run_callback(struct taskqueue *tq,
513    enum taskqueue_callback_type cb_type)
514{
515	taskqueue_callback_fn tq_callback;
516
517	TQ_ASSERT_UNLOCKED(tq);
518	tq_callback = tq->tq_callbacks[cb_type];
519	if (tq_callback != NULL)
520		tq_callback(tq->tq_cb_contexts[cb_type]);
521}
522
523void
524taskqueue_thread_loop(void *arg)
525{
526	struct taskqueue **tqp, *tq;
527
528	tqp = arg;
529	tq = *tqp;
530	taskqueue_run_callback(tq, TASKQUEUE_CALLBACK_TYPE_INIT);
531	TQ_LOCK(tq);
532	while ((tq->tq_flags & TQ_FLAGS_ACTIVE) != 0) {
533		taskqueue_run_locked(tq);
534		/*
535		 * Because taskqueue_run() can drop tq_mutex, we need to
536		 * check if the TQ_FLAGS_ACTIVE flag wasn't removed in the
537		 * meantime, which means we missed a wakeup.
538		 */
539		if ((tq->tq_flags & TQ_FLAGS_ACTIVE) == 0)
540			break;
541		TQ_SLEEP(tq, tq, &tq->tq_mutex, 0, "-", 0);
542	}
543	taskqueue_run_locked(tq);
544
545	/*
546	 * This thread is on its way out, so just drop the lock temporarily
547	 * in order to call the shutdown callback.  This allows the callback
548	 * to look at the taskqueue, even just before it dies.
549	 */
550	TQ_UNLOCK(tq);
551	taskqueue_run_callback(tq, TASKQUEUE_CALLBACK_TYPE_SHUTDOWN);
552	TQ_LOCK(tq);
553
554	/* rendezvous with thread that asked us to terminate */
555	tq->tq_tcount--;
556	wakeup_one(tq->tq_threads);
557	TQ_UNLOCK(tq);
558	kthread_exit();
559}
560
561void
562taskqueue_thread_enqueue(void *context)
563{
564	struct taskqueue **tqp, *tq;
565
566	tqp = context;
567	tq = *tqp;
568
569	TQ_ASSERT_LOCKED(tq);
570	wakeup_one(tq);
571}
572
573TASKQUEUE_DEFINE(swi, taskqueue_swi_enqueue, NULL,
574		 swi_add(NULL, "task queue", taskqueue_swi_run, NULL, SWI_TQ,
575		     INTR_MPSAFE, &taskqueue_ih));
576
577TASKQUEUE_DEFINE(swi_giant, taskqueue_swi_giant_enqueue, NULL,
578		 swi_add(NULL, "Giant taskq", taskqueue_swi_giant_run,
579		     NULL, SWI_TQ_GIANT, 0, &taskqueue_giant_ih));
580
581TASKQUEUE_DEFINE_THREAD(thread);
582
583struct taskqueue *
584taskqueue_create_fast(const char *name, int mflags,
585		 taskqueue_enqueue_fn enqueue, void *context)
586{
587	return _taskqueue_create(name, mflags, enqueue, context,
588			MTX_SPIN, "fast_taskqueue");
589}
590
591/* NB: for backwards compatibility */
592int
593taskqueue_enqueue_fast(struct taskqueue *queue, struct task *task)
594{
595	return taskqueue_enqueue(queue, task);
596}
597
598static void	*taskqueue_fast_ih;
599
600static void
601taskqueue_fast_enqueue(void *context)
602{
603	swi_sched(taskqueue_fast_ih, 0);
604}
605
606static void
607taskqueue_fast_run(void *dummy)
608{
609	taskqueue_run(taskqueue_fast);
610}
611
612TASKQUEUE_FAST_DEFINE(fast, taskqueue_fast_enqueue, NULL,
613	swi_add(NULL, "fast taskq", taskqueue_fast_run, NULL,
614	SWI_TQ_FAST, INTR_MPSAFE, &taskqueue_fast_ih));
615
616int
617taskqueue_member(struct taskqueue *queue, struct thread *td)
618{
619	int i, j, ret = 0;
620
621	for (i = 0, j = 0; ; i++) {
622		if (queue->tq_threads[i] == NULL)
623			continue;
624		if (queue->tq_threads[i] == td) {
625			ret = 1;
626			break;
627		}
628		if (++j >= queue->tq_tcount)
629			break;
630	}
631	return (ret);
632}
633