VirtualBox

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

Last change on this file since 69901 was 69500, checked in by vboxsync, 7 years ago

*: scm --update-copyright-year

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