xref: /freebsd/sys/compat/linuxkpi/common/src/linux_work.c (revision 389e4940069316fe667ffa263fa7d6390d0a960f)
1 /*-
2  * Copyright (c) 2017 Hans Petter Selasky
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 unmodified, this list of conditions, and the following
10  *    disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <linux/workqueue.h>
31 #include <linux/wait.h>
32 #include <linux/compat.h>
33 #include <linux/spinlock.h>
34 
35 #include <sys/kernel.h>
36 
37 /*
38  * Define all work struct states
39  */
40 enum {
41 	WORK_ST_IDLE,			/* idle - not started */
42 	WORK_ST_TIMER,			/* timer is being started */
43 	WORK_ST_TASK,			/* taskqueue is being queued */
44 	WORK_ST_EXEC,			/* callback is being called */
45 	WORK_ST_CANCEL,			/* cancel is being requested */
46 	WORK_ST_MAX,
47 };
48 
49 /*
50  * Define global workqueues
51  */
52 static struct workqueue_struct *linux_system_short_wq;
53 static struct workqueue_struct *linux_system_long_wq;
54 
55 struct workqueue_struct *system_wq;
56 struct workqueue_struct *system_long_wq;
57 struct workqueue_struct *system_unbound_wq;
58 struct workqueue_struct *system_highpri_wq;
59 struct workqueue_struct *system_power_efficient_wq;
60 
61 static int linux_default_wq_cpus = 4;
62 
63 static void linux_delayed_work_timer_fn(void *);
64 
65 /*
66  * This function atomically updates the work state and returns the
67  * previous state at the time of update.
68  */
69 static uint8_t
70 linux_update_state(atomic_t *v, const uint8_t *pstate)
71 {
72 	int c, old;
73 
74 	c = v->counter;
75 
76 	while ((old = atomic_cmpxchg(v, c, pstate[c])) != c)
77 		c = old;
78 
79 	return (c);
80 }
81 
82 /*
83  * A LinuxKPI task is allowed to free itself inside the callback function
84  * and cannot safely be referred after the callback function has
85  * completed. This function gives the linux_work_fn() function a hint,
86  * that the task is not going away and can have its state checked
87  * again. Without this extra hint LinuxKPI tasks cannot be serialized
88  * accross multiple worker threads.
89  */
90 static bool
91 linux_work_exec_unblock(struct work_struct *work)
92 {
93 	struct workqueue_struct *wq;
94 	struct work_exec *exec;
95 	bool retval = 0;
96 
97 	wq = work->work_queue;
98 	if (unlikely(wq == NULL))
99 		goto done;
100 
101 	WQ_EXEC_LOCK(wq);
102 	TAILQ_FOREACH(exec, &wq->exec_head, entry) {
103 		if (exec->target == work) {
104 			exec->target = NULL;
105 			retval = 1;
106 			break;
107 		}
108 	}
109 	WQ_EXEC_UNLOCK(wq);
110 done:
111 	return (retval);
112 }
113 
114 static void
115 linux_delayed_work_enqueue(struct delayed_work *dwork)
116 {
117 	struct taskqueue *tq;
118 
119 	tq = dwork->work.work_queue->taskqueue;
120 	taskqueue_enqueue(tq, &dwork->work.work_task);
121 }
122 
123 /*
124  * This function queues the given work structure on the given
125  * workqueue. It returns non-zero if the work was successfully
126  * [re-]queued. Else the work is already pending for completion.
127  */
128 bool
129 linux_queue_work_on(int cpu __unused, struct workqueue_struct *wq,
130     struct work_struct *work)
131 {
132 	static const uint8_t states[WORK_ST_MAX] __aligned(8) = {
133 		[WORK_ST_IDLE] = WORK_ST_TASK,		/* start queuing task */
134 		[WORK_ST_TIMER] = WORK_ST_TIMER,	/* NOP */
135 		[WORK_ST_TASK] = WORK_ST_TASK,		/* NOP */
136 		[WORK_ST_EXEC] = WORK_ST_TASK,		/* queue task another time */
137 		[WORK_ST_CANCEL] = WORK_ST_TASK,	/* start queuing task again */
138 	};
139 
140 	if (atomic_read(&wq->draining) != 0)
141 		return (!work_pending(work));
142 
143 	switch (linux_update_state(&work->state, states)) {
144 	case WORK_ST_EXEC:
145 	case WORK_ST_CANCEL:
146 		if (linux_work_exec_unblock(work) != 0)
147 			return (1);
148 		/* FALLTHROUGH */
149 	case WORK_ST_IDLE:
150 		work->work_queue = wq;
151 		taskqueue_enqueue(wq->taskqueue, &work->work_task);
152 		return (1);
153 	default:
154 		return (0);		/* already on a queue */
155 	}
156 }
157 
158 /*
159  * This function queues the given work structure on the given
160  * workqueue after a given delay in ticks. It returns non-zero if the
161  * work was successfully [re-]queued. Else the work is already pending
162  * for completion.
163  */
164 bool
165 linux_queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
166     struct delayed_work *dwork, unsigned delay)
167 {
168 	static const uint8_t states[WORK_ST_MAX] __aligned(8) = {
169 		[WORK_ST_IDLE] = WORK_ST_TIMER,		/* start timeout */
170 		[WORK_ST_TIMER] = WORK_ST_TIMER,	/* NOP */
171 		[WORK_ST_TASK] = WORK_ST_TASK,		/* NOP */
172 		[WORK_ST_EXEC] = WORK_ST_TIMER,		/* start timeout */
173 		[WORK_ST_CANCEL] = WORK_ST_TIMER,	/* start timeout */
174 	};
175 
176 	if (atomic_read(&wq->draining) != 0)
177 		return (!work_pending(&dwork->work));
178 
179 	switch (linux_update_state(&dwork->work.state, states)) {
180 	case WORK_ST_EXEC:
181 	case WORK_ST_CANCEL:
182 		if (delay == 0 && linux_work_exec_unblock(&dwork->work) != 0) {
183 			dwork->timer.expires = jiffies;
184 			return (1);
185 		}
186 		/* FALLTHROUGH */
187 	case WORK_ST_IDLE:
188 		dwork->work.work_queue = wq;
189 		dwork->timer.expires = jiffies + delay;
190 
191 		if (delay == 0) {
192 			linux_delayed_work_enqueue(dwork);
193 		} else if (unlikely(cpu != WORK_CPU_UNBOUND)) {
194 			mtx_lock(&dwork->timer.mtx);
195 			callout_reset_on(&dwork->timer.callout, delay,
196 			    &linux_delayed_work_timer_fn, dwork, cpu);
197 			mtx_unlock(&dwork->timer.mtx);
198 		} else {
199 			mtx_lock(&dwork->timer.mtx);
200 			callout_reset(&dwork->timer.callout, delay,
201 			    &linux_delayed_work_timer_fn, dwork);
202 			mtx_unlock(&dwork->timer.mtx);
203 		}
204 		return (1);
205 	default:
206 		return (0);		/* already on a queue */
207 	}
208 }
209 
210 void
211 linux_work_fn(void *context, int pending)
212 {
213 	static const uint8_t states[WORK_ST_MAX] __aligned(8) = {
214 		[WORK_ST_IDLE] = WORK_ST_IDLE,		/* NOP */
215 		[WORK_ST_TIMER] = WORK_ST_EXEC,		/* delayed work w/o timeout */
216 		[WORK_ST_TASK] = WORK_ST_EXEC,		/* call callback */
217 		[WORK_ST_EXEC] = WORK_ST_IDLE,		/* complete callback */
218 		[WORK_ST_CANCEL] = WORK_ST_EXEC,	/* failed to cancel */
219 	};
220 	struct work_struct *work;
221 	struct workqueue_struct *wq;
222 	struct work_exec exec;
223 
224 	linux_set_current(curthread);
225 
226 	/* setup local variables */
227 	work = context;
228 	wq = work->work_queue;
229 
230 	/* store target pointer */
231 	exec.target = work;
232 
233 	/* insert executor into list */
234 	WQ_EXEC_LOCK(wq);
235 	TAILQ_INSERT_TAIL(&wq->exec_head, &exec, entry);
236 	while (1) {
237 		switch (linux_update_state(&work->state, states)) {
238 		case WORK_ST_TIMER:
239 		case WORK_ST_TASK:
240 		case WORK_ST_CANCEL:
241 			WQ_EXEC_UNLOCK(wq);
242 
243 			/* call work function */
244 			work->func(work);
245 
246 			WQ_EXEC_LOCK(wq);
247 			/* check if unblocked */
248 			if (exec.target != work) {
249 				/* reapply block */
250 				exec.target = work;
251 				break;
252 			}
253 			/* FALLTHROUGH */
254 		default:
255 			goto done;
256 		}
257 	}
258 done:
259 	/* remove executor from list */
260 	TAILQ_REMOVE(&wq->exec_head, &exec, entry);
261 	WQ_EXEC_UNLOCK(wq);
262 }
263 
264 void
265 linux_delayed_work_fn(void *context, int pending)
266 {
267 	struct delayed_work *dwork = context;
268 
269 	/*
270 	 * Make sure the timer belonging to the delayed work gets
271 	 * drained before invoking the work function. Else the timer
272 	 * mutex may still be in use which can lead to use-after-free
273 	 * situations, because the work function might free the work
274 	 * structure before returning.
275 	 */
276 	callout_drain(&dwork->timer.callout);
277 
278 	linux_work_fn(&dwork->work, pending);
279 }
280 
281 static void
282 linux_delayed_work_timer_fn(void *arg)
283 {
284 	static const uint8_t states[WORK_ST_MAX] __aligned(8) = {
285 		[WORK_ST_IDLE] = WORK_ST_IDLE,		/* NOP */
286 		[WORK_ST_TIMER] = WORK_ST_TASK,		/* start queueing task */
287 		[WORK_ST_TASK] = WORK_ST_TASK,		/* NOP */
288 		[WORK_ST_EXEC] = WORK_ST_EXEC,		/* NOP */
289 		[WORK_ST_CANCEL] = WORK_ST_TASK,	/* failed to cancel */
290 	};
291 	struct delayed_work *dwork = arg;
292 
293 	switch (linux_update_state(&dwork->work.state, states)) {
294 	case WORK_ST_TIMER:
295 	case WORK_ST_CANCEL:
296 		linux_delayed_work_enqueue(dwork);
297 		break;
298 	default:
299 		break;
300 	}
301 }
302 
303 /*
304  * This function cancels the given work structure in a synchronous
305  * fashion. It returns non-zero if the work was successfully
306  * cancelled. Else the work was already cancelled.
307  */
308 bool
309 linux_cancel_work_sync(struct work_struct *work)
310 {
311 	static const uint8_t states[WORK_ST_MAX] __aligned(8) = {
312 		[WORK_ST_IDLE] = WORK_ST_IDLE,		/* NOP */
313 		[WORK_ST_TIMER] = WORK_ST_TIMER,	/* can't happen */
314 		[WORK_ST_TASK] = WORK_ST_IDLE,		/* cancel and drain */
315 		[WORK_ST_EXEC] = WORK_ST_IDLE,		/* too late, drain */
316 		[WORK_ST_CANCEL] = WORK_ST_IDLE,	/* cancel and drain */
317 	};
318 	struct taskqueue *tq;
319 
320 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
321 	    "linux_cancel_work_sync() might sleep");
322 
323 	switch (linux_update_state(&work->state, states)) {
324 	case WORK_ST_IDLE:
325 	case WORK_ST_TIMER:
326 		return (0);
327 	case WORK_ST_EXEC:
328 		tq = work->work_queue->taskqueue;
329 		if (taskqueue_cancel(tq, &work->work_task, NULL) != 0)
330 			taskqueue_drain(tq, &work->work_task);
331 		return (0);
332 	default:
333 		tq = work->work_queue->taskqueue;
334 		if (taskqueue_cancel(tq, &work->work_task, NULL) != 0)
335 			taskqueue_drain(tq, &work->work_task);
336 		return (1);
337 	}
338 }
339 
340 /*
341  * This function atomically stops the timer and callback. The timer
342  * callback will not be called after this function returns. This
343  * functions returns true when the timeout was cancelled. Else the
344  * timeout was not started or has already been called.
345  */
346 static inline bool
347 linux_cancel_timer(struct delayed_work *dwork, bool drain)
348 {
349 	bool cancelled;
350 
351 	mtx_lock(&dwork->timer.mtx);
352 	cancelled = (callout_stop(&dwork->timer.callout) == 1);
353 	mtx_unlock(&dwork->timer.mtx);
354 
355 	/* check if we should drain */
356 	if (drain)
357 		callout_drain(&dwork->timer.callout);
358 	return (cancelled);
359 }
360 
361 /*
362  * This function cancels the given delayed work structure in a
363  * non-blocking fashion. It returns non-zero if the work was
364  * successfully cancelled. Else the work may still be busy or already
365  * cancelled.
366  */
367 bool
368 linux_cancel_delayed_work(struct delayed_work *dwork)
369 {
370 	static const uint8_t states[WORK_ST_MAX] __aligned(8) = {
371 		[WORK_ST_IDLE] = WORK_ST_IDLE,		/* NOP */
372 		[WORK_ST_TIMER] = WORK_ST_CANCEL,	/* try to cancel */
373 		[WORK_ST_TASK] = WORK_ST_CANCEL,	/* try to cancel */
374 		[WORK_ST_EXEC] = WORK_ST_EXEC,		/* NOP */
375 		[WORK_ST_CANCEL] = WORK_ST_CANCEL,	/* NOP */
376 	};
377 	struct taskqueue *tq;
378 
379 	switch (linux_update_state(&dwork->work.state, states)) {
380 	case WORK_ST_TIMER:
381 	case WORK_ST_CANCEL:
382 		if (linux_cancel_timer(dwork, 0)) {
383 			atomic_cmpxchg(&dwork->work.state,
384 			    WORK_ST_CANCEL, WORK_ST_IDLE);
385 			return (1);
386 		}
387 		/* FALLTHROUGH */
388 	case WORK_ST_TASK:
389 		tq = dwork->work.work_queue->taskqueue;
390 		if (taskqueue_cancel(tq, &dwork->work.work_task, NULL) == 0) {
391 			atomic_cmpxchg(&dwork->work.state,
392 			    WORK_ST_CANCEL, WORK_ST_IDLE);
393 			return (1);
394 		}
395 		/* FALLTHROUGH */
396 	default:
397 		return (0);
398 	}
399 }
400 
401 /*
402  * This function cancels the given work structure in a synchronous
403  * fashion. It returns non-zero if the work was successfully
404  * cancelled. Else the work was already cancelled.
405  */
406 bool
407 linux_cancel_delayed_work_sync(struct delayed_work *dwork)
408 {
409 	static const uint8_t states[WORK_ST_MAX] __aligned(8) = {
410 		[WORK_ST_IDLE] = WORK_ST_IDLE,		/* NOP */
411 		[WORK_ST_TIMER] = WORK_ST_IDLE,		/* cancel and drain */
412 		[WORK_ST_TASK] = WORK_ST_IDLE,		/* cancel and drain */
413 		[WORK_ST_EXEC] = WORK_ST_IDLE,		/* too late, drain */
414 		[WORK_ST_CANCEL] = WORK_ST_IDLE,	/* cancel and drain */
415 	};
416 	struct taskqueue *tq;
417 
418 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
419 	    "linux_cancel_delayed_work_sync() might sleep");
420 
421 	switch (linux_update_state(&dwork->work.state, states)) {
422 	case WORK_ST_IDLE:
423 		return (0);
424 	case WORK_ST_EXEC:
425 		tq = dwork->work.work_queue->taskqueue;
426 		if (taskqueue_cancel(tq, &dwork->work.work_task, NULL) != 0)
427 			taskqueue_drain(tq, &dwork->work.work_task);
428 		return (0);
429 	case WORK_ST_TIMER:
430 	case WORK_ST_CANCEL:
431 		if (linux_cancel_timer(dwork, 1)) {
432 			/*
433 			 * Make sure taskqueue is also drained before
434 			 * returning:
435 			 */
436 			tq = dwork->work.work_queue->taskqueue;
437 			taskqueue_drain(tq, &dwork->work.work_task);
438 			return (1);
439 		}
440 		/* FALLTHROUGH */
441 	default:
442 		tq = dwork->work.work_queue->taskqueue;
443 		if (taskqueue_cancel(tq, &dwork->work.work_task, NULL) != 0)
444 			taskqueue_drain(tq, &dwork->work.work_task);
445 		return (1);
446 	}
447 }
448 
449 /*
450  * This function waits until the given work structure is completed.
451  * It returns non-zero if the work was successfully
452  * waited for. Else the work was not waited for.
453  */
454 bool
455 linux_flush_work(struct work_struct *work)
456 {
457 	struct taskqueue *tq;
458 	int retval;
459 
460 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
461 	    "linux_flush_work() might sleep");
462 
463 	switch (atomic_read(&work->state)) {
464 	case WORK_ST_IDLE:
465 		return (0);
466 	default:
467 		tq = work->work_queue->taskqueue;
468 		retval = taskqueue_poll_is_busy(tq, &work->work_task);
469 		taskqueue_drain(tq, &work->work_task);
470 		return (retval);
471 	}
472 }
473 
474 /*
475  * This function waits until the given delayed work structure is
476  * completed. It returns non-zero if the work was successfully waited
477  * for. Else the work was not waited for.
478  */
479 bool
480 linux_flush_delayed_work(struct delayed_work *dwork)
481 {
482 	struct taskqueue *tq;
483 	int retval;
484 
485 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
486 	    "linux_flush_delayed_work() might sleep");
487 
488 	switch (atomic_read(&dwork->work.state)) {
489 	case WORK_ST_IDLE:
490 		return (0);
491 	case WORK_ST_TIMER:
492 		if (linux_cancel_timer(dwork, 1))
493 			linux_delayed_work_enqueue(dwork);
494 		/* FALLTHROUGH */
495 	default:
496 		tq = dwork->work.work_queue->taskqueue;
497 		retval = taskqueue_poll_is_busy(tq, &dwork->work.work_task);
498 		taskqueue_drain(tq, &dwork->work.work_task);
499 		return (retval);
500 	}
501 }
502 
503 /*
504  * This function returns true if the given work is pending, and not
505  * yet executing:
506  */
507 bool
508 linux_work_pending(struct work_struct *work)
509 {
510 	switch (atomic_read(&work->state)) {
511 	case WORK_ST_TIMER:
512 	case WORK_ST_TASK:
513 	case WORK_ST_CANCEL:
514 		return (1);
515 	default:
516 		return (0);
517 	}
518 }
519 
520 /*
521  * This function returns true if the given work is busy.
522  */
523 bool
524 linux_work_busy(struct work_struct *work)
525 {
526 	struct taskqueue *tq;
527 
528 	switch (atomic_read(&work->state)) {
529 	case WORK_ST_IDLE:
530 		return (0);
531 	case WORK_ST_EXEC:
532 		tq = work->work_queue->taskqueue;
533 		return (taskqueue_poll_is_busy(tq, &work->work_task));
534 	default:
535 		return (1);
536 	}
537 }
538 
539 struct workqueue_struct *
540 linux_create_workqueue_common(const char *name, int cpus)
541 {
542 	struct workqueue_struct *wq;
543 
544 	/*
545 	 * If zero CPUs are specified use the default number of CPUs:
546 	 */
547 	if (cpus == 0)
548 		cpus = linux_default_wq_cpus;
549 
550 	wq = kmalloc(sizeof(*wq), M_WAITOK | M_ZERO);
551 	wq->taskqueue = taskqueue_create(name, M_WAITOK,
552 	    taskqueue_thread_enqueue, &wq->taskqueue);
553 	atomic_set(&wq->draining, 0);
554 	taskqueue_start_threads(&wq->taskqueue, cpus, PWAIT, "%s", name);
555 	TAILQ_INIT(&wq->exec_head);
556 	mtx_init(&wq->exec_mtx, "linux_wq_exec", NULL, MTX_DEF);
557 
558 	return (wq);
559 }
560 
561 void
562 linux_destroy_workqueue(struct workqueue_struct *wq)
563 {
564 	atomic_inc(&wq->draining);
565 	drain_workqueue(wq);
566 	taskqueue_free(wq->taskqueue);
567 	mtx_destroy(&wq->exec_mtx);
568 	kfree(wq);
569 }
570 
571 void
572 linux_init_delayed_work(struct delayed_work *dwork, work_func_t func)
573 {
574 	memset(dwork, 0, sizeof(*dwork));
575 	dwork->work.func = func;
576 	TASK_INIT(&dwork->work.work_task, 0, linux_delayed_work_fn, dwork);
577 	mtx_init(&dwork->timer.mtx, spin_lock_name("lkpi-dwork"), NULL,
578 	    MTX_DEF | MTX_NOWITNESS);
579 	callout_init_mtx(&dwork->timer.callout, &dwork->timer.mtx, 0);
580 }
581 
582 static void
583 linux_work_init(void *arg)
584 {
585 	int max_wq_cpus = mp_ncpus + 1;
586 
587 	/* avoid deadlock when there are too few threads */
588 	if (max_wq_cpus < 4)
589 		max_wq_cpus = 4;
590 
591 	/* set default number of CPUs */
592 	linux_default_wq_cpus = max_wq_cpus;
593 
594 	linux_system_short_wq = alloc_workqueue("linuxkpi_short_wq", 0, max_wq_cpus);
595 	linux_system_long_wq = alloc_workqueue("linuxkpi_long_wq", 0, max_wq_cpus);
596 
597 	/* populate the workqueue pointers */
598 	system_long_wq = linux_system_long_wq;
599 	system_wq = linux_system_short_wq;
600 	system_power_efficient_wq = linux_system_short_wq;
601 	system_unbound_wq = linux_system_short_wq;
602 	system_highpri_wq = linux_system_short_wq;
603 }
604 SYSINIT(linux_work_init, SI_SUB_TASKQ, SI_ORDER_THIRD, linux_work_init, NULL);
605 
606 static void
607 linux_work_uninit(void *arg)
608 {
609 	destroy_workqueue(linux_system_short_wq);
610 	destroy_workqueue(linux_system_long_wq);
611 
612 	/* clear workqueue pointers */
613 	system_long_wq = NULL;
614 	system_wq = NULL;
615 	system_power_efficient_wq = NULL;
616 	system_unbound_wq = NULL;
617 	system_highpri_wq = NULL;
618 }
619 SYSUNINIT(linux_work_uninit, SI_SUB_TASKQ, SI_ORDER_THIRD, linux_work_uninit, NULL);
620