VirtualBox

source: vbox/trunk/src/VBox/Devices/USB/linux/USBProxyDevice-linux.cpp@ 31557

Last change on this file since 31557 was 31557, checked in by vboxsync, 15 years ago

Devices/USB and RDP/client: share USB code

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 65.4 KB
Line 
1/* $Id: USBProxyDevice-linux.cpp 31557 2010-08-11 09:15:04Z vboxsync $ */
2/** @file
3 * USB device proxy - the Linux backend.
4 */
5
6/*
7 * Copyright (C) 2006-2010 Oracle Corporation
8 *
9 * Oracle Corporation confidential
10 * All rights reserved
11 */
12
13/* START */
14
15/*******************************************************************************
16* Defined Constants And Macros *
17*******************************************************************************/
18/** Define NO_PORT_RESET to skip the slow and broken linux port reset.
19 * Resetting will break PalmOne. */
20#define NO_PORT_RESET
21/** Define NO_LOGICAL_RECONNECT to skip the broken logical reconnect handling. */
22#define NO_LOGICAL_RECONNECT
23
24
25/*******************************************************************************
26* Header Files *
27*******************************************************************************/
28#define LOG_GROUP LOG_GROUP_DRV_USBPROXY
29#ifndef RDESKTOP
30# include <iprt/stdint.h>
31# include <iprt/err.h>
32#endif
33#include <sys/types.h>
34#include <sys/stat.h>
35#include <sys/vfs.h>
36#include <sys/ioctl.h>
37#include <sys/poll.h>
38#include <stdint.h>
39#include <stdio.h>
40#include <string.h>
41#include <stdlib.h>
42#include <limits.h>
43#include <unistd.h>
44#include <fcntl.h>
45#include <errno.h>
46#ifdef VBOX_WITH_LINUX_COMPILER_H
47# include <linux/compiler.h>
48#endif
49#include <linux/usbdevice_fs.h>
50/*
51 * Backlevel 2.4 headers doesn't have these two defines.
52 * They were added some time between 2.4.21 and 2.4.26, probably in 2.4.23.
53 */
54#ifndef USBDEVFS_DISCONNECT
55# define USBDEVFS_DISCONNECT _IO('U', 22)
56# define USBDEVFS_CONNECT _IO('U', 23)
57#endif
58
59#ifndef USBDEVFS_URB_SHORT_NOT_OK
60# define USBDEVFS_URB_SHORT_NOT_OK 0 /* rhel3 doesn't have this. darn! */
61#endif
62
63
64/* FedoraCore 4 does not have the bit defined by default. */
65#ifndef POLLWRNORM
66# define POLLWRNORM 0x0100
67#endif
68
69#ifndef RDESKTOP
70# include <VBox/pdm.h>
71# include <VBox/err.h>
72# include <VBox/log.h>
73# include <iprt/alloc.h>
74# include <iprt/assert.h>
75# include <iprt/asm.h>
76# include <iprt/ctype.h>
77# include <iprt/file.h>
78# include <iprt/linux/sysfs.h>
79# include <iprt/stream.h>
80# include <iprt/string.h>
81# include <iprt/thread.h>
82# include <iprt/time.h>
83# include "../USBProxyDevice.h"
84#else
85
86# include "../rdesktop.h"
87# include "runtime.h"
88# include "USBProxyDevice.h"
89# ifdef VBOX_USB_WITH_SYSFS
90# include "sysfs.h"
91# endif
92#endif
93
94
95/*******************************************************************************
96* Structures and Typedefs *
97*******************************************************************************/
98/**
99 * Wrapper around the linux urb request structure.
100 * This is required to track in-flight and landed URBs.
101 */
102typedef struct USBPROXYURBLNX
103{
104 /** The kernel URB data */
105 struct usbdevfs_urb KUrb;
106 /** Space filler for the isochronous packets. */
107 struct usbdevfs_iso_packet_desc aIsocPktsDonUseTheseUseTheOnesInKUrb[8];
108 /** The millisecond timestamp when this URB was submitted. */
109 uint64_t u64SubmitTS;
110 /** Pointer to the next linux URB. */
111 struct USBPROXYURBLNX *pNext;
112 /** Pointer to the previous linux URB. */
113 struct USBPROXYURBLNX *pPrev;
114 /** If we've split the VUSBURB up into multiple linux URBs, this is points to the head. */
115 struct USBPROXYURBLNX *pSplitHead;
116 /** The next linux URB if split up. */
117 struct USBPROXYURBLNX *pSplitNext;
118 /** Whether it has timed out and should be shot down on the next failing reap call. */
119 bool fTimedOut;
120 /** Indicates that this URB has been canceled by timeout and should return an CRC error. */
121 bool fCanceledByTimedOut;
122 /** Don't report these back. */
123 bool fCanceledBySubmit;
124 /** This split element is reaped. */
125 bool fSplitElementReaped;
126 /** Size to transfer in remaining fragments of a split URB */
127 uint32_t cbSplitRemaining;
128} USBPROXYURBLNX, *PUSBPROXYURBLNX;
129
130/**
131 * Data for the linux usb proxy backend.
132 */
133typedef struct USBPROXYDEVLNX
134{
135 /** The open file. */
136 RTFILE File;
137 /** Critical section protecting the two lists. */
138 RTCRITSECT CritSect;
139 /** The list of free linux URBs. Singly linked. */
140 PUSBPROXYURBLNX pFreeHead;
141 /** The list of active linux URBs. Doubly linked.
142 * We must maintain this so we can properly reap URBs of a detached device.
143 * Only the split head will appear in this list. */
144 PUSBPROXYURBLNX pInFlightHead;
145 /** The list of landed linux URBs. Doubly linked.
146 * Only the split head will appear in this list. */
147 PUSBPROXYURBLNX pTaxingHead;
148 /** The tail of the landed linux URBs. */
149 PUSBPROXYURBLNX pTaxingTail;
150 /** Are we using sysfs to find the active configuration? */
151 bool fUsingSysfs;
152 /** The device node/sysfs path of the device.
153 * Used to figure out the configuration after a reset. */
154 char szPath[1];
155} USBPROXYDEVLNX, *PUSBPROXYDEVLNX;
156
157
158/*******************************************************************************
159* Internal Functions *
160*******************************************************************************/
161static int usbProxyLinuxDoIoCtl(PUSBPROXYDEV pProxyDev, unsigned long iCmd, void *pvArg, bool fHandleNoDev, uint32_t cTries);
162static void usbProxLinuxUrbUnplugged(PUSBPROXYDEV pProxyDev);
163static void usbProxyLinuxSetConnected(PUSBPROXYDEV pProyxDev, int iIf, bool fConnect, bool fQuiet);
164static PUSBPROXYURBLNX usbProxyLinuxUrbAlloc(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pSplitHead);
165static void usbProxyLinuxUrbFree(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pUrbLnx);
166static void usbProxyLinuxUrbFreeSplitList(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pUrbLnx);
167static int usbProxyLinuxFindActiveConfig(PUSBPROXYDEV pProxyDev, const char *pszPath, int *piFirstCfg);
168
169
170
171/**
172 * Wrapper for the ioctl call.
173 *
174 * This wrapper will repeate the call if we get an EINTR or EAGAIN. It can also
175 * handle ENODEV (detached device) errors.
176 *
177 * @returns whatever ioctl returns.
178 * @param pProxyDev The proxy device.
179 * @param iCmd The ioctl command / function.
180 * @param pvArg The ioctl argument / data.
181 * @param fHandleNoDev Whether to handle ENODEV.
182 * @param cTries The number of retries. Use UINT32_MAX for (kind of) indefinite retries.
183 * @internal
184 */
185static int usbProxyLinuxDoIoCtl(PUSBPROXYDEV pProxyDev, unsigned long iCmd, void *pvArg, bool fHandleNoDev, uint32_t cTries)
186{
187 int rc;
188 PUSBPROXYDEVLNX pDevLnx = (PUSBPROXYDEVLNX)pProxyDev->Backend.pv;
189 do
190 {
191 do
192 {
193 rc = ioctl(pDevLnx->File, iCmd, pvArg);
194 if (rc >= 0)
195 return rc;
196 } while (errno == EINTR);
197
198 if (errno == ENODEV && fHandleNoDev)
199 {
200 usbProxLinuxUrbUnplugged(pProxyDev);
201 Log(("usb-linux: ENODEV -> unplugged. pProxyDev=%s\n", usbProxyGetName(pProxyDev)));
202 errno = ENODEV;
203 break;
204 }
205 if (errno != EAGAIN)
206 break;
207 } while (cTries-- > 0);
208
209 return rc;
210}
211
212
213/**
214 * The device has been unplugged.
215 * Cancel all in-flight URBs and put them up for reaping.
216 */
217static void usbProxLinuxUrbUnplugged(PUSBPROXYDEV pProxyDev)
218{
219 PUSBPROXYDEVLNX pDevLnx = (PUSBPROXYDEVLNX)pProxyDev->Backend.pv;
220
221 /*
222 * Shoot down all flying URBs.
223 */
224 RTCritSectEnter(&pDevLnx->CritSect);
225 pProxyDev->fDetached = true;
226
227 PUSBPROXYURBLNX pUrbTaxing = NULL;
228 PUSBPROXYURBLNX pUrbLnx = pDevLnx->pInFlightHead;
229 pDevLnx->pInFlightHead = NULL;
230 while (pUrbLnx)
231 {
232 PUSBPROXYURBLNX pCur = pUrbLnx;
233 pUrbLnx = pUrbLnx->pNext;
234
235 ioctl(pDevLnx->File, USBDEVFS_DISCARDURB, &pCur->KUrb); /* not sure if this is required.. */
236 if (!pCur->KUrb.status)
237 pCur->KUrb.status = -ENODEV;
238
239 /* insert into the taxing list. */
240 pCur->pPrev = NULL;
241 if ( !pCur->pSplitHead
242 || pCur == pCur->pSplitHead)
243 {
244 pCur->pNext = pUrbTaxing;
245 if (pUrbTaxing)
246 pUrbTaxing->pPrev = pCur;
247 pUrbTaxing = pCur;
248 }
249 else
250 pCur->pNext = NULL;
251 }
252
253 /* Append the URBs we shot down to the taxing queue. */
254 if (pUrbTaxing)
255 {
256 pUrbTaxing->pPrev = pDevLnx->pTaxingTail;
257 if (pUrbTaxing->pPrev)
258 pUrbTaxing->pPrev->pNext = pUrbTaxing;
259 else
260 pDevLnx->pTaxingTail = pDevLnx->pTaxingHead = pUrbTaxing;
261 }
262
263 RTCritSectLeave(&pDevLnx->CritSect);
264}
265
266
267/**
268 * Set the connect state seen by kernel drivers
269 * @internal
270 */
271static void usbProxyLinuxSetConnected(PUSBPROXYDEV pProxyDev, int iIf, bool fConnect, bool fQuiet)
272{
273 if ( iIf >= 32
274 || !(pProxyDev->fMaskedIfs & RT_BIT(iIf)))
275 {
276 struct usbdevfs_ioctl IoCtl;
277 if (!fQuiet)
278 LogFlow(("usbProxyLinuxSetConnected: pProxyDev=%s iIf=%#x fConnect=%s\n",
279 usbProxyGetName(pProxyDev), iIf, fConnect ? "true" : "false"));
280
281 IoCtl.ifno = iIf;
282 IoCtl.ioctl_code = fConnect ? USBDEVFS_CONNECT : USBDEVFS_DISCONNECT;
283 IoCtl.data = NULL;
284 if ( usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_IOCTL, &IoCtl, true, UINT32_MAX)
285 && !fQuiet)
286 Log(("usbProxyLinuxSetConnected: failure, errno=%d. pProxyDev=%s\n",
287 errno, usbProxyGetName(pProxyDev)));
288 }
289}
290
291
292/**
293 * Allocates a linux URB request structure.
294 * @returns Pointer to an active URB request.
295 * @returns NULL on failure.
296 * @param pProxyDev The proxy device instance.
297 * @param pSplitHead The split list head if allocating for a split list.
298 */
299static PUSBPROXYURBLNX usbProxyLinuxUrbAlloc(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pSplitHead)
300{
301 PUSBPROXYDEVLNX pDevLnx = (PUSBPROXYDEVLNX)pProxyDev->Backend.pv;
302 PUSBPROXYURBLNX pUrbLnx;
303
304 RTCritSectEnter(&pDevLnx->CritSect);
305
306 /*
307 * Try remove a linux URB from the free list, if none there allocate a new one.
308 */
309 pUrbLnx = pDevLnx->pFreeHead;
310 if (pUrbLnx)
311 pDevLnx->pFreeHead = pUrbLnx->pNext;
312 else
313 {
314 RTCritSectLeave(&pDevLnx->CritSect);
315 pUrbLnx = (PUSBPROXYURBLNX)RTMemAlloc(sizeof(*pUrbLnx));
316 if (!pUrbLnx)
317 return NULL;
318 RTCritSectEnter(&pDevLnx->CritSect);
319 }
320 pUrbLnx->pSplitHead = pSplitHead;
321 pUrbLnx->pSplitNext = NULL;
322 pUrbLnx->fTimedOut = false;
323 pUrbLnx->fCanceledByTimedOut = false;
324 pUrbLnx->fCanceledBySubmit = false;
325 pUrbLnx->fSplitElementReaped = false;
326
327 /*
328 * Link it into the active list
329 */
330 if (!pSplitHead)
331 {
332 pUrbLnx->pPrev = NULL;
333 pUrbLnx->pNext = pDevLnx->pInFlightHead;
334 if (pUrbLnx->pNext)
335 pUrbLnx->pNext->pPrev = pUrbLnx;
336 pDevLnx->pInFlightHead = pUrbLnx;
337 }
338 else
339 pUrbLnx->pPrev = pUrbLnx->pNext = (PUSBPROXYURBLNX)0xdead;
340
341 RTCritSectLeave(&pDevLnx->CritSect);
342 return pUrbLnx;
343}
344
345
346/**
347 * Frees a linux URB request structure.
348 *
349 * @param pProxyDev The proxy device instance.
350 * @param pUrbLnx The linux URB to free.
351 */
352static void usbProxyLinuxUrbFree(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pUrbLnx)
353{
354 PUSBPROXYDEVLNX pDevLnx = (PUSBPROXYDEVLNX)pProxyDev->Backend.pv;
355
356 RTCritSectEnter(&pDevLnx->CritSect);
357
358 /*
359 * Remove from the active list.
360 */
361 if ( !pUrbLnx->pSplitHead
362 || pUrbLnx->pSplitHead == pUrbLnx)
363 {
364 if (pUrbLnx->pNext)
365 pUrbLnx->pNext->pPrev = pUrbLnx->pPrev;
366 if (pUrbLnx->pPrev)
367 pUrbLnx->pPrev->pNext = pUrbLnx->pNext;
368 else
369 pDevLnx->pInFlightHead = pUrbLnx->pNext;
370 }
371 pUrbLnx->pSplitHead = pUrbLnx->pSplitNext = NULL;
372
373 /*
374 * Link it into the free list.
375 */
376 pUrbLnx->pPrev = NULL;
377 pUrbLnx->pNext = pDevLnx->pFreeHead;
378 pDevLnx->pFreeHead = pUrbLnx;
379
380 RTCritSectLeave(&pDevLnx->CritSect);
381}
382
383
384/**
385 * Frees split list of a linux URB request structure.
386 *
387 * @param pProxyDev The proxy device instance.
388 * @param pUrbLnx A linux URB to in the split list to be freed.
389 */
390static void usbProxyLinuxUrbFreeSplitList(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pUrbLnx)
391{
392 PUSBPROXYDEVLNX pDevLnx = (PUSBPROXYDEVLNX)pProxyDev->Backend.pv;
393
394 RTCritSectEnter(&pDevLnx->CritSect);
395
396 pUrbLnx = pUrbLnx->pSplitHead;
397 Assert(pUrbLnx);
398 while (pUrbLnx)
399 {
400 PUSBPROXYURBLNX pFree = pUrbLnx;
401 pUrbLnx = pUrbLnx->pSplitNext;
402 Assert(pFree->pSplitHead);
403 usbProxyLinuxUrbFree(pProxyDev, pFree);
404 }
405
406 RTCritSectLeave(&pDevLnx->CritSect);
407}
408
409
410/**
411 * This finds the device in the /proc/bus/usb/bus/addr file and finds
412 * the config with an asterix.
413 *
414 * @returns The Cfg#.
415 * @returns -1 if no active config.
416 * @param pszDevNode The path to the device. We infere the location of
417 * the devices file, which bus and device number we're
418 * looking for.
419 * @param iFirstCfg The first configuration. (optional)
420 * @internal
421 */
422static int usbProxyLinuxFindActiveConfigUsbfs(PUSBPROXYDEV pProxyDev, const char *pszDevNode, int *piFirstCfg)
423{
424 /*
425 * Set return defaults.
426 */
427 int iActiveCfg = -1;
428 if (piFirstCfg)
429 *piFirstCfg = 1;
430
431 /*
432 * Parse the usbfs device node path and turn it into a path to the "devices" file,
433 * picking up the device number and bus along the way.
434 */
435 size_t cchDevNode = strlen(pszDevNode);
436 char *pszDevices = (char *)RTMemDupEx(pszDevNode, cchDevNode, sizeof("devices"));
437 AssertReturn(pszDevices, iActiveCfg);
438
439 /* the device number */
440 char *psz = pszDevices + cchDevNode;
441 while (*psz != '/')
442 psz--;
443 Assert(pszDevices < psz);
444 uint32_t uDev;
445 int rc = RTStrToUInt32Ex(psz + 1, NULL, 10, &uDev);
446 if (RT_SUCCESS(rc))
447 {
448 /* the bus number */
449 *psz-- = '\0';
450 while (*psz != '/')
451 psz--;
452 Assert(pszDevices < psz);
453 uint32_t uBus;
454 rc = RTStrToUInt32Ex(psz + 1, NULL, 10, &uBus);
455 if (RT_SUCCESS(rc))
456 {
457 strcpy(psz + 1, "devices");
458
459 /*
460 * Open and scan the devices file.
461 * We're ASSUMING that each device starts off with a 'T:' line.
462 */
463 PRTSTREAM pFile;
464 rc = RTStrmOpen(pszDevices, "r", &pFile);
465 if (RT_SUCCESS(rc))
466 {
467 char szLine[1024];
468 while (RT_SUCCESS(RTStrmGetLine(pFile, szLine, sizeof(szLine))))
469 {
470 /* we're only interested in 'T:' lines. */
471 psz = RTStrStripL(szLine);
472 if (psz[0] != 'T' || psz[1] != ':')
473 continue;
474
475 /* Skip ahead to 'Bus' and compare */
476 psz = RTStrStripL(psz + 2); Assert(!strncmp(psz, "Bus=", 4));
477 psz = RTStrStripL(psz + 4);
478 char *pszNext;
479 uint32_t u;
480 rc = RTStrToUInt32Ex(psz, &pszNext, 10, &u); AssertRC(rc);
481 if (RT_FAILURE(rc))
482 continue;
483 if (u != uBus)
484 continue;
485
486 /* Skip ahead to 'Dev#' and compare */
487 psz = strstr(psz, "Dev#="); Assert(psz);
488 if (!psz)
489 continue;
490 psz = RTStrStripL(psz + 5);
491 rc = RTStrToUInt32Ex(psz, &pszNext, 10, &u); AssertRC(rc);
492 if (RT_FAILURE(rc))
493 continue;
494 if (u != uDev)
495 continue;
496
497 /*
498 * Ok, we've found the device.
499 * Scan until we find a selected configuration, the next device, or EOF.
500 */
501 while (RT_SUCCESS(RTStrmGetLine(pFile, szLine, sizeof(szLine))))
502 {
503 psz = RTStrStripL(szLine);
504 if (psz[0] == 'T')
505 break;
506 if (psz[0] != 'C' || psz[1] != ':')
507 continue;
508 const bool fActive = psz[2] == '*';
509 if (!fActive && !piFirstCfg)
510 continue;
511
512 /* Get the 'Cfg#' value. */
513 psz = strstr(psz, "Cfg#="); Assert(psz);
514 if (psz)
515 {
516 psz = RTStrStripL(psz + 5);
517 rc = RTStrToUInt32Ex(psz, &pszNext, 10, &u); AssertRC(rc);
518 if (RT_SUCCESS(rc))
519 {
520 if (piFirstCfg)
521 {
522 *piFirstCfg = u;
523 piFirstCfg = NULL;
524 }
525 if (fActive)
526 iActiveCfg = u;
527 }
528 }
529 if (fActive)
530 break;
531 }
532 break;
533 }
534 RTStrmClose(pFile);
535 }
536 }
537 }
538 RTMemFree(pszDevices);
539
540 return iActiveCfg;
541}
542
543
544/**
545 * This finds the active configuration from sysfs.
546 *
547 * @returns The Cfg#.
548 * @returns -1 if no active config.
549 * @param pszPath The sysfs path for the device.
550 * @param piFirstCfg The first configuration. (optional)
551 * @internal
552 */
553static int usbProxyLinuxFindActiveConfigSysfs(PUSBPROXYDEV pProxyDev, const char *pszPath, int *piFirstCfg)
554{
555#ifdef VBOX_USB_WITH_SYSFS
556 if (piFirstCfg != NULL)
557 *piFirstCfg = pProxyDev->paCfgDescs != NULL
558 ? pProxyDev->paCfgDescs[0].Core.bConfigurationValue
559 : 1;
560 return RTLinuxSysFsReadIntFile(10, "%s/bConfigurationValue", pszPath); /* returns -1 on failure */
561#else /* !VBOX_USB_WITH_SYSFS */
562 return -1;
563#endif /* !VBOX_USB_WITH_SYSFS */
564}
565
566
567/**
568 * This finds the active configuration.
569 *
570 * @returns The Cfg#.
571 * @returns -1 if no active config.
572 * @param pszPath The sysfs path for the device, or the usbfs device
573 * node path.
574 * @param iFirstCfg The first configuration. (optional)
575 * @internal
576 */
577static int usbProxyLinuxFindActiveConfig(PUSBPROXYDEV pProxyDev, const char *pszPath, int *piFirstCfg)
578{
579 PUSBPROXYDEVLNX pDevLnx = (PUSBPROXYDEVLNX)pProxyDev->Backend.pv;
580 if (pDevLnx->fUsingSysfs)
581 return usbProxyLinuxFindActiveConfigSysfs(pProxyDev, pszPath, piFirstCfg);
582 return usbProxyLinuxFindActiveConfigUsbfs(pProxyDev, pszPath, piFirstCfg);
583}
584
585
586/**
587 * Extracts the Linux file descriptor associated with the kernel USB device.
588 * This is used by rdesktop-vrdp for polling for events.
589 * @returns the FD, or asserts and returns -1 on error
590 * @param pProxyDev The device instance
591 */
592RTDECL(int) USBProxyDeviceLinuxGetFD(PUSBPROXYDEV pProxyDev)
593{
594 PUSBPROXYDEVLNX pDevLnx = (PUSBPROXYDEVLNX)pProxyDev->Backend.pv;
595 AssertReturn(pDevLnx->File != NIL_RTFILE, -1);
596 return pDevLnx->File;
597}
598
599
600/**
601 * Opens the device file.
602 *
603 * @returns VBox status code.
604 * @param pProxyDev The device instance.
605 * @param pszAddress If we are using usbfs, this is the path to the
606 * device. If we are using sysfs, this is a string of
607 * the form "sysfs:<sysfs path>//device:<device node>".
608 * In the second case, the two paths are guaranteed
609 * not to contain the substring "//".
610 * @param pvBackend Backend specific pointer, unused for the linux backend.
611 */
612static int usbProxyLinuxOpen(PUSBPROXYDEV pProxyDev, const char *pszAddress, void *pvBackend)
613{
614 LogFlow(("usbProxyLinuxOpen: pProxyDev=%p pszAddress=%s\n", pProxyDev, pszAddress));
615 const char *pszDevNode;
616 const char *pszPath;
617 size_t cchPath;
618 bool fUsingSysfs;
619
620 /*
621 * Are we using sysfs or usbfs?
622 */
623#ifdef VBOX_USB_WITH_SYSFS
624 fUsingSysfs = strncmp(pszAddress, "sysfs:", sizeof("sysfs:") - 1) == 0;
625 if (fUsingSysfs)
626 {
627 pszDevNode = strstr(pszAddress, "//device:");
628 if (!pszDevNode)
629 {
630 LogRel(("usbProxyLinuxOpen: Invalid device address: '%s'\n", pszAddress));
631 pProxyDev->Backend.pv = NULL;
632 return VERR_INVALID_PARAMETER;
633 }
634
635 pszPath = pszAddress + sizeof("sysfs:") - 1;
636 cchPath = pszDevNode - pszPath;
637 pszDevNode += sizeof("//device:") - 1;
638 }
639 else
640#endif /* VBOX_USB_WITH_SYSFS */
641 {
642#ifndef VBOX_USB_WITH_SYSFS
643 fUsingSysfs = false;
644#endif
645 pszPath = pszDevNode = pszAddress;
646 cchPath = strlen(pszPath);
647 }
648
649 /*
650 * Try open the device node.
651 */
652 RTFILE File;
653 int rc = RTFileOpen(&File, pszDevNode, RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
654 if (RT_SUCCESS(rc))
655 {
656 /*
657 * Allocate and initialize the linux backend data.
658 */
659 PUSBPROXYDEVLNX pDevLnx = (PUSBPROXYDEVLNX)RTMemAllocZVar(sizeof(*pDevLnx) + cchPath);
660 if (pDevLnx)
661 {
662 pDevLnx->fUsingSysfs = fUsingSysfs;
663 memcpy(&pDevLnx->szPath[0], pszPath, cchPath);
664 pDevLnx->szPath[cchPath] = '\0';
665 pDevLnx->File = File;
666 rc = RTCritSectInit(&pDevLnx->CritSect);
667 if (RT_SUCCESS(rc))
668 {
669 pProxyDev->Backend.pv = pDevLnx;
670
671 LogFlow(("usbProxyLinuxOpen(%p, %s): returns successfully File=%d iActiveCfg=%d\n",
672 pProxyDev, pszAddress, pDevLnx->File, pProxyDev->iActiveCfg));
673
674 return VINF_SUCCESS;
675 }
676
677 RTMemFree(pDevLnx);
678 }
679 else
680 rc = VERR_NO_MEMORY;
681 RTFileClose(File);
682 }
683 else if (rc == VERR_ACCESS_DENIED)
684 rc = VERR_VUSB_USBFS_PERMISSION;
685
686 Log(("usbProxyLinuxOpen(%p, %s) failed, rc=%s!\n", pProxyDev, pszAddress,
687 RTErrGetShort(rc)));
688 pProxyDev->Backend.pv = NULL;
689
690 NOREF(pvBackend);
691 return rc;
692}
693
694
695/**
696 * Claims all the interfaces and figures out the
697 * current configuration.
698 *
699 * @returns VINF_SUCCESS.
700 * @param pProxyDev The proxy device.
701 */
702static int usbProxyLinuxInit(PUSBPROXYDEV pProxyDev)
703{
704 PUSBPROXYDEVLNX pDevLnx = (PUSBPROXYDEVLNX)pProxyDev->Backend.pv;
705
706 /*
707 * Brute force rulez.
708 * usbProxyLinuxSetConnected check for masked interfaces.
709 */
710 unsigned iIf;
711 for (iIf = 0; iIf < 256; iIf++)
712 usbProxyLinuxSetConnected(pProxyDev, iIf, false, true);
713
714 /*
715 * Determin the active configuration.
716 *
717 * If there isn't any active configuration, we will get EHOSTUNREACH (113) errors
718 * when trying to read the device descriptors in usbProxyDevCreate. So, we'll make
719 * the first one active (usually 1) then.
720 */
721 pProxyDev->cIgnoreSetConfigs = 1;
722 int iFirstCfg;
723 pProxyDev->iActiveCfg = usbProxyLinuxFindActiveConfig(pProxyDev, pDevLnx->szPath, &iFirstCfg);
724 if (pProxyDev->iActiveCfg == -1)
725 {
726 usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_SETCONFIGURATION, &iFirstCfg, false, UINT32_MAX);
727 pProxyDev->iActiveCfg = usbProxyLinuxFindActiveConfig(pProxyDev, pDevLnx->szPath, NULL);
728 Log(("usbProxyLinuxInit: No active config! Tried to set %d: iActiveCfg=%d\n", iFirstCfg, pProxyDev->iActiveCfg));
729 }
730 else
731 Log(("usbProxyLinuxInit(%p): iActiveCfg=%d\n", pProxyDev, pProxyDev->iActiveCfg));
732 return VINF_SUCCESS;
733}
734
735
736/**
737 * Closes the proxy device.
738 */
739static void usbProxyLinuxClose(PUSBPROXYDEV pProxyDev)
740{
741 LogFlow(("usbProxyLinuxClose: pProxyDev=%s\n", usbProxyGetName(pProxyDev)));
742 PUSBPROXYDEVLNX pDevLnx = (PUSBPROXYDEVLNX)pProxyDev->Backend.pv;
743 Assert(pDevLnx);
744 if (!pDevLnx)
745 return;
746
747 /*
748 * Try put the device in a state which linux can cope with before we release it.
749 * Resetting it would be a nice start, although we must remember
750 * that it might have been disconnected...
751 *
752 * Don't reset if we're masking interfaces or if construction failed.
753 */
754 if (pProxyDev->fInited)
755 {
756 /* ASSUMES: thread == EMT */
757 if ( pProxyDev->fMaskedIfs
758 || !usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_RESET, NULL, false, 10))
759 {
760 /* Connect drivers. */
761 unsigned iIf;
762 for (iIf = 0; iIf < 256; iIf++)
763 usbProxyLinuxSetConnected(pProxyDev, iIf, true, true);
764 LogRel(("USB: Successfully reset device pProxyDev=%s\n", usbProxyGetName(pProxyDev)));
765 }
766 else if (errno != ENODEV)
767 LogRel(("USB: Reset failed, errno=%d, pProxyDev=%s.\n", errno, usbProxyGetName(pProxyDev)));
768 else
769 Log(("USB: Reset failed, errno=%d (ENODEV), pProxyDev=%s.\n", errno, usbProxyGetName(pProxyDev)));
770 }
771
772 /*
773 * Now we can free all the resources and close the device.
774 */
775 RTCritSectDelete(&pDevLnx->CritSect);
776
777 PUSBPROXYURBLNX pUrbLnx;
778 while ((pUrbLnx = pDevLnx->pInFlightHead) != NULL)
779 {
780 pDevLnx->pInFlightHead = pUrbLnx->pNext;
781 if ( usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_DISCARDURB, &pUrbLnx->KUrb, false, UINT32_MAX)
782 && errno != ENODEV
783 && errno != ENOENT)
784 AssertMsgFailed(("errno=%d\n", errno));
785 if (pUrbLnx->pSplitHead)
786 {
787 PUSBPROXYURBLNX pCur = pUrbLnx->pSplitNext;
788 while (pCur)
789 {
790 PUSBPROXYURBLNX pFree = pCur;
791 pCur = pFree->pSplitNext;
792 if ( !pFree->fSplitElementReaped
793 && usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_DISCARDURB, &pFree->KUrb, false, UINT32_MAX)
794 && errno != ENODEV
795 && errno != ENOENT)
796 AssertMsgFailed(("errno=%d\n", errno));
797 RTMemFree(pFree);
798 }
799 }
800 else
801 Assert(!pUrbLnx->pSplitNext);
802 RTMemFree(pUrbLnx);
803 }
804
805 while ((pUrbLnx = pDevLnx->pFreeHead) != NULL)
806 {
807 pDevLnx->pFreeHead = pUrbLnx->pNext;
808 RTMemFree(pUrbLnx);
809 }
810
811 RTFileClose(pDevLnx->File);
812 pDevLnx->File = NIL_RTFILE;
813
814 RTMemFree(pDevLnx);
815 pProxyDev->Backend.pv = NULL;
816 LogFlow(("usbProxyLinuxClose: returns\n"));
817}
818
819
820#if defined(NO_PORT_RESET) && !defined(NO_LOGICAL_RECONNECT)
821/**
822 * Look for the logically reconnected device.
823 * After 5 seconds we'll give up.
824 *
825 * @returns VBox status code.
826 * @thread Reset thread or EMT.
827 */
828static int usb_reset_logical_reconnect(PUSBPROXYDEV pDev)
829{
830 FILE * pFile;
831 uint64_t u64StartTS = RTTimeMilliTS();
832
833 Log2(("usb_reset_logical_reconnect: pDev=%p:{.bBus=%#x, .bDevNum=%#x, .idVendor=%#x, .idProduct=%#x, .bcdDevice=%#x, .u64SerialHash=%#llx .bDevNumParent=%#x .bPort=%#x .bLevel=%#x}\n",
834 pDev, pDev->Info.bBus, pDev->Info.bDevNum, pDev->Info.idVendor, pDev->Info.idProduct, pDev->Info.bcdDevice,
835 pDev->Info.u64SerialHash, pDev->Info.bDevNumParent, pDev->Info.bPort, pDev->Info.bLevel));
836
837 /* First, let hubd get a chance to logically reconnect the device. */
838 if (!RTThreadYield())
839 RTThreadSleep(1);
840
841 /*
842 * Search for the new device address.
843 */
844 pFile = get_devices_file();
845 if (!pFile)
846 return VERR_FILE_NOT_FOUND;
847
848 /*
849 * Loop until found or 5seconds have elapsed.
850 */
851 for (;;) {
852 struct pollfd pfd;
853 uint8_t tmp;
854 int rc;
855 char buf[512];
856 uint64_t u64Elapsed;
857 int got = 0;
858 struct usb_dev_entry id = {0};
859
860 /*
861 * Since this is kernel ABI we don't need to be too fussy about
862 * the parsing.
863 */
864 while (fgets(buf, sizeof(buf), pFile)) {
865 char *psz = strchr(buf, '\n');
866 if ( psz == NULL ) {
867 AssertMsgFailed(("usb_reset_logical_reconnect: Line to long!!\n"));
868 break;
869 }
870 *psz = '\0';
871
872 switch ( buf[0] ) {
873 case 'T': /* topology */
874 /* Check if we've got enough for a device. */
875 if (got >= 2) {
876 Log2(("usb_reset_logical_reconnect: {.bBus=%#x, .bDevNum=%#x, .idVendor=%#x, .idProduct=%#x, .bcdDevice=%#x, .u64SerialHash=%#llx, .bDevNumParent=%#x, .bPort=%#x, .bLevel=%#x}\n",
877 id.bBus, id.bDevNum, id.idVendor, id.idProduct, id.bcdDevice, id.u64SerialHash, id.bDevNumParent, id.bPort, id.bLevel));
878 if ( id.bDevNumParent == pDev->Info.bDevNumParent
879 && id.idVendor == pDev->Info.idVendor
880 && id.idProduct == pDev->Info.idProduct
881 && id.bcdDevice == pDev->Info.bcdDevice
882 && id.u64SerialHash == pDev->Info.u64SerialHash
883 && id.bBus == pDev->Info.bBus
884 && id.bPort == pDev->Info.bPort
885 && id.bLevel == pDev->Info.bLevel) {
886 goto l_found;
887 }
888 }
889
890 /* restart */
891 got = 0;
892 memset(&id, 0, sizeof(id));
893
894 /*T: Bus=04 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#= 3 Spd=1.5 MxCh= 0*/
895 Log2(("usb_reset_logical_reconnect: %s\n", buf));
896 buf[10] = '\0';
897 if ( !get_u8(buf + 8, &id.bBus) )
898 break;
899 buf[49] = '\0';
900 psz = buf + 46;
901 while ( *psz == ' ' )
902 psz++;
903 if ( !get_u8(psz, &id.bDevNum) )
904 break;
905
906 buf[17] = '\0';
907 if ( !get_u8(buf + 15, &id.bLevel) )
908 break;
909 buf[25] = '\0';
910 if ( !get_u8(buf + 23, &id.bDevNumParent) )
911 break;
912 buf[33] = '\0';
913 if ( !get_u8(buf + 31, &id.bPort) )
914 break;
915 got++;
916 break;
917
918 case 'P': /* product */
919 Log2(("usb_reset_logical_reconnect: %s\n", buf));
920 buf[15] = '\0';
921 if ( !get_x16(buf + 11, &id.idVendor) )
922 break;
923 buf[27] = '\0';
924 if ( !get_x16(buf + 23, &id.idProduct) )
925 break;
926 buf[34] = '\0';
927 if ( buf[32] == ' ' )
928 buf[32] = '0';
929 id.bcdDevice = 0;
930 if ( !get_x8(buf + 32, &tmp) )
931 break;
932 id.bcdDevice = tmp << 8;
933 if ( !get_x8(buf + 35, &tmp) )
934 break;
935 id.bcdDevice |= tmp;
936 got++;
937 break;
938
939 case 'S': /* String descriptor */
940 /* Skip past "S:" and then the whitespace */
941 for(psz = buf + 2; *psz != '\0'; psz++)
942 if ( !RT_C_IS_SPACE(*psz) )
943 break;
944
945 /* If it is a serial number string, skip past
946 * "SerialNumber="
947 */
948 if ( strncmp(psz, "SerialNumber=", sizeof("SerialNumber=") - 1) )
949 break;
950
951 Log2(("usb_reset_logical_reconnect: %s\n", buf));
952 psz += sizeof("SerialNumber=") - 1;
953
954 usb_serial_hash(psz, &id.u64SerialHash);
955 break;
956 }
957 }
958
959 /*
960 * Check last.
961 */
962 if ( got >= 2
963 && id.bDevNumParent == pDev->Info.bDevNumParent
964 && id.idVendor == pDev->Info.idVendor
965 && id.idProduct == pDev->Info.idProduct
966 && id.bcdDevice == pDev->Info.bcdDevice
967 && id.u64SerialHash == pDev->Info.u64SerialHash
968 && id.bBus == pDev->Info.bBus
969 && id.bPort == pDev->Info.bPort
970 && id.bLevel == pDev->Info.bLevel) {
971 l_found:
972 /* close the existing file descriptor. */
973 RTFileClose(pDevLnx->File);
974 pDevLnx->File = NIL_RTFILE;
975
976 /* open stuff at the new address. */
977 pDev->Info = id;
978 if (usbProxyLinuxOpen(pDev, &id))
979 return VINF_SUCCESS;
980 break;
981 }
982
983 /*
984 * Wait for a while and then check the file again.
985 */
986 u64Elapsed = RTTimeMilliTS() - u64StartTS;
987 if (u64Elapsed >= 5000/*ms*/)
988 break; /* done */
989
990 pfd.fd = fileno(pFile);
991 pfd.events = POLLIN;
992 rc = poll(&pfd, 1, 5000 - u64Elapsed);
993 if (rc < 0) {
994 AssertMsg(errno == EINTR, ("errno=%d\n", errno));
995 RTThreadSleep(32); /* paranoia: don't eat cpu on failure */
996 }
997
998 rewind(pFile);
999 } /* for loop */
1000
1001 return VERR_GENERAL_FAILURE;
1002}
1003#endif /* !NO_PORT_RESET && !NO_LOGICAL_RECONNECT */
1004
1005
1006/**
1007 * Reset a device.
1008 *
1009 * @returns VBox status code.
1010 * @param pDev The device to reset.
1011 */
1012static int usbProxyLinuxReset(PUSBPROXYDEV pProxyDev, bool fResetOnLinux)
1013{
1014#ifdef NO_PORT_RESET
1015 PUSBPROXYDEVLNX pDevLnx = (PUSBPROXYDEVLNX)pProxyDev->Backend.pv;
1016
1017 /*
1018 * Specific device resets are NOPs.
1019 * Root hub resets that affects all devices are executed.
1020 *
1021 * The reasoning is that when a root hub reset is done, the guest shouldn't
1022 * will have to re enumerate the devices after doing this kind of reset.
1023 * So, it doesn't really matter if a device is 'logically disconnected'.
1024 */
1025 if ( !fResetOnLinux
1026 || pProxyDev->fMaskedIfs)
1027 LogFlow(("usbProxyLinuxReset: pProxyDev=%s - NO_PORT_RESET\n", usbProxyGetName(pProxyDev)));
1028 else
1029 {
1030 LogFlow(("usbProxyLinuxReset: pProxyDev=%s - Real Reset!\n", usbProxyGetName(pProxyDev)));
1031 if (usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_RESET, NULL, false, 10))
1032 {
1033 int rc = errno;
1034 Log(("usb-linux: Reset failed, rc=%s errno=%d.\n",
1035 RTErrGetShort(RTErrConvertFromErrno(rc)), rc));
1036 pProxyDev->iActiveCfg = -1;
1037 return RTErrConvertFromErrno(rc);
1038 }
1039
1040 /* find the active config - damn annoying. */
1041 pProxyDev->iActiveCfg = usbProxyLinuxFindActiveConfig(pProxyDev, pDevLnx->szPath, NULL);
1042 LogFlow(("usbProxyLinuxReset: returns successfully iActiveCfg=%d\n", pProxyDev->iActiveCfg));
1043 }
1044 pProxyDev->cIgnoreSetConfigs = 2;
1045
1046#else /* !NO_PORT_RESET */
1047
1048 /*
1049 * This is the alternative, we will allways reset when asked to do so.
1050 *
1051 * The problem we're facing here is that on reset failure linux will do
1052 * a 'logical reconnect' on the device. This will invalidate the current
1053 * handle and we'll have to reopen the device. This is problematic to say
1054 * the least, especially since it happens pretty often.
1055 */
1056 LogFlow(("usbProxyLinuxReset: pProxyDev=%s\n", usbProxyGetName(pProxyDev)));
1057# ifndef NO_LOGICAL_RECONNECT
1058 ASMAtomicIncU32(&g_cResetActive);
1059# endif
1060
1061 if (usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_RESET, NULL, false, 10))
1062 {
1063 int rc = errno;
1064# ifndef NO_LOGICAL_RECONNECT
1065 if (rc == ENODEV)
1066 {
1067 /*
1068 * This usually happens because of a 'logical disconnection'.
1069 * So, we're in for a real treat from our excellent OS now...
1070 */
1071 rc2 = usb_reset_logical_reconnect(pProxyDev);
1072 if (RT_FAILURE(rc2))
1073 usbProxLinuxUrbUnplugged(pProxyDev);
1074 if (RT_SUCCESS(rc2))
1075 {
1076 ASMAtomicDecU32(&g_cResetActive);
1077 LogFlow(("usbProxyLinuxReset: returns success (after recovering disconnected device!)\n"));
1078 return VINF_SUCCESS;
1079 }
1080 }
1081 ASMAtomicDecU32(&g_cResetActive);
1082# endif /* NO_LOGICAL_RECONNECT */
1083
1084 Log(("usb-linux: Reset failed, rc=%s errno=%d.\n",
1085 RTErrGetShort(RTErrConvertFromErrno(rc)), rc));
1086 pProxyDev->iActiveCfg = -1;
1087 return RTErrConvertFromErrno(rc);
1088 }
1089
1090# ifndef NO_LOGICAL_RECONNECT
1091 ASMAtomicDecU32(&g_cResetActive);
1092# endif
1093
1094 pProxyDev->cIgnoreSetConfigs = 2;
1095 LogFlow(("usbProxyLinuxReset: returns success\n"));
1096#endif /* !NO_PORT_RESET */
1097 return VINF_SUCCESS;
1098}
1099
1100
1101/**
1102 * SET_CONFIGURATION.
1103 *
1104 * The caller makes sure that it's not called first time after open or reset
1105 * with the active interface.
1106 *
1107 * @returns success indicator.
1108 * @param pProxyDev The device instance data.
1109 * @param iCfg The configuration to set.
1110 */
1111static int usbProxyLinuxSetConfig(PUSBPROXYDEV pProxyDev, int iCfg)
1112{
1113 LogFlow(("usbProxyLinuxSetConfig: pProxyDev=%s cfg=%#x\n",
1114 usbProxyGetName(pProxyDev), iCfg));
1115
1116 if (usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_SETCONFIGURATION, &iCfg, true, UINT32_MAX))
1117 {
1118 Log(("usb-linux: Set configuration. errno=%d\n", errno));
1119 return false;
1120 }
1121 return true;
1122}
1123
1124
1125/**
1126 * Claims an interface.
1127 * @returns success indicator.
1128 */
1129static int usbProxyLinuxClaimInterface(PUSBPROXYDEV pProxyDev, int iIf)
1130{
1131 LogFlow(("usbProxyLinuxClaimInterface: pProxyDev=%s ifnum=%#x\n", usbProxyGetName(pProxyDev), iIf));
1132 usbProxyLinuxSetConnected(pProxyDev, iIf, false, false);
1133
1134 if (usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_CLAIMINTERFACE, &iIf, true, UINT32_MAX))
1135 {
1136 Log(("usb-linux: Claim interface. errno=%d pProxyDev=%s\n", errno, usbProxyGetName(pProxyDev)));
1137 return false;
1138 }
1139 return true;
1140}
1141
1142
1143/**
1144 * Releases an interface.
1145 * @returns success indicator.
1146 */
1147static int usbProxyLinuxReleaseInterface(PUSBPROXYDEV pProxyDev, int iIf)
1148{
1149 LogFlow(("usbProxyLinuxReleaseInterface: pProxyDev=%s ifnum=%#x\n", usbProxyGetName(pProxyDev), iIf));
1150
1151 if (usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_RELEASEINTERFACE, &iIf, true, UINT32_MAX))
1152 {
1153 Log(("usb-linux: Release interface, errno=%d. pProxyDev=%s\n", errno, usbProxyGetName(pProxyDev)));
1154 return false;
1155 }
1156 return true;
1157}
1158
1159
1160/**
1161 * SET_INTERFACE.
1162 *
1163 * @returns success indicator.
1164 */
1165static int usbProxyLinuxSetInterface(PUSBPROXYDEV pProxyDev, int iIf, int iAlt)
1166{
1167 struct usbdevfs_setinterface SetIf;
1168 LogFlow(("usbProxyLinuxSetInterface: pProxyDev=%p iIf=%#x iAlt=%#x\n", pProxyDev, iIf, iAlt));
1169
1170 SetIf.interface = iIf;
1171 SetIf.altsetting = iAlt;
1172 if (usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_SETINTERFACE, &SetIf, true, UINT32_MAX))
1173 {
1174 Log(("usb-linux: Set interface, errno=%d. pProxyDev=%s\n", errno, usbProxyGetName(pProxyDev)));
1175 return false;
1176 }
1177 return true;
1178}
1179
1180
1181/**
1182 * Clears the halted endpoint 'EndPt'.
1183 */
1184static bool usbProxyLinuxClearHaltedEp(PUSBPROXYDEV pProxyDev, unsigned int EndPt)
1185{
1186 LogFlow(("usbProxyLinuxClearHaltedEp: pProxyDev=%s EndPt=%u\n", usbProxyGetName(pProxyDev), EndPt));
1187
1188 if (usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_CLEAR_HALT, &EndPt, true, UINT32_MAX))
1189 {
1190 /*
1191 * Unfortunately this doesn't work on control pipes.
1192 * Windows doing this on the default endpoint and possibly other pipes too,
1193 * so we'll feign success for ENOENT errors.
1194 */
1195 if (errno == ENOENT)
1196 {
1197 Log(("usb-linux: clear_halted_ep failed errno=%d. pProxyDev=%s ep=%d - IGNORED\n",
1198 errno, usbProxyGetName(pProxyDev), EndPt));
1199 return true;
1200 }
1201 Log(("usb-linux: clear_halted_ep failed errno=%d. pProxyDev=%s ep=%d\n",
1202 errno, usbProxyGetName(pProxyDev), EndPt));
1203 return false;
1204 }
1205 return true;
1206}
1207
1208
1209/**
1210 * Setup packet byte-swapping routines.
1211 */
1212static void usbProxyLinuxUrbSwapSetup(PVUSBSETUP pSetup)
1213{
1214 pSetup->wValue = RT_H2LE_U16(pSetup->wValue);
1215 pSetup->wIndex = RT_H2LE_U16(pSetup->wIndex);
1216 pSetup->wLength = RT_H2LE_U16(pSetup->wLength);
1217}
1218
1219
1220/**
1221 * Clean up after a failed URB submit.
1222 */
1223static void usbProxyLinuxCleanupFailedSubmit(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pUrbLnx, PUSBPROXYURBLNX pCur, PVUSBURB pUrb, bool *pfUnplugged)
1224{
1225 if (pUrb->enmType == VUSBXFERTYPE_MSG)
1226 usbProxyLinuxUrbSwapSetup((PVUSBSETUP)pUrb->abData);
1227
1228 /* discard and reap later (walking with pUrbLnx). */
1229 if (pUrbLnx != pCur)
1230 {
1231 for (;;)
1232 {
1233 pUrbLnx->fCanceledBySubmit = true;
1234 pUrbLnx->KUrb.usercontext = NULL;
1235 if (usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_DISCARDURB, &pUrbLnx->KUrb, false, UINT32_MAX))
1236 {
1237 if (errno == ENODEV)
1238 *pfUnplugged = true;
1239 else if (errno == ENOENT)
1240 pUrbLnx->fSplitElementReaped = true;
1241 else
1242 LogRel(("USB: Failed to discard %p! errno=%d (pUrb=%p)\n", pUrbLnx->KUrb.usercontext, errno, pUrb)); /* serious! */
1243 }
1244 if (pUrbLnx->pSplitNext == pCur)
1245 {
1246 pUrbLnx->pSplitNext = NULL;
1247 break;
1248 }
1249 pUrbLnx = pUrbLnx->pSplitNext; Assert(pUrbLnx);
1250 }
1251 }
1252
1253 /* free the unsubmitted ones. */
1254 while (pCur)
1255 {
1256 PUSBPROXYURBLNX pFree = pCur;
1257 pCur = pCur->pSplitNext;
1258 usbProxyLinuxUrbFree(pProxyDev, pFree);
1259 }
1260
1261 /* send unplug event if we failed with ENODEV originally. */
1262 if (*pfUnplugged)
1263 usbProxLinuxUrbUnplugged(pProxyDev);
1264}
1265
1266/**
1267 * Submit one URB through the usbfs IOCTL interface, with
1268 * retries
1269 *
1270 * @returns true / false.
1271 */
1272static bool usbProxyLinuxSubmitURB(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pCur, PVUSBURB pUrb, bool *pfUnplugged)
1273{
1274 PUSBPROXYDEVLNX pDevLnx = (PUSBPROXYDEVLNX)pProxyDev->Backend.pv;
1275 unsigned cTries = 0;
1276
1277 while (ioctl(pDevLnx->File, USBDEVFS_SUBMITURB, &pCur->KUrb))
1278 {
1279 if (errno == EINTR)
1280 continue;
1281 if (errno == ENODEV)
1282 {
1283 Log(("usbProxyLinuxSubmitURB: ENODEV -> unplugged. pProxyDev=%s\n", usbProxyGetName(pProxyDev)));
1284 *pfUnplugged = true;
1285 return false;
1286 }
1287
1288 Log(("usb-linux: Submit URB %p -> %d!!! type=%d ep=%#x buffer_length=%#x cTries=%d\n",
1289 pUrb, errno, pCur->KUrb.type, pCur->KUrb.endpoint, pCur->KUrb.buffer_length, cTries));
1290 if (errno != EBUSY && ++cTries < 3) /* this doesn't work for the floppy :/ */
1291 {
1292 pCur->u64SubmitTS = RTTimeMilliTS();
1293 continue;
1294 }
1295 return false;
1296 }
1297 return true;
1298}
1299
1300/** The split size. 16K in known Linux kernel versions. */
1301#define SPLIT_SIZE 0x4000
1302
1303/**
1304 * Create a URB fragment of up to SPLIT_SIZE size and hook it
1305 * into the list of fragments.
1306 *
1307 * @returns pointer to newly allocated URB fragment or NULL.
1308 */
1309static PUSBPROXYURBLNX usbProxyLinuxSplitURBFragment(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pHead, PUSBPROXYURBLNX pCur)
1310{
1311 PUSBPROXYURBLNX pNew;
1312 uint32_t cbLeft = pCur->cbSplitRemaining;
1313 uint8_t *pb = (uint8_t *)pCur->KUrb.buffer;
1314
1315 Assert(cbLeft != 0);
1316 pNew = pCur->pSplitNext = usbProxyLinuxUrbAlloc(pProxyDev, pHead);
1317 if (!pNew)
1318 {
1319 usbProxyLinuxUrbFreeSplitList(pProxyDev, pHead);
1320 return NULL;
1321 }
1322 Assert(pHead->pNext != pNew); Assert(pHead->pPrev != pNew); Assert(pNew->pNext == pNew->pPrev);
1323 Assert(pNew->pSplitHead == pHead);
1324 Assert(pNew->pSplitNext == NULL);
1325
1326 pNew->KUrb = pHead->KUrb;
1327 pNew->KUrb.buffer = pb + pCur->KUrb.buffer_length;
1328 pNew->KUrb.buffer_length = RT_MIN(cbLeft, SPLIT_SIZE);
1329 pNew->KUrb.actual_length = 0;
1330
1331 cbLeft -= pNew->KUrb.buffer_length;
1332 Assert(cbLeft < INT32_MAX);
1333 pNew->cbSplitRemaining = cbLeft;
1334 return pNew;
1335}
1336
1337/**
1338 * Try splitting up a VUSB URB into smaller URBs which the
1339 * linux kernel (usbfs) can deal with.
1340 *
1341 * NB: For ShortOK reads things get a little tricky - we don't
1342 * know how much data is going to arrive and not all the
1343 * fragment URBs might be filled. We can only safely set up one
1344 * URB at a time -> worse performance but correct behaviour.
1345 *
1346 * @returns true / false.
1347 * @param pProxyDev The proxy device.
1348 * @param pUrbLnx The linux URB which was rejected because of being too big.
1349 * @param pUrb The VUSB URB.
1350 */
1351static int usbProxyLinuxUrbQueueSplit(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pUrbLnx, PVUSBURB pUrb)
1352{
1353 /*
1354 * Split it up into SPLIT_SIZE sized blocks.
1355 */
1356 const unsigned cKUrbs = (pUrb->cbData + SPLIT_SIZE - 1) / SPLIT_SIZE;
1357 LogFlow(("usbProxyLinuxUrbQueueSplit: pUrb=%p cKUrbs=%d cbData=%d\n", pUrb, cKUrbs, pUrb->cbData));
1358
1359 uint32_t cbLeft = pUrb->cbData;
1360 uint8_t *pb = &pUrb->abData[0];
1361
1362 /* the first one (already allocated) */
1363 switch (pUrb->enmType)
1364 {
1365 default: /* shut up gcc */
1366 case VUSBXFERTYPE_BULK: pUrbLnx->KUrb.type = USBDEVFS_URB_TYPE_BULK; break;
1367 case VUSBXFERTYPE_INTR: pUrbLnx->KUrb.type = USBDEVFS_URB_TYPE_INTERRUPT; break;
1368 case VUSBXFERTYPE_MSG: pUrbLnx->KUrb.type = USBDEVFS_URB_TYPE_CONTROL; break;
1369 case VUSBXFERTYPE_ISOC:
1370 AssertMsgFailed(("We can't split isochronous URBs!\n"));
1371 usbProxyLinuxUrbFree(pProxyDev, pUrbLnx);
1372 return false;
1373 }
1374 pUrbLnx->KUrb.endpoint = pUrb->EndPt;
1375 if (pUrb->enmDir == VUSBDIRECTION_IN)
1376 pUrbLnx->KUrb.endpoint |= 0x80;
1377 pUrbLnx->KUrb.status = 0;
1378 pUrbLnx->KUrb.flags = pUrb->fShortNotOk ? USBDEVFS_URB_SHORT_NOT_OK : 0; /* ISO_ASAP too? */
1379 pUrbLnx->KUrb.buffer = pb;
1380 pUrbLnx->KUrb.buffer_length = RT_MIN(cbLeft, SPLIT_SIZE);
1381 pUrbLnx->KUrb.actual_length = 0;
1382 pUrbLnx->KUrb.start_frame = 0;
1383 pUrbLnx->KUrb.number_of_packets = 0;
1384 pUrbLnx->KUrb.error_count = 0;
1385 pUrbLnx->KUrb.signr = 0;
1386 pUrbLnx->KUrb.usercontext = pUrb;
1387 pUrbLnx->pSplitHead = pUrbLnx;
1388 pUrbLnx->pSplitNext = NULL;
1389
1390 PUSBPROXYURBLNX pCur = pUrbLnx;
1391
1392 cbLeft -= pUrbLnx->KUrb.buffer_length;
1393 pUrbLnx->cbSplitRemaining = cbLeft;
1394
1395 bool fSucceeded = false;
1396 bool fUnplugged = false;
1397 if (pUrb->enmDir == VUSBDIRECTION_IN && !pUrb->fShortNotOk)
1398 {
1399 /* Subsequent fragments will be queued only after the previous fragment is reaped
1400 * and only if necessary.
1401 */
1402 fSucceeded = true;
1403 Log(("usb-linux: Large ShortOK read, only queuing first fragment.\n"));
1404 Assert(pUrbLnx->cbSplitRemaining > 0 && pUrbLnx->cbSplitRemaining < 256 * _1K);
1405 fSucceeded = usbProxyLinuxSubmitURB(pProxyDev, pUrbLnx, pUrb, &fUnplugged);
1406 }
1407 else
1408 {
1409 /* the rest. */
1410 unsigned i;
1411 for (i = 1; i < cKUrbs; i++)
1412 {
1413 pCur = usbProxyLinuxSplitURBFragment(pProxyDev, pUrbLnx, pCur);
1414 if (!pCur)
1415 {
1416 return false;
1417 }
1418 }
1419 Assert(pCur->cbSplitRemaining == 0);
1420
1421 /* Submit the blocks. */
1422 pCur = pUrbLnx;
1423 for (i = 0; i < cKUrbs; i++, pCur = pCur->pSplitNext)
1424 {
1425 fSucceeded = usbProxyLinuxSubmitURB(pProxyDev, pCur, pUrb, &fUnplugged);
1426 if (!fSucceeded)
1427 break;
1428 }
1429 }
1430
1431 if (fSucceeded)
1432 {
1433 pUrb->Dev.pvPrivate = pUrbLnx;
1434 LogFlow(("usbProxyLinuxUrbQueueSplit: ok\n"));
1435 return true;
1436 }
1437
1438 usbProxyLinuxCleanupFailedSubmit(pProxyDev, pUrbLnx, pCur, pUrb, &fUnplugged);
1439 return false;
1440}
1441
1442
1443/**
1444 * @copydoc USBPROXYBACK::pfnUrbQueue
1445 */
1446static int usbProxyLinuxUrbQueue(PVUSBURB pUrb)
1447{
1448 unsigned cTries;
1449#ifndef RDESKTOP
1450 PUSBPROXYDEV pProxyDev = PDMINS_2_DATA(pUrb->pUsbIns, PUSBPROXYDEV);
1451#else
1452 PUSBPROXYDEV pProxyDev = usbProxyFromVusbDev(pUrb->pDev);
1453#endif
1454 PUSBPROXYDEVLNX pDevLnx = (PUSBPROXYDEVLNX)pProxyDev->Backend.pv;
1455 LogFlow(("usbProxyLinuxUrbQueue: pProxyDev=%s pUrb=%p EndPt=%d cbData=%d\n",
1456 usbProxyGetName(pProxyDev), pUrb, pUrb->EndPt, pUrb->cbData));
1457
1458 /*
1459 * Allocate a linux urb.
1460 */
1461 PUSBPROXYURBLNX pUrbLnx = usbProxyLinuxUrbAlloc(pProxyDev, NULL);
1462 if (!pUrbLnx)
1463 return false;
1464
1465 pUrbLnx->KUrb.endpoint = pUrb->EndPt | (pUrb->enmDir == VUSBDIRECTION_IN ? 0x80 : 0);
1466 pUrbLnx->KUrb.status = 0;
1467 pUrbLnx->KUrb.flags = pUrb->fShortNotOk ? USBDEVFS_URB_SHORT_NOT_OK : 0;
1468 pUrbLnx->KUrb.buffer = pUrb->abData;
1469 pUrbLnx->KUrb.buffer_length = pUrb->cbData;
1470 pUrbLnx->KUrb.actual_length = 0;
1471 pUrbLnx->KUrb.start_frame = 0;
1472 pUrbLnx->KUrb.number_of_packets = 0;
1473 pUrbLnx->KUrb.error_count = 0;
1474 pUrbLnx->KUrb.signr = 0;
1475 pUrbLnx->KUrb.usercontext = pUrb;
1476
1477 switch (pUrb->enmType)
1478 {
1479 case VUSBXFERTYPE_MSG:
1480 pUrbLnx->KUrb.type = USBDEVFS_URB_TYPE_CONTROL;
1481 if (pUrb->cbData < sizeof(VUSBSETUP))
1482 {
1483 usbProxyLinuxUrbFree(pProxyDev, pUrbLnx);
1484 return false;
1485 }
1486 usbProxyLinuxUrbSwapSetup((PVUSBSETUP)pUrb->abData);
1487 LogFlow(("usbProxyLinuxUrbQueue: message\n"));
1488 break;
1489 case VUSBXFERTYPE_BULK:
1490 pUrbLnx->KUrb.type = USBDEVFS_URB_TYPE_BULK;
1491 break;
1492 case VUSBXFERTYPE_ISOC:
1493 pUrbLnx->KUrb.type = USBDEVFS_URB_TYPE_ISO;
1494 pUrbLnx->KUrb.flags |= USBDEVFS_URB_ISO_ASAP;
1495 pUrbLnx->KUrb.number_of_packets = pUrb->cIsocPkts;
1496 unsigned i;
1497 for (i = 0; i < pUrb->cIsocPkts; i++)
1498 {
1499 pUrbLnx->KUrb.iso_frame_desc[i].length = pUrb->aIsocPkts[i].cb;
1500 pUrbLnx->KUrb.iso_frame_desc[i].actual_length = 0;
1501 pUrbLnx->KUrb.iso_frame_desc[i].status = 0x7fff;
1502 }
1503 break;
1504 case VUSBXFERTYPE_INTR:
1505 pUrbLnx->KUrb.type = USBDEVFS_URB_TYPE_INTERRUPT;
1506 break;
1507 default:
1508 goto l_err;
1509 }
1510
1511 /*
1512 * Submit it.
1513 */
1514 cTries = 0;
1515 while (ioctl(pDevLnx->File, USBDEVFS_SUBMITURB, &pUrbLnx->KUrb))
1516 {
1517 if (errno == EINTR)
1518 continue;
1519 if (errno == ENODEV)
1520 {
1521 Log(("usbProxyLinuxUrbQueue: ENODEV -> unplugged. pProxyDev=%s\n", usbProxyGetName(pProxyDev)));
1522 if (pUrb->enmType == VUSBXFERTYPE_MSG)
1523 usbProxyLinuxUrbSwapSetup((PVUSBSETUP)pUrb->abData);
1524 usbProxyLinuxUrbFree(pProxyDev, pUrbLnx);
1525
1526 usbProxLinuxUrbUnplugged(pProxyDev);
1527 return false;
1528 }
1529
1530 /*
1531 * usbfs has or used to have a low buffer limit (16KB) in order to prevent
1532 * processes wasting kmalloc'ed memory. It will return EINVAL if break that
1533 * limit, and we'll have to split the VUSB URB up into multiple linux URBs.
1534 *
1535 * Since this is a limit which is subject to change, we cannot check for it
1536 * before submitting the URB. We just have to try and fail.
1537 */
1538 if ( errno == EINVAL
1539 && pUrb->cbData >= 8*_1K)
1540 return usbProxyLinuxUrbQueueSplit(pProxyDev, pUrbLnx, pUrb);
1541
1542 Log(("usb-linux: Queue URB %p -> %d!!! type=%d ep=%#x buffer_length=%#x cTries=%d\n",
1543 pUrb, errno, pUrbLnx->KUrb.type, pUrbLnx->KUrb.endpoint, pUrbLnx->KUrb.buffer_length, cTries));
1544 if (errno != EBUSY && ++cTries < 3) /* this doesn't work for the floppy :/ */
1545 continue;
1546l_err:
1547 if (pUrb->enmType == VUSBXFERTYPE_MSG)
1548 usbProxyLinuxUrbSwapSetup((PVUSBSETUP)pUrb->abData);
1549 usbProxyLinuxUrbFree(pProxyDev, pUrbLnx);
1550 return false;
1551 }
1552 pUrbLnx->u64SubmitTS = RTTimeMilliTS();
1553
1554 LogFlow(("usbProxyLinuxUrbQueue: ok\n"));
1555 pUrb->Dev.pvPrivate = pUrbLnx;
1556 return true;
1557}
1558
1559
1560/**
1561 * Check if any or the in-flight URBs are taking too long and should be cancelled.
1562 *
1563 * Cancelling is done in three turns, first a URB is marked for timeout if it's
1564 * exceeding a certain time limit. Then the next time it's encountered it is actually
1565 * cancelled. The idea now is that it's supposed to be reaped and returned in the next
1566 * round of calls.
1567 *
1568 * @param pProxyDev The proxy device.
1569 * @param pDevLnx The linux backend data.
1570 *
1571 * @todo Make the HCI do proper timeout handling! Current timeout is 3 min and 20 seconds
1572 * as not to break bloomberg which queues IN packages with 3 min timeouts.
1573 */
1574static void vusbProxyLinuxUrbDoTimeouts(PUSBPROXYDEV pProxyDev, PUSBPROXYDEVLNX pDevLnx)
1575{
1576 RTCritSectEnter(&pDevLnx->CritSect);
1577 uint64_t u64MilliTS = RTTimeMilliTS();
1578 PUSBPROXYURBLNX pCur;
1579 for (pCur = pDevLnx->pInFlightHead;
1580 pCur;
1581 pCur = pCur->pNext)
1582 {
1583 if (pCur->fTimedOut)
1584 {
1585 if (pCur->pSplitHead)
1586 {
1587 /* split */
1588 Assert(pCur == pCur->pSplitHead);
1589 unsigned cFailures = 0;
1590 PUSBPROXYURBLNX pCur2;
1591 for (pCur2 = pCur; pCur2; pCur2 = pCur2->pSplitNext)
1592 {
1593 if (pCur2->fSplitElementReaped)
1594 continue;
1595
1596 if ( !usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_DISCARDURB, &pCur2->KUrb, true, UINT32_MAX)
1597 || errno == ENOENT)
1598 pCur2->fCanceledByTimedOut = true;
1599 else if (errno != ENODEV)
1600 Log(("vusbProxyLinuxUrbDoTimeouts: pUrb=%p failed errno=%d (!!split!!)\n", pCur2->KUrb.usercontext, errno));
1601 else
1602 goto l_leave; /* ENODEV means break and everything cancelled elsewhere. */
1603 }
1604 LogRel(("USB: Cancelled URB (%p) after %llums!! (cFailures=%d)\n",
1605 pCur->KUrb.usercontext, (long long unsigned) u64MilliTS - pCur->u64SubmitTS, cFailures));
1606 }
1607 else
1608 {
1609 /* unsplit */
1610 if ( !usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_DISCARDURB, &pCur->KUrb, true, UINT32_MAX)
1611 || errno == -ENOENT)
1612 {
1613 pCur->fCanceledByTimedOut = true;
1614 LogRel(("USB: Cancelled URB (%p) after %llums!!\n", pCur->KUrb.usercontext, (long long unsigned) u64MilliTS - pCur->u64SubmitTS));
1615 }
1616 else if (errno != ENODEV)
1617 LogFlow(("vusbProxyLinuxUrbDoTimeouts: pUrb=%p failed errno=%d\n", pCur->KUrb.usercontext, errno));
1618 else
1619 goto l_leave; /* ENODEV means break and everything cancelled elsewhere. */
1620 }
1621 }
1622#if 0
1623 /* Disabled for the time beeing as some USB devices have URBs pending for an unknown amount of time.
1624 * One example is the OmniKey CardMan 3821. */
1625 else if (u64MilliTS - pCur->u64SubmitTS >= 200*1000 /* 200 sec (180 sec has been observed with XP) */)
1626 pCur->fTimedOut = true;
1627#endif
1628 }
1629
1630l_leave:
1631 RTCritSectLeave(&pDevLnx->CritSect);
1632}
1633
1634
1635/**
1636 * Translate the linux status to a VUSB status.
1637 *
1638 * @remarks see cc_to_error in ohci.h, uhci_map_status in uhci-q.c,
1639 * sitd_complete+itd_complete in ehci-sched.c, and qtd_copy_status in
1640 * ehci-q.c.
1641 */
1642static VUSBSTATUS vusbProxyLinuxStatusToVUsbStatus(int iStatus)
1643{
1644 switch (iStatus)
1645 {
1646 /** @todo VUSBSTATUS_NOT_ACCESSED */
1647 case -EXDEV: /* iso transfer, partial result. */
1648 case 0:
1649 return VUSBSTATUS_OK;
1650
1651 case -EILSEQ:
1652 return VUSBSTATUS_CRC;
1653
1654 case -EREMOTEIO: /* ehci and ohci uses this for underflow error. */
1655 return VUSBSTATUS_DATA_UNDERRUN;
1656 case -EOVERFLOW:
1657 return VUSBSTATUS_DATA_OVERRUN;
1658
1659 case -ETIME:
1660 case -ENODEV:
1661 return VUSBSTATUS_DNR;
1662
1663 //case -ECOMM:
1664 // return VUSBSTATUS_BUFFER_OVERRUN;
1665 //case -ENOSR:
1666 // return VUSBSTATUS_BUFFER_UNDERRUN;
1667
1668 //case -EPROTO:
1669 // return VUSBSTATUS_BIT_STUFFING;
1670
1671 case -EPIPE:
1672 Log(("vusbProxyLinuxStatusToVUsbStatus: STALL/EPIPE!!\n"));
1673 return VUSBSTATUS_STALL;
1674
1675 case -ESHUTDOWN:
1676 Log(("vusbProxyLinuxStatusToVUsbStatus: SHUTDOWN!!\n"));
1677 return VUSBSTATUS_STALL;
1678
1679 default:
1680 Log(("vusbProxyLinuxStatusToVUsbStatus: status %d!!\n", iStatus));
1681 return VUSBSTATUS_STALL;
1682 }
1683}
1684
1685
1686/**
1687 * Get and translates the linux status to a VUSB status.
1688 */
1689static VUSBSTATUS vusbProxyLinuxUrbGetStatus(PUSBPROXYURBLNX pUrbLnx)
1690{
1691 if ( pUrbLnx->fCanceledByTimedOut
1692 && pUrbLnx->KUrb.status == 0)
1693 return VUSBSTATUS_CRC;
1694 return vusbProxyLinuxStatusToVUsbStatus(pUrbLnx->KUrb.status);
1695}
1696
1697
1698/**
1699 * Reap URBs in-flight on a device.
1700 *
1701 * @returns Pointer to a completed URB.
1702 * @returns NULL if no URB was completed.
1703 * @param pProxyDev The device.
1704 * @param cMillies Number of milliseconds to wait. Use 0 to not wait at all.
1705 */
1706static PVUSBURB usbProxyLinuxUrbReap(PUSBPROXYDEV pProxyDev, RTMSINTERVAL cMillies)
1707{
1708 PUSBPROXYURBLNX pUrbLnx = NULL;
1709 PUSBPROXYDEVLNX pDevLnx = (PUSBPROXYDEVLNX)pProxyDev->Backend.pv;
1710
1711 /*
1712 * Any URBs pending delivery?
1713 */
1714 if (pDevLnx->pTaxingHead)
1715 {
1716 RTCritSectEnter(&pDevLnx->CritSect);
1717 pUrbLnx = pDevLnx->pTaxingHead;
1718 if (pUrbLnx)
1719 {
1720 /* unlink from the pending delivery list */
1721 if (pUrbLnx->pNext)
1722 {
1723 pUrbLnx->pNext->pPrev = NULL;
1724 pDevLnx->pTaxingHead = pUrbLnx->pNext;
1725 }
1726 else
1727 pDevLnx->pTaxingHead = pDevLnx->pTaxingTail = NULL;
1728
1729 /* temporarily into the active list, so free works right. */
1730 pUrbLnx->pPrev = NULL;
1731 pUrbLnx->pNext = pDevLnx->pInFlightHead;
1732 if (pUrbLnx->pNext)
1733 pUrbLnx->pNext->pPrev = pUrbLnx;
1734 pDevLnx->pInFlightHead = pUrbLnx;
1735 }
1736 RTCritSectLeave(&pDevLnx->CritSect);
1737 }
1738 if (!pUrbLnx)
1739 {
1740 /*
1741 * Don't block if nothing is in the air.
1742 */
1743 if (!pDevLnx->pInFlightHead)
1744 return NULL;
1745
1746 /*
1747 * Block for requested period.
1748 *
1749 * It seems to me that the path of poll() is shorter and
1750 * involves less semaphores than ioctl() on usbfs. So, we'll
1751 * do a poll regardless of whether cMillies == 0 or not.
1752 */
1753 if (cMillies)
1754 {
1755
1756 for (;;)
1757 {
1758 struct pollfd pfd;
1759 int rc;
1760
1761 pfd.fd = pDevLnx->File;
1762 pfd.events = POLLOUT | POLLWRNORM /* completed async */
1763 | POLLERR | POLLHUP /* disconnected */;
1764 pfd.revents = 0;
1765 rc = poll(&pfd, 1, cMillies);
1766 Log(("usbProxyLinuxUrbReap: poll rc = %d\n", rc));
1767 if (rc >= 1)
1768 break;
1769 if (rc >= 0 /*|| errno == ETIMEOUT*/)
1770 {
1771 vusbProxyLinuxUrbDoTimeouts(pProxyDev, pDevLnx);
1772 return NULL;
1773 }
1774 if (errno != EAGAIN)
1775 {
1776 Log(("usb-linux: Reap URB - poll -> %d errno=%d pProxyDev=%s\n", rc, errno, usbProxyGetName(pProxyDev)));
1777 return NULL;
1778 }
1779 Log(("usbProxyLinuxUrbReap: poll again - weird!!!\n"));
1780 }
1781 }
1782
1783 /*
1784 * Reap URBs, non-blocking.
1785 */
1786 for (;;)
1787 {
1788 struct usbdevfs_urb *pKUrb;
1789 while (ioctl(pDevLnx->File, USBDEVFS_REAPURBNDELAY, &pKUrb))
1790 if (errno != EINTR)
1791 {
1792 if (errno == ENODEV)
1793 usbProxLinuxUrbUnplugged(pProxyDev);
1794 else if (errno == EAGAIN)
1795 vusbProxyLinuxUrbDoTimeouts(pProxyDev, pDevLnx);
1796 else
1797 Log(("usb-linux: Reap URB. errno=%d pProxyDev=%s\n", errno, usbProxyGetName(pProxyDev)));
1798 return NULL;
1799 }
1800 pUrbLnx = (PUSBPROXYURBLNX)pKUrb;
1801
1802 /* split list: Is the entire split list done yet? */
1803 if (pUrbLnx->pSplitHead)
1804 {
1805 pUrbLnx->fSplitElementReaped = true;
1806
1807 /* for variable size URBs, we may need to queue more if the just-reaped URB was completely filled */
1808 if (pUrbLnx->cbSplitRemaining && (pKUrb->actual_length == pKUrb->buffer_length) && !pUrbLnx->pSplitNext)
1809 {
1810 bool fUnplugged = false;
1811 bool fSucceeded;
1812
1813 Assert(pUrbLnx->pSplitHead);
1814 Assert((pKUrb->endpoint & 0x80) && (!pKUrb->flags & USBDEVFS_URB_SHORT_NOT_OK));
1815 PUSBPROXYURBLNX pNew = usbProxyLinuxSplitURBFragment(pProxyDev, pUrbLnx->pSplitHead, pUrbLnx);
1816 if (!pNew)
1817 {
1818 Log(("usb-linux: Allocating URB fragment failed. errno=%d pProxyDev=%s\n", errno, usbProxyGetName(pProxyDev)));
1819 return NULL;
1820 }
1821 PVUSBURB pUrb = (PVUSBURB)pUrbLnx->KUrb.usercontext;
1822 fSucceeded = usbProxyLinuxSubmitURB(pProxyDev, pNew, pUrb, &fUnplugged);
1823 if (fUnplugged)
1824 usbProxLinuxUrbUnplugged(pProxyDev);
1825 if (!fSucceeded)
1826 return NULL;
1827 continue; /* try reaping another URB */
1828 }
1829 PUSBPROXYURBLNX pCur;
1830 for (pCur = pUrbLnx->pSplitHead; pCur; pCur = pCur->pSplitNext)
1831 if (!pCur->fSplitElementReaped)
1832 {
1833 pUrbLnx = NULL;
1834 break;
1835 }
1836 if (!pUrbLnx)
1837 continue;
1838 pUrbLnx = pUrbLnx->pSplitHead;
1839 }
1840 break;
1841 }
1842 }
1843
1844 /*
1845 * Ok, we got one!
1846 */
1847 PVUSBURB pUrb = (PVUSBURB)pUrbLnx->KUrb.usercontext;
1848 if ( pUrb
1849 && !pUrbLnx->fCanceledBySubmit)
1850 {
1851 if (pUrbLnx->pSplitHead)
1852 {
1853 /* split - find the end byte and the first error status. */
1854 Assert(pUrbLnx == pUrbLnx->pSplitHead);
1855 uint8_t *pbEnd = &pUrb->abData[0];
1856 pUrb->enmStatus = VUSBSTATUS_OK;
1857 PUSBPROXYURBLNX pCur;
1858 for (pCur = pUrbLnx; pCur; pCur = pCur->pSplitNext)
1859 {
1860 if (pCur->KUrb.actual_length)
1861 pbEnd = (uint8_t *)pCur->KUrb.buffer + pCur->KUrb.actual_length;
1862 if (pUrb->enmStatus == VUSBSTATUS_OK)
1863 pUrb->enmStatus = vusbProxyLinuxUrbGetStatus(pCur);
1864 }
1865 pUrb->cbData = pbEnd - &pUrb->abData[0];
1866 usbProxyLinuxUrbFreeSplitList(pProxyDev, pUrbLnx);
1867 }
1868 else
1869 {
1870 /* unsplit. */
1871 pUrb->enmStatus = vusbProxyLinuxUrbGetStatus(pUrbLnx);
1872 pUrb->cbData = pUrbLnx->KUrb.actual_length;
1873 if (pUrb->enmType == VUSBXFERTYPE_ISOC)
1874 {
1875 unsigned i, off;
1876 for (i = 0, off = 0; i < pUrb->cIsocPkts; i++)
1877 {
1878 pUrb->aIsocPkts[i].enmStatus = vusbProxyLinuxStatusToVUsbStatus(pUrbLnx->KUrb.iso_frame_desc[i].status);
1879 Assert(pUrb->aIsocPkts[i].off == off);
1880 pUrb->aIsocPkts[i].cb = pUrbLnx->KUrb.iso_frame_desc[i].actual_length;
1881 off += pUrbLnx->KUrb.iso_frame_desc[i].length;
1882 }
1883 }
1884 usbProxyLinuxUrbFree(pProxyDev, pUrbLnx);
1885 }
1886 pUrb->Dev.pvPrivate = NULL;
1887
1888 /* some adjustments for message transfers. */
1889 if (pUrb->enmType == VUSBXFERTYPE_MSG)
1890 {
1891 pUrb->cbData += sizeof(VUSBSETUP);
1892 usbProxyLinuxUrbSwapSetup((PVUSBSETUP)pUrb->abData);
1893 }
1894 }
1895 else
1896 {
1897 usbProxyLinuxUrbFree(pProxyDev, pUrbLnx);
1898 pUrb = NULL;
1899 }
1900
1901 LogFlow(("usbProxyLinuxUrbReap: pProxyDev=%s returns %p\n", usbProxyGetName(pProxyDev), pUrb));
1902 return pUrb;
1903}
1904
1905
1906/**
1907 * Cancels the URB.
1908 * The URB requires reaping, so we don't change its state.
1909 */
1910static void usbProxyLinuxUrbCancel(PVUSBURB pUrb)
1911{
1912#ifndef RDESKTOP
1913 PUSBPROXYDEV pProxyDev = PDMINS_2_DATA(pUrb->pUsbIns, PUSBPROXYDEV);
1914#else
1915 PUSBPROXYDEV pProxyDev = usbProxyFromVusbDev(pUrb->pDev);
1916#endif
1917 PUSBPROXYURBLNX pUrbLnx = (PUSBPROXYURBLNX)pUrb->Dev.pvPrivate;
1918 if (pUrbLnx->pSplitHead)
1919 {
1920 /* split */
1921 Assert(pUrbLnx == pUrbLnx->pSplitHead);
1922 PUSBPROXYURBLNX pCur;
1923 for (pCur = pUrbLnx; pCur; pCur = pCur->pSplitNext)
1924 {
1925 if (pCur->fSplitElementReaped)
1926 continue;
1927 if ( !usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_DISCARDURB, &pCur->KUrb, true, UINT32_MAX)
1928 || errno == ENOENT)
1929 continue;
1930 if (errno == ENODEV)
1931 break;
1932 Log(("usb-linux: Discard URB %p failed, errno=%d. pProxyDev=%s!!! (split)\n",
1933 pUrb, errno, usbProxyGetName(pProxyDev)));
1934 }
1935 }
1936 else
1937 {
1938 /* unsplit */
1939 if ( usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_DISCARDURB, &pUrbLnx->KUrb, true, UINT32_MAX)
1940 && errno != ENODEV /* deal with elsewhere. */
1941 && errno != ENOENT)
1942 Log(("usb-linux: Discard URB %p failed, errno=%d. pProxyDev=%s!!!\n",
1943 pUrb, errno, usbProxyGetName(pProxyDev)));
1944 }
1945}
1946
1947
1948/**
1949 * The Linux USB Proxy Backend.
1950 */
1951const USBPROXYBACK g_USBProxyDeviceHost =
1952{
1953 "host",
1954 usbProxyLinuxOpen,
1955 usbProxyLinuxInit,
1956 usbProxyLinuxClose,
1957 usbProxyLinuxReset,
1958 usbProxyLinuxSetConfig,
1959 usbProxyLinuxClaimInterface,
1960 usbProxyLinuxReleaseInterface,
1961 usbProxyLinuxSetInterface,
1962 usbProxyLinuxClearHaltedEp,
1963 usbProxyLinuxUrbQueue,
1964 usbProxyLinuxUrbCancel,
1965 usbProxyLinuxUrbReap,
1966 0
1967};
1968
1969
1970/*
1971 * Local Variables:
1972 * mode: c
1973 * c-file-style: "bsd"
1974 * c-basic-offset: 4
1975 * tab-width: 4
1976 * indent-tabs-mode: s
1977 * End:
1978 */
1979
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette