VirtualBox

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

Last change on this file since 68080 was 64766, checked in by vboxsync, 8 years ago

src/VBox: Make the use of the iterator for RTListForEach()/RTListForEachSafe() more obvious. There is no need to initialize the iterator and we also must not depend on the iterator being NULL if the list was empty.

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