VirtualBox

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

Last change on this file since 76337 was 76337, checked in by vboxsync, 6 years ago

Whitespace.

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