VirtualBox

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

Last change on this file since 59083 was 58640, checked in by vboxsync, 9 years ago

USBProxyDevice-linux: map -EPROTO to VUSBSTATUS_DNR

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

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