xref: /freebsd-13.1/sys/dev/usb/usb_process.c (revision cfbd8d46)
1 /* $FreeBSD$ */
2 /*-
3  * Copyright (c) 2008 Hans Petter Selasky. 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 #define	USB_DEBUG_VAR usb_proc_debug
28 
29 #include <sys/stdint.h>
30 #include <sys/stddef.h>
31 #include <sys/param.h>
32 #include <sys/queue.h>
33 #include <sys/types.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/bus.h>
37 #include <sys/module.h>
38 #include <sys/lock.h>
39 #include <sys/mutex.h>
40 #include <sys/condvar.h>
41 #include <sys/sysctl.h>
42 #include <sys/sx.h>
43 #include <sys/unistd.h>
44 #include <sys/callout.h>
45 #include <sys/malloc.h>
46 #include <sys/priv.h>
47 
48 #include <dev/usb/usb.h>
49 #include <dev/usb/usbdi.h>
50 #include <dev/usb/usbdi_util.h>
51 #include <dev/usb/usb_process.h>
52 #include <dev/usb/usb_debug.h>
53 #include <dev/usb/usb_util.h>
54 
55 #include <sys/proc.h>
56 #include <sys/kthread.h>
57 #include <sys/sched.h>
58 
59 #if (__FreeBSD_version < 700000)
60 #define	thread_lock(td) mtx_lock_spin(&sched_lock)
61 #define	thread_unlock(td) mtx_unlock_spin(&sched_lock)
62 #endif
63 
64 #if (__FreeBSD_version >= 800000)
65 static struct proc *usbproc;
66 static int usb_pcount;
67 #define	USB_THREAD_CREATE(f, s, p, ...) \
68 		kproc_kthread_add((f), (s), &usbproc, (p), RFHIGHPID, \
69 		    0, "usb", __VA_ARGS__)
70 #define	USB_THREAD_SUSPEND_CHECK() kthread_suspend_check()
71 #define	USB_THREAD_SUSPEND(p)   kthread_suspend(p,0)
72 #define	USB_THREAD_EXIT(err)	kthread_exit()
73 #else
74 #define	USB_THREAD_CREATE(f, s, p, ...) \
75 		kthread_create((f), (s), (p), RFHIGHPID, 0, __VA_ARGS__)
76 #define	USB_THREAD_SUSPEND_CHECK() kthread_suspend_check()
77 #define	USB_THREAD_SUSPEND(p)   kthread_suspend(p,0)
78 #define	USB_THREAD_EXIT(err)	kthread_exit(err)
79 #endif
80 
81 #ifdef USB_DEBUG
82 static int usb_proc_debug;
83 
84 SYSCTL_NODE(_hw_usb, OID_AUTO, proc, CTLFLAG_RW, 0, "USB process");
85 SYSCTL_INT(_hw_usb_proc, OID_AUTO, debug, CTLFLAG_RW, &usb_proc_debug, 0,
86     "Debug level");
87 
88 TUNABLE_INT("hw.usb.proc.debug", &usb_proc_debug);
89 #endif
90 
91 /*------------------------------------------------------------------------*
92  *	usb_process
93  *
94  * This function is the USB process dispatcher.
95  *------------------------------------------------------------------------*/
96 static void
97 usb_process(void *arg)
98 {
99 	struct usb_process *up = arg;
100 	struct usb_proc_msg *pm;
101 	struct thread *td;
102 
103 	/* in case of attach error, check for suspended */
104 	USB_THREAD_SUSPEND_CHECK();
105 
106 	/* adjust priority */
107 	td = curthread;
108 	thread_lock(td);
109 	sched_prio(td, up->up_prio);
110 	thread_unlock(td);
111 
112 	mtx_lock(up->up_mtx);
113 
114 	up->up_curtd = td;
115 
116 	while (1) {
117 
118 		if (up->up_gone)
119 			break;
120 
121 		/*
122 		 * NOTE to reimplementors: dequeueing a command from the
123 		 * "used" queue and executing it must be atomic, with regard
124 		 * to the "up_mtx" mutex. That means any attempt to queue a
125 		 * command by another thread must be blocked until either:
126 		 *
127 		 * 1) the command sleeps
128 		 *
129 		 * 2) the command returns
130 		 *
131 		 * Here is a practical example that shows how this helps
132 		 * solving a problem:
133 		 *
134 		 * Assume that you want to set the baud rate on a USB serial
135 		 * device. During the programming of the device you don't
136 		 * want to receive nor transmit any data, because it will be
137 		 * garbage most likely anyway. The programming of our USB
138 		 * device takes 20 milliseconds and it needs to call
139 		 * functions that sleep.
140 		 *
141 		 * Non-working solution: Before we queue the programming
142 		 * command, we stop transmission and reception of data. Then
143 		 * we queue a programming command. At the end of the
144 		 * programming command we enable transmission and reception
145 		 * of data.
146 		 *
147 		 * Problem: If a second programming command is queued while the
148 		 * first one is sleeping, we end up enabling transmission
149 		 * and reception of data too early.
150 		 *
151 		 * Working solution: Before we queue the programming command,
152 		 * we stop transmission and reception of data. Then we queue
153 		 * a programming command. Then we queue a second command
154 		 * that only enables transmission and reception of data.
155 		 *
156 		 * Why it works: If a second programming command is queued
157 		 * while the first one is sleeping, then the queueing of a
158 		 * second command to enable the data transfers, will cause
159 		 * the previous one, which is still on the queue, to be
160 		 * removed from the queue, and re-inserted after the last
161 		 * baud rate programming command, which then gives the
162 		 * desired result.
163 		 */
164 		pm = TAILQ_FIRST(&up->up_qhead);
165 
166 		if (pm) {
167 			DPRINTF("Message pm=%p, cb=%p (enter)\n",
168 			    pm, pm->pm_callback);
169 
170 			(pm->pm_callback) (pm);
171 
172 			if (pm == TAILQ_FIRST(&up->up_qhead)) {
173 				/* nothing changed */
174 				TAILQ_REMOVE(&up->up_qhead, pm, pm_qentry);
175 				pm->pm_qentry.tqe_prev = NULL;
176 			}
177 			DPRINTF("Message pm=%p (leave)\n", pm);
178 
179 			continue;
180 		}
181 		/* end if messages - check if anyone is waiting for sync */
182 		if (up->up_dsleep) {
183 			up->up_dsleep = 0;
184 			cv_broadcast(&up->up_drain);
185 		}
186 		up->up_msleep = 1;
187 		cv_wait(&up->up_cv, up->up_mtx);
188 	}
189 
190 	up->up_ptr = NULL;
191 	cv_signal(&up->up_cv);
192 	mtx_unlock(up->up_mtx);
193 #if (__FreeBSD_version >= 800000)
194 	/* Clear the proc pointer if this is the last thread. */
195 	if (--usb_pcount == 0)
196 		usbproc = NULL;
197 #endif
198 
199 	USB_THREAD_EXIT(0);
200 }
201 
202 /*------------------------------------------------------------------------*
203  *	usb_proc_create
204  *
205  * This function will create a process using the given "prio" that can
206  * execute callbacks. The mutex pointed to by "p_mtx" will be applied
207  * before calling the callbacks and released after that the callback
208  * has returned. The structure pointed to by "up" is assumed to be
209  * zeroed before this function is called.
210  *
211  * Return values:
212  *    0: success
213  * Else: failure
214  *------------------------------------------------------------------------*/
215 int
216 usb_proc_create(struct usb_process *up, struct mtx *p_mtx,
217     const char *pmesg, uint8_t prio)
218 {
219 	up->up_mtx = p_mtx;
220 	up->up_prio = prio;
221 
222 	TAILQ_INIT(&up->up_qhead);
223 
224 	cv_init(&up->up_cv, "-");
225 	cv_init(&up->up_drain, "usbdrain");
226 
227 	if (USB_THREAD_CREATE(&usb_process, up,
228 	    &up->up_ptr, "%s", pmesg)) {
229 		DPRINTFN(0, "Unable to create USB process.");
230 		up->up_ptr = NULL;
231 		goto error;
232 	}
233 #if (__FreeBSD_version >= 800000)
234 	usb_pcount++;
235 #endif
236 	return (0);
237 
238 error:
239 	usb_proc_free(up);
240 	return (ENOMEM);
241 }
242 
243 /*------------------------------------------------------------------------*
244  *	usb_proc_free
245  *
246  * NOTE: If the structure pointed to by "up" is all zero, this
247  * function does nothing.
248  *
249  * NOTE: Messages that are pending on the process queue will not be
250  * removed nor called.
251  *------------------------------------------------------------------------*/
252 void
253 usb_proc_free(struct usb_process *up)
254 {
255 	/* check if not initialised */
256 	if (up->up_mtx == NULL)
257 		return;
258 
259 	usb_proc_drain(up);
260 
261 	cv_destroy(&up->up_cv);
262 	cv_destroy(&up->up_drain);
263 
264 	/* make sure that we do not enter here again */
265 	up->up_mtx = NULL;
266 }
267 
268 /*------------------------------------------------------------------------*
269  *	usb_proc_msignal
270  *
271  * This function will queue one of the passed USB process messages on
272  * the USB process queue. The first message that is not already queued
273  * will get queued. If both messages are already queued the one queued
274  * last will be removed from the queue and queued in the end. The USB
275  * process mutex must be locked when calling this function. This
276  * function exploits the fact that a process can only do one callback
277  * at a time. The message that was queued is returned.
278  *------------------------------------------------------------------------*/
279 void   *
280 usb_proc_msignal(struct usb_process *up, void *_pm0, void *_pm1)
281 {
282 	struct usb_proc_msg *pm0 = _pm0;
283 	struct usb_proc_msg *pm1 = _pm1;
284 	struct usb_proc_msg *pm2;
285 	usb_size_t d;
286 	uint8_t t;
287 
288 	/* check if gone, return dummy value */
289 	if (up->up_gone)
290 		return (_pm0);
291 
292 	mtx_assert(up->up_mtx, MA_OWNED);
293 
294 	t = 0;
295 
296 	if (pm0->pm_qentry.tqe_prev) {
297 		t |= 1;
298 	}
299 	if (pm1->pm_qentry.tqe_prev) {
300 		t |= 2;
301 	}
302 	if (t == 0) {
303 		/*
304 		 * No entries are queued. Queue "pm0" and use the existing
305 		 * message number.
306 		 */
307 		pm2 = pm0;
308 	} else if (t == 1) {
309 		/* Check if we need to increment the message number. */
310 		if (pm0->pm_num == up->up_msg_num) {
311 			up->up_msg_num++;
312 		}
313 		pm2 = pm1;
314 	} else if (t == 2) {
315 		/* Check if we need to increment the message number. */
316 		if (pm1->pm_num == up->up_msg_num) {
317 			up->up_msg_num++;
318 		}
319 		pm2 = pm0;
320 	} else if (t == 3) {
321 		/*
322 		 * Both entries are queued. Re-queue the entry closest to
323 		 * the end.
324 		 */
325 		d = (pm1->pm_num - pm0->pm_num);
326 
327 		/* Check sign after subtraction */
328 		if (d & 0x80000000) {
329 			pm2 = pm0;
330 		} else {
331 			pm2 = pm1;
332 		}
333 
334 		TAILQ_REMOVE(&up->up_qhead, pm2, pm_qentry);
335 	} else {
336 		pm2 = NULL;		/* panic - should not happen */
337 	}
338 
339 	DPRINTF(" t=%u, num=%u\n", t, up->up_msg_num);
340 
341 	/* Put message last on queue */
342 
343 	pm2->pm_num = up->up_msg_num;
344 	TAILQ_INSERT_TAIL(&up->up_qhead, pm2, pm_qentry);
345 
346 	/* Check if we need to wakeup the USB process. */
347 
348 	if (up->up_msleep) {
349 		up->up_msleep = 0;	/* save "cv_signal()" calls */
350 		cv_signal(&up->up_cv);
351 	}
352 	return (pm2);
353 }
354 
355 /*------------------------------------------------------------------------*
356  *	usb_proc_is_gone
357  *
358  * Return values:
359  *    0: USB process is running
360  * Else: USB process is tearing down
361  *------------------------------------------------------------------------*/
362 uint8_t
363 usb_proc_is_gone(struct usb_process *up)
364 {
365 	if (up->up_gone)
366 		return (1);
367 
368 	/*
369 	 * Allow calls when up_mtx is NULL, before the USB process
370 	 * structure is initialised.
371 	 */
372 	if (up->up_mtx != NULL)
373 		mtx_assert(up->up_mtx, MA_OWNED);
374 	return (0);
375 }
376 
377 /*------------------------------------------------------------------------*
378  *	usb_proc_mwait
379  *
380  * This function will return when the USB process message pointed to
381  * by "pm" is no longer on a queue. This function must be called
382  * having "up->up_mtx" locked.
383  *------------------------------------------------------------------------*/
384 void
385 usb_proc_mwait(struct usb_process *up, void *_pm0, void *_pm1)
386 {
387 	struct usb_proc_msg *pm0 = _pm0;
388 	struct usb_proc_msg *pm1 = _pm1;
389 
390 	/* check if gone */
391 	if (up->up_gone)
392 		return;
393 
394 	mtx_assert(up->up_mtx, MA_OWNED);
395 
396 	if (up->up_curtd == curthread) {
397 		/* Just remove the messages from the queue. */
398 		if (pm0->pm_qentry.tqe_prev) {
399 			TAILQ_REMOVE(&up->up_qhead, pm0, pm_qentry);
400 			pm0->pm_qentry.tqe_prev = NULL;
401 		}
402 		if (pm1->pm_qentry.tqe_prev) {
403 			TAILQ_REMOVE(&up->up_qhead, pm1, pm_qentry);
404 			pm1->pm_qentry.tqe_prev = NULL;
405 		}
406 	} else
407 		while (pm0->pm_qentry.tqe_prev ||
408 		    pm1->pm_qentry.tqe_prev) {
409 			/* check if config thread is gone */
410 			if (up->up_gone)
411 				break;
412 			up->up_dsleep = 1;
413 			cv_wait(&up->up_drain, up->up_mtx);
414 		}
415 }
416 
417 /*------------------------------------------------------------------------*
418  *	usb_proc_drain
419  *
420  * This function will tear down an USB process, waiting for the
421  * currently executing command to return.
422  *
423  * NOTE: If the structure pointed to by "up" is all zero,
424  * this function does nothing.
425  *------------------------------------------------------------------------*/
426 void
427 usb_proc_drain(struct usb_process *up)
428 {
429 	/* check if not initialised */
430 	if (up->up_mtx == NULL)
431 		return;
432 	/* handle special case with Giant */
433 	if (up->up_mtx != &Giant)
434 		mtx_assert(up->up_mtx, MA_NOTOWNED);
435 
436 	mtx_lock(up->up_mtx);
437 
438 	/* Set the gone flag */
439 
440 	up->up_gone = 1;
441 
442 	while (up->up_ptr) {
443 
444 		/* Check if we need to wakeup the USB process */
445 
446 		if (up->up_msleep || up->up_csleep) {
447 			up->up_msleep = 0;
448 			up->up_csleep = 0;
449 			cv_signal(&up->up_cv);
450 		}
451 		/* Check if we are still cold booted */
452 
453 		if (cold) {
454 			USB_THREAD_SUSPEND(up->up_ptr);
455 			printf("WARNING: A USB process has "
456 			    "been left suspended\n");
457 			break;
458 		}
459 		cv_wait(&up->up_cv, up->up_mtx);
460 	}
461 	/* Check if someone is waiting - should not happen */
462 
463 	if (up->up_dsleep) {
464 		up->up_dsleep = 0;
465 		cv_broadcast(&up->up_drain);
466 		DPRINTF("WARNING: Someone is waiting "
467 		    "for USB process drain!\n");
468 	}
469 	mtx_unlock(up->up_mtx);
470 }
471 
472 /*------------------------------------------------------------------------*
473  *	usb_proc_rewakeup
474  *
475  * This function is called to re-wakeup the given USB
476  * process. This usually happens after that the USB system has been in
477  * polling mode, like during a panic. This function must be called
478  * having "up->up_mtx" locked.
479  *------------------------------------------------------------------------*/
480 void
481 usb_proc_rewakeup(struct usb_process *up)
482 {
483 	/* check if not initialised */
484 	if (up->up_mtx == NULL)
485 		return;
486 	/* check if gone */
487 	if (up->up_gone)
488 		return;
489 
490 	mtx_assert(up->up_mtx, MA_OWNED);
491 
492 	if (up->up_msleep == 0) {
493 		/* re-wakeup */
494 		cv_signal(&up->up_cv);
495 	}
496 }
497