VirtualBox

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

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

USBProxyDevice-linux.cpp: cppcheck warning

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 66.0 KB
Line 
1/* $Id: USBProxyDevice-linux.cpp 61879 2016-06-24 11:30:31Z vboxsync $ */
2/** @file
3 * USB device proxy - the Linux backend.
4 */
5
6/*
7 * Copyright (C) 2006-2015 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Defined Constants And Macros *
21*********************************************************************************************************************************/
22/** Define NO_PORT_RESET to skip the slow and broken linux port reset.
23 * Resetting will break PalmOne. */
24#define NO_PORT_RESET
25/** Define NO_LOGICAL_RECONNECT to skip the broken logical reconnect handling. */
26#define NO_LOGICAL_RECONNECT
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define LOG_GROUP LOG_GROUP_DRV_USBPROXY
33
34#include <iprt/stdint.h>
35#include <iprt/err.h>
36#include <iprt/pipe.h>
37
38#include <sys/types.h>
39#include <sys/stat.h>
40#include <sys/vfs.h>
41#include <sys/ioctl.h>
42#include <sys/poll.h>
43#include <stdint.h>
44#include <stdio.h>
45#include <string.h>
46#include <stdlib.h>
47#include <limits.h>
48#include <unistd.h>
49#include <fcntl.h>
50#include <errno.h>
51#ifdef VBOX_WITH_LINUX_COMPILER_H
52# include <linux/compiler.h>
53#endif
54#include <linux/usbdevice_fs.h>
55/*
56 * Backlevel 2.4 headers doesn't have these two defines.
57 * They were added some time between 2.4.21 and 2.4.26, probably in 2.4.23.
58 */
59#ifndef USBDEVFS_DISCONNECT
60# define USBDEVFS_DISCONNECT _IO('U', 22)
61# define USBDEVFS_CONNECT _IO('U', 23)
62#endif
63
64#ifndef USBDEVFS_URB_SHORT_NOT_OK
65# define USBDEVFS_URB_SHORT_NOT_OK 0 /* rhel3 doesn't have this. darn! */
66#endif
67
68
69/* FedoraCore 4 does not have the bit defined by default. */
70#ifndef POLLWRNORM
71# define POLLWRNORM 0x0100
72#endif
73
74#ifndef RDESKTOP
75# include <VBox/vmm/pdm.h>
76#else
77# define RTCRITSECT void *
78static inline int rtcsNoop() { return VINF_SUCCESS; }
79static inline bool rtcsTrue() { return true; }
80# define RTCritSectInit(a) rtcsNoop()
81# define RTCritSectDelete(a) rtcsNoop()
82# define RTCritSectEnter(a) rtcsNoop()
83# define RTCritSectLeave(a) rtcsNoop()
84# define RTCritSectIsOwner(a) rtcsTrue()
85#endif
86#include <VBox/err.h>
87#include <VBox/log.h>
88#include <iprt/alloc.h>
89#include <iprt/assert.h>
90#include <iprt/asm.h>
91#include <iprt/ctype.h>
92#include <iprt/file.h>
93#include <iprt/linux/sysfs.h>
94#include <iprt/stream.h>
95#include <iprt/string.h>
96#include <iprt/list.h>
97#if defined(NO_PORT_RESET) && !defined(NO_LOGICAL_RECONNECT)
98# include <iprt/thread.h>
99#endif
100#include <iprt/time.h>
101#include "../USBProxyDevice.h"
102
103
104/*********************************************************************************************************************************
105* Structures and Typedefs *
106*********************************************************************************************************************************/
107/**
108 * Wrapper around the linux urb request structure.
109 * This is required to track in-flight and landed URBs.
110 */
111typedef struct USBPROXYURBLNX
112{
113 /** The kernel URB data */
114 struct usbdevfs_urb KUrb;
115 /** Space filler for the isochronous packets. */
116 struct usbdevfs_iso_packet_desc aIsocPktsDonUseTheseUseTheOnesInKUrb[8];
117 /** Node to link the URB in of the existing lists. */
118 RTLISTNODE NodeList;
119 /** If we've split the VUSBURB up into multiple linux URBs, this is points to the head. */
120 struct USBPROXYURBLNX *pSplitHead;
121 /** The next linux URB if split up. */
122 struct USBPROXYURBLNX *pSplitNext;
123 /** Don't report these back. */
124 bool fCanceledBySubmit;
125 /** This split element is reaped. */
126 bool fSplitElementReaped;
127 /** Size to transfer in remaining fragments of a split URB */
128 uint32_t cbSplitRemaining;
129} USBPROXYURBLNX, *PUSBPROXYURBLNX;
130
131/**
132 * Data for the linux usb proxy backend.
133 */
134typedef struct USBPROXYDEVLNX
135{
136 /** The open file. */
137 RTFILE hFile;
138 /** Critical section protecting the lists. */
139 RTCRITSECT CritSect;
140 /** The list of free linux URBs (USBPROXYURBLNX). */
141 RTLISTANCHOR ListFree;
142 /** The list of active linux URBs.
143 * We must maintain this so we can properly reap URBs of a detached device.
144 * Only the split head will appear in this list. (USBPROXYURBLNX) */
145 RTLISTANCHOR ListInFlight;
146 /** The list of landed linux URBs. Doubly linked.
147 * Only the split head will appear in this list. (USBPROXYURBLNX) */
148 RTLISTANCHOR ListTaxing;
149 /** Are we using sysfs to find the active configuration? */
150 bool fUsingSysfs;
151 /** Pipe handle for waiking up - writing end. */
152 RTPIPE hPipeWakeupW;
153 /** Pipe handle for waiking up - reading end. */
154 RTPIPE hPipeWakeupR;
155 /** The device node/sysfs path of the device.
156 * Used to figure out the configuration after a reset. */
157 char *pszPath;
158} USBPROXYDEVLNX, *PUSBPROXYDEVLNX;
159
160
161/*********************************************************************************************************************************
162* Internal Functions *
163*********************************************************************************************************************************/
164static int usbProxyLinuxDoIoCtl(PUSBPROXYDEV pProxyDev, unsigned long iCmd, void *pvArg, bool fHandleNoDev, uint32_t cTries);
165static void usbProxLinuxUrbUnplugged(PUSBPROXYDEV pProxyDev);
166static void usbProxyLinuxSetConnected(PUSBPROXYDEV pProyxDev, int iIf, bool fConnect, bool fQuiet);
167static PUSBPROXYURBLNX usbProxyLinuxUrbAlloc(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pSplitHead);
168static void usbProxyLinuxUrbFree(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pUrbLnx);
169static void usbProxyLinuxUrbFreeSplitList(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pUrbLnx);
170static int usbProxyLinuxFindActiveConfig(PUSBPROXYDEV pProxyDev, const char *pszPath, int *piFirstCfg);
171
172
173
174/**
175 * Wrapper for the ioctl call.
176 *
177 * This wrapper will repeat the call if we get an EINTR or EAGAIN. It can also
178 * handle ENODEV (detached device) errors.
179 *
180 * @returns whatever ioctl returns.
181 * @param pProxyDev The proxy device.
182 * @param iCmd The ioctl command / function.
183 * @param pvArg The ioctl argument / data.
184 * @param fHandleNoDev Whether to handle ENODEV.
185 * @param cTries The number of retries. Use UINT32_MAX for (kind of) indefinite retries.
186 * @internal
187 */
188static int usbProxyLinuxDoIoCtl(PUSBPROXYDEV pProxyDev, unsigned long iCmd, void *pvArg, bool fHandleNoDev, uint32_t cTries)
189{
190 int rc;
191 PUSBPROXYDEVLNX pDevLnx = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVLNX);
192 do
193 {
194 do
195 {
196 rc = ioctl(RTFileToNative(pDevLnx->hFile), iCmd, pvArg);
197 if (rc >= 0)
198 return rc;
199 } while (errno == EINTR);
200
201 if (errno == ENODEV && fHandleNoDev)
202 {
203 usbProxLinuxUrbUnplugged(pProxyDev);
204 Log(("usb-linux: ENODEV -> unplugged. pProxyDev=%s\n", usbProxyGetName(pProxyDev)));
205 errno = ENODEV;
206 break;
207 }
208 if (errno != EAGAIN)
209 break;
210 } while (cTries-- > 0);
211
212 return rc;
213}
214
215
216/**
217 * The device has been unplugged.
218 * Cancel all in-flight URBs and put them up for reaping.
219 */
220static void usbProxLinuxUrbUnplugged(PUSBPROXYDEV pProxyDev)
221{
222 PUSBPROXYDEVLNX pDevLnx = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVLNX);
223
224 /*
225 * Shoot down all flying URBs.
226 */
227 RTCritSectEnter(&pDevLnx->CritSect);
228 pProxyDev->fDetached = true;
229
230 PUSBPROXYURBLNX pUrbLnx;
231 PUSBPROXYURBLNX pUrbLnxNext;
232
233 RTListForEachSafe(&pDevLnx->ListInFlight, pUrbLnx, pUrbLnxNext, USBPROXYURBLNX, NodeList)
234 {
235 RTListNodeRemove(&pUrbLnx->NodeList);
236
237 ioctl(RTFileToNative(pDevLnx->hFile), USBDEVFS_DISCARDURB, &pUrbLnx->KUrb); /* not sure if this is required.. */
238 if (!pUrbLnx->KUrb.status)
239 pUrbLnx->KUrb.status = -ENODEV;
240
241 /* insert into the taxing list. */
242 if ( !pUrbLnx->pSplitHead
243 || pUrbLnx == pUrbLnx->pSplitHead)
244 RTListAppend(&pDevLnx->ListTaxing, &pUrbLnx->NodeList);
245 }
246
247 RTCritSectLeave(&pDevLnx->CritSect);
248}
249
250
251/**
252 * Set the connect state seen by kernel drivers
253 * @internal
254 */
255static void usbProxyLinuxSetConnected(PUSBPROXYDEV pProxyDev, int iIf, bool fConnect, bool fQuiet)
256{
257 if ( iIf >= 32
258 || !(pProxyDev->fMaskedIfs & RT_BIT(iIf)))
259 {
260 struct usbdevfs_ioctl IoCtl;
261 if (!fQuiet)
262 LogFlow(("usbProxyLinuxSetConnected: pProxyDev=%s iIf=%#x fConnect=%s\n",
263 usbProxyGetName(pProxyDev), iIf, fConnect ? "true" : "false"));
264
265 IoCtl.ifno = iIf;
266 IoCtl.ioctl_code = fConnect ? USBDEVFS_CONNECT : USBDEVFS_DISCONNECT;
267 IoCtl.data = NULL;
268 if ( usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_IOCTL, &IoCtl, true, UINT32_MAX)
269 && !fQuiet)
270 Log(("usbProxyLinuxSetConnected: failure, errno=%d. pProxyDev=%s\n",
271 errno, usbProxyGetName(pProxyDev)));
272 }
273}
274
275
276/**
277 * Links the given URB into the in flight list.
278 *
279 * @returns nothing.
280 * @param pDevLnx The proxy device instance - Linux specific data.
281 * @param pUrbLnx The URB to link into the in flight list.
282 */
283static void usbProxyLinuxUrbLinkInFlight(PUSBPROXYDEVLNX pDevLnx, PUSBPROXYURBLNX pUrbLnx)
284{
285 LogFlowFunc(("pDevLnx=%p pUrbLnx=%p\n", pDevLnx, pUrbLnx));
286 Assert(RTCritSectIsOwner(&pDevLnx->CritSect));
287 Assert(!pUrbLnx->pSplitHead || pUrbLnx->pSplitHead == pUrbLnx);
288 RTListAppend(&pDevLnx->ListInFlight, &pUrbLnx->NodeList);
289}
290
291/**
292 * Unlinks the given URB from the in flight list.
293 * @returns nothing.
294 * @param pDevLnx The proxy device instance - Linux specific data.
295 * @param pUrbLnx The URB to link into the in flight list.
296 */
297static void usbProxyLinuxUrbUnlinkInFlight(PUSBPROXYDEVLNX pDevLnx, PUSBPROXYURBLNX pUrbLnx)
298{
299 LogFlowFunc(("pDevLnx=%p pUrbLnx=%p\n", pDevLnx, pUrbLnx));
300 RTCritSectEnter(&pDevLnx->CritSect);
301
302 /*
303 * Remove from the active list.
304 */
305 Assert(!pUrbLnx->pSplitHead || pUrbLnx->pSplitHead == pUrbLnx);
306
307 RTListNodeRemove(&pUrbLnx->NodeList);
308
309 RTCritSectLeave(&pDevLnx->CritSect);
310}
311
312/**
313 * Allocates a linux URB request structure.
314 * @returns Pointer to an active URB request.
315 * @returns NULL on failure.
316 * @param pProxyDev The proxy device instance.
317 * @param pSplitHead The split list head if allocating for a split list.
318 */
319static PUSBPROXYURBLNX usbProxyLinuxUrbAlloc(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pSplitHead)
320{
321 PUSBPROXYDEVLNX pDevLnx = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVLNX);
322 PUSBPROXYURBLNX pUrbLnx;
323
324 LogFlowFunc(("pProxyDev=%p pSplitHead=%p\n", pProxyDev, pSplitHead));
325
326 RTCritSectEnter(&pDevLnx->CritSect);
327
328 /*
329 * Try remove a linux URB from the free list, if none there allocate a new one.
330 */
331 pUrbLnx = RTListGetFirst(&pDevLnx->ListFree, USBPROXYURBLNX, NodeList);
332 if (pUrbLnx)
333 {
334 RTListNodeRemove(&pUrbLnx->NodeList);
335 RTCritSectLeave(&pDevLnx->CritSect);
336 }
337 else
338 {
339 RTCritSectLeave(&pDevLnx->CritSect);
340 pUrbLnx = (PUSBPROXYURBLNX)RTMemAlloc(sizeof(*pUrbLnx));
341 if (!pUrbLnx)
342 return NULL;
343 }
344
345 pUrbLnx->pSplitHead = pSplitHead;
346 pUrbLnx->pSplitNext = NULL;
347 pUrbLnx->fCanceledBySubmit = false;
348 pUrbLnx->fSplitElementReaped = false;
349 LogFlowFunc(("returns pUrbLnx=%p\n", pUrbLnx));
350 return pUrbLnx;
351}
352
353
354/**
355 * Frees a linux URB request structure.
356 *
357 * @param pProxyDev The proxy device instance.
358 * @param pUrbLnx The linux URB to free.
359 */
360static void usbProxyLinuxUrbFree(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pUrbLnx)
361{
362 PUSBPROXYDEVLNX pDevLnx = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVLNX);
363
364 LogFlowFunc(("pProxyDev=%p pUrbLnx=%p\n", pProxyDev, pUrbLnx));
365
366 /*
367 * Link it into the free list.
368 */
369 RTCritSectEnter(&pDevLnx->CritSect);
370 RTListAppend(&pDevLnx->ListFree, &pUrbLnx->NodeList);
371 RTCritSectLeave(&pDevLnx->CritSect);
372}
373
374
375/**
376 * Frees split list of a linux URB request structure.
377 *
378 * @param pProxyDev The proxy device instance.
379 * @param pUrbLnx A linux URB to in the split list to be freed.
380 */
381static void usbProxyLinuxUrbFreeSplitList(PUSBPROXYDEV pProxyDev, PUSBPROXYURBLNX pUrbLnx)
382{
383 PUSBPROXYDEVLNX pDevLnx = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVLNX);
384
385 LogFlowFunc(("pProxyDev=%p pUrbLnx=%p\n", pProxyDev, pUrbLnx));
386
387 RTCritSectEnter(&pDevLnx->CritSect);
388
389 pUrbLnx = pUrbLnx->pSplitHead;
390 Assert(pUrbLnx);
391 while (pUrbLnx)
392 {
393 PUSBPROXYURBLNX pFree = pUrbLnx;
394 pUrbLnx = pUrbLnx->pSplitNext;
395 Assert(pFree->pSplitHead);
396 pFree->pSplitHead = pFree->pSplitNext = NULL;
397 usbProxyLinuxUrbFree(pProxyDev, pFree);
398 }
399
400 RTCritSectLeave(&pDevLnx->CritSect);
401}
402
403
404/**
405 * This finds the device in the /proc/bus/usb/bus/addr file and finds
406 * the config with an asterix.
407 *
408 * @returns The Cfg#.
409 * @returns -1 if no active config.
410 * @param pszDevNode The path to the device. We infere the location of
411 * the devices file, which bus and device number we're
412 * looking for.
413 * @param iFirstCfg The first configuration. (optional)
414 * @internal
415 */
416static int usbProxyLinuxFindActiveConfigUsbfs(PUSBPROXYDEV pProxyDev, const char *pszDevNode, int *piFirstCfg)
417{
418 /*
419 * Set return defaults.
420 */
421 int iActiveCfg = -1;
422 if (piFirstCfg)
423 *piFirstCfg = 1;
424
425 /*
426 * Parse the usbfs device node path and turn it into a path to the "devices" file,
427 * picking up the device number and bus along the way.
428 */
429 size_t cchDevNode = strlen(pszDevNode);
430 char *pszDevices = (char *)RTMemDupEx(pszDevNode, cchDevNode, sizeof("devices"));
431 AssertReturn(pszDevices, iActiveCfg);
432
433 /* the device number */
434 char *psz = pszDevices + cchDevNode;
435 while (*psz != '/')
436 psz--;
437 Assert(pszDevices < psz);
438 uint32_t uDev;
439 int rc = RTStrToUInt32Ex(psz + 1, NULL, 10, &uDev);
440 if (RT_SUCCESS(rc))
441 {
442 /* the bus number */
443 *psz-- = '\0';
444 while (*psz != '/')
445 psz--;
446 Assert(pszDevices < psz);
447 uint32_t uBus;
448 rc = RTStrToUInt32Ex(psz + 1, NULL, 10, &uBus);
449 if (RT_SUCCESS(rc))
450 {
451 strcpy(psz + 1, "devices");
452
453 /*
454 * Open and scan the devices file.
455 * We're ASSUMING that each device starts off with a 'T:' line.
456 */
457 PRTSTREAM pFile;
458 rc = RTStrmOpen(pszDevices, "r", &pFile);
459 if (RT_SUCCESS(rc))
460 {
461 char szLine[1024];
462 while (RT_SUCCESS(RTStrmGetLine(pFile, szLine, sizeof(szLine))))
463 {
464 /* we're only interested in 'T:' lines. */
465 psz = RTStrStripL(szLine);
466 if (psz[0] != 'T' || psz[1] != ':')
467 continue;
468
469 /* Skip ahead to 'Bus' and compare */
470 psz = RTStrStripL(psz + 2); Assert(!strncmp(psz, RT_STR_TUPLE("Bus=")));
471 psz = RTStrStripL(psz + 4);
472 char *pszNext;
473 uint32_t u;
474 rc = RTStrToUInt32Ex(psz, &pszNext, 10, &u); AssertRC(rc);
475 if (RT_FAILURE(rc))
476 continue;
477 if (u != uBus)
478 continue;
479
480 /* Skip ahead to 'Dev#' and compare */
481 psz = strstr(psz, "Dev#="); Assert(psz);
482 if (!psz)
483 continue;
484 psz = RTStrStripL(psz + 5);
485 rc = RTStrToUInt32Ex(psz, &pszNext, 10, &u); AssertRC(rc);
486 if (RT_FAILURE(rc))
487 continue;
488 if (u != uDev)
489 continue;
490
491 /*
492 * Ok, we've found the device.
493 * Scan until we find a selected configuration, the next device, or EOF.
494 */
495 while (RT_SUCCESS(RTStrmGetLine(pFile, szLine, sizeof(szLine))))
496 {
497 psz = RTStrStripL(szLine);
498 if (psz[0] == 'T')
499 break;
500 if (psz[0] != 'C' || psz[1] != ':')
501 continue;
502 const bool fActive = psz[2] == '*';
503 if (!fActive && !piFirstCfg)
504 continue;
505
506 /* Get the 'Cfg#' value. */
507 psz = strstr(psz, "Cfg#="); Assert(psz);
508 if (psz)
509 {
510 psz = RTStrStripL(psz + 5);
511 rc = RTStrToUInt32Ex(psz, &pszNext, 10, &u); AssertRC(rc);
512 if (RT_SUCCESS(rc))
513 {
514 if (piFirstCfg)
515 {
516 *piFirstCfg = u;
517 piFirstCfg = NULL;
518 }
519 if (fActive)
520 iActiveCfg = u;
521 }
522 }
523 if (fActive)
524 break;
525 }
526 break;
527 }
528 RTStrmClose(pFile);
529 }
530 }
531 }
532 RTMemFree(pszDevices);
533
534 return iActiveCfg;
535}
536
537
538/**
539 * This finds the active configuration from sysfs.
540 *
541 * @returns The Cfg#.
542 * @returns -1 if no active config.
543 * @param pszPath The sysfs path for the device.
544 * @param piFirstCfg The first configuration. (optional)
545 * @internal
546 */
547static int usbProxyLinuxFindActiveConfigSysfs(PUSBPROXYDEV pProxyDev, const char *pszPath, int *piFirstCfg)
548{
549#ifdef VBOX_USB_WITH_SYSFS
550 if (piFirstCfg != NULL)
551 *piFirstCfg = pProxyDev->paCfgDescs != NULL
552 ? pProxyDev->paCfgDescs[0].Core.bConfigurationValue
553 : 1;
554 int64_t bCfg = 0;
555 int rc = RTLinuxSysFsReadIntFile(10, &bCfg, "%s/bConfigurationValue", pszPath);
556 if (RT_FAILURE(rc))
557 bCfg = -1;
558 return (int)bCfg;
559#else /* !VBOX_USB_WITH_SYSFS */
560 return -1;
561#endif /* !VBOX_USB_WITH_SYSFS */
562}
563
564
565/**
566 * This finds the active configuration.
567 *
568 * @returns The Cfg#.
569 * @returns -1 if no active config.
570 * @param pszPath The sysfs path for the device, or the usbfs device
571 * node path.
572 * @param iFirstCfg The first configuration. (optional)
573 * @internal
574 */
575static int usbProxyLinuxFindActiveConfig(PUSBPROXYDEV pProxyDev, const char *pszPath, int *piFirstCfg)
576{
577 PUSBPROXYDEVLNX pDevLnx = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVLNX);
578 if (pDevLnx->fUsingSysfs)
579 return usbProxyLinuxFindActiveConfigSysfs(pProxyDev, pszPath, piFirstCfg);
580 return usbProxyLinuxFindActiveConfigUsbfs(pProxyDev, pszPath, piFirstCfg);
581}
582
583
584/**
585 * Extracts the Linux file descriptor associated with the kernel USB device.
586 * This is used by rdesktop-vrdp for polling for events.
587 * @returns the FD, or asserts and returns -1 on error
588 * @param pProxyDev The device instance
589 */
590RTDECL(int) USBProxyDeviceLinuxGetFD(PUSBPROXYDEV pProxyDev)
591{
592 PUSBPROXYDEVLNX pDevLnx = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVLNX);
593 AssertReturn(pDevLnx->hFile != NIL_RTFILE, -1);
594 return RTFileToNative(pDevLnx->hFile);
595}
596
597
598/**
599 * Opens the device file.
600 *
601 * @returns VBox status code.
602 * @param pProxyDev The device instance.
603 * @param pszAddress If we are using usbfs, this is the path to the
604 * device. If we are using sysfs, this is a string of
605 * the form "sysfs:<sysfs path>//device:<device node>".
606 * In the second case, the two paths are guaranteed
607 * not to contain the substring "//".
608 * @param pvBackend Backend specific pointer, unused for the linux backend.
609 */
610static DECLCALLBACK(int) usbProxyLinuxOpen(PUSBPROXYDEV pProxyDev, const char *pszAddress, void *pvBackend)
611{
612 LogFlow(("usbProxyLinuxOpen: pProxyDev=%p pszAddress=%s\n", pProxyDev, pszAddress));
613 const char *pszDevNode;
614 const char *pszPath;
615 size_t cchPath;
616 bool fUsingSysfs;
617
618 /*
619 * Are we using sysfs or usbfs?
620 */
621#ifdef VBOX_USB_WITH_SYSFS
622 fUsingSysfs = strncmp(pszAddress, RT_STR_TUPLE("sysfs:")) == 0;
623 if (fUsingSysfs)
624 {
625 pszDevNode = strstr(pszAddress, "//device:");
626 if (!pszDevNode)
627 {
628 LogRel(("usbProxyLinuxOpen: Invalid device address: '%s'\n", pszAddress));
629 return VERR_INVALID_PARAMETER;
630 }
631
632 pszPath = pszAddress + sizeof("sysfs:") - 1;
633 cchPath = pszDevNode - pszPath;
634 pszDevNode += sizeof("//device:") - 1;
635 }
636 else
637#endif /* VBOX_USB_WITH_SYSFS */
638 {
639#ifndef VBOX_USB_WITH_SYSFS
640 fUsingSysfs = false;
641#endif
642 pszPath = pszDevNode = pszAddress;
643 cchPath = strlen(pszPath);
644 }
645
646 /*
647 * Try open the device node.
648 */
649 RTFILE hFile;
650 int rc = RTFileOpen(&hFile, pszDevNode, RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
651 if (RT_SUCCESS(rc))
652 {
653 /*
654 * Initialize the linux backend data.
655 */
656 PUSBPROXYDEVLNX pDevLnx = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVLNX);
657
658 RTListInit(&pDevLnx->ListFree);
659 RTListInit(&pDevLnx->ListInFlight);
660 RTListInit(&pDevLnx->ListTaxing);
661 pDevLnx->pszPath = RTStrDupN(pszPath, cchPath);
662 if (pDevLnx->pszPath)
663 {
664 rc = RTPipeCreate(&pDevLnx->hPipeWakeupR, &pDevLnx->hPipeWakeupW, 0);
665 if (RT_SUCCESS(rc))
666 {
667 pDevLnx->fUsingSysfs = fUsingSysfs;
668 pDevLnx->hFile = hFile;
669 rc = RTCritSectInit(&pDevLnx->CritSect);
670 if (RT_SUCCESS(rc))
671 {
672 LogFlow(("usbProxyLinuxOpen(%p, %s): returns successfully File=%RTfile iActiveCfg=%d\n",
673 pProxyDev, pszAddress, pDevLnx->hFile, pProxyDev->iActiveCfg));
674
675 return VINF_SUCCESS;
676 }
677 RTPipeClose(pDevLnx->hPipeWakeupR);
678 RTPipeClose(pDevLnx->hPipeWakeupW);
679 }
680 }
681 else
682 rc = VERR_NO_MEMORY;
683
684 RTFileClose(hFile);
685 }
686 else if (rc == VERR_ACCESS_DENIED)
687 rc = VERR_VUSB_USBFS_PERMISSION;
688
689 Log(("usbProxyLinuxOpen(%p, %s) failed, rc=%s!\n", pProxyDev, pszAddress,
690 RTErrGetShort(rc)));
691
692 NOREF(pvBackend);
693 return rc;
694}
695
696
697/**
698 * Claims all the interfaces and figures out the
699 * current configuration.
700 *
701 * @returns VINF_SUCCESS.
702 * @param pProxyDev The proxy device.
703 */
704static DECLCALLBACK(int) usbProxyLinuxInit(PUSBPROXYDEV pProxyDev)
705{
706 PUSBPROXYDEVLNX pDevLnx = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVLNX);
707
708 /*
709 * Brute force rulez.
710 * usbProxyLinuxSetConnected check for masked interfaces.
711 */
712 unsigned iIf;
713 for (iIf = 0; iIf < 256; iIf++)
714 usbProxyLinuxSetConnected(pProxyDev, iIf, false, true);
715
716 /*
717 * Determine the active configuration.
718 *
719 * If there isn't any active configuration, we will get EHOSTUNREACH (113) errors
720 * when trying to read the device descriptors in usbProxyDevCreate. So, we'll make
721 * the first one active (usually 1) then.
722 */
723 pProxyDev->cIgnoreSetConfigs = 1;
724 int iFirstCfg;
725 pProxyDev->iActiveCfg = usbProxyLinuxFindActiveConfig(pProxyDev, pDevLnx->pszPath, &iFirstCfg);
726 if (pProxyDev->iActiveCfg == -1)
727 {
728 usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_SETCONFIGURATION, &iFirstCfg, false, UINT32_MAX);
729 pProxyDev->iActiveCfg = usbProxyLinuxFindActiveConfig(pProxyDev, pDevLnx->pszPath, NULL);
730 Log(("usbProxyLinuxInit: No active config! Tried to set %d: iActiveCfg=%d\n", iFirstCfg, pProxyDev->iActiveCfg));
731 }
732 else
733 Log(("usbProxyLinuxInit(%p): iActiveCfg=%d\n", pProxyDev, pProxyDev->iActiveCfg));
734 return VINF_SUCCESS;
735}
736
737
738/**
739 * Closes the proxy device.
740 */
741static DECLCALLBACK(void) usbProxyLinuxClose(PUSBPROXYDEV pProxyDev)
742{
743 LogFlow(("usbProxyLinuxClose: pProxyDev=%s\n", usbProxyGetName(pProxyDev)));
744 PUSBPROXYDEVLNX pDevLnx = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVLNX);
745 AssertPtrReturnVoid(pDevLnx);
746
747 /*
748 * Try put the device in a state which linux can cope with before we release it.
749 * Resetting it would be a nice start, although we must remember
750 * that it might have been disconnected...
751 *
752 * Don't reset if we're masking interfaces or if construction failed.
753 */
754 if (pProxyDev->fInited)
755 {
756 /* ASSUMES: thread == EMT */
757 if ( pProxyDev->fMaskedIfs
758 || !usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_RESET, NULL, false, 10))
759 {
760 /* Connect drivers. */
761 unsigned iIf;
762 for (iIf = 0; iIf < 256; iIf++)
763 usbProxyLinuxSetConnected(pProxyDev, iIf, true, true);
764 LogRel(("USB: Successfully reset device pProxyDev=%s\n", usbProxyGetName(pProxyDev)));
765 }
766 else if (errno != ENODEV)
767 LogRel(("USB: Reset failed, errno=%d, pProxyDev=%s.\n", errno, usbProxyGetName(pProxyDev)));
768 else
769 Log(("USB: Reset failed, errno=%d (ENODEV), pProxyDev=%s.\n", errno, usbProxyGetName(pProxyDev)));
770 }
771
772 /*
773 * Now we can free all the resources and close the device.
774 */
775 RTCritSectDelete(&pDevLnx->CritSect);
776
777 PUSBPROXYURBLNX pUrbLnx;
778 PUSBPROXYURBLNX pUrbLnxNext;
779 RTListForEachSafe(&pDevLnx->ListInFlight, pUrbLnx, pUrbLnxNext, USBPROXYURBLNX, NodeList)
780 {
781 RTListNodeRemove(&pUrbLnx->NodeList);
782
783 if ( usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_DISCARDURB, &pUrbLnx->KUrb, false, UINT32_MAX)
784 && errno != ENODEV
785 && errno != ENOENT)
786 AssertMsgFailed(("errno=%d\n", errno));
787
788 if (pUrbLnx->pSplitHead)
789 {
790 PUSBPROXYURBLNX pCur = pUrbLnx->pSplitNext;
791 while (pCur)
792 {
793 PUSBPROXYURBLNX pFree = pCur;
794 pCur = pFree->pSplitNext;
795 if ( !pFree->fSplitElementReaped
796 && usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_DISCARDURB, &pFree->KUrb, false, UINT32_MAX)
797 && errno != ENODEV
798 && errno != ENOENT)
799 AssertMsgFailed(("errno=%d\n", errno));
800 RTMemFree(pFree);
801 }
802 }
803 else
804 Assert(!pUrbLnx->pSplitNext);
805 RTMemFree(pUrbLnx);
806 }
807
808 RTListForEachSafe(&pDevLnx->ListFree, pUrbLnx, pUrbLnxNext, USBPROXYURBLNX, NodeList)
809 {
810 RTListNodeRemove(&pUrbLnx->NodeList);
811 RTMemFree(pUrbLnx);
812 }
813
814 RTFileClose(pDevLnx->hFile);
815 pDevLnx->hFile = NIL_RTFILE;
816
817 RTPipeClose(pDevLnx->hPipeWakeupR);
818 RTPipeClose(pDevLnx->hPipeWakeupW);
819
820 RTStrFree(pDevLnx->pszPath);
821
822 LogFlow(("usbProxyLinuxClose: returns\n"));
823}
824
825
826#if defined(NO_PORT_RESET) && !defined(NO_LOGICAL_RECONNECT)
827/**
828 * Look for the logically reconnected device.
829 * After 5 seconds we'll give up.
830 *
831 * @returns VBox status code.
832 * @thread Reset thread or EMT.
833 */
834static int usb_reset_logical_reconnect(PUSBPROXYDEV pDev)
835{
836 FILE * pFile;
837 uint64_t u64StartTS = RTTimeMilliTS();
838
839 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",
840 pDev, pDev->Info.bBus, pDev->Info.bDevNum, pDev->Info.idVendor, pDev->Info.idProduct, pDev->Info.bcdDevice,
841 pDev->Info.u64SerialHash, pDev->Info.bDevNumParent, pDev->Info.bPort, pDev->Info.bLevel));
842
843 /* First, let hubd get a chance to logically reconnect the device. */
844 if (!RTThreadYield())
845 RTThreadSleep(1);
846
847 /*
848 * Search for the new device address.
849 */
850 pFile = get_devices_file();
851 if (!pFile)
852 return VERR_FILE_NOT_FOUND;
853
854 /*
855 * Loop until found or 5seconds have elapsed.
856 */
857 for (;;) {
858 struct pollfd pfd;
859 uint8_t tmp;
860 int rc;
861 char buf[512];
862 uint64_t u64Elapsed;
863 int got = 0;
864 struct usb_dev_entry id = {0};
865
866 /*
867 * Since this is kernel ABI we don't need to be too fussy about
868 * the parsing.
869 */
870 while (fgets(buf, sizeof(buf), pFile)) {
871 char *psz = strchr(buf, '\n');
872 if ( psz == NULL ) {
873 AssertMsgFailed(("usb_reset_logical_reconnect: Line to long!!\n"));
874 break;
875 }
876 *psz = '\0';
877
878 switch ( buf[0] ) {
879 case 'T': /* topology */
880 /* Check if we've got enough for a device. */
881 if (got >= 2) {
882 Log2(("usb_reset_logical_reconnect: {.bBus=%#x, .bDevNum=%#x, .idVendor=%#x, .idProduct=%#x, .bcdDevice=%#x, .u64SerialHash=%#llx, .bDevNumParent=%#x, .bPort=%#x, .bLevel=%#x}\n",
883 id.bBus, id.bDevNum, id.idVendor, id.idProduct, id.bcdDevice, id.u64SerialHash, id.bDevNumParent, id.bPort, id.bLevel));
884 if ( id.bDevNumParent == pDev->Info.bDevNumParent
885 && id.idVendor == pDev->Info.idVendor
886 && id.idProduct == pDev->Info.idProduct
887 && id.bcdDevice == pDev->Info.bcdDevice
888 && id.u64SerialHash == pDev->Info.u64SerialHash
889 && id.bBus == pDev->Info.bBus
890 && id.bPort == pDev->Info.bPort
891 && id.bLevel == pDev->Info.bLevel) {
892 goto l_found;
893 }
894 }
895
896 /* restart */
897 got = 0;
898 memset(&id, 0, sizeof(id));
899
900 /*T: Bus=04 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#= 3 Spd=1.5 MxCh= 0*/
901 Log2(("usb_reset_logical_reconnect: %s\n", buf));
902 buf[10] = '\0';
903 if ( !get_u8(buf + 8, &id.bBus) )
904 break;
905 buf[49] = '\0';
906 psz = buf + 46;
907 while ( *psz == ' ' )
908 psz++;
909 if ( !get_u8(psz, &id.bDevNum) )
910 break;
911
912 buf[17] = '\0';
913 if ( !get_u8(buf + 15, &id.bLevel) )
914 break;
915 buf[25] = '\0';
916 if ( !get_u8(buf + 23, &id.bDevNumParent) )
917 break;
918 buf[33] = '\0';
919 if ( !get_u8(buf + 31, &id.bPort) )
920 break;
921 got++;
922 break;
923
924 case 'P': /* product */
925 Log2(("usb_reset_logical_reconnect: %s\n", buf));
926 buf[15] = '\0';
927 if ( !get_x16(buf + 11, &id.idVendor) )
928 break;
929 buf[27] = '\0';
930 if ( !get_x16(buf + 23, &id.idProduct) )
931 break;
932 buf[34] = '\0';
933 if ( buf[32] == ' ' )
934 buf[32] = '0';
935 id.bcdDevice = 0;
936 if ( !get_x8(buf + 32, &tmp) )
937 break;
938 id.bcdDevice = tmp << 8;
939 if ( !get_x8(buf + 35, &tmp) )
940 break;
941 id.bcdDevice |= tmp;
942 got++;
943 break;
944
945 case 'S': /* String descriptor */
946 /* Skip past "S:" and then the whitespace */
947 for(psz = buf + 2; *psz != '\0'; psz++)
948 if ( !RT_C_IS_SPACE(*psz) )
949 break;
950
951 /* If it is a serial number string, skip past
952 * "SerialNumber="
953 */
954 if (strncmp(psz, RT_STR_TUPLE("SerialNumber=")))
955 break;
956
957 Log2(("usb_reset_logical_reconnect: %s\n", buf));
958 psz += sizeof("SerialNumber=") - 1;
959
960 usb_serial_hash(psz, &id.u64SerialHash);
961 break;
962 }
963 }
964
965 /*
966 * Check last.
967 */
968 if ( got >= 2
969 && id.bDevNumParent == pDev->Info.bDevNumParent
970 && id.idVendor == pDev->Info.idVendor
971 && id.idProduct == pDev->Info.idProduct
972 && id.bcdDevice == pDev->Info.bcdDevice
973 && id.u64SerialHash == pDev->Info.u64SerialHash
974 && id.bBus == pDev->Info.bBus
975 && id.bPort == pDev->Info.bPort
976 && id.bLevel == pDev->Info.bLevel) {
977 l_found:
978 /* close the existing file descriptor. */
979 RTFileClose(pDevLnx->File);
980 pDevLnx->File = NIL_RTFILE;
981
982 /* open stuff at the new address. */
983 pDev->Info = id;
984 if (usbProxyLinuxOpen(pDev, &id))
985 return VINF_SUCCESS;
986 break;
987 }
988
989 /*
990 * Wait for a while and then check the file again.
991 */
992 u64Elapsed = RTTimeMilliTS() - u64StartTS;
993 if (u64Elapsed >= 5000/*ms*/)
994 break; /* done */
995
996 pfd.fd = fileno(pFile);
997 pfd.events = POLLIN;
998 rc = poll(&pfd, 1, 5000 - u64Elapsed);
999 if (rc < 0) {
1000 AssertMsg(errno == EINTR, ("errno=%d\n", errno));
1001 RTThreadSleep(32); /* paranoia: don't eat cpu on failure */
1002 }
1003
1004 rewind(pFile);
1005 } /* for loop */
1006
1007 return VERR_GENERAL_FAILURE;
1008}
1009#endif /* !NO_PORT_RESET && !NO_LOGICAL_RECONNECT */
1010
1011
1012/**
1013 * Reset a device.
1014 *
1015 * @returns VBox status code.
1016 * @param pDev The device to reset.
1017 */
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 int rc = VINF_SUCCESS;
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 * @copydoc 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 pUrbLnx->KUrb.iso_frame_desc[i].length = pUrb->aIsocPkts[i].cb;
1505 pUrbLnx->KUrb.iso_frame_desc[i].actual_length = 0;
1506 pUrbLnx->KUrb.iso_frame_desc[i].status = 0x7fff;
1507 }
1508 break;
1509 case VUSBXFERTYPE_INTR:
1510 pUrbLnx->KUrb.type = USBDEVFS_URB_TYPE_INTERRUPT;
1511 break;
1512 default:
1513 rc = VERR_INVALID_PARAMETER; /** @todo: better status code. */
1514 }
1515
1516 /*
1517 * We have to serialize access by using the critial section here because this
1518 * thread might be suspended after submitting the URB but before linking it into
1519 * the in flight list. This would get us in trouble when reaping the URB on another
1520 * thread while it isn't in the in flight list.
1521 *
1522 * Linking the URB into the list before submitting it like it was done in the past is not
1523 * possible either because submitting the URB might fail here because the device gets
1524 * detached. The reaper thread gets this event too and might race this thread before we
1525 * can unlink the URB from the active list and the common code might end up freeing
1526 * the common URB structure twice.
1527 */
1528 RTCritSectEnter(&pDevLnx->CritSect);
1529 /*
1530 * Submit it.
1531 */
1532 cTries = 0;
1533 while (ioctl(RTFileToNative(pDevLnx->hFile), USBDEVFS_SUBMITURB, &pUrbLnx->KUrb))
1534 {
1535 if (errno == EINTR)
1536 continue;
1537 if (errno == ENODEV)
1538 {
1539 rc = RTErrConvertFromErrno(errno);
1540 Log(("usbProxyLinuxUrbQueue: ENODEV -> unplugged. pProxyDev=%s\n", usbProxyGetName(pProxyDev)));
1541 if (pUrb->enmType == VUSBXFERTYPE_MSG)
1542 usbProxyLinuxUrbSwapSetup((PVUSBSETUP)pUrb->abData);
1543
1544 RTCritSectLeave(&pDevLnx->CritSect);
1545 usbProxyLinuxUrbFree(pProxyDev, pUrbLnx);
1546 usbProxLinuxUrbUnplugged(pProxyDev);
1547 return rc;
1548 }
1549
1550 /*
1551 * usbfs has or used to have a low buffer limit (16KB) in order to prevent
1552 * processes wasting kmalloc'ed memory. It will return EINVAL if break that
1553 * limit, and we'll have to split the VUSB URB up into multiple linux URBs.
1554 *
1555 * Since this is a limit which is subject to change, we cannot check for it
1556 * before submitting the URB. We just have to try and fail.
1557 */
1558 if ( errno == EINVAL
1559 && pUrb->cbData >= 8*_1K)
1560 {
1561 rc = usbProxyLinuxUrbQueueSplit(pProxyDev, pUrbLnx, pUrb);
1562 RTCritSectLeave(&pDevLnx->CritSect);
1563 return rc;
1564 }
1565
1566 Log(("usb-linux: Queue URB %p -> %d!!! type=%d ep=%#x buffer_length=%#x cTries=%d\n",
1567 pUrb, errno, pUrbLnx->KUrb.type, pUrbLnx->KUrb.endpoint, pUrbLnx->KUrb.buffer_length, cTries));
1568 if (errno != EBUSY && ++cTries < 3) /* this doesn't work for the floppy :/ */
1569 continue;
1570
1571 RTCritSectLeave(&pDevLnx->CritSect);
1572 rc = RTErrConvertFromErrno(errno);
1573 if (pUrb->enmType == VUSBXFERTYPE_MSG)
1574 usbProxyLinuxUrbSwapSetup((PVUSBSETUP)pUrb->abData);
1575 usbProxyLinuxUrbFree(pProxyDev, pUrbLnx);
1576 return rc;
1577 }
1578
1579 usbProxyLinuxUrbLinkInFlight(pDevLnx, pUrbLnx);
1580 RTCritSectLeave(&pDevLnx->CritSect);
1581
1582 LogFlow(("usbProxyLinuxUrbQueue: ok\n"));
1583 pUrb->Dev.pvPrivate = pUrbLnx;
1584 return rc;
1585}
1586
1587
1588/**
1589 * Translate the linux status to a VUSB status.
1590 *
1591 * @remarks see cc_to_error in ohci.h, uhci_map_status in uhci-q.c,
1592 * sitd_complete+itd_complete in ehci-sched.c, and qtd_copy_status in
1593 * ehci-q.c.
1594 */
1595static VUSBSTATUS vusbProxyLinuxStatusToVUsbStatus(int iStatus)
1596{
1597 switch (iStatus)
1598 {
1599 /** @todo VUSBSTATUS_NOT_ACCESSED */
1600 case -EXDEV: /* iso transfer, partial result. */
1601 case 0:
1602 return VUSBSTATUS_OK;
1603
1604 case -EILSEQ:
1605 return VUSBSTATUS_CRC;
1606
1607 case -EREMOTEIO: /* ehci and ohci uses this for underflow error. */
1608 return VUSBSTATUS_DATA_UNDERRUN;
1609 case -EOVERFLOW:
1610 return VUSBSTATUS_DATA_OVERRUN;
1611
1612 case -ETIME:
1613 case -ENODEV:
1614 return VUSBSTATUS_DNR;
1615
1616 //case -ECOMM:
1617 // return VUSBSTATUS_BUFFER_OVERRUN;
1618 //case -ENOSR:
1619 // return VUSBSTATUS_BUFFER_UNDERRUN;
1620
1621 case -EPROTO:
1622 Log(("vusbProxyLinuxStatusToVUsbStatus: DNR/EPPROTO!!\n"));
1623 return VUSBSTATUS_DNR;
1624
1625 case -EPIPE:
1626 Log(("vusbProxyLinuxStatusToVUsbStatus: STALL/EPIPE!!\n"));
1627 return VUSBSTATUS_STALL;
1628
1629 case -ESHUTDOWN:
1630 Log(("vusbProxyLinuxStatusToVUsbStatus: SHUTDOWN!!\n"));
1631 return VUSBSTATUS_STALL;
1632
1633 default:
1634 Log(("vusbProxyLinuxStatusToVUsbStatus: status %d!!\n", iStatus));
1635 return VUSBSTATUS_STALL;
1636 }
1637}
1638
1639
1640/**
1641 * Get and translates the linux status to a VUSB status.
1642 */
1643static VUSBSTATUS vusbProxyLinuxUrbGetStatus(PUSBPROXYURBLNX pUrbLnx)
1644{
1645 return vusbProxyLinuxStatusToVUsbStatus(pUrbLnx->KUrb.status);
1646}
1647
1648
1649/**
1650 * Reap URBs in-flight on a device.
1651 *
1652 * @returns Pointer to a completed URB.
1653 * @returns NULL if no URB was completed.
1654 * @param pProxyDev The device.
1655 * @param cMillies Number of milliseconds to wait. Use 0 to not wait at all.
1656 */
1657static DECLCALLBACK(PVUSBURB) usbProxyLinuxUrbReap(PUSBPROXYDEV pProxyDev, RTMSINTERVAL cMillies)
1658{
1659 PUSBPROXYURBLNX pUrbLnx = NULL;
1660 PUSBPROXYDEVLNX pDevLnx = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVLNX);
1661
1662 /*
1663 * Any URBs pending delivery?
1664 */
1665 if (!RTListIsEmpty(&pDevLnx->ListTaxing))
1666 {
1667 RTCritSectEnter(&pDevLnx->CritSect);
1668 pUrbLnx = RTListGetFirst(&pDevLnx->ListTaxing, USBPROXYURBLNX, NodeList);
1669 if (pUrbLnx)
1670 {
1671 /* unlink from the pending delivery list */
1672 RTListNodeRemove(&pUrbLnx->NodeList);
1673
1674 /* temporarily into the active list, so free works right. */
1675 RTListAppend(&pDevLnx->ListInFlight, &pUrbLnx->NodeList);
1676 }
1677 RTCritSectLeave(&pDevLnx->CritSect);
1678 }
1679 if (!pUrbLnx)
1680 {
1681 /*
1682 * Block for requested period.
1683 *
1684 * It seems to me that the path of poll() is shorter and
1685 * involves less semaphores than ioctl() on usbfs. So, we'll
1686 * do a poll regardless of whether cMillies == 0 or not.
1687 */
1688 if (cMillies)
1689 {
1690 int cMilliesWait = cMillies == RT_INDEFINITE_WAIT ? -1 : cMillies;
1691
1692 for (;;)
1693 {
1694 struct pollfd pfd[2];
1695 pfd[0].fd = RTFileToNative(pDevLnx->hFile);
1696 pfd[0].events = POLLOUT | POLLWRNORM /* completed async */
1697 | POLLERR | POLLHUP /* disconnected */;
1698 pfd[0].revents = 0;
1699
1700 pfd[1].fd = RTPipeToNative(pDevLnx->hPipeWakeupR);
1701 pfd[1].events = POLLIN | POLLHUP;
1702 pfd[1].revents = 0;
1703
1704 int rc = poll(&pfd[0], 2, cMilliesWait);
1705 Log(("usbProxyLinuxUrbReap: poll rc = %d\n", rc));
1706 if (rc >= 1)
1707 {
1708 /* If the pipe caused the return drain it. */
1709 if (pfd[1].revents & POLLIN)
1710 {
1711 uint8_t bRead;
1712 size_t cbIgnored = 0;
1713 RTPipeRead(pDevLnx->hPipeWakeupR, &bRead, 1, &cbIgnored);
1714 }
1715 break;
1716 }
1717 if (rc >= 0)
1718 return NULL;
1719
1720 if (errno != EAGAIN)
1721 {
1722 Log(("usb-linux: Reap URB - poll -> %d errno=%d pProxyDev=%s\n", rc, errno, usbProxyGetName(pProxyDev)));
1723 return NULL;
1724 }
1725 Log(("usbProxyLinuxUrbReap: poll again - weird!!!\n"));
1726 }
1727 }
1728
1729 /*
1730 * Reap URBs, non-blocking.
1731 */
1732 for (;;)
1733 {
1734 struct usbdevfs_urb *pKUrb;
1735 while (ioctl(RTFileToNative(pDevLnx->hFile), USBDEVFS_REAPURBNDELAY, &pKUrb))
1736 if (errno != EINTR)
1737 {
1738 if (errno == ENODEV)
1739 usbProxLinuxUrbUnplugged(pProxyDev);
1740 else
1741 Log(("usb-linux: Reap URB. errno=%d pProxyDev=%s\n", errno, usbProxyGetName(pProxyDev)));
1742 return NULL;
1743 }
1744 pUrbLnx = (PUSBPROXYURBLNX)pKUrb;
1745
1746 /* split list: Is the entire split list done yet? */
1747 if (pUrbLnx->pSplitHead)
1748 {
1749 pUrbLnx->fSplitElementReaped = true;
1750
1751 /* for variable size URBs, we may need to queue more if the just-reaped URB was completely filled */
1752 if (pUrbLnx->cbSplitRemaining && (pKUrb->actual_length == pKUrb->buffer_length) && !pUrbLnx->pSplitNext)
1753 {
1754 bool fUnplugged = false;
1755 bool fSucceeded;
1756
1757 Assert(pUrbLnx->pSplitHead);
1758 Assert((pKUrb->endpoint & 0x80) && !(pKUrb->flags & USBDEVFS_URB_SHORT_NOT_OK));
1759 PUSBPROXYURBLNX pNew = usbProxyLinuxSplitURBFragment(pProxyDev, pUrbLnx->pSplitHead, pUrbLnx);
1760 if (!pNew)
1761 {
1762 Log(("usb-linux: Allocating URB fragment failed. errno=%d pProxyDev=%s\n", errno, usbProxyGetName(pProxyDev)));
1763 return NULL;
1764 }
1765 PVUSBURB pUrb = (PVUSBURB)pUrbLnx->KUrb.usercontext;
1766 fSucceeded = usbProxyLinuxSubmitURB(pProxyDev, pNew, pUrb, &fUnplugged);
1767 if (fUnplugged)
1768 usbProxLinuxUrbUnplugged(pProxyDev);
1769 if (!fSucceeded)
1770 return NULL;
1771 continue; /* try reaping another URB */
1772 }
1773 PUSBPROXYURBLNX pCur;
1774 for (pCur = pUrbLnx->pSplitHead; pCur; pCur = pCur->pSplitNext)
1775 if (!pCur->fSplitElementReaped)
1776 {
1777 pUrbLnx = NULL;
1778 break;
1779 }
1780 if (!pUrbLnx)
1781 continue;
1782 pUrbLnx = pUrbLnx->pSplitHead;
1783 }
1784 break;
1785 }
1786 }
1787
1788 /*
1789 * Ok, we got one!
1790 */
1791 PVUSBURB pUrb = (PVUSBURB)pUrbLnx->KUrb.usercontext;
1792 if ( pUrb
1793 && !pUrbLnx->fCanceledBySubmit)
1794 {
1795 if (pUrbLnx->pSplitHead)
1796 {
1797 /* split - find the end byte and the first error status. */
1798 Assert(pUrbLnx == pUrbLnx->pSplitHead);
1799 uint8_t *pbEnd = &pUrb->abData[0];
1800 pUrb->enmStatus = VUSBSTATUS_OK;
1801 PUSBPROXYURBLNX pCur;
1802 for (pCur = pUrbLnx; pCur; pCur = pCur->pSplitNext)
1803 {
1804 if (pCur->KUrb.actual_length)
1805 pbEnd = (uint8_t *)pCur->KUrb.buffer + pCur->KUrb.actual_length;
1806 if (pUrb->enmStatus == VUSBSTATUS_OK)
1807 pUrb->enmStatus = vusbProxyLinuxUrbGetStatus(pCur);
1808 }
1809 pUrb->cbData = pbEnd - &pUrb->abData[0];
1810 usbProxyLinuxUrbUnlinkInFlight(pDevLnx, pUrbLnx);
1811 usbProxyLinuxUrbFreeSplitList(pProxyDev, pUrbLnx);
1812 }
1813 else
1814 {
1815 /* unsplit. */
1816 pUrb->enmStatus = vusbProxyLinuxUrbGetStatus(pUrbLnx);
1817 pUrb->cbData = pUrbLnx->KUrb.actual_length;
1818 if (pUrb->enmType == VUSBXFERTYPE_ISOC)
1819 {
1820 unsigned i, off;
1821 for (i = 0, off = 0; i < pUrb->cIsocPkts; i++)
1822 {
1823 pUrb->aIsocPkts[i].enmStatus = vusbProxyLinuxStatusToVUsbStatus(pUrbLnx->KUrb.iso_frame_desc[i].status);
1824 Assert(pUrb->aIsocPkts[i].off == off);
1825 pUrb->aIsocPkts[i].cb = pUrbLnx->KUrb.iso_frame_desc[i].actual_length;
1826 off += pUrbLnx->KUrb.iso_frame_desc[i].length;
1827 }
1828 }
1829 usbProxyLinuxUrbUnlinkInFlight(pDevLnx, pUrbLnx);
1830 usbProxyLinuxUrbFree(pProxyDev, pUrbLnx);
1831 }
1832 pUrb->Dev.pvPrivate = NULL;
1833
1834 /* some adjustments for message transfers. */
1835 if (pUrb->enmType == VUSBXFERTYPE_MSG)
1836 {
1837 pUrb->cbData += sizeof(VUSBSETUP);
1838 usbProxyLinuxUrbSwapSetup((PVUSBSETUP)pUrb->abData);
1839 }
1840 }
1841 else
1842 {
1843 usbProxyLinuxUrbUnlinkInFlight(pDevLnx, pUrbLnx);
1844 usbProxyLinuxUrbFree(pProxyDev, pUrbLnx);
1845 pUrb = NULL;
1846 }
1847
1848 LogFlow(("usbProxyLinuxUrbReap: pProxyDev=%s returns %p\n", usbProxyGetName(pProxyDev), pUrb));
1849 return pUrb;
1850}
1851
1852
1853/**
1854 * Cancels the URB.
1855 * The URB requires reaping, so we don't change its state.
1856 */
1857static DECLCALLBACK(int) usbProxyLinuxUrbCancel(PUSBPROXYDEV pProxyDev, PVUSBURB pUrb)
1858{
1859 int rc = VINF_SUCCESS;
1860 PUSBPROXYURBLNX pUrbLnx = (PUSBPROXYURBLNX)pUrb->Dev.pvPrivate;
1861 if (pUrbLnx->pSplitHead)
1862 {
1863 /* split */
1864 Assert(pUrbLnx == pUrbLnx->pSplitHead);
1865 PUSBPROXYURBLNX pCur;
1866 for (pCur = pUrbLnx; pCur; pCur = pCur->pSplitNext)
1867 {
1868 if (pCur->fSplitElementReaped)
1869 continue;
1870 if ( !usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_DISCARDURB, &pCur->KUrb, true, UINT32_MAX)
1871 || errno == ENOENT)
1872 continue;
1873 if (errno == ENODEV)
1874 break;
1875 /** @todo: Think about how to handle errors wrt. to the status code. */
1876 Log(("usb-linux: Discard URB %p failed, errno=%d. pProxyDev=%s!!! (split)\n",
1877 pUrb, errno, usbProxyGetName(pProxyDev)));
1878 }
1879 }
1880 else
1881 {
1882 /* unsplit */
1883 if ( usbProxyLinuxDoIoCtl(pProxyDev, USBDEVFS_DISCARDURB, &pUrbLnx->KUrb, true, UINT32_MAX)
1884 && errno != ENODEV /* deal with elsewhere. */
1885 && errno != ENOENT)
1886 {
1887 Log(("usb-linux: Discard URB %p failed, errno=%d. pProxyDev=%s!!!\n",
1888 pUrb, errno, usbProxyGetName(pProxyDev)));
1889 rc = RTErrConvertFromErrno(errno);
1890 }
1891 }
1892
1893 return rc;
1894}
1895
1896
1897static DECLCALLBACK(int) usbProxyLinuxWakeup(PUSBPROXYDEV pProxyDev)
1898{
1899 PUSBPROXYDEVLNX pDevLnx = USBPROXYDEV_2_DATA(pProxyDev, PUSBPROXYDEVLNX);
1900 size_t cbIgnored;
1901
1902 LogFlowFunc(("pProxyDev=%p\n", pProxyDev));
1903
1904 return RTPipeWrite(pDevLnx->hPipeWakeupW, "", 1, &cbIgnored);
1905}
1906
1907/**
1908 * The Linux USB Proxy Backend.
1909 */
1910const USBPROXYBACK g_USBProxyDeviceHost =
1911{
1912 /* pszName */
1913 "host",
1914 /* cbBackend */
1915 sizeof(USBPROXYDEVLNX),
1916 usbProxyLinuxOpen,
1917 usbProxyLinuxInit,
1918 usbProxyLinuxClose,
1919 usbProxyLinuxReset,
1920 usbProxyLinuxSetConfig,
1921 usbProxyLinuxClaimInterface,
1922 usbProxyLinuxReleaseInterface,
1923 usbProxyLinuxSetInterface,
1924 usbProxyLinuxClearHaltedEp,
1925 usbProxyLinuxUrbQueue,
1926 usbProxyLinuxUrbCancel,
1927 usbProxyLinuxUrbReap,
1928 usbProxyLinuxWakeup,
1929 0
1930};
1931
1932
1933/*
1934 * Local Variables:
1935 * mode: c
1936 * c-file-style: "bsd"
1937 * c-basic-offset: 4
1938 * End:
1939 */
1940
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