VirtualBox

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

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

Devices: warnings

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