VirtualBox

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

Last change on this file since 55365 was 52948, checked in by vboxsync, 10 years ago

USBProxyDevice-linux: various fixes for the split URB code paths used on older Linux kernels

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