VirtualBox

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

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

VUSB: Doxygen fixes

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

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