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