VirtualBox

source: vbox/trunk/src/VBox/Devices/USB/VUSBDevice.cpp@ 62506

Last change on this file since 62506 was 62502, checked in by vboxsync, 8 years ago

(C) 2016

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 60.0 KB
Line 
1/* $Id: VUSBDevice.cpp 62502 2016-07-22 19:09:14Z vboxsync $ */
2/** @file
3 * Virtual USB - Device.
4 */
5
6/*
7 * Copyright (C) 2006-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DRV_VUSB
23#include <VBox/vmm/pdm.h>
24#include <VBox/vmm/vmapi.h>
25#include <VBox/err.h>
26#include <VBox/log.h>
27#include <iprt/alloc.h>
28#include <iprt/time.h>
29#include <iprt/thread.h>
30#include <iprt/semaphore.h>
31#include <iprt/string.h>
32#include <iprt/assert.h>
33#include <iprt/asm.h>
34#include "VUSBInternal.h"
35
36#include "VUSBSniffer.h"
37
38
39/*********************************************************************************************************************************
40* Structures and Typedefs *
41*********************************************************************************************************************************/
42/**
43 * Argument package of vusbDevResetThread().
44 */
45typedef struct vusb_reset_args
46{
47 /** Pointer to the device which is being reset. */
48 PVUSBDEV pDev;
49 /** The reset return code. */
50 int rc;
51 /** Pointer to the completion callback. */
52 PFNVUSBRESETDONE pfnDone;
53 /** User argument to pfnDone. */
54 void *pvUser;
55} VUSBRESETARGS, *PVUSBRESETARGS;
56
57
58/*********************************************************************************************************************************
59* Global Variables *
60*********************************************************************************************************************************/
61/** Default message pipe. */
62const VUSBDESCENDPOINTEX g_Endpoint0 =
63{
64 {
65 /* .bLength = */ VUSB_DT_ENDPOINT_MIN_LEN,
66 /* .bDescriptorType = */ VUSB_DT_ENDPOINT,
67 /* .bEndpointAddress = */ 0,
68 /* .bmAttributes = */ 0,
69 /* .wMaxPacketSize = */ 64,
70 /* .bInterval = */ 0
71 },
72 NULL
73};
74
75/** Default configuration. */
76const VUSBDESCCONFIGEX g_Config0 =
77{
78 {
79 /* .bLength = */ VUSB_DT_CONFIG_MIN_LEN,
80 /* .bDescriptorType = */ VUSB_DT_CONFIG,
81 /* .WTotalLength = */ 0, /* (auto-calculated) */
82 /* .bNumInterfaces = */ 0,
83 /* .bConfigurationValue =*/ 0,
84 /* .iConfiguration = */ 0,
85 /* .bmAttributes = */ 0x80,
86 /* .MaxPower = */ 14
87 },
88 NULL,
89 NULL
90};
91
92
93
94static PCVUSBDESCCONFIGEX vusbDevFindCfgDesc(PVUSBDEV pDev, int iCfg)
95{
96 if (iCfg == 0)
97 return &g_Config0;
98
99 for (unsigned i = 0; i < pDev->pDescCache->pDevice->bNumConfigurations; i++)
100 if (pDev->pDescCache->paConfigs[i].Core.bConfigurationValue == iCfg)
101 return &pDev->pDescCache->paConfigs[i];
102 return NULL;
103}
104
105static PVUSBINTERFACESTATE vusbDevFindIfState(PVUSBDEV pDev, int iIf)
106{
107 for (unsigned i = 0; i < pDev->pCurCfgDesc->Core.bNumInterfaces; i++)
108 if (pDev->paIfStates[i].pIf->paSettings[0].Core.bInterfaceNumber == iIf)
109 return &pDev->paIfStates[i];
110 return NULL;
111}
112
113static PCVUSBDESCINTERFACEEX vusbDevFindAltIfDesc(PVUSBDEV pDev, PCVUSBINTERFACESTATE pIfState, int iAlt)
114{
115 for (uint32_t i = 0; i < pIfState->pIf->cSettings; i++)
116 if (pIfState->pIf->paSettings[i].Core.bAlternateSetting == iAlt)
117 return &pIfState->pIf->paSettings[i];
118 return NULL;
119}
120
121void vusbDevMapEndpoint(PVUSBDEV pDev, PCVUSBDESCENDPOINTEX pEndPtDesc)
122{
123 uint8_t i8Addr = pEndPtDesc->Core.bEndpointAddress & 0xF;
124 PVUSBPIPE pPipe = &pDev->aPipes[i8Addr];
125 LogFlow(("vusbDevMapEndpoint: pDev=%p[%s] pEndPtDesc=%p{.bEndpointAddress=%#x, .bmAttributes=%#x} p=%p stage %s->SETUP\n",
126 pDev, pDev->pUsbIns->pszName, pEndPtDesc, pEndPtDesc->Core.bEndpointAddress, pEndPtDesc->Core.bmAttributes,
127 pPipe, g_apszCtlStates[pPipe->pCtrl ? pPipe->pCtrl->enmStage : 3]));
128
129 if ((pEndPtDesc->Core.bmAttributes & 0x3) == 0)
130 {
131 Log(("vusb: map message pipe on address %u\n", i8Addr));
132 pPipe->in = pEndPtDesc;
133 pPipe->out = pEndPtDesc;
134 }
135 else if (pEndPtDesc->Core.bEndpointAddress & 0x80)
136 {
137 Log(("vusb: map input pipe on address %u\n", i8Addr));
138 pPipe->in = pEndPtDesc;
139 }
140 else
141 {
142 Log(("vusb: map output pipe on address %u\n", i8Addr));
143 pPipe->out = pEndPtDesc;
144
145#if 0
146 if ((pEndPtDesc->Core.bmAttributes & 0x03) == 1)
147 {
148 int rc = vusbBufferedPipeCreate(pDev, pPipe, VUSBDIRECTION_OUT, pDev->pUsbIns->enmSpeed,
149 32 /* cLatencyMs*/, &pPipe->hBuffer);
150 if (RT_SUCCESS(rc))
151 LogRel(("VUSB: Created a buffered pipe for isochronous output endpoint\n"));
152 else
153 LogRel(("VUSB: Failed to create a buffered pipe for isochronous output endpoint with rc=%Rrc\n", rc));
154 }
155#endif
156 }
157
158 if (pPipe->pCtrl)
159 {
160 vusbMsgFreeExtraData(pPipe->pCtrl);
161 pPipe->pCtrl = NULL;
162 }
163}
164
165static void unmap_endpoint(PVUSBDEV pDev, PCVUSBDESCENDPOINTEX pEndPtDesc)
166{
167 uint8_t EndPt = pEndPtDesc->Core.bEndpointAddress & 0xF;
168 PVUSBPIPE pPipe = &pDev->aPipes[EndPt];
169 LogFlow(("unmap_endpoint: pDev=%p[%s] pEndPtDesc=%p{.bEndpointAddress=%#x, .bmAttributes=%#x} p=%p stage %s->SETUP\n",
170 pDev, pDev->pUsbIns->pszName, pEndPtDesc, pEndPtDesc->Core.bEndpointAddress, pEndPtDesc->Core.bmAttributes,
171 pPipe, g_apszCtlStates[pPipe->pCtrl ? pPipe->pCtrl->enmStage : 3]));
172
173 if ((pEndPtDesc->Core.bmAttributes & 0x3) == 0)
174 {
175 Log(("vusb: unmap MSG pipe from address %u (%#x)\n", EndPt, pEndPtDesc->Core.bEndpointAddress));
176 pPipe->in = NULL;
177 pPipe->out = NULL;
178 }
179 else if (pEndPtDesc->Core.bEndpointAddress & 0x80)
180 {
181 Log(("vusb: unmap IN pipe from address %u (%#x)\n", EndPt, pEndPtDesc->Core.bEndpointAddress));
182 pPipe->in = NULL;
183
184 /* Terminate the pipe buffer if created. */
185 if (pPipe->hBuffer)
186 {
187 vusbBufferedPipeDestroy(pPipe->hBuffer);
188 pPipe->hBuffer = NULL;
189 }
190 }
191 else
192 {
193 Log(("vusb: unmap OUT pipe from address %u (%#x)\n", EndPt, pEndPtDesc->Core.bEndpointAddress));
194 pPipe->out = NULL;
195
196 /* Terminate the pipe buffer if created. */
197 if (pPipe->hBuffer)
198 {
199 vusbBufferedPipeDestroy(pPipe->hBuffer);
200 pPipe->hBuffer = NULL;
201 }
202 }
203
204 if (pPipe->pCtrl)
205 {
206 vusbMsgFreeExtraData(pPipe->pCtrl);
207 pPipe->pCtrl = NULL;
208 }
209}
210
211static void map_interface(PVUSBDEV pDev, PCVUSBDESCINTERFACEEX pIfDesc)
212{
213 LogFlow(("map_interface: pDev=%p[%s] pIfDesc=%p:{.iInterface=%d, .bAlternateSetting=%d}\n",
214 pDev, pDev->pUsbIns->pszName, pIfDesc, pIfDesc->Core.iInterface, pIfDesc->Core.bAlternateSetting));
215
216 for (unsigned i = 0; i < pIfDesc->Core.bNumEndpoints; i++)
217 {
218 if ((pIfDesc->paEndpoints[i].Core.bEndpointAddress & 0xF) == VUSB_PIPE_DEFAULT)
219 Log(("vusb: Endpoint 0x%x on interface %u.%u tried to override the default message pipe!!!\n",
220 pIfDesc->paEndpoints[i].Core.bEndpointAddress, pIfDesc->Core.bInterfaceNumber, pIfDesc->Core.bAlternateSetting));
221 else
222 vusbDevMapEndpoint(pDev, &pIfDesc->paEndpoints[i]);
223 }
224}
225
226
227/**
228 * Worker that resets the pipe data on select config and detach.
229 *
230 * This leaves the critical section unmolested
231 *
232 * @param pPipe The pipe which data should be reset.
233 */
234static void vusbDevResetPipeData(PVUSBPIPE pPipe)
235{
236 vusbMsgFreeExtraData(pPipe->pCtrl);
237 pPipe->pCtrl = NULL;
238
239 if (pPipe->hBuffer)
240 {
241 vusbBufferedPipeDestroy(pPipe->hBuffer);
242 pPipe->hBuffer = NULL;
243 }
244
245 RT_ZERO(pPipe->in);
246 RT_ZERO(pPipe->out);
247 pPipe->async = 0;
248}
249
250
251bool vusbDevDoSelectConfig(PVUSBDEV pDev, PCVUSBDESCCONFIGEX pCfgDesc)
252{
253 LogFlow(("vusbDevDoSelectConfig: pDev=%p[%s] pCfgDesc=%p:{.iConfiguration=%d}\n",
254 pDev, pDev->pUsbIns->pszName, pCfgDesc, pCfgDesc->Core.iConfiguration));
255
256 /*
257 * Clean up all pipes and interfaces.
258 */
259 unsigned i;
260 for (i = 0; i < VUSB_PIPE_MAX; i++)
261 if (i != VUSB_PIPE_DEFAULT)
262 vusbDevResetPipeData(&pDev->aPipes[i]);
263 memset(pDev->paIfStates, 0, pCfgDesc->Core.bNumInterfaces * sizeof(pDev->paIfStates[0]));
264
265 /*
266 * Map in the default setting for every interface.
267 */
268 for (i = 0; i < pCfgDesc->Core.bNumInterfaces; i++)
269 {
270 PCVUSBINTERFACE pIf;
271 struct vusb_interface_state *pIfState;
272
273 pIf = &pCfgDesc->paIfs[i];
274 pIfState = &pDev->paIfStates[i];
275 pIfState->pIf = pIf;
276
277 /*
278 * Find the 0 setting, if it is not present we just use
279 * the lowest numbered one.
280 */
281 for (uint32_t j = 0; j < pIf->cSettings; j++)
282 {
283 if ( !pIfState->pCurIfDesc
284 || pIf->paSettings[j].Core.bAlternateSetting < pIfState->pCurIfDesc->Core.bAlternateSetting)
285 pIfState->pCurIfDesc = &pIf->paSettings[j];
286 if (pIfState->pCurIfDesc->Core.bAlternateSetting == 0)
287 break;
288 }
289
290 if (pIfState->pCurIfDesc)
291 map_interface(pDev, pIfState->pCurIfDesc);
292 }
293
294 pDev->pCurCfgDesc = pCfgDesc;
295
296 if (pCfgDesc->Core.bmAttributes & 0x40)
297 pDev->u16Status |= (1 << VUSB_DEV_SELF_POWERED);
298 else
299 pDev->u16Status &= ~(1 << VUSB_DEV_SELF_POWERED);
300
301 return true;
302}
303
304/**
305 * Standard device request: SET_CONFIGURATION
306 * @returns success indicator.
307 */
308static bool vusbDevStdReqSetConfig(PVUSBDEV pDev, int EndPt, PVUSBSETUP pSetup, uint8_t *pbBuf, uint32_t *pcbBuf)
309{
310 unsigned iCfg = pSetup->wValue & 0xff;
311
312 if ((pSetup->bmRequestType & VUSB_RECIP_MASK) != VUSB_TO_DEVICE)
313 {
314 Log(("vusb: error: %s: SET_CONFIGURATION - invalid request (dir) !!!\n", pDev->pUsbIns->pszName));
315 return false;
316 }
317
318 /*
319 * Check that the device is in a valid state.
320 * (The caller has already checked that it's not being reset.)
321 */
322 const VUSBDEVICESTATE enmState = vusbDevGetState(pDev);
323 if (enmState == VUSB_DEVICE_STATE_DEFAULT)
324 {
325 LogFlow(("vusbDevStdReqSetConfig: %s: default dev state !!?\n", pDev->pUsbIns->pszName));
326 return false;
327 }
328
329 PCVUSBDESCCONFIGEX pNewCfgDesc = vusbDevFindCfgDesc(pDev, iCfg);
330 if (!pNewCfgDesc)
331 {
332 Log(("vusb: error: %s: config %i not found !!!\n", pDev->pUsbIns->pszName, iCfg));
333 return false;
334 }
335
336 if (iCfg == 0)
337 vusbDevSetState(pDev, VUSB_DEVICE_STATE_ADDRESS);
338 else
339 vusbDevSetState(pDev, VUSB_DEVICE_STATE_CONFIGURED);
340 if (pDev->pUsbIns->pReg->pfnUsbSetConfiguration)
341 {
342 int rc = vusbDevIoThreadExecSync(pDev, (PFNRT)pDev->pUsbIns->pReg->pfnUsbSetConfiguration, 5,
343 pDev->pUsbIns, pNewCfgDesc->Core.bConfigurationValue,
344 pDev->pCurCfgDesc, pDev->paIfStates, pNewCfgDesc);
345 if (RT_FAILURE(rc))
346 {
347 Log(("vusb: error: %s: failed to set config %i (%Rrc) !!!\n", pDev->pUsbIns->pszName, iCfg, rc));
348 return false;
349 }
350 }
351 Log(("vusb: %p[%s]: SET_CONFIGURATION: Selected config %u\n", pDev, pDev->pUsbIns->pszName, iCfg));
352 return vusbDevDoSelectConfig(pDev, pNewCfgDesc);
353}
354
355
356/**
357 * Standard device request: GET_CONFIGURATION
358 * @returns success indicator.
359 */
360static bool vusbDevStdReqGetConfig(PVUSBDEV pDev, int EndPt, PVUSBSETUP pSetup, uint8_t *pbBuf, uint32_t *pcbBuf)
361{
362 if ((pSetup->bmRequestType & VUSB_RECIP_MASK) != VUSB_TO_DEVICE)
363 {
364 Log(("vusb: error: %s: GET_CONFIGURATION - invalid request (dir) !!!\n", pDev->pUsbIns->pszName));
365 return false;
366 }
367
368 /*
369 * Check that the device is in a valid state.
370 * (The caller has already checked that it's not being reset.)
371 */
372 const VUSBDEVICESTATE enmState = vusbDevGetState(pDev);
373 if ( enmState != VUSB_DEVICE_STATE_CONFIGURED
374 && enmState != VUSB_DEVICE_STATE_ADDRESS)
375 {
376 LogFlow(("vusbDevStdReqGetConfig: error: %s: invalid device state %d!!!\n", pDev->pUsbIns->pszName, enmState));
377 return false;
378 }
379
380 if (*pcbBuf < 1)
381 {
382 LogFlow(("vusbDevStdReqGetConfig: %s: no space for data!\n", pDev->pUsbIns->pszName));
383 return true;
384 }
385
386 uint8_t iCfg;
387 if (enmState == VUSB_DEVICE_STATE_ADDRESS)
388 iCfg = 0;
389 else
390 iCfg = pDev->pCurCfgDesc->Core.bConfigurationValue;
391
392 *pbBuf = iCfg;
393 *pcbBuf = 1;
394 LogFlow(("vusbDevStdReqGetConfig: %s: returns iCfg=%d\n", pDev->pUsbIns->pszName, iCfg));
395 return true;
396}
397
398/**
399 * Standard device request: GET_INTERFACE
400 * @returns success indicator.
401 */
402static bool vusbDevStdReqGetInterface(PVUSBDEV pDev, int EndPt, PVUSBSETUP pSetup, uint8_t *pbBuf, uint32_t *pcbBuf)
403{
404 if ((pSetup->bmRequestType & VUSB_RECIP_MASK) != VUSB_TO_INTERFACE)
405 {
406 Log(("vusb: error: %s: GET_INTERFACE - invalid request (dir) !!!\n", pDev->pUsbIns->pszName));
407 return false;
408 }
409
410 /*
411 * Check that the device is in a valid state.
412 * (The caller has already checked that it's not being reset.)
413 */
414 const VUSBDEVICESTATE enmState = vusbDevGetState(pDev);
415 if (enmState != VUSB_DEVICE_STATE_CONFIGURED)
416 {
417 LogFlow(("vusbDevStdReqGetInterface: error: %s: invalid device state %d!!!\n", pDev->pUsbIns->pszName, enmState));
418 return false;
419 }
420
421 if (*pcbBuf < 1)
422 {
423 LogFlow(("vusbDevStdReqGetInterface: %s: no space for data!\n", pDev->pUsbIns->pszName));
424 return true;
425 }
426
427 for (unsigned i = 0; i < pDev->pCurCfgDesc->Core.bNumInterfaces; i++)
428 {
429 PCVUSBDESCINTERFACEEX pIfDesc = pDev->paIfStates[i].pCurIfDesc;
430 if ( pIfDesc
431 && pSetup->wIndex == pIfDesc->Core.bInterfaceNumber)
432 {
433 *pbBuf = pIfDesc->Core.bAlternateSetting;
434 *pcbBuf = 1;
435 Log(("vusb: %s: GET_INTERFACE: %u.%u\n", pDev->pUsbIns->pszName, pIfDesc->Core.bInterfaceNumber, *pbBuf));
436 return true;
437 }
438 }
439
440 Log(("vusb: error: %s: GET_INTERFACE - unknown iface %u !!!\n", pDev->pUsbIns->pszName, pSetup->wIndex));
441 return false;
442}
443
444/**
445 * Standard device request: SET_INTERFACE
446 * @returns success indicator.
447 */
448static bool vusbDevStdReqSetInterface(PVUSBDEV pDev, int EndPt, PVUSBSETUP pSetup, uint8_t *pbBuf, uint32_t *pcbBuf)
449{
450 if ((pSetup->bmRequestType & VUSB_RECIP_MASK) != VUSB_TO_INTERFACE)
451 {
452 Log(("vusb: error: %s: SET_INTERFACE - invalid request (dir) !!!\n", pDev->pUsbIns->pszName));
453 return false;
454 }
455
456 /*
457 * Check that the device is in a valid state.
458 * (The caller has already checked that it's not being reset.)
459 */
460 const VUSBDEVICESTATE enmState = vusbDevGetState(pDev);
461 if (enmState != VUSB_DEVICE_STATE_CONFIGURED)
462 {
463 LogFlow(("vusbDevStdReqSetInterface: error: %s: invalid device state %d !!!\n", pDev->pUsbIns->pszName, enmState));
464 return false;
465 }
466
467 /*
468 * Find the interface.
469 */
470 uint8_t iIf = pSetup->wIndex;
471 PVUSBINTERFACESTATE pIfState = vusbDevFindIfState(pDev, iIf);
472 if (!pIfState)
473 {
474 LogFlow(("vusbDevStdReqSetInterface: error: %s: couldn't find interface %u !!!\n", pDev->pUsbIns->pszName, iIf));
475 return false;
476 }
477 uint8_t iAlt = pSetup->wValue;
478 PCVUSBDESCINTERFACEEX pIfDesc = vusbDevFindAltIfDesc(pDev, pIfState, iAlt);
479 if (!pIfDesc)
480 {
481 LogFlow(("vusbDevStdReqSetInterface: error: %s: couldn't find alt interface %u.%u !!!\n", pDev->pUsbIns->pszName, iIf, iAlt));
482 return false;
483 }
484
485 if (pDev->pUsbIns->pReg->pfnUsbSetInterface)
486 {
487 int rc = vusbDevIoThreadExecSync(pDev, (PFNRT)pDev->pUsbIns->pReg->pfnUsbSetInterface, 3, pDev->pUsbIns, iIf, iAlt);
488 if (RT_FAILURE(rc))
489 {
490 LogFlow(("vusbDevStdReqSetInterface: error: %s: couldn't find alt interface %u.%u (%Rrc)\n", pDev->pUsbIns->pszName, iIf, iAlt, rc));
491 return false;
492 }
493 }
494
495 for (unsigned i = 0; i < pIfState->pCurIfDesc->Core.bNumEndpoints; i++)
496 unmap_endpoint(pDev, &pIfState->pCurIfDesc->paEndpoints[i]);
497
498 Log(("vusb: SET_INTERFACE: Selected %u.%u\n", iIf, iAlt));
499
500 map_interface(pDev, pIfDesc);
501 pIfState->pCurIfDesc = pIfDesc;
502
503 return true;
504}
505
506/**
507 * Standard device request: SET_ADDRESS
508 * @returns success indicator.
509 */
510static bool vusbDevStdReqSetAddress(PVUSBDEV pDev, int EndPt, PVUSBSETUP pSetup, uint8_t *pbBuf, uint32_t *pcbBuf)
511{
512 if ((pSetup->bmRequestType & VUSB_RECIP_MASK) != VUSB_TO_DEVICE)
513 {
514 Log(("vusb: error: %s: SET_ADDRESS - invalid request (dir) !!!\n", pDev->pUsbIns->pszName));
515 return false;
516 }
517
518 /*
519 * Check that the device is in a valid state.
520 * (The caller has already checked that it's not being reset.)
521 */
522 const VUSBDEVICESTATE enmState = vusbDevGetState(pDev);
523 if ( enmState != VUSB_DEVICE_STATE_DEFAULT
524 && enmState != VUSB_DEVICE_STATE_ADDRESS)
525 {
526 LogFlow(("vusbDevStdReqSetAddress: error: %s: invalid device state %d !!!\n", pDev->pUsbIns->pszName, enmState));
527 return false;
528 }
529
530 pDev->u8NewAddress = pSetup->wValue;
531 return true;
532}
533
534/**
535 * Standard device request: CLEAR_FEATURE
536 * @returns success indicator.
537 *
538 * @remark This is only called for VUSB_TO_ENDPOINT && ep == 0 && wValue == ENDPOINT_HALT.
539 * All other cases of CLEAR_FEATURE is handled in the normal async/sync manner.
540 */
541static bool vusbDevStdReqClearFeature(PVUSBDEV pDev, int EndPt, PVUSBSETUP pSetup, uint8_t *pbBuf, uint32_t *pcbBuf)
542{
543 switch (pSetup->bmRequestType & VUSB_RECIP_MASK)
544 {
545 case VUSB_TO_DEVICE:
546 Log(("vusb: ClearFeature: dev(%u): selector=%u\n", pSetup->wIndex, pSetup->wValue));
547 break;
548 case VUSB_TO_INTERFACE:
549 Log(("vusb: ClearFeature: iface(%u): selector=%u\n", pSetup->wIndex, pSetup->wValue));
550 break;
551 case VUSB_TO_ENDPOINT:
552 Log(("vusb: ClearFeature: ep(%u): selector=%u\n", pSetup->wIndex, pSetup->wValue));
553 if ( !EndPt /* Default control pipe only */
554 && pSetup->wValue == 0 /* ENDPOINT_HALT */
555 && pDev->pUsbIns->pReg->pfnUsbClearHaltedEndpoint)
556 {
557 int rc = vusbDevIoThreadExecSync(pDev, (PFNRT)pDev->pUsbIns->pReg->pfnUsbClearHaltedEndpoint,
558 2, pDev->pUsbIns, pSetup->wIndex);
559 return RT_SUCCESS(rc);
560 }
561 break;
562 default:
563 AssertMsgFailed(("VUSB_TO_OTHER!\n"));
564 break;
565 }
566
567 AssertMsgFailed(("Invalid safe check !!!\n"));
568 return false;
569}
570
571/**
572 * Standard device request: SET_FEATURE
573 * @returns success indicator.
574 */
575static bool vusbDevStdReqSetFeature(PVUSBDEV pDev, int EndPt, PVUSBSETUP pSetup, uint8_t *pbBuf, uint32_t *pcbBuf)
576{
577 switch (pSetup->bmRequestType & VUSB_RECIP_MASK)
578 {
579 case VUSB_TO_DEVICE:
580 Log(("vusb: SetFeature: dev(%u): selector=%u\n",
581 pSetup->wIndex, pSetup->wValue));
582 break;
583 case VUSB_TO_INTERFACE:
584 Log(("vusb: SetFeature: if(%u): selector=%u\n",
585 pSetup->wIndex, pSetup->wValue));
586 break;
587 case VUSB_TO_ENDPOINT:
588 Log(("vusb: SetFeature: ep(%u): selector=%u\n",
589 pSetup->wIndex, pSetup->wValue));
590 break;
591 default:
592 AssertMsgFailed(("VUSB_TO_OTHER!\n"));
593 return false;
594 }
595 AssertMsgFailed(("This stuff is bogus\n"));
596 return false;
597}
598
599static bool vusbDevStdReqGetStatus(PVUSBDEV pDev, int EndPt, PVUSBSETUP pSetup, uint8_t *pbBuf, uint32_t *pcbBuf)
600{
601 if (*pcbBuf != 2)
602 {
603 LogFlow(("vusbDevStdReqGetStatus: %s: buffer is too small! (%d)\n", pDev->pUsbIns->pszName, *pcbBuf));
604 return false;
605 }
606
607 uint16_t u16Status;
608 switch (pSetup->bmRequestType & VUSB_RECIP_MASK)
609 {
610 case VUSB_TO_DEVICE:
611 u16Status = pDev->u16Status;
612 LogFlow(("vusbDevStdReqGetStatus: %s: device status %#x (%d)\n", pDev->pUsbIns->pszName, u16Status, u16Status));
613 break;
614 case VUSB_TO_INTERFACE:
615 u16Status = 0;
616 LogFlow(("vusbDevStdReqGetStatus: %s: bogus interface status request!!\n", pDev->pUsbIns->pszName));
617 break;
618 case VUSB_TO_ENDPOINT:
619 u16Status = 0;
620 LogFlow(("vusbDevStdReqGetStatus: %s: bogus endpoint status request!!\n", pDev->pUsbIns->pszName));
621 break;
622 default:
623 AssertMsgFailed(("VUSB_TO_OTHER!\n"));
624 return false;
625 }
626
627 *(uint16_t *)pbBuf = u16Status;
628 return true;
629}
630
631
632/**
633 * Finds a cached string.
634 *
635 * @returns Pointer to the cached string if found. NULL if not.
636 * @param paLanguages The languages to search.
637 * @param cLanguages The number of languages in the table.
638 * @param idLang The language ID.
639 * @param iString The string index.
640 */
641static PCPDMUSBDESCCACHESTRING FindCachedString(PCPDMUSBDESCCACHELANG paLanguages, unsigned cLanguages,
642 uint16_t idLang, uint8_t iString)
643{
644 /** @todo binary lookups! */
645 unsigned iCurLang = cLanguages;
646 while (iCurLang-- > 0)
647 if (paLanguages[iCurLang].idLang == idLang)
648 {
649 PCPDMUSBDESCCACHESTRING paStrings = paLanguages[iCurLang].paStrings;
650 unsigned iCurStr = paLanguages[iCurLang].cStrings;
651 while (iCurStr-- > 0)
652 if (paStrings[iCurStr].idx == iString)
653 return &paStrings[iCurStr];
654 break;
655 }
656 return NULL;
657}
658
659
660/** Macro for copying descriptor data. */
661#define COPY_DATA(pbDst, cbLeft, pvSrc, cbSrc) \
662 do { \
663 uint32_t cbSrc_ = cbSrc; \
664 uint32_t cbCopy = RT_MIN(cbLeft, cbSrc_); \
665 if (cbCopy) \
666 memcpy(pbBuf, pvSrc, cbCopy); \
667 cbLeft -= cbCopy; \
668 if (!cbLeft) \
669 return; \
670 pbBuf += cbCopy; \
671 } while (0)
672
673/**
674 * Internal function for reading the language IDs.
675 */
676static void ReadCachedStringDesc(PCPDMUSBDESCCACHESTRING pString, uint8_t *pbBuf, uint32_t *pcbBuf)
677{
678 uint32_t cbLeft = *pcbBuf;
679
680 RTUTF16 wsz[128]; /* 128-1 => bLength=0xff */
681 PRTUTF16 pwsz = wsz;
682 size_t cwc;
683 int rc = RTStrToUtf16Ex(pString->psz, RT_ELEMENTS(wsz) - 1, &pwsz, RT_ELEMENTS(wsz), &cwc);
684 if (RT_FAILURE(rc))
685 {
686 AssertRC(rc);
687 wsz[0] = 'e';
688 wsz[1] = 'r';
689 wsz[2] = 'r';
690 cwc = 3;
691 }
692
693 VUSBDESCSTRING StringDesc;
694 StringDesc.bLength = (uint8_t)(sizeof(StringDesc) + cwc * sizeof(RTUTF16));
695 StringDesc.bDescriptorType = VUSB_DT_STRING;
696 COPY_DATA(pbBuf, cbLeft, &StringDesc, sizeof(StringDesc));
697 COPY_DATA(pbBuf, cbLeft, wsz, (uint32_t)cwc * sizeof(RTUTF16));
698
699 /* updated the size of the output buffer. */
700 *pcbBuf -= cbLeft;
701}
702
703
704/**
705 * Internal function for reading the language IDs.
706 */
707static void ReadCachedLangIdDesc(PCPDMUSBDESCCACHELANG paLanguages, unsigned cLanguages,
708 uint8_t *pbBuf, uint32_t *pcbBuf)
709{
710 uint32_t cbLeft = *pcbBuf;
711
712 VUSBDESCLANGID LangIdDesc;
713 size_t cbDesc = sizeof(LangIdDesc) + cLanguages * sizeof(paLanguages[0].idLang);
714 LangIdDesc.bLength = (uint8_t)RT_MIN(0xff, cbDesc);
715 LangIdDesc.bDescriptorType = VUSB_DT_STRING;
716 COPY_DATA(pbBuf, cbLeft, &LangIdDesc, sizeof(LangIdDesc));
717
718 unsigned iLanguage = cLanguages;
719 while (iLanguage-- > 0)
720 COPY_DATA(pbBuf, cbLeft, &paLanguages[iLanguage].idLang, sizeof(paLanguages[iLanguage].idLang));
721
722 /* updated the size of the output buffer. */
723 *pcbBuf -= cbLeft;
724}
725
726
727/**
728 * Internal function which performs a descriptor read on the cached descriptors.
729 */
730static void ReadCachedConfigDesc(PCVUSBDESCCONFIGEX pCfgDesc, uint8_t *pbBuf, uint32_t *pcbBuf)
731{
732 uint32_t cbLeft = *pcbBuf;
733
734/** @todo See @bugref{2693} */
735 /*
736 * Make a copy of the config descriptor and calculate the wTotalLength field.
737 */
738 VUSBDESCCONFIG CfgDesc;
739 memcpy(&CfgDesc, pCfgDesc, VUSB_DT_CONFIG_MIN_LEN);
740 uint32_t cbTotal = pCfgDesc->Core.bLength;
741 for (unsigned i = 0; i < pCfgDesc->Core.bNumInterfaces; i++)
742 {
743 PCVUSBINTERFACE pIf = &pCfgDesc->paIfs[i];
744 for (uint32_t j = 0; j < pIf->cSettings; j++)
745 {
746 cbTotal += pIf->paSettings[j].cbIAD;
747 cbTotal += pIf->paSettings[j].Core.bLength;
748 cbTotal += pIf->paSettings[j].cbClass;
749 for (unsigned k = 0; k < pIf->paSettings[j].Core.bNumEndpoints; k++)
750 {
751 cbTotal += pIf->paSettings[j].paEndpoints[k].Core.bLength;
752 cbTotal += pIf->paSettings[j].paEndpoints[k].cbSsepc;
753 cbTotal += pIf->paSettings[j].paEndpoints[k].cbClass;
754 }
755 }
756 }
757 CfgDesc.wTotalLength = RT_H2LE_U16(cbTotal);
758
759 /*
760 * Copy the config descriptor
761 */
762 COPY_DATA(pbBuf, cbLeft, &CfgDesc, VUSB_DT_CONFIG_MIN_LEN);
763 COPY_DATA(pbBuf, cbLeft, pCfgDesc->pvMore, pCfgDesc->Core.bLength - VUSB_DT_CONFIG_MIN_LEN);
764
765 /*
766 * Copy out all the interfaces for this configuration
767 */
768 for (unsigned i = 0; i < pCfgDesc->Core.bNumInterfaces; i++)
769 {
770 PCVUSBINTERFACE pIf = &pCfgDesc->paIfs[i];
771 for (uint32_t j = 0; j < pIf->cSettings; j++)
772 {
773 PCVUSBDESCINTERFACEEX pIfDesc = &pIf->paSettings[j];
774
775 COPY_DATA(pbBuf, cbLeft, pIfDesc->pIAD, pIfDesc->cbIAD);
776 COPY_DATA(pbBuf, cbLeft, pIfDesc, VUSB_DT_INTERFACE_MIN_LEN);
777 COPY_DATA(pbBuf, cbLeft, pIfDesc->pvMore, pIfDesc->Core.bLength - VUSB_DT_INTERFACE_MIN_LEN);
778 COPY_DATA(pbBuf, cbLeft, pIfDesc->pvClass, pIfDesc->cbClass);
779
780 /*
781 * Copy out all the endpoints for this interface
782 */
783 for (unsigned k = 0; k < pIfDesc->Core.bNumEndpoints; k++)
784 {
785 VUSBDESCENDPOINT EndPtDesc;
786 memcpy(&EndPtDesc, &pIfDesc->paEndpoints[k], VUSB_DT_ENDPOINT_MIN_LEN);
787 EndPtDesc.wMaxPacketSize = RT_H2LE_U16(EndPtDesc.wMaxPacketSize);
788
789 COPY_DATA(pbBuf, cbLeft, &EndPtDesc, VUSB_DT_ENDPOINT_MIN_LEN);
790 COPY_DATA(pbBuf, cbLeft, pIfDesc->paEndpoints[k].pvMore, EndPtDesc.bLength - VUSB_DT_ENDPOINT_MIN_LEN);
791 COPY_DATA(pbBuf, cbLeft, pIfDesc->paEndpoints[k].pvSsepc, pIfDesc->paEndpoints[k].cbSsepc);
792 COPY_DATA(pbBuf, cbLeft, pIfDesc->paEndpoints[k].pvClass, pIfDesc->paEndpoints[k].cbClass);
793 }
794 }
795 }
796
797 /* updated the size of the output buffer. */
798 *pcbBuf -= cbLeft;
799}
800
801/**
802 * Internal function which performs a descriptor read on the cached descriptors.
803 */
804static void ReadCachedDeviceDesc(PCVUSBDESCDEVICE pDevDesc, uint8_t *pbBuf, uint32_t *pcbBuf)
805{
806 uint32_t cbLeft = *pcbBuf;
807
808 /*
809 * Duplicate the device description and update some fields we keep in cpu type.
810 */
811 Assert(sizeof(VUSBDESCDEVICE) == 18);
812 VUSBDESCDEVICE DevDesc = *pDevDesc;
813 DevDesc.bcdUSB = RT_H2LE_U16(DevDesc.bcdUSB);
814 DevDesc.idVendor = RT_H2LE_U16(DevDesc.idVendor);
815 DevDesc.idProduct = RT_H2LE_U16(DevDesc.idProduct);
816 DevDesc.bcdDevice = RT_H2LE_U16(DevDesc.bcdDevice);
817
818 COPY_DATA(pbBuf, cbLeft, &DevDesc, sizeof(DevDesc));
819 COPY_DATA(pbBuf, cbLeft, pDevDesc + 1, pDevDesc->bLength - sizeof(DevDesc));
820
821 /* updated the size of the output buffer. */
822 *pcbBuf -= cbLeft;
823}
824
825#undef COPY_DATA
826
827/**
828 * Standard device request: GET_DESCRIPTOR
829 * @returns success indicator.
830 * @remark not really used yet as we consider GET_DESCRIPTOR 'safe'.
831 */
832static bool vusbDevStdReqGetDescriptor(PVUSBDEV pDev, int EndPt, PVUSBSETUP pSetup, uint8_t *pbBuf, uint32_t *pcbBuf)
833{
834 if ((pSetup->bmRequestType & VUSB_RECIP_MASK) == VUSB_TO_DEVICE)
835 {
836 switch (pSetup->wValue >> 8)
837 {
838 case VUSB_DT_DEVICE:
839 ReadCachedDeviceDesc(pDev->pDescCache->pDevice, pbBuf, pcbBuf);
840 LogFlow(("vusbDevStdReqGetDescriptor: %s: %u bytes of device descriptors\n", pDev->pUsbIns->pszName, *pcbBuf));
841 return true;
842
843 case VUSB_DT_CONFIG:
844 {
845 unsigned int iIndex = (pSetup->wValue & 0xff);
846 if (iIndex >= pDev->pDescCache->pDevice->bNumConfigurations)
847 {
848 LogFlow(("vusbDevStdReqGetDescriptor: %s: iIndex=%p >= bNumConfigurations=%d !!!\n",
849 pDev->pUsbIns->pszName, iIndex, pDev->pDescCache->pDevice->bNumConfigurations));
850 return false;
851 }
852 ReadCachedConfigDesc(&pDev->pDescCache->paConfigs[iIndex], pbBuf, pcbBuf);
853 LogFlow(("vusbDevStdReqGetDescriptor: %s: %u bytes of config descriptors\n", pDev->pUsbIns->pszName, *pcbBuf));
854 return true;
855 }
856
857 case VUSB_DT_STRING:
858 {
859 if (pSetup->wIndex == 0)
860 {
861 ReadCachedLangIdDesc(pDev->pDescCache->paLanguages, pDev->pDescCache->cLanguages, pbBuf, pcbBuf);
862 LogFlow(("vusbDevStdReqGetDescriptor: %s: %u bytes of language ID (string) descriptors\n", pDev->pUsbIns->pszName, *pcbBuf));
863 return true;
864 }
865 PCPDMUSBDESCCACHESTRING pString;
866 pString = FindCachedString(pDev->pDescCache->paLanguages, pDev->pDescCache->cLanguages,
867 pSetup->wIndex, pSetup->wValue & 0xff);
868 if (pString)
869 {
870 ReadCachedStringDesc(pString, pbBuf, pcbBuf);
871 LogFlow(("vusbDevStdReqGetDescriptor: %s: %u bytes of string descriptors \"%s\"\n",
872 pDev->pUsbIns->pszName, *pcbBuf, pString->psz));
873 return true;
874 }
875 break;
876 }
877
878 default:
879 break;
880 }
881 }
882 Log(("vusb: %s: warning: unknown descriptor: type=%u descidx=%u lang=%u len=%u!!!\n",
883 pDev->pUsbIns->pszName, pSetup->wValue >> 8, pSetup->wValue & 0xff, pSetup->wIndex, pSetup->wLength));
884 return false;
885}
886
887
888/**
889 * Service the standard USB requests.
890 *
891 * Devices may call this from controlmsg() if you want vusb core to handle your standard
892 * request, it's not necessary - you could handle them manually
893 *
894 * @param pDev The device.
895 * @param EndPoint The endpoint.
896 * @param pSetup Pointer to the setup request structure.
897 * @param pvBuf Buffer?
898 * @param pcbBuf ?
899 */
900bool vusbDevStandardRequest(PVUSBDEV pDev, int EndPoint, PVUSBSETUP pSetup, void *pvBuf, uint32_t *pcbBuf)
901{
902 static bool (* const s_apfnStdReq[VUSB_REQ_MAX])(PVUSBDEV, int, PVUSBSETUP, uint8_t *, uint32_t *) =
903 {
904 vusbDevStdReqGetStatus,
905 vusbDevStdReqClearFeature,
906 NULL,
907 vusbDevStdReqSetFeature,
908 NULL,
909 vusbDevStdReqSetAddress,
910 vusbDevStdReqGetDescriptor,
911 NULL,
912 vusbDevStdReqGetConfig,
913 vusbDevStdReqSetConfig,
914 vusbDevStdReqGetInterface,
915 vusbDevStdReqSetInterface,
916 NULL /* for iso */
917 };
918
919 /*
920 * Check that the device is in a valid state.
921 */
922 const VUSBDEVICESTATE enmState = vusbDevGetState(pDev);
923 if (enmState == VUSB_DEVICE_STATE_RESET)
924 {
925 LogRel(("VUSB: %s: standard control message ignored, the device is resetting\n", pDev->pUsbIns->pszName));
926 return false;
927 }
928
929 /*
930 * Do the request if it's one we want to deal with.
931 */
932 if ( pSetup->bRequest >= VUSB_REQ_MAX
933 || !s_apfnStdReq[pSetup->bRequest])
934 {
935 Log(("vusb: warning: standard req not implemented: message %u: val=%u idx=%u len=%u !!!\n",
936 pSetup->bRequest, pSetup->wValue, pSetup->wIndex, pSetup->wLength));
937 return false;
938 }
939
940 return s_apfnStdReq[pSetup->bRequest](pDev, EndPoint, pSetup, (uint8_t *)pvBuf, pcbBuf);
941}
942
943
944/**
945 * Add a device to the address hash
946 */
947static void vusbDevAddressHash(PVUSBDEV pDev)
948{
949 if (pDev->u8Address == VUSB_INVALID_ADDRESS)
950 return;
951 uint8_t u8Hash = vusbHashAddress(pDev->u8Address);
952 pDev->pNextHash = pDev->pHub->pRootHub->apAddrHash[u8Hash];
953 pDev->pHub->pRootHub->apAddrHash[u8Hash] = pDev;
954}
955
956/**
957 * Remove a device from the address hash
958 */
959static void vusbDevAddressUnHash(PVUSBDEV pDev)
960{
961 if (pDev->u8Address == VUSB_INVALID_ADDRESS)
962 return;
963
964 uint8_t u8Hash = vusbHashAddress(pDev->u8Address);
965 pDev->u8Address = VUSB_INVALID_ADDRESS;
966 pDev->u8NewAddress = VUSB_INVALID_ADDRESS;
967
968 RTCritSectEnter(&pDev->pHub->pRootHub->CritSectDevices);
969 PVUSBDEV pCur = pDev->pHub->pRootHub->apAddrHash[u8Hash];
970 if (pCur == pDev)
971 {
972 /* special case, we're at the head */
973 pDev->pHub->pRootHub->apAddrHash[u8Hash] = pDev->pNextHash;
974 pDev->pNextHash = NULL;
975 }
976 else
977 {
978 /* search the list */
979 PVUSBDEV pPrev;
980 for (pPrev = pCur, pCur = pCur->pNextHash;
981 pCur;
982 pPrev = pCur, pCur = pCur->pNextHash)
983 {
984 if (pCur == pDev)
985 {
986 pPrev->pNextHash = pCur->pNextHash;
987 pDev->pNextHash = NULL;
988 break;
989 }
990 }
991 }
992 RTCritSectLeave(&pDev->pHub->pRootHub->CritSectDevices);
993}
994
995/**
996 * Sets the address of a device.
997 *
998 * Called by status_completion() and vusbDevResetWorker().
999 */
1000void vusbDevSetAddress(PVUSBDEV pDev, uint8_t u8Address)
1001{
1002 LogFlow(("vusbDevSetAddress: pDev=%p[%s]/%i u8Address=%#x\n",
1003 pDev, pDev->pUsbIns->pszName, pDev->i16Port, u8Address));
1004
1005 /*
1006 * Check that the device is in a valid state.
1007 */
1008 const VUSBDEVICESTATE enmState = vusbDevGetState(pDev);
1009 VUSBDEV_ASSERT_VALID_STATE(enmState);
1010 if ( enmState == VUSB_DEVICE_STATE_ATTACHED
1011 || enmState == VUSB_DEVICE_STATE_DETACHED)
1012 {
1013 LogFlow(("vusbDevSetAddress: %s: fails because %d < POWERED\n", pDev->pUsbIns->pszName, pDev->enmState));
1014 return;
1015 }
1016 if (enmState == VUSB_DEVICE_STATE_RESET)
1017 {
1018 LogRel(("VUSB: %s: set address ignored, the device is resetting\n", pDev->pUsbIns->pszName));
1019 return;
1020 }
1021
1022 /*
1023 * Ok, get on with it.
1024 */
1025 if (pDev->u8Address == u8Address)
1026 return;
1027
1028 PVUSBROOTHUB pRh = vusbDevGetRh(pDev);
1029 AssertPtrReturnVoid(pRh);
1030 if (pDev->u8Address == VUSB_DEFAULT_ADDRESS)
1031 pRh->pDefaultAddress = NULL;
1032
1033 vusbDevAddressUnHash(pDev);
1034
1035 if (u8Address == VUSB_DEFAULT_ADDRESS)
1036 {
1037 if (pRh->pDefaultAddress != NULL)
1038 {
1039 vusbDevAddressUnHash(pRh->pDefaultAddress);
1040 vusbDevSetStateCmp(pRh->pDefaultAddress, VUSB_DEVICE_STATE_POWERED, VUSB_DEVICE_STATE_DEFAULT);
1041 Log(("2 DEFAULT ADDRS\n"));
1042 }
1043
1044 pRh->pDefaultAddress = pDev;
1045 vusbDevSetState(pDev, VUSB_DEVICE_STATE_DEFAULT);
1046 }
1047 else
1048 vusbDevSetState(pDev, VUSB_DEVICE_STATE_ADDRESS);
1049
1050 pDev->u8Address = u8Address;
1051 vusbDevAddressHash(pDev);
1052
1053 Log(("vusb: %p[%s]/%i: Assigned address %u\n",
1054 pDev, pDev->pUsbIns->pszName, pDev->i16Port, u8Address));
1055}
1056
1057
1058static DECLCALLBACK(int) vusbDevCancelAllUrbsWorker(PVUSBDEV pDev, bool fDetaching)
1059{
1060 /*
1061 * Iterate the URBs and cancel them.
1062 */
1063 PVUSBURBVUSB pVUsbUrb, pVUsbUrbNext;
1064 RTListForEachSafe(&pDev->LstAsyncUrbs, pVUsbUrb, pVUsbUrbNext, VUSBURBVUSBINT, NdLst)
1065 {
1066 PVUSBURB pUrb = pVUsbUrb->pUrb;
1067
1068 Assert(pUrb->pVUsb->pDev == pDev);
1069
1070 LogFlow(("%s: vusbDevCancelAllUrbs: CANCELING URB\n", pUrb->pszDesc));
1071 int rc = vusbUrbCancelWorker(pUrb, CANCELMODE_FAIL);
1072 AssertRC(rc);
1073 }
1074
1075 /*
1076 * Reap any URBs which became ripe during cancel now.
1077 */
1078 RTCritSectEnter(&pDev->CritSectAsyncUrbs);
1079 unsigned cReaped;
1080 do
1081 {
1082 cReaped = 0;
1083 pVUsbUrb = RTListGetFirst(&pDev->LstAsyncUrbs, VUSBURBVUSBINT, NdLst);
1084 while (pVUsbUrb)
1085 {
1086 PVUSBURBVUSB pNext = RTListGetNext(&pDev->LstAsyncUrbs, pVUsbUrb, VUSBURBVUSBINT, NdLst);
1087 PVUSBURB pUrb = pVUsbUrb->pUrb;
1088 Assert(pUrb->pVUsb->pDev == pDev);
1089
1090 PVUSBURB pRipe = NULL;
1091 if (pUrb->enmState == VUSBURBSTATE_REAPED)
1092 pRipe = pUrb;
1093 else if (pUrb->enmState == VUSBURBSTATE_CANCELLED)
1094#ifdef RT_OS_WINDOWS /** @todo Windows doesn't do cancelling, thus this kludge to prevent really bad
1095 * things from happening if we leave a pending URB behinds. */
1096 pRipe = pDev->pUsbIns->pReg->pfnUrbReap(pDev->pUsbIns, fDetaching ? 1500 : 0 /*ms*/);
1097#else
1098 pRipe = pDev->pUsbIns->pReg->pfnUrbReap(pDev->pUsbIns, fDetaching ? 10 : 0 /*ms*/);
1099#endif
1100 else
1101 AssertMsgFailed(("pUrb=%p enmState=%d\n", pUrb, pUrb->enmState));
1102 if (pRipe)
1103 {
1104 if ( pNext
1105 && pRipe == pNext->pUrb)
1106 pNext = RTListGetNext(&pDev->LstAsyncUrbs, pNext, VUSBURBVUSBINT, NdLst);
1107 vusbUrbRipe(pRipe);
1108 cReaped++;
1109 }
1110
1111 pVUsbUrb = pNext;
1112 }
1113 } while (cReaped > 0);
1114
1115 /*
1116 * If we're detaching, we'll have to orphan any leftover URBs.
1117 */
1118 if (fDetaching)
1119 {
1120 RTListForEachSafe(&pDev->LstAsyncUrbs, pVUsbUrb, pVUsbUrbNext, VUSBURBVUSBINT, NdLst)
1121 {
1122 PVUSBURB pUrb = pVUsbUrb->pUrb;
1123 Assert(pUrb->pVUsb->pDev == pDev);
1124
1125 AssertMsgFailed(("%s: Leaking left over URB! state=%d pDev=%p[%s]\n",
1126 pUrb->pszDesc, pUrb->enmState, pDev, pDev->pUsbIns->pszName));
1127 vusbUrbUnlink(pUrb);
1128 /* Unlink isn't enough, because boundary timer and detaching will try to reap it.
1129 * It was tested with MSD & iphone attachment to vSMP guest, if
1130 * it breaks anything, please add comment here, why we should unlink only.
1131 */
1132 pUrb->pVUsb->pfnFree(pUrb);
1133 }
1134 }
1135 RTCritSectLeave(&pDev->CritSectAsyncUrbs);
1136 return VINF_SUCCESS;
1137}
1138
1139/**
1140 * Cancels and completes (with CRC failure) all async URBs pending
1141 * on a device. This is typically done as part of a reset and
1142 * before detaching a device.
1143 *
1144 * @param fDetaching If set, we will unconditionally unlink (and leak)
1145 * any URBs which isn't reaped.
1146 */
1147DECLHIDDEN(void) vusbDevCancelAllUrbs(PVUSBDEV pDev, bool fDetaching)
1148{
1149 int rc = vusbDevIoThreadExecSync(pDev, (PFNRT)vusbDevCancelAllUrbsWorker, 2, pDev, fDetaching);
1150 AssertRC(rc);
1151}
1152
1153
1154static DECLCALLBACK(int) vusbDevUrbIoThread(RTTHREAD hThread, void *pvUser)
1155{
1156 PVUSBDEV pDev = (PVUSBDEV)pvUser;
1157
1158 /* Notify the starter that we are up and running. */
1159 RTThreadUserSignal(hThread);
1160
1161 LogFlowFunc(("Entering work loop\n"));
1162
1163 while (!ASMAtomicReadBool(&pDev->fTerminate))
1164 {
1165 if (vusbDevGetState(pDev) != VUSB_DEVICE_STATE_RESET)
1166 vusbUrbDoReapAsyncDev(pDev, RT_INDEFINITE_WAIT);
1167
1168 /* Process any URBs waiting to be cancelled first. */
1169 int rc = RTReqQueueProcess(pDev->hReqQueueSync, 0); /* Don't wait if there is nothing to do. */
1170 Assert(RT_SUCCESS(rc) || rc == VERR_TIMEOUT);
1171 }
1172
1173 return VINF_SUCCESS;
1174}
1175
1176int vusbDevUrbIoThreadWakeup(PVUSBDEV pDev)
1177{
1178 ASMAtomicXchgBool(&pDev->fWokenUp, true);
1179 return pDev->pUsbIns->pReg->pfnWakeup(pDev->pUsbIns);
1180}
1181
1182/**
1183 * Create the URB I/O thread.
1184 *
1185 * @returns VBox status code.
1186 * @param pDev The VUSB device.
1187 */
1188int vusbDevUrbIoThreadCreate(PVUSBDEV pDev)
1189{
1190 int rc = VINF_SUCCESS;
1191
1192 ASMAtomicXchgBool(&pDev->fTerminate, false);
1193 rc = RTThreadCreateF(&pDev->hUrbIoThread, vusbDevUrbIoThread, pDev, 0, RTTHREADTYPE_IO,
1194 RTTHREADFLAGS_WAITABLE, "USBDevIo-%d", pDev->i16Port);
1195 if (RT_SUCCESS(rc))
1196 {
1197 /* Wait for it to become active. */
1198 rc = RTThreadUserWait(pDev->hUrbIoThread, RT_INDEFINITE_WAIT);
1199 }
1200
1201 return rc;
1202}
1203
1204/**
1205 * Destro the URB I/O thread.
1206 *
1207 * @returns VBox status code.
1208 * @param pDev The VUSB device.
1209 */
1210int vusbDevUrbIoThreadDestroy(PVUSBDEV pDev)
1211{
1212 int rc = VINF_SUCCESS;
1213 int rcThread = VINF_SUCCESS;
1214
1215 ASMAtomicXchgBool(&pDev->fTerminate, true);
1216 vusbDevUrbIoThreadWakeup(pDev);
1217
1218 rc = RTThreadWait(pDev->hUrbIoThread, RT_INDEFINITE_WAIT, &rcThread);
1219 if (RT_SUCCESS(rc))
1220 rc = rcThread;
1221
1222 pDev->hUrbIoThread = NIL_RTTHREAD;
1223
1224 return rc;
1225}
1226
1227
1228/**
1229 * Detaches a device from the hub it's attached to.
1230 *
1231 * @returns VBox status code.
1232 * @param pDev The device to detach.
1233 *
1234 * @remark This can be called in any state but reset.
1235 */
1236int vusbDevDetach(PVUSBDEV pDev)
1237{
1238 LogFlow(("vusbDevDetach: pDev=%p[%s] enmState=%#x\n", pDev, pDev->pUsbIns->pszName, pDev->enmState));
1239 VUSBDEV_ASSERT_VALID_STATE(pDev->enmState);
1240 Assert(pDev->enmState != VUSB_DEVICE_STATE_RESET);
1241
1242 vusbDevCancelAllUrbs(pDev, true);
1243 vusbDevAddressUnHash(pDev);
1244
1245 PVUSBROOTHUB pRh = vusbDevGetRh(pDev);
1246 if (!pRh)
1247 AssertMsgFailedReturn(("Not attached!\n"), VERR_VUSB_DEVICE_NOT_ATTACHED);
1248 if (pRh->pDefaultAddress == pDev)
1249 pRh->pDefaultAddress = NULL;
1250
1251 pDev->pHub->pOps->pfnDetach(pDev->pHub, pDev);
1252 pDev->i16Port = -1;
1253 vusbDevSetState(pDev, VUSB_DEVICE_STATE_DETACHED);
1254 pDev->pHub = NULL;
1255
1256 /* Remove the configuration */
1257 pDev->pCurCfgDesc = NULL;
1258 for (unsigned i = 0; i < RT_ELEMENTS(pDev->aPipes); i++)
1259 vusbDevResetPipeData(&pDev->aPipes[i]);
1260 return VINF_SUCCESS;
1261}
1262
1263
1264/**
1265 * Destroys a device, detaching it from the hub if necessary.
1266 *
1267 * @param pDev The device.
1268 * @thread any.
1269 */
1270void vusbDevDestroy(PVUSBDEV pDev)
1271{
1272 LogFlow(("vusbDevDestroy: pDev=%p[%s] enmState=%d\n", pDev, pDev->pUsbIns->pszName, pDev->enmState));
1273
1274 RTMemFree(pDev->paIfStates);
1275 TMR3TimerDestroy(pDev->pResetTimer);
1276 pDev->pResetTimer = NULL;
1277 for (unsigned i = 0; i < RT_ELEMENTS(pDev->aPipes); i++)
1278 {
1279 Assert(pDev->aPipes[i].pCtrl == NULL);
1280 RTCritSectDelete(&pDev->aPipes[i].CritSectCtrl);
1281 }
1282
1283 /*
1284 * Destroy I/O thread and request queue last because they might still be used
1285 * when cancelling URBs.
1286 */
1287 vusbDevUrbIoThreadDestroy(pDev);
1288
1289 int rc = RTReqQueueDestroy(pDev->hReqQueueSync);
1290 AssertRC(rc);
1291
1292 if (pDev->hSniffer != VUSBSNIFFER_NIL)
1293 VUSBSnifferDestroy(pDev->hSniffer);
1294
1295 vusbUrbPoolDestroy(&pDev->UrbPool);
1296
1297 RTCritSectDelete(&pDev->CritSectAsyncUrbs);
1298 /* Not using vusbDevSetState() deliberately here because it would assert on the state. */
1299 pDev->enmState = VUSB_DEVICE_STATE_DESTROYED;
1300 pDev->pUsbIns->pvVUsbDev2 = NULL;
1301 RTMemFree(pDev);
1302}
1303
1304
1305/* -=-=-=-=-=- VUSBIDEVICE methods -=-=-=-=-=- */
1306
1307
1308/**
1309 * The actual reset has been done, do completion on EMT.
1310 *
1311 * There are several things we have to do now, like set default
1312 * config and address, and cleanup the state of control pipes.
1313 *
1314 * It's possible that the device has a delayed destroy request
1315 * pending when we get here. This can happen for async resetting.
1316 * We deal with it here, since we're now executing on the EMT
1317 * thread and the destruction will be properly serialized now.
1318 *
1319 * @param pDev The device that is being reset.
1320 * @param rc The vusbDevResetWorker return code.
1321 * @param pfnDone The done callback specified by the caller of vusbDevReset().
1322 * @param pvUser The user argument for the callback.
1323 */
1324static void vusbDevResetDone(PVUSBDEV pDev, int rc, PFNVUSBRESETDONE pfnDone, void *pvUser)
1325{
1326 VUSBDEV_ASSERT_VALID_STATE(pDev->enmState);
1327 Assert(pDev->enmState == VUSB_DEVICE_STATE_RESET);
1328
1329 /*
1330 * Do control pipe cleanup regardless of state and result.
1331 */
1332 for (unsigned i = 0; i < VUSB_PIPE_MAX; i++)
1333 if (pDev->aPipes[i].pCtrl)
1334 vusbMsgResetExtraData(pDev->aPipes[i].pCtrl);
1335
1336 /*
1337 * Switch to the default state.
1338 */
1339 vusbDevSetState(pDev, VUSB_DEVICE_STATE_DEFAULT);
1340 pDev->u16Status = 0;
1341 vusbDevDoSelectConfig(pDev, &g_Config0);
1342 if (!vusbDevIsRh(pDev))
1343 vusbDevSetAddress(pDev, VUSB_DEFAULT_ADDRESS);
1344 if (pfnDone)
1345 pfnDone(&pDev->IDevice, rc, pvUser);
1346}
1347
1348
1349/**
1350 * Timer callback for doing reset completion.
1351 *
1352 * @param pUsbIns The USB device instance.
1353 * @param pTimer The timer instance.
1354 * @param pvUser The VUSB device data.
1355 * @thread EMT
1356 */
1357static DECLCALLBACK(void) vusbDevResetDoneTimer(PPDMUSBINS pUsbIns, PTMTIMER pTimer, void *pvUser)
1358{
1359 PVUSBDEV pDev = (PVUSBDEV)pvUser;
1360 PVUSBRESETARGS pArgs = (PVUSBRESETARGS)pDev->pvArgs;
1361 Assert(pDev->pUsbIns == pUsbIns);
1362
1363 AssertPtr(pArgs);
1364
1365 /*
1366 * Reset-done processing and cleanup.
1367 */
1368 pDev->pvArgs = NULL;
1369 vusbDevResetDone(pDev, pArgs->rc, pArgs->pfnDone, pArgs->pvUser);
1370 RTMemFree(pArgs);
1371}
1372
1373
1374/**
1375 * Perform the actual reset.
1376 *
1377 * @thread EMT or a VUSB reset thread.
1378 */
1379static int vusbDevResetWorker(PVUSBDEV pDev, bool fResetOnLinux, bool fUseTimer, PVUSBRESETARGS pArgs)
1380{
1381 int rc = VINF_SUCCESS;
1382 uint64_t u64EndTS = TMTimerGet(pDev->pResetTimer) + TMTimerFromMilli(pDev->pResetTimer, 10);
1383
1384 if (pDev->pUsbIns->pReg->pfnUsbReset)
1385 rc = pDev->pUsbIns->pReg->pfnUsbReset(pDev->pUsbIns, fResetOnLinux);
1386
1387 if (pArgs)
1388 {
1389 pArgs->rc = rc;
1390 rc = VINF_SUCCESS;
1391 }
1392
1393 if (fUseTimer)
1394 {
1395 /*
1396 * We use a timer to communicate the result back to EMT.
1397 * This avoids suspend + poweroff issues, and it should give
1398 * us more accurate scheduling than making this thread sleep.
1399 */
1400 int rc2 = TMTimerSet(pDev->pResetTimer, u64EndTS);
1401 AssertReleaseRC(rc2);
1402 }
1403
1404 LogFlow(("vusbDevResetWorker: %s: returns %Rrc\n", pDev->pUsbIns->pszName, rc));
1405 return rc;
1406}
1407
1408
1409/**
1410 * Resets a device.
1411 *
1412 * Since a device reset shall take at least 10ms from the guest point of view,
1413 * it must be performed asynchronously. We create a thread which performs this
1414 * operation and ensures it will take at least 10ms.
1415 *
1416 * At times - like init - a synchronous reset is required, this can be done
1417 * by passing NULL for pfnDone.
1418 *
1419 * While the device is being reset it is in the VUSB_DEVICE_STATE_RESET state.
1420 * On completion it will be in the VUSB_DEVICE_STATE_DEFAULT state if successful,
1421 * or in the VUSB_DEVICE_STATE_DETACHED state if the rest failed.
1422 *
1423 * @returns VBox status code.
1424 *
1425 * @param pDev Pointer to the VUSB device interface.
1426 * @param fResetOnLinux Whether it's safe to reset the device(s) on a linux
1427 * host system. See discussion of logical reconnects elsewhere.
1428 * @param pfnDone Pointer to the completion routine. If NULL a synchronous
1429 * reset is preformed not respecting the 10ms.
1430 * @param pVM Pointer to the VM handle for performing the done function
1431 * on the EMT thread.
1432 * @thread EMT
1433 */
1434static DECLCALLBACK(int) vusbIDeviceReset(PVUSBIDEVICE pDevice, bool fResetOnLinux, PFNVUSBRESETDONE pfnDone, void *pvUser, PVM pVM)
1435{
1436 PVUSBDEV pDev = (PVUSBDEV)pDevice;
1437 Assert(!pfnDone || pVM);
1438 LogFlow(("vusb: reset: [%s]/%i\n", pDev->pUsbIns->pszName, pDev->i16Port));
1439
1440 /*
1441 * Only one reset operation at a time.
1442 */
1443 const VUSBDEVICESTATE enmStateOld = vusbDevSetState(pDev, VUSB_DEVICE_STATE_RESET);
1444 if (enmStateOld == VUSB_DEVICE_STATE_RESET)
1445 {
1446 LogRel(("VUSB: %s: reset request is ignored, the device is already resetting!\n", pDev->pUsbIns->pszName));
1447 return VERR_VUSB_DEVICE_IS_RESETTING;
1448 }
1449
1450 /*
1451 * First, cancel all async URBs.
1452 */
1453 vusbDevCancelAllUrbs(pDev, false);
1454
1455 /* Async or sync? */
1456 if (pfnDone)
1457 {
1458 /*
1459 * Async fashion.
1460 */
1461 PVUSBRESETARGS pArgs = (PVUSBRESETARGS)RTMemTmpAlloc(sizeof(*pArgs));
1462 if (pArgs)
1463 {
1464 pArgs->pDev = pDev;
1465 pArgs->pfnDone = pfnDone;
1466 pArgs->pvUser = pvUser;
1467 pArgs->rc = VINF_SUCCESS;
1468 AssertPtrNull(pDev->pvArgs);
1469 pDev->pvArgs = pArgs;
1470 int rc = vusbDevIoThreadExec(pDev, 0 /* fFlags */, (PFNRT)vusbDevResetWorker, 4, pDev, fResetOnLinux, true, pArgs);
1471 if (RT_SUCCESS(rc))
1472 return rc;
1473
1474 RTMemTmpFree(pArgs);
1475 }
1476 /* fall back to sync on failure */
1477 }
1478
1479 /*
1480 * Sync fashion.
1481 */
1482 int rc = vusbDevResetWorker(pDev, fResetOnLinux, false, NULL);
1483 vusbDevResetDone(pDev, rc, pfnDone, pvUser);
1484 return rc;
1485}
1486
1487
1488/**
1489 * Powers on the device.
1490 *
1491 * @returns VBox status code.
1492 * @param pInterface Pointer to the device interface structure.
1493 */
1494static DECLCALLBACK(int) vusbIDevicePowerOn(PVUSBIDEVICE pInterface)
1495{
1496 PVUSBDEV pDev = (PVUSBDEV)pInterface;
1497 LogFlow(("vusbDevPowerOn: pDev=%p[%s]\n", pDev, pDev->pUsbIns->pszName));
1498
1499 /*
1500 * Check that the device is in a valid state.
1501 */
1502 const VUSBDEVICESTATE enmState = vusbDevGetState(pDev);
1503 if (enmState == VUSB_DEVICE_STATE_DETACHED)
1504 {
1505 Log(("vusb: warning: attempt to power on detached device %p[%s]\n", pDev, pDev->pUsbIns->pszName));
1506 return VERR_VUSB_DEVICE_NOT_ATTACHED;
1507 }
1508 if (enmState == VUSB_DEVICE_STATE_RESET)
1509 {
1510 LogRel(("VUSB: %s: power on ignored, the device is resetting!\n", pDev->pUsbIns->pszName));
1511 return VERR_VUSB_DEVICE_IS_RESETTING;
1512 }
1513
1514 /*
1515 * Do the job.
1516 */
1517 if (enmState == VUSB_DEVICE_STATE_ATTACHED)
1518 vusbDevSetState(pDev, VUSB_DEVICE_STATE_POWERED);
1519
1520 return VINF_SUCCESS;
1521}
1522
1523
1524/**
1525 * Powers off the device.
1526 *
1527 * @returns VBox status code.
1528 * @param pInterface Pointer to the device interface structure.
1529 */
1530static DECLCALLBACK(int) vusbIDevicePowerOff(PVUSBIDEVICE pInterface)
1531{
1532 PVUSBDEV pDev = (PVUSBDEV)pInterface;
1533 LogFlow(("vusbDevPowerOff: pDev=%p[%s]\n", pDev, pDev->pUsbIns->pszName));
1534
1535 /*
1536 * Check that the device is in a valid state.
1537 */
1538 const VUSBDEVICESTATE enmState = vusbDevGetState(pDev);
1539 if (enmState == VUSB_DEVICE_STATE_DETACHED)
1540 {
1541 Log(("vusb: warning: attempt to power off detached device %p[%s]\n", pDev, pDev->pUsbIns->pszName));
1542 return VERR_VUSB_DEVICE_NOT_ATTACHED;
1543 }
1544 if (enmState == VUSB_DEVICE_STATE_RESET)
1545 {
1546 LogRel(("VUSB: %s: power off ignored, the device is resetting!\n", pDev->pUsbIns->pszName));
1547 return VERR_VUSB_DEVICE_IS_RESETTING;
1548 }
1549
1550 /*
1551 * If it's a root hub, we will have to cancel all URBs and reap them.
1552 */
1553 if (vusbDevIsRh(pDev))
1554 {
1555 PVUSBROOTHUB pRh = (PVUSBROOTHUB)pDev;
1556 VUSBIRhCancelAllUrbs(&pRh->IRhConnector);
1557 VUSBIRhReapAsyncUrbs(&pRh->IRhConnector, pInterface, 0);
1558 }
1559
1560 vusbDevSetState(pDev, VUSB_DEVICE_STATE_ATTACHED);
1561 return VINF_SUCCESS;
1562}
1563
1564
1565/**
1566 * Get the state of the device.
1567 *
1568 * @returns Device state.
1569 * @param pInterface Pointer to the device interface structure.
1570 */
1571static DECLCALLBACK(VUSBDEVICESTATE) vusbIDeviceGetState(PVUSBIDEVICE pInterface)
1572{
1573 return vusbDevGetState((PVUSBDEV)pInterface);
1574}
1575
1576
1577/**
1578 * @interface_method_impl{VUSBIDEVICE,pfnIsSavedStateSupported}
1579 */
1580static DECLCALLBACK(bool) vusbIDeviceIsSavedStateSupported(PVUSBIDEVICE pInterface)
1581{
1582 PVUSBDEV pDev = (PVUSBDEV)pInterface;
1583 bool fSavedStateSupported = RT_BOOL(pDev->pUsbIns->pReg->fFlags & PDM_USBREG_SAVED_STATE_SUPPORTED);
1584
1585 LogFlowFunc(("pInterface=%p\n", pInterface));
1586
1587 LogFlowFunc(("returns %RTbool\n", fSavedStateSupported));
1588 return fSavedStateSupported;
1589}
1590
1591
1592/**
1593 * @interface_method_impl{VUSBIDEVICE,pfnGetState}
1594 */
1595static DECLCALLBACK(VUSBSPEED) vusbIDeviceGetSpeed(PVUSBIDEVICE pInterface)
1596{
1597 PVUSBDEV pDev = (PVUSBDEV)pInterface;
1598 VUSBSPEED enmSpeed = pDev->pUsbIns->enmSpeed;
1599
1600 LogFlowFunc(("pInterface=%p, returns %u\n", pInterface, enmSpeed));
1601 return enmSpeed;
1602}
1603
1604
1605/**
1606 * The maximum number of interfaces the device can have in all of it's configuration.
1607 *
1608 * @returns Number of interfaces.
1609 * @param pDev The device.
1610 */
1611size_t vusbDevMaxInterfaces(PVUSBDEV pDev)
1612{
1613 uint8_t cMax = 0;
1614 unsigned i = pDev->pDescCache->pDevice->bNumConfigurations;
1615 while (i-- > 0)
1616 {
1617 if (pDev->pDescCache->paConfigs[i].Core.bNumInterfaces > cMax)
1618 cMax = pDev->pDescCache->paConfigs[i].Core.bNumInterfaces;
1619 }
1620
1621 return cMax;
1622}
1623
1624
1625/**
1626 * Executes a given function on the I/O thread.
1627 *
1628 * @returns IPRT status code.
1629 * @param pDev The USB device instance data.
1630 * @param fFlags Combination of VUSB_DEV_IO_THREAD_EXEC_FLAGS_*
1631 * @param pfnFunction The function to execute.
1632 * @param cArgs Number of arguments to the function.
1633 * @param Args The parameter list.
1634 *
1635 * @remarks See remarks on RTReqQueueCallV
1636 */
1637DECLHIDDEN(int) vusbDevIoThreadExecV(PVUSBDEV pDev, uint32_t fFlags, PFNRT pfnFunction, unsigned cArgs, va_list Args)
1638{
1639 int rc = VINF_SUCCESS;
1640 PRTREQ hReq = NULL;
1641
1642 Assert(pDev->hUrbIoThread != NIL_RTTHREAD);
1643 if (RT_LIKELY(pDev->hUrbIoThread != NIL_RTTHREAD))
1644 {
1645 uint32_t fReqFlags = RTREQFLAGS_IPRT_STATUS;
1646
1647 if (!(fFlags & VUSB_DEV_IO_THREAD_EXEC_FLAGS_SYNC))
1648 fReqFlags |= RTREQFLAGS_NO_WAIT;
1649
1650 rc = RTReqQueueCallV(pDev->hReqQueueSync, &hReq, 0 /* cMillies */, fReqFlags, pfnFunction, cArgs, Args);
1651 Assert(RT_SUCCESS(rc) || rc == VERR_TIMEOUT);
1652
1653 /* In case we are called on the I/O thread just process the request. */
1654 if ( pDev->hUrbIoThread == RTThreadSelf()
1655 && (fFlags & VUSB_DEV_IO_THREAD_EXEC_FLAGS_SYNC))
1656 {
1657 int rc2 = RTReqQueueProcess(pDev->hReqQueueSync, 0);
1658 Assert(RT_SUCCESS(rc2) || rc2 == VERR_TIMEOUT);
1659 }
1660 else
1661 vusbDevUrbIoThreadWakeup(pDev);
1662
1663 if ( rc == VERR_TIMEOUT
1664 && (fFlags & VUSB_DEV_IO_THREAD_EXEC_FLAGS_SYNC))
1665 {
1666 rc = RTReqWait(hReq, RT_INDEFINITE_WAIT);
1667 AssertRC(rc);
1668 }
1669 RTReqRelease(hReq);
1670 }
1671 else
1672 rc = VERR_INVALID_STATE;
1673
1674 return rc;
1675}
1676
1677
1678/**
1679 * Executes a given function on the I/O thread.
1680 *
1681 * @returns IPRT status code.
1682 * @param pDev The USB device instance data.
1683 * @param fFlags Combination of VUSB_DEV_IO_THREAD_EXEC_FLAGS_*
1684 * @param pfnFunction The function to execute.
1685 * @param cArgs Number of arguments to the function.
1686 * @param ... The parameter list.
1687 *
1688 * @remarks See remarks on RTReqQueueCallV
1689 */
1690DECLHIDDEN(int) vusbDevIoThreadExec(PVUSBDEV pDev, uint32_t fFlags, PFNRT pfnFunction, unsigned cArgs, ...)
1691{
1692 int rc = VINF_SUCCESS;
1693 va_list va;
1694
1695 va_start(va, cArgs);
1696 rc = vusbDevIoThreadExecV(pDev, fFlags, pfnFunction, cArgs, va);
1697 va_end(va);
1698 return rc;
1699}
1700
1701
1702/**
1703 * Executes a given function synchronously on the I/O thread waiting for it to complete.
1704 *
1705 * @returns IPRT status code.
1706 * @param pDev The USB device instance data
1707 * @param pfnFunction The function to execute.
1708 * @param cArgs Number of arguments to the function.
1709 * @param ... The parameter list.
1710 *
1711 * @remarks See remarks on RTReqQueueCallV
1712 */
1713DECLHIDDEN(int) vusbDevIoThreadExecSync(PVUSBDEV pDev, PFNRT pfnFunction, unsigned cArgs, ...)
1714{
1715 int rc = VINF_SUCCESS;
1716 va_list va;
1717
1718 va_start(va, cArgs);
1719 rc = vusbDevIoThreadExecV(pDev, VUSB_DEV_IO_THREAD_EXEC_FLAGS_SYNC, pfnFunction, cArgs, va);
1720 va_end(va);
1721 return rc;
1722}
1723
1724
1725static DECLCALLBACK(int) vusbDevGetDescriptorCacheWorker(PPDMUSBINS pUsbIns, PCPDMUSBDESCCACHE *ppDescCache)
1726{
1727 *ppDescCache = pUsbIns->pReg->pfnUsbGetDescriptorCache(pUsbIns);
1728 return VINF_SUCCESS;
1729}
1730
1731/**
1732 * Initialize a new VUSB device.
1733 *
1734 * @returns VBox status code.
1735 * @param pDev The VUSB device to initialize.
1736 * @param pUsbIns Pointer to the PDM USB Device instance.
1737 */
1738int vusbDevInit(PVUSBDEV pDev, PPDMUSBINS pUsbIns, const char *pszCaptureFilename)
1739{
1740 /*
1741 * Initialize the device data members.
1742 * (All that are Non-Zero at least.)
1743 */
1744 Assert(!pDev->IDevice.pfnReset);
1745 Assert(!pDev->IDevice.pfnPowerOn);
1746 Assert(!pDev->IDevice.pfnPowerOff);
1747 Assert(!pDev->IDevice.pfnGetState);
1748 Assert(!pDev->IDevice.pfnIsSavedStateSupported);
1749
1750 pDev->IDevice.pfnReset = vusbIDeviceReset;
1751 pDev->IDevice.pfnPowerOn = vusbIDevicePowerOn;
1752 pDev->IDevice.pfnPowerOff = vusbIDevicePowerOff;
1753 pDev->IDevice.pfnGetState = vusbIDeviceGetState;
1754 pDev->IDevice.pfnIsSavedStateSupported = vusbIDeviceIsSavedStateSupported;
1755 pDev->IDevice.pfnGetSpeed = vusbIDeviceGetSpeed;
1756 pDev->pUsbIns = pUsbIns;
1757 pDev->pNext = NULL;
1758 pDev->pNextHash = NULL;
1759 pDev->pHub = NULL;
1760 pDev->enmState = VUSB_DEVICE_STATE_DETACHED;
1761 pDev->cRefs = 1;
1762 pDev->u8Address = VUSB_INVALID_ADDRESS;
1763 pDev->u8NewAddress = VUSB_INVALID_ADDRESS;
1764 pDev->i16Port = -1;
1765 pDev->u16Status = 0;
1766 pDev->pDescCache = NULL;
1767 pDev->pCurCfgDesc = NULL;
1768 pDev->paIfStates = NULL;
1769 RTListInit(&pDev->LstAsyncUrbs);
1770 memset(&pDev->aPipes[0], 0, sizeof(pDev->aPipes));
1771 for (unsigned i = 0; i < RT_ELEMENTS(pDev->aPipes); i++)
1772 {
1773 int rc = RTCritSectInit(&pDev->aPipes[i].CritSectCtrl);
1774 AssertRCReturn(rc, rc);
1775 }
1776 pDev->pResetTimer = NULL;
1777 pDev->hSniffer = VUSBSNIFFER_NIL;
1778
1779 int rc = RTCritSectInit(&pDev->CritSectAsyncUrbs);
1780 AssertRCReturn(rc, rc);
1781
1782 /* Create the URB pool. */
1783 rc = vusbUrbPoolInit(&pDev->UrbPool);
1784 AssertRCReturn(rc, rc);
1785
1786 /* Setup request queue executing synchronous tasks on the I/O thread. */
1787 rc = RTReqQueueCreate(&pDev->hReqQueueSync);
1788 AssertRCReturn(rc, rc);
1789
1790 /* Create I/O thread. */
1791 rc = vusbDevUrbIoThreadCreate(pDev);
1792 AssertRCReturn(rc, rc);
1793
1794 /*
1795 * Create the reset timer.
1796 */
1797 rc = PDMUsbHlpTMTimerCreate(pDev->pUsbIns, TMCLOCK_VIRTUAL, vusbDevResetDoneTimer, pDev, 0 /*fFlags*/,
1798 "USB Device Reset Timer", &pDev->pResetTimer);
1799 AssertRCReturn(rc, rc);
1800
1801 if (pszCaptureFilename)
1802 {
1803 rc = VUSBSnifferCreate(&pDev->hSniffer, 0, pszCaptureFilename, NULL, NULL);
1804 AssertRCReturn(rc, rc);
1805 }
1806
1807 /*
1808 * Get the descriptor cache from the device. (shall cannot fail)
1809 */
1810 rc = vusbDevIoThreadExecSync(pDev, (PFNRT)vusbDevGetDescriptorCacheWorker, 2, pUsbIns, &pDev->pDescCache);
1811 AssertRC(rc);
1812 AssertPtr(pDev->pDescCache);
1813#ifdef VBOX_STRICT
1814 if (pDev->pDescCache->fUseCachedStringsDescriptors)
1815 {
1816 int32_t iPrevId = -1;
1817 for (unsigned iLang = 0; iLang < pDev->pDescCache->cLanguages; iLang++)
1818 {
1819 Assert((int32_t)pDev->pDescCache->paLanguages[iLang].idLang > iPrevId);
1820 iPrevId = pDev->pDescCache->paLanguages[iLang].idLang;
1821
1822 int32_t idxPrevStr = -1;
1823 PCPDMUSBDESCCACHESTRING paStrings = pDev->pDescCache->paLanguages[iLang].paStrings;
1824 unsigned cStrings = pDev->pDescCache->paLanguages[iLang].cStrings;
1825 for (unsigned iStr = 0; iStr < cStrings; iStr++)
1826 {
1827 Assert((int32_t)paStrings[iStr].idx > idxPrevStr);
1828 idxPrevStr = paStrings[iStr].idx;
1829 size_t cch = strlen(paStrings[iStr].psz);
1830 Assert(cch <= 127);
1831 }
1832 }
1833 }
1834#endif
1835
1836 /*
1837 * Allocate memory for the interface states.
1838 */
1839 size_t cbIface = vusbDevMaxInterfaces(pDev) * sizeof(*pDev->paIfStates);
1840 pDev->paIfStates = (PVUSBINTERFACESTATE)RTMemAllocZ(cbIface);
1841 AssertMsgReturn(pDev->paIfStates, ("RTMemAllocZ(%d) failed\n", cbIface), VERR_NO_MEMORY);
1842
1843 return VINF_SUCCESS;
1844}
1845
1846/*
1847 * Local Variables:
1848 * mode: c
1849 * c-file-style: "bsd"
1850 * c-basic-offset: 4
1851 * tab-width: 4
1852 * indent-tabs-mode: s
1853 * End:
1854 */
1855
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