VirtualBox

source: vbox/trunk/src/VBox/Devices/Storage/UsbMsd.cpp@ 74441

Last change on this file since 74441 was 73097, checked in by vboxsync, 6 years ago

*: Made RT_UOFFSETOF, RT_OFFSETOF, RT_UOFFSETOF_ADD and RT_OFFSETOF_ADD work like builtin_offsetof() and require compile time resolvable requests, adding RT_UOFFSETOF_DYN for the dynamic questions that can only be answered at runtime.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 80.7 KB
Line 
1/* $Id: UsbMsd.cpp 73097 2018-07-12 21:06:33Z vboxsync $ */
2/** @file
3 * UsbMSD - USB Mass Storage Device Emulation.
4 */
5
6/*
7 * Copyright (C) 2007-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_USB_MSD
23#include <VBox/vmm/pdmusb.h>
24#include <VBox/vmm/pdmstorageifs.h>
25#include <VBox/log.h>
26#include <VBox/err.h>
27#include <VBox/scsi.h>
28#include <iprt/assert.h>
29#include <iprt/critsect.h>
30#include <iprt/mem.h>
31#include <iprt/semaphore.h>
32#include <iprt/string.h>
33#include <iprt/uuid.h>
34#include "VBoxDD.h"
35
36
37/*********************************************************************************************************************************
38* Defined Constants And Macros *
39*********************************************************************************************************************************/
40/** @name USB MSD string IDs
41 * @{ */
42#define USBMSD_STR_ID_MANUFACTURER 1
43#define USBMSD_STR_ID_PRODUCT_HD 2
44#define USBMSD_STR_ID_PRODUCT_CDROM 3
45/** @} */
46
47/** @name USB MSD vendor and product IDs
48 * @{ */
49#define VBOX_USB_VENDOR 0x80EE
50#define USBMSD_PID_HD 0x0030
51#define USBMSD_PID_CD 0x0031
52/** @} */
53
54/** Saved state version. */
55#define USB_MSD_SAVED_STATE_VERSION 2
56/** Saved state vesion before the cleanup. */
57#define USB_MSD_SAVED_STATE_VERSION_PRE_CLEANUP 1
58
59
60/*********************************************************************************************************************************
61* Structures and Typedefs *
62*********************************************************************************************************************************/
63
64/**
65 * USB MSD Command Block Wrapper or CBW. The command block
66 * itself (CBWCB) contains protocol-specific data (here SCSI).
67 */
68#pragma pack(1)
69typedef struct USBCBW
70{
71 uint32_t dCBWSignature;
72#define USBCBW_SIGNATURE UINT32_C(0x43425355)
73 uint32_t dCBWTag;
74 uint32_t dCBWDataTransferLength;
75 uint8_t bmCBWFlags;
76#define USBCBW_DIR_MASK RT_BIT(7)
77#define USBCBW_DIR_OUT 0
78#define USBCBW_DIR_IN RT_BIT(7)
79 uint8_t bCBWLun;
80 uint8_t bCBWCBLength;
81 uint8_t CBWCB[16];
82} USBCBW;
83#pragma pack()
84AssertCompileSize(USBCBW, 31);
85/** Pointer to a Command Block Wrapper. */
86typedef USBCBW *PUSBCBW;
87/** Pointer to a const Command Block Wrapper. */
88typedef const USBCBW *PCUSBCBW;
89
90/**
91 * USB MSD Command Status Wrapper or CSW.
92 */
93#pragma pack(1)
94typedef struct USBCSW
95{
96 uint32_t dCSWSignature;
97#define USBCSW_SIGNATURE UINT32_C(0x53425355)
98 uint32_t dCSWTag;
99 uint32_t dCSWDataResidue;
100#define USBCSW_STATUS_OK UINT8_C(0)
101#define USBCSW_STATUS_FAILED UINT8_C(1)
102#define USBCSW_STATUS_PHASE_ERROR UINT8_C(2)
103 uint8_t bCSWStatus;
104} USBCSW;
105#pragma pack()
106AssertCompileSize(USBCSW, 13);
107/** Pointer to a Command Status Wrapper. */
108typedef USBCSW *PUSBCSW;
109/** Pointer to a const Command Status Wrapper. */
110typedef const USBCSW *PCUSBCSW;
111
112
113/**
114 * The USB MSD request state.
115 */
116typedef enum USBMSDREQSTATE
117{
118 /** Invalid status. */
119 USBMSDREQSTATE_INVALID = 0,
120 /** Ready to receive a new SCSI command. */
121 USBMSDREQSTATE_READY,
122 /** Waiting for the host to supply data. */
123 USBMSDREQSTATE_DATA_FROM_HOST,
124 /** The SCSI request is being executed by the driver. */
125 USBMSDREQSTATE_EXECUTING,
126 /** Have (more) data for the host. */
127 USBMSDREQSTATE_DATA_TO_HOST,
128 /** Waiting to supply status information to the host. */
129 USBMSDREQSTATE_STATUS,
130 /** Destroy the request upon completion.
131 * This is set when the SCSI request doesn't complete before for the device or
132 * mass storage reset operation times out. USBMSD::pReq will be set to NULL
133 * and the only reference to this request will be with DrvSCSI. */
134 USBMSDREQSTATE_DESTROY_ON_COMPLETION,
135 /** The end of the valid states. */
136 USBMSDREQSTATE_END,
137 /** 32bit blow up hack. */
138 USBMSDREQSTATE_32BIT_HACK = 0x7fffffff
139} USBMSDREQSTATE;
140
141
142/**
143 * A pending USB MSD request.
144 */
145typedef struct USBMSDREQ
146{
147 /** The state of the request. */
148 USBMSDREQSTATE enmState;
149 /** The I/O requesthandle .*/
150 PDMMEDIAEXIOREQ hIoReq;
151 /** The size of the data buffer. */
152 uint32_t cbBuf;
153 /** Pointer to the data buffer. */
154 uint8_t *pbBuf;
155 /** Current buffer offset. */
156 uint32_t offBuf;
157 /** The current Cbw when we're in the pending state. */
158 USBCBW Cbw;
159 /** The status of a completed SCSI request. */
160 uint8_t iScsiReqStatus;
161} USBMSDREQ;
162/** Pointer to a USB MSD request. */
163typedef USBMSDREQ *PUSBMSDREQ;
164
165
166/**
167 * Endpoint status data.
168 */
169typedef struct USBMSDEP
170{
171 bool fHalted;
172} USBMSDEP;
173/** Pointer to the endpoint status. */
174typedef USBMSDEP *PUSBMSDEP;
175
176
177/**
178 * A URB queue.
179 */
180typedef struct USBMSDURBQUEUE
181{
182 /** The head pointer. */
183 PVUSBURB pHead;
184 /** Where to insert the next entry. */
185 PVUSBURB *ppTail;
186} USBMSDURBQUEUE;
187/** Pointer to a URB queue. */
188typedef USBMSDURBQUEUE *PUSBMSDURBQUEUE;
189/** Pointer to a const URB queue. */
190typedef USBMSDURBQUEUE const *PCUSBMSDURBQUEUE;
191
192
193/**
194 * The USB MSD instance data.
195 */
196typedef struct USBMSD
197{
198 /** Pointer back to the PDM USB Device instance structure. */
199 PPDMUSBINS pUsbIns;
200 /** Critical section protecting the device state. */
201 RTCRITSECT CritSect;
202
203 /** The current configuration.
204 * (0 - default, 1 - the only, i.e configured.) */
205 uint8_t bConfigurationValue;
206 /** Endpoint 0 is the default control pipe, 1 is the host->dev bulk pipe and 2
207 * is the dev->host one. */
208 USBMSDEP aEps[3];
209 /** The current request. */
210 PUSBMSDREQ pReq;
211
212 /** Pending to-host queue.
213 * The URBs waiting here are pending the completion of the current request and
214 * data or status to become available.
215 */
216 USBMSDURBQUEUE ToHostQueue;
217
218 /** Done queue
219 * The URBs stashed here are waiting to be reaped. */
220 USBMSDURBQUEUE DoneQueue;
221 /** Signalled when adding an URB to the done queue and fHaveDoneQueueWaiter
222 * is set. */
223 RTSEMEVENT hEvtDoneQueue;
224 /** Someone is waiting on the done queue. */
225 bool fHaveDoneQueueWaiter;
226
227 /** Whether to signal the reset semaphore when the current request completes. */
228 bool fSignalResetSem;
229 /** Semaphore usbMsdUsbReset waits on when a request is executing at reset
230 * time. Only signalled when fSignalResetSem is set. */
231 RTSEMEVENTMULTI hEvtReset;
232 /** The reset URB.
233 * This is waiting for SCSI request completion before finishing the reset. */
234 PVUSBURB pResetUrb;
235 /** Indicates that PDMUsbHlpAsyncNotificationCompleted should be called when
236 * the MSD is entering the idle state. */
237 volatile bool fSignalIdle;
238
239 /** Indicates that this device is a CD-ROM. */
240 bool fIsCdrom;
241
242 /**
243 * LUN\#0 data.
244 */
245 struct
246 {
247 /** The base interface for LUN\#0. */
248 PDMIBASE IBase;
249 /** The media port interface fo LUN\#0. */
250 PDMIMEDIAPORT IMediaPort;
251 /** The extended media port interface for LUN\#0 */
252 PDMIMEDIAEXPORT IMediaExPort;
253
254 /** The base interface for the SCSI driver connected to LUN\#0. */
255 PPDMIBASE pIBase;
256 /** The media interface for th SCSI drver conected to LUN\#0. */
257 PPDMIMEDIA pIMedia;
258 /** The extended media inerface for the SCSI driver connected to LUN\#0. */
259 PPDMIMEDIAEX pIMediaEx;
260 } Lun0;
261
262} USBMSD;
263/** Pointer to the USB MSD instance data. */
264typedef USBMSD *PUSBMSD;
265
266
267/*********************************************************************************************************************************
268* Global Variables *
269*********************************************************************************************************************************/
270static const PDMUSBDESCCACHESTRING g_aUsbMsdStrings_en_US[] =
271{
272 { USBMSD_STR_ID_MANUFACTURER, "VirtualBox" },
273 { USBMSD_STR_ID_PRODUCT_HD, "USB Harddisk" },
274 { USBMSD_STR_ID_PRODUCT_CDROM, "USB CD-ROM" }
275};
276
277static const PDMUSBDESCCACHELANG g_aUsbMsdLanguages[] =
278{
279 { 0x0409, RT_ELEMENTS(g_aUsbMsdStrings_en_US), g_aUsbMsdStrings_en_US }
280};
281
282static const VUSBDESCENDPOINTEX g_aUsbMsdEndpointDescsFS[2] =
283{
284 {
285 {
286 /* .bLength = */ sizeof(VUSBDESCENDPOINT),
287 /* .bDescriptorType = */ VUSB_DT_ENDPOINT,
288 /* .bEndpointAddress = */ 0x81 /* ep=1, in */,
289 /* .bmAttributes = */ 2 /* bulk */,
290 /* .wMaxPacketSize = */ 64 /* maximum possible */,
291 /* .bInterval = */ 0 /* not applicable for bulk EP */
292 },
293 /* .pvMore = */ NULL,
294 /* .pvClass = */ NULL,
295 /* .cbClass = */ 0,
296 /* .pvSsepc = */ NULL,
297 /* .cbSsepc = */ 0
298 },
299 {
300 {
301 /* .bLength = */ sizeof(VUSBDESCENDPOINT),
302 /* .bDescriptorType = */ VUSB_DT_ENDPOINT,
303 /* .bEndpointAddress = */ 0x02 /* ep=2, out */,
304 /* .bmAttributes = */ 2 /* bulk */,
305 /* .wMaxPacketSize = */ 64 /* maximum possible */,
306 /* .bInterval = */ 0 /* not applicable for bulk EP */
307 },
308 /* .pvMore = */ NULL,
309 /* .pvClass = */ NULL,
310 /* .cbClass = */ 0,
311 /* .pvSsepc = */ NULL,
312 /* .cbSsepc = */ 0
313 }
314};
315
316static const VUSBDESCENDPOINTEX g_aUsbMsdEndpointDescsHS[2] =
317{
318 {
319 {
320 /* .bLength = */ sizeof(VUSBDESCENDPOINT),
321 /* .bDescriptorType = */ VUSB_DT_ENDPOINT,
322 /* .bEndpointAddress = */ 0x81 /* ep=1, in */,
323 /* .bmAttributes = */ 2 /* bulk */,
324 /* .wMaxPacketSize = */ 512 /* HS bulk packet size */,
325 /* .bInterval = */ 0 /* no NAKs */
326 },
327 /* .pvMore = */ NULL,
328 /* .pvClass = */ NULL,
329 /* .cbClass = */ 0,
330 /* .pvSsepc = */ NULL,
331 /* .cbSsepc = */ 0
332 },
333 {
334 {
335 /* .bLength = */ sizeof(VUSBDESCENDPOINT),
336 /* .bDescriptorType = */ VUSB_DT_ENDPOINT,
337 /* .bEndpointAddress = */ 0x02 /* ep=2, out */,
338 /* .bmAttributes = */ 2 /* bulk */,
339 /* .wMaxPacketSize = */ 512 /* HS bulk packet size */,
340 /* .bInterval = */ 0 /* no NAKs */
341 },
342 /* .pvMore = */ NULL,
343 /* .pvClass = */ NULL,
344 /* .cbClass = */ 0,
345 /* .pvSsepc = */ NULL,
346 /* .cbSsepc = */ 0
347 }
348};
349
350static const VUSBDESCSSEPCOMPANION g_aUsbMsdEpCompanionSS =
351{
352 /* .bLength = */ sizeof(VUSBDESCSSEPCOMPANION),
353 /* .bDescriptorType = */ VUSB_DT_SS_ENDPOINT_COMPANION,
354 /* .bMaxBurst = */ 15 /* we can burst all the way */,
355 /* .bmAttributes = */ 0 /* no streams */,
356 /* .wBytesPerInterval = */ 0 /* not a periodic endpoint */
357};
358
359static const VUSBDESCENDPOINTEX g_aUsbMsdEndpointDescsSS[2] =
360{
361 {
362 {
363 /* .bLength = */ sizeof(VUSBDESCENDPOINT),
364 /* .bDescriptorType = */ VUSB_DT_ENDPOINT,
365 /* .bEndpointAddress = */ 0x81 /* ep=1, in */,
366 /* .bmAttributes = */ 2 /* bulk */,
367 /* .wMaxPacketSize = */ 1024 /* SS bulk packet size */,
368 /* .bInterval = */ 0 /* no NAKs */
369 },
370 /* .pvMore = */ NULL,
371 /* .pvClass = */ NULL,
372 /* .cbClass = */ 0,
373 /* .pvSsepc = */ &g_aUsbMsdEpCompanionSS,
374 /* .cbSsepc = */ sizeof(g_aUsbMsdEpCompanionSS)
375 },
376 {
377 {
378 /* .bLength = */ sizeof(VUSBDESCENDPOINT),
379 /* .bDescriptorType = */ VUSB_DT_ENDPOINT,
380 /* .bEndpointAddress = */ 0x02 /* ep=2, out */,
381 /* .bmAttributes = */ 2 /* bulk */,
382 /* .wMaxPacketSize = */ 1024 /* SS bulk packet size */,
383 /* .bInterval = */ 0 /* no NAKs */
384 },
385 /* .pvMore = */ NULL,
386 /* .pvClass = */ NULL,
387 /* .cbClass = */ 0,
388 /* .pvSsepc = */ &g_aUsbMsdEpCompanionSS,
389 /* .cbSsepc = */ sizeof(g_aUsbMsdEpCompanionSS)
390 }
391};
392
393static const VUSBDESCINTERFACEEX g_UsbMsdInterfaceDescFS =
394{
395 {
396 /* .bLength = */ sizeof(VUSBDESCINTERFACE),
397 /* .bDescriptorType = */ VUSB_DT_INTERFACE,
398 /* .bInterfaceNumber = */ 0,
399 /* .bAlternateSetting = */ 0,
400 /* .bNumEndpoints = */ 2,
401 /* .bInterfaceClass = */ 8 /* Mass Storage */,
402 /* .bInterfaceSubClass = */ 6 /* SCSI transparent command set */,
403 /* .bInterfaceProtocol = */ 0x50 /* Bulk-Only Transport */,
404 /* .iInterface = */ 0
405 },
406 /* .pvMore = */ NULL,
407 /* .pvClass = */ NULL,
408 /* .cbClass = */ 0,
409 &g_aUsbMsdEndpointDescsFS[0],
410 /* .pIAD = */ NULL,
411 /* .cbIAD = */ 0
412};
413
414static const VUSBDESCINTERFACEEX g_UsbMsdInterfaceDescHS =
415{
416 {
417 /* .bLength = */ sizeof(VUSBDESCINTERFACE),
418 /* .bDescriptorType = */ VUSB_DT_INTERFACE,
419 /* .bInterfaceNumber = */ 0,
420 /* .bAlternateSetting = */ 0,
421 /* .bNumEndpoints = */ 2,
422 /* .bInterfaceClass = */ 8 /* Mass Storage */,
423 /* .bInterfaceSubClass = */ 6 /* SCSI transparent command set */,
424 /* .bInterfaceProtocol = */ 0x50 /* Bulk-Only Transport */,
425 /* .iInterface = */ 0
426 },
427 /* .pvMore = */ NULL,
428 /* .pvClass = */ NULL,
429 /* .cbClass = */ 0,
430 &g_aUsbMsdEndpointDescsHS[0],
431 /* .pIAD = */ NULL,
432 /* .cbIAD = */ 0
433};
434
435static const VUSBDESCINTERFACEEX g_UsbMsdInterfaceDescSS =
436{
437 {
438 /* .bLength = */ sizeof(VUSBDESCINTERFACE),
439 /* .bDescriptorType = */ VUSB_DT_INTERFACE,
440 /* .bInterfaceNumber = */ 0,
441 /* .bAlternateSetting = */ 0,
442 /* .bNumEndpoints = */ 2,
443 /* .bInterfaceClass = */ 8 /* Mass Storage */,
444 /* .bInterfaceSubClass = */ 6 /* SCSI transparent command set */,
445 /* .bInterfaceProtocol = */ 0x50 /* Bulk-Only Transport */,
446 /* .iInterface = */ 0
447 },
448 /* .pvMore = */ NULL,
449 /* .pvClass = */ NULL,
450 /* .cbClass = */ 0,
451 &g_aUsbMsdEndpointDescsSS[0],
452 /* .pIAD = */ NULL,
453 /* .cbIAD = */ 0
454};
455
456static const VUSBINTERFACE g_aUsbMsdInterfacesFS[] =
457{
458 { &g_UsbMsdInterfaceDescFS, /* .cSettings = */ 1 },
459};
460
461static const VUSBINTERFACE g_aUsbMsdInterfacesHS[] =
462{
463 { &g_UsbMsdInterfaceDescHS, /* .cSettings = */ 1 },
464};
465
466static const VUSBINTERFACE g_aUsbMsdInterfacesSS[] =
467{
468 { &g_UsbMsdInterfaceDescSS, /* .cSettings = */ 1 },
469};
470
471static const VUSBDESCCONFIGEX g_UsbMsdConfigDescFS =
472{
473 {
474 /* .bLength = */ sizeof(VUSBDESCCONFIG),
475 /* .bDescriptorType = */ VUSB_DT_CONFIG,
476 /* .wTotalLength = */ 0 /* recalculated on read */,
477 /* .bNumInterfaces = */ RT_ELEMENTS(g_aUsbMsdInterfacesFS),
478 /* .bConfigurationValue =*/ 1,
479 /* .iConfiguration = */ 0,
480 /* .bmAttributes = */ RT_BIT(7),
481 /* .MaxPower = */ 50 /* 100mA */
482 },
483 NULL, /* pvMore */
484 NULL, /* pvClass */
485 0, /* cbClass */
486 &g_aUsbMsdInterfacesFS[0],
487 NULL /* pvOriginal */
488};
489
490static const VUSBDESCCONFIGEX g_UsbMsdConfigDescHS =
491{
492 {
493 /* .bLength = */ sizeof(VUSBDESCCONFIG),
494 /* .bDescriptorType = */ VUSB_DT_CONFIG,
495 /* .wTotalLength = */ 0 /* recalculated on read */,
496 /* .bNumInterfaces = */ RT_ELEMENTS(g_aUsbMsdInterfacesHS),
497 /* .bConfigurationValue =*/ 1,
498 /* .iConfiguration = */ 0,
499 /* .bmAttributes = */ RT_BIT(7),
500 /* .MaxPower = */ 50 /* 100mA */
501 },
502 NULL, /* pvMore */
503 NULL, /* pvClass */
504 0, /* cbClass */
505 &g_aUsbMsdInterfacesHS[0],
506 NULL /* pvOriginal */
507};
508
509static const VUSBDESCCONFIGEX g_UsbMsdConfigDescSS =
510{
511 {
512 /* .bLength = */ sizeof(VUSBDESCCONFIG),
513 /* .bDescriptorType = */ VUSB_DT_CONFIG,
514 /* .wTotalLength = */ 0 /* recalculated on read */,
515 /* .bNumInterfaces = */ RT_ELEMENTS(g_aUsbMsdInterfacesSS),
516 /* .bConfigurationValue =*/ 1,
517 /* .iConfiguration = */ 0,
518 /* .bmAttributes = */ RT_BIT(7),
519 /* .MaxPower = */ 50 /* 100mA */
520 },
521 NULL, /* pvMore */
522 NULL, /* pvClass */
523 0, /* cbClass */
524 &g_aUsbMsdInterfacesSS[0],
525 NULL /* pvOriginal */
526};
527
528static const VUSBDESCDEVICE g_UsbMsdDeviceDesc20 =
529{
530 /* .bLength = */ sizeof(g_UsbMsdDeviceDesc20),
531 /* .bDescriptorType = */ VUSB_DT_DEVICE,
532 /* .bcdUsb = */ 0x200, /* USB 2.0 */
533 /* .bDeviceClass = */ 0 /* Class specified in the interface desc. */,
534 /* .bDeviceSubClass = */ 0 /* Subclass specified in the interface desc. */,
535 /* .bDeviceProtocol = */ 0 /* Protocol specified in the interface desc. */,
536 /* .bMaxPacketSize0 = */ 64,
537 /* .idVendor = */ VBOX_USB_VENDOR,
538 /* .idProduct = */ USBMSD_PID_HD,
539 /* .bcdDevice = */ 0x0100, /* 1.0 */
540 /* .iManufacturer = */ USBMSD_STR_ID_MANUFACTURER,
541 /* .iProduct = */ USBMSD_STR_ID_PRODUCT_HD,
542 /* .iSerialNumber = */ 0,
543 /* .bNumConfigurations = */ 1
544};
545
546static const VUSBDESCDEVICE g_UsbCdDeviceDesc20 =
547{
548 /* .bLength = */ sizeof(g_UsbCdDeviceDesc20),
549 /* .bDescriptorType = */ VUSB_DT_DEVICE,
550 /* .bcdUsb = */ 0x200, /* USB 2.0 */
551 /* .bDeviceClass = */ 0 /* Class specified in the interface desc. */,
552 /* .bDeviceSubClass = */ 0 /* Subclass specified in the interface desc. */,
553 /* .bDeviceProtocol = */ 0 /* Protocol specified in the interface desc. */,
554 /* .bMaxPacketSize0 = */ 64,
555 /* .idVendor = */ VBOX_USB_VENDOR,
556 /* .idProduct = */ USBMSD_PID_CD,
557 /* .bcdDevice = */ 0x0100, /* 1.0 */
558 /* .iManufacturer = */ USBMSD_STR_ID_MANUFACTURER,
559 /* .iProduct = */ USBMSD_STR_ID_PRODUCT_CDROM,
560 /* .iSerialNumber = */ 0,
561 /* .bNumConfigurations = */ 1
562};
563
564static const VUSBDESCDEVICE g_UsbMsdDeviceDesc30 =
565{
566 /* .bLength = */ sizeof(g_UsbMsdDeviceDesc30),
567 /* .bDescriptorType = */ VUSB_DT_DEVICE,
568 /* .bcdUsb = */ 0x300, /* USB 2.0 */
569 /* .bDeviceClass = */ 0 /* Class specified in the interface desc. */,
570 /* .bDeviceSubClass = */ 0 /* Subclass specified in the interface desc. */,
571 /* .bDeviceProtocol = */ 0 /* Protocol specified in the interface desc. */,
572 /* .bMaxPacketSize0 = */ 9 /* 512, the only option for USB3. */,
573 /* .idVendor = */ VBOX_USB_VENDOR,
574 /* .idProduct = */ USBMSD_PID_HD,
575 /* .bcdDevice = */ 0x0110, /* 1.10 */
576 /* .iManufacturer = */ USBMSD_STR_ID_MANUFACTURER,
577 /* .iProduct = */ USBMSD_STR_ID_PRODUCT_HD,
578 /* .iSerialNumber = */ 0,
579 /* .bNumConfigurations = */ 1
580};
581
582static const VUSBDESCDEVICE g_UsbCdDeviceDesc30 =
583{
584 /* .bLength = */ sizeof(g_UsbCdDeviceDesc30),
585 /* .bDescriptorType = */ VUSB_DT_DEVICE,
586 /* .bcdUsb = */ 0x300, /* USB 2.0 */
587 /* .bDeviceClass = */ 0 /* Class specified in the interface desc. */,
588 /* .bDeviceSubClass = */ 0 /* Subclass specified in the interface desc. */,
589 /* .bDeviceProtocol = */ 0 /* Protocol specified in the interface desc. */,
590 /* .bMaxPacketSize0 = */ 9 /* 512, the only option for USB3. */,
591 /* .idVendor = */ VBOX_USB_VENDOR,
592 /* .idProduct = */ USBMSD_PID_CD,
593 /* .bcdDevice = */ 0x0110, /* 1.10 */
594 /* .iManufacturer = */ USBMSD_STR_ID_MANUFACTURER,
595 /* .iProduct = */ USBMSD_STR_ID_PRODUCT_CDROM,
596 /* .iSerialNumber = */ 0,
597 /* .bNumConfigurations = */ 1
598};
599
600static const VUSBDEVICEQUALIFIER g_UsbMsdDeviceQualifier =
601{
602 /* .bLength = */ sizeof(g_UsbMsdDeviceQualifier),
603 /* .bDescriptorType = */ VUSB_DT_DEVICE_QUALIFIER,
604 /* .bcdUsb = */ 0x200, /* USB 2.0 */
605 /* .bDeviceClass = */ 0 /* Class specified in the interface desc. */,
606 /* .bDeviceSubClass = */ 0 /* Subclass specified in the interface desc. */,
607 /* .bDeviceProtocol = */ 0 /* Protocol specified in the interface desc. */,
608 /* .bMaxPacketSize0 = */ 64,
609 /* .bNumConfigurations = */ 1,
610 /* .bReserved = */ 0
611};
612
613static const struct {
614 VUSBDESCBOS bos;
615 VUSBDESCSSDEVCAP sscap;
616} g_UsbMsdBOS =
617{
618 {
619 /* .bLength = */ sizeof(g_UsbMsdBOS.bos),
620 /* .bDescriptorType = */ VUSB_DT_BOS,
621 /* .wTotalLength = */ sizeof(g_UsbMsdBOS),
622 /* .bNumDeviceCaps = */ 1
623 },
624 {
625 /* .bLength = */ sizeof(VUSBDESCSSDEVCAP),
626 /* .bDescriptorType = */ VUSB_DT_DEVICE_CAPABILITY,
627 /* .bDevCapabilityType = */ VUSB_DCT_SUPERSPEED_USB,
628 /* .bmAttributes = */ 0 /* No LTM. */,
629 /* .wSpeedsSupported = */ 0xe /* Any speed is good. */,
630 /* .bFunctionalitySupport = */ 2 /* Want HS at least. */,
631 /* .bU1DevExitLat = */ 0, /* We are blazingly fast. */
632 /* .wU2DevExitLat = */ 0
633 }
634};
635
636static const PDMUSBDESCCACHE g_UsbMsdDescCacheFS =
637{
638 /* .pDevice = */ &g_UsbMsdDeviceDesc20,
639 /* .paConfigs = */ &g_UsbMsdConfigDescFS,
640 /* .paLanguages = */ g_aUsbMsdLanguages,
641 /* .cLanguages = */ RT_ELEMENTS(g_aUsbMsdLanguages),
642 /* .fUseCachedDescriptors = */ true,
643 /* .fUseCachedStringsDescriptors = */ true
644};
645
646static const PDMUSBDESCCACHE g_UsbCdDescCacheFS =
647{
648 /* .pDevice = */ &g_UsbCdDeviceDesc20,
649 /* .paConfigs = */ &g_UsbMsdConfigDescFS,
650 /* .paLanguages = */ g_aUsbMsdLanguages,
651 /* .cLanguages = */ RT_ELEMENTS(g_aUsbMsdLanguages),
652 /* .fUseCachedDescriptors = */ true,
653 /* .fUseCachedStringsDescriptors = */ true
654};
655
656static const PDMUSBDESCCACHE g_UsbMsdDescCacheHS =
657{
658 /* .pDevice = */ &g_UsbMsdDeviceDesc20,
659 /* .paConfigs = */ &g_UsbMsdConfigDescHS,
660 /* .paLanguages = */ g_aUsbMsdLanguages,
661 /* .cLanguages = */ RT_ELEMENTS(g_aUsbMsdLanguages),
662 /* .fUseCachedDescriptors = */ true,
663 /* .fUseCachedStringsDescriptors = */ true
664};
665
666static const PDMUSBDESCCACHE g_UsbCdDescCacheHS =
667{
668 /* .pDevice = */ &g_UsbCdDeviceDesc20,
669 /* .paConfigs = */ &g_UsbMsdConfigDescHS,
670 /* .paLanguages = */ g_aUsbMsdLanguages,
671 /* .cLanguages = */ RT_ELEMENTS(g_aUsbMsdLanguages),
672 /* .fUseCachedDescriptors = */ true,
673 /* .fUseCachedStringsDescriptors = */ true
674};
675
676static const PDMUSBDESCCACHE g_UsbMsdDescCacheSS =
677{
678 /* .pDevice = */ &g_UsbMsdDeviceDesc30,
679 /* .paConfigs = */ &g_UsbMsdConfigDescSS,
680 /* .paLanguages = */ g_aUsbMsdLanguages,
681 /* .cLanguages = */ RT_ELEMENTS(g_aUsbMsdLanguages),
682 /* .fUseCachedDescriptors = */ true,
683 /* .fUseCachedStringsDescriptors = */ true
684};
685
686static const PDMUSBDESCCACHE g_UsbCdDescCacheSS =
687{
688 /* .pDevice = */ &g_UsbCdDeviceDesc30,
689 /* .paConfigs = */ &g_UsbMsdConfigDescSS,
690 /* .paLanguages = */ g_aUsbMsdLanguages,
691 /* .cLanguages = */ RT_ELEMENTS(g_aUsbMsdLanguages),
692 /* .fUseCachedDescriptors = */ true,
693 /* .fUseCachedStringsDescriptors = */ true
694};
695
696
697/*********************************************************************************************************************************
698* Internal Functions *
699*********************************************************************************************************************************/
700static int usbMsdHandleBulkDevToHost(PUSBMSD pThis, PUSBMSDEP pEp, PVUSBURB pUrb);
701
702
703/**
704 * Initializes an URB queue.
705 *
706 * @param pQueue The URB queue.
707 */
708static void usbMsdQueueInit(PUSBMSDURBQUEUE pQueue)
709{
710 pQueue->pHead = NULL;
711 pQueue->ppTail = &pQueue->pHead;
712}
713
714
715
716/**
717 * Inserts an URB at the end of the queue.
718 *
719 * @param pQueue The URB queue.
720 * @param pUrb The URB to insert.
721 */
722DECLINLINE(void) usbMsdQueueAddTail(PUSBMSDURBQUEUE pQueue, PVUSBURB pUrb)
723{
724 pUrb->Dev.pNext = NULL;
725 *pQueue->ppTail = pUrb;
726 pQueue->ppTail = &pUrb->Dev.pNext;
727}
728
729
730/**
731 * Unlinks the head of the queue and returns it.
732 *
733 * @returns The head entry.
734 * @param pQueue The URB queue.
735 */
736DECLINLINE(PVUSBURB) usbMsdQueueRemoveHead(PUSBMSDURBQUEUE pQueue)
737{
738 PVUSBURB pUrb = pQueue->pHead;
739 if (pUrb)
740 {
741 PVUSBURB pNext = pUrb->Dev.pNext;
742 pQueue->pHead = pNext;
743 if (!pNext)
744 pQueue->ppTail = &pQueue->pHead;
745 else
746 pUrb->Dev.pNext = NULL;
747 }
748 return pUrb;
749}
750
751
752/**
753 * Removes an URB from anywhere in the queue.
754 *
755 * @returns true if found, false if not.
756 * @param pQueue The URB queue.
757 * @param pUrb The URB to remove.
758 */
759DECLINLINE(bool) usbMsdQueueRemove(PUSBMSDURBQUEUE pQueue, PVUSBURB pUrb)
760{
761 PVUSBURB pCur = pQueue->pHead;
762 if (pCur == pUrb)
763 pQueue->pHead = pUrb->Dev.pNext;
764 else
765 {
766 while (pCur)
767 {
768 if (pCur->Dev.pNext == pUrb)
769 {
770 pCur->Dev.pNext = pUrb->Dev.pNext;
771 break;
772 }
773 pCur = pCur->Dev.pNext;
774 }
775 if (!pCur)
776 return false;
777 }
778 if (!pUrb->Dev.pNext)
779 pQueue->ppTail = &pQueue->pHead;
780 return true;
781}
782
783
784#ifdef VBOX_STRICT
785/**
786 * Checks if the queue is empty or not.
787 *
788 * @returns true if it is, false if it isn't.
789 * @param pQueue The URB queue.
790 */
791DECLINLINE(bool) usbMsdQueueIsEmpty(PCUSBMSDURBQUEUE pQueue)
792{
793 return pQueue->pHead == NULL;
794}
795#endif /* VBOX_STRICT */
796
797
798/**
799 * Links an URB into the done queue.
800 *
801 * @param pThis The MSD instance.
802 * @param pUrb The URB.
803 */
804static void usbMsdLinkDone(PUSBMSD pThis, PVUSBURB pUrb)
805{
806 usbMsdQueueAddTail(&pThis->DoneQueue, pUrb);
807
808 if (pThis->fHaveDoneQueueWaiter)
809 {
810 int rc = RTSemEventSignal(pThis->hEvtDoneQueue);
811 AssertRC(rc);
812 }
813}
814
815
816
817
818/**
819 * Allocates a new request and does basic init.
820 *
821 * @returns Pointer to the new request. NULL if we're out of memory.
822 * @param pThis The MSD instance.
823 */
824static PUSBMSDREQ usbMsdReqAlloc(PUSBMSD pThis)
825{
826 PUSBMSDREQ pReq = NULL;
827 PDMMEDIAEXIOREQ hIoReq = NULL;
828
829 int rc = pThis->Lun0.pIMediaEx->pfnIoReqAlloc(pThis->Lun0.pIMediaEx, &hIoReq, (void **)&pReq,
830 0 /* uTag */, PDMIMEDIAEX_F_DEFAULT);
831 if (RT_SUCCESS(rc))
832 {
833 pReq->hIoReq = hIoReq;
834 pReq->enmState = USBMSDREQSTATE_READY;
835 pReq->iScsiReqStatus = 0xff;
836 }
837 else
838 LogRel(("usbMsdReqAlloc: Out of memory (%Rrc)\n", rc));
839
840 return pReq;
841}
842
843
844/**
845 * Frees a request.
846 *
847 * @param pThis The MSD instance.
848 * @param pReq The request.
849 */
850static void usbMsdReqFree(PUSBMSD pThis, PUSBMSDREQ pReq)
851{
852 /*
853 * Check the input.
854 */
855 AssertReturnVoid( pReq->enmState > USBMSDREQSTATE_INVALID
856 && pReq->enmState != USBMSDREQSTATE_EXECUTING
857 && pReq->enmState < USBMSDREQSTATE_END);
858 PPDMUSBINS pUsbIns = pThis->pUsbIns;
859 AssertPtrReturnVoid(pUsbIns);
860 AssertReturnVoid(PDM_VERSION_ARE_COMPATIBLE(pUsbIns->u32Version, PDM_USBINS_VERSION));
861
862 /*
863 * Invalidate it and free the associated resources.
864 */
865 pReq->enmState = USBMSDREQSTATE_INVALID;
866 pReq->cbBuf = 0;
867 pReq->offBuf = 0;
868
869 if (pReq->pbBuf)
870 {
871 PDMUsbHlpMMHeapFree(pUsbIns, pReq->pbBuf);
872 pReq->pbBuf = NULL;
873 }
874
875 int rc = pThis->Lun0.pIMediaEx->pfnIoReqFree(pThis->Lun0.pIMediaEx, pReq->hIoReq);
876 AssertRC(rc);
877}
878
879
880/**
881 * Prepares a request for execution or data buffering.
882 *
883 * @param pReq The request.
884 * @param pCbw The SCSI command block wrapper.
885 */
886static void usbMsdReqPrepare(PUSBMSDREQ pReq, PCUSBCBW pCbw)
887{
888 /* Copy the CBW */
889 size_t cbCopy = RT_UOFFSETOF_DYN(USBCBW, CBWCB[pCbw->bCBWCBLength]);
890 memcpy(&pReq->Cbw, pCbw, cbCopy);
891 memset((uint8_t *)&pReq->Cbw + cbCopy, 0, sizeof(pReq->Cbw) - cbCopy);
892
893 /* Setup the SCSI request. */
894 pReq->offBuf = 0;
895 pReq->iScsiReqStatus = 0xff;
896}
897
898
899/**
900 * Makes sure that there is sufficient buffer space available.
901 *
902 * @returns Success indicator (true/false)
903 * @param pThis The MSD instance.
904 * @param pReq The request.
905 * @param cbBuf The required buffer space.
906 */
907static int usbMsdReqEnsureBuffer(PUSBMSD pThis, PUSBMSDREQ pReq, uint32_t cbBuf)
908{
909 if (RT_LIKELY(pReq->cbBuf >= cbBuf))
910 RT_BZERO(pReq->pbBuf, cbBuf);
911 else
912 {
913 PDMUsbHlpMMHeapFree(pThis->pUsbIns, pReq->pbBuf);
914 pReq->cbBuf = 0;
915
916 cbBuf = RT_ALIGN_Z(cbBuf, 0x1000);
917 pReq->pbBuf = (uint8_t *)PDMUsbHlpMMHeapAllocZ(pThis->pUsbIns, cbBuf);
918 if (!pReq->pbBuf)
919 return false;
920
921 pReq->cbBuf = cbBuf;
922 }
923 return true;
924}
925
926
927/**
928 * Completes the URB with a stalled state, halting the pipe.
929 */
930static int usbMsdCompleteStall(PUSBMSD pThis, PUSBMSDEP pEp, PVUSBURB pUrb, const char *pszWhy)
931{
932 RT_NOREF(pszWhy);
933 Log(("usbMsdCompleteStall/#%u: pUrb=%p:%s: %s\n", pThis->pUsbIns->iInstance, pUrb, pUrb->pszDesc, pszWhy));
934
935 pUrb->enmStatus = VUSBSTATUS_STALL;
936
937 /** @todo figure out if the stall is global or pipe-specific or both. */
938 if (pEp)
939 pEp->fHalted = true;
940 else
941 {
942 pThis->aEps[1].fHalted = true;
943 pThis->aEps[2].fHalted = true;
944 }
945
946 usbMsdLinkDone(pThis, pUrb);
947 return VINF_SUCCESS;
948}
949
950
951/**
952 * Completes the URB with a OK state.
953 */
954static int usbMsdCompleteOk(PUSBMSD pThis, PVUSBURB pUrb, size_t cbData)
955{
956 Log(("usbMsdCompleteOk/#%u: pUrb=%p:%s cbData=%#zx\n", pThis->pUsbIns->iInstance, pUrb, pUrb->pszDesc, cbData));
957
958 pUrb->enmStatus = VUSBSTATUS_OK;
959 pUrb->cbData = (uint32_t)cbData;
960
961 usbMsdLinkDone(pThis, pUrb);
962 return VINF_SUCCESS;
963}
964
965
966/**
967 * Reset worker for usbMsdUsbReset, usbMsdUsbSetConfiguration and
968 * usbMsdUrbHandleDefaultPipe.
969 *
970 * @returns VBox status code.
971 * @param pThis The MSD instance.
972 * @param pUrb Set when usbMsdUrbHandleDefaultPipe is the
973 * caller.
974 * @param fSetConfig Set when usbMsdUsbSetConfiguration is the
975 * caller.
976 */
977static int usbMsdResetWorker(PUSBMSD pThis, PVUSBURB pUrb, bool fSetConfig)
978{
979 /*
980 * Wait for the any command currently executing to complete before
981 * resetting. (We cannot cancel its execution.) How we do this depends
982 * on the reset method.
983 */
984 PUSBMSDREQ pReq = pThis->pReq;
985 if ( pReq
986 && pReq->enmState == USBMSDREQSTATE_EXECUTING)
987 {
988 /* Don't try to deal with the set config variant nor multiple build-only
989 mass storage resets. */
990 if (pThis->pResetUrb && (pUrb || fSetConfig))
991 {
992 Log(("usbMsdResetWorker: pResetUrb is already %p:%s - stalling\n", pThis->pResetUrb, pThis->pResetUrb->pszDesc));
993 return usbMsdCompleteStall(pThis, NULL, pUrb, "pResetUrb");
994 }
995
996 /* Bulk-Only Mass Storage Reset: Complete the reset on request completion. */
997 if (pUrb)
998 {
999 pThis->pResetUrb = pUrb;
1000 Log(("usbMsdResetWorker: Setting pResetUrb to %p:%s\n", pThis->pResetUrb, pThis->pResetUrb->pszDesc));
1001 return VINF_SUCCESS;
1002 }
1003
1004 /* Device reset: Wait for up to 10 ms. If it doesn't work, ditch
1005 whole the request structure. We'll allocate a new one when needed. */
1006 Log(("usbMsdResetWorker: Waiting for completion...\n"));
1007 Assert(!pThis->fSignalResetSem);
1008 pThis->fSignalResetSem = true;
1009 RTSemEventMultiReset(pThis->hEvtReset);
1010 RTCritSectLeave(&pThis->CritSect);
1011
1012 int rc = RTSemEventMultiWait(pThis->hEvtReset, 10 /*ms*/);
1013
1014 RTCritSectEnter(&pThis->CritSect);
1015 pThis->fSignalResetSem = false;
1016 if ( RT_FAILURE(rc)
1017 || pReq->enmState == USBMSDREQSTATE_EXECUTING)
1018 {
1019 Log(("usbMsdResetWorker: Didn't complete, ditching the current request (%p)!\n", pReq));
1020 Assert(pReq == pThis->pReq);
1021 pReq->enmState = USBMSDREQSTATE_DESTROY_ON_COMPLETION;
1022 pThis->pReq = NULL;
1023 pReq = NULL;
1024 }
1025 }
1026
1027 /*
1028 * Reset the request and device state.
1029 */
1030 if (pReq)
1031 {
1032 pReq->enmState = USBMSDREQSTATE_READY;
1033 pReq->iScsiReqStatus = 0xff;
1034 }
1035
1036 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aEps); i++)
1037 pThis->aEps[i].fHalted = false;
1038
1039 if (!pUrb && !fSetConfig) /* (only device reset) */
1040 pThis->bConfigurationValue = 0; /* default */
1041
1042 /*
1043 * Ditch all pending URBs.
1044 */
1045 PVUSBURB pCurUrb;
1046 while ((pCurUrb = usbMsdQueueRemoveHead(&pThis->ToHostQueue)) != NULL)
1047 {
1048 pCurUrb->enmStatus = VUSBSTATUS_CRC;
1049 usbMsdLinkDone(pThis, pCurUrb);
1050 }
1051
1052 pCurUrb = pThis->pResetUrb;
1053 if (pCurUrb)
1054 {
1055 pThis->pResetUrb = NULL;
1056 pCurUrb->enmStatus = VUSBSTATUS_CRC;
1057 usbMsdLinkDone(pThis, pCurUrb);
1058 }
1059
1060 if (pUrb)
1061 return usbMsdCompleteOk(pThis, pUrb, 0);
1062 return VINF_SUCCESS;
1063}
1064
1065
1066/**
1067 * Process a completed request.
1068 *
1069 * @returns nothing.
1070 * @param pThis The MSD instance.
1071 * @param pReq The request.
1072 * @param rcReq The completion status.
1073 */
1074static void usbMsdReqComplete(PUSBMSD pThis, PUSBMSDREQ pReq, int rcReq)
1075{
1076 RT_NOREF1(rcReq);
1077
1078 Log(("usbMsdLun0IoReqCompleteNotify: pReq=%p dCBWTag=%#x iScsiReqStatus=%u \n", pReq, pReq->Cbw.dCBWTag, pReq->iScsiReqStatus));
1079 RTCritSectEnter(&pThis->CritSect);
1080
1081 if (pReq->enmState != USBMSDREQSTATE_DESTROY_ON_COMPLETION)
1082 {
1083 Assert(pReq->enmState == USBMSDREQSTATE_EXECUTING);
1084 Assert(pThis->pReq == pReq);
1085
1086 /*
1087 * Advance the state machine. The state machine is not affected by
1088 * SCSI errors.
1089 */
1090 if ((pReq->Cbw.bmCBWFlags & USBCBW_DIR_MASK) == USBCBW_DIR_OUT)
1091 {
1092 pReq->enmState = USBMSDREQSTATE_STATUS;
1093 Log(("usbMsdLun0IoReqCompleteNotify: Entering STATUS\n"));
1094 }
1095 else
1096 {
1097 pReq->enmState = USBMSDREQSTATE_DATA_TO_HOST;
1098 Log(("usbMsdLun0IoReqCompleteNotify: Entering DATA_TO_HOST\n"));
1099 }
1100
1101 /*
1102 * Deal with pending to-host URBs.
1103 */
1104 for (;;)
1105 {
1106 PVUSBURB pUrb = usbMsdQueueRemoveHead(&pThis->ToHostQueue);
1107 if (!pUrb)
1108 break;
1109
1110 /* Process it the normal way. */
1111 usbMsdHandleBulkDevToHost(pThis, &pThis->aEps[1], pUrb);
1112 }
1113 }
1114 else
1115 {
1116 Log(("usbMsdLun0IoReqCompleteNotify: freeing %p\n", pReq));
1117 usbMsdReqFree(pThis, pReq);
1118 }
1119
1120 if (pThis->fSignalResetSem)
1121 RTSemEventMultiSignal(pThis->hEvtReset);
1122
1123 if (pThis->pResetUrb)
1124 {
1125 pThis->pResetUrb = NULL;
1126 usbMsdResetWorker(pThis, pThis->pResetUrb, false /*fSetConfig*/);
1127 }
1128
1129 RTCritSectLeave(&pThis->CritSect);
1130}
1131
1132
1133/**
1134 * @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqCopyFromBuf}
1135 */
1136static DECLCALLBACK(int) usbMsdLun0IoReqCopyFromBuf(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
1137 void *pvIoReqAlloc, uint32_t offDst, PRTSGBUF pSgBuf,
1138 size_t cbCopy)
1139{
1140 RT_NOREF2(pInterface, hIoReq);
1141 int rc = VINF_SUCCESS;
1142 PUSBMSDREQ pReq = (PUSBMSDREQ)pvIoReqAlloc;
1143
1144 if (RT_UNLIKELY(offDst + cbCopy > pReq->cbBuf))
1145 rc = VERR_PDM_MEDIAEX_IOBUF_OVERFLOW;
1146 else
1147 {
1148 size_t cbCopied = RTSgBufCopyToBuf(pSgBuf, pReq->pbBuf + offDst, cbCopy);
1149 Assert(cbCopied == cbCopy); RT_NOREF(cbCopied);
1150 }
1151
1152 return rc;
1153}
1154
1155
1156/**
1157 * @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqCopyToBuf}
1158 */
1159static DECLCALLBACK(int) usbMsdLun0IoReqCopyToBuf(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
1160 void *pvIoReqAlloc, uint32_t offSrc, PRTSGBUF pSgBuf,
1161 size_t cbCopy)
1162{
1163 RT_NOREF2(pInterface, hIoReq);
1164 int rc = VINF_SUCCESS;
1165 PUSBMSDREQ pReq = (PUSBMSDREQ)pvIoReqAlloc;
1166
1167 if (RT_UNLIKELY(offSrc + cbCopy > pReq->cbBuf))
1168 rc = VERR_PDM_MEDIAEX_IOBUF_UNDERRUN;
1169 else
1170 {
1171 size_t cbCopied = RTSgBufCopyFromBuf(pSgBuf, pReq->pbBuf + offSrc, cbCopy);
1172 Assert(cbCopied == cbCopy); RT_NOREF(cbCopied);
1173 }
1174
1175 return rc;
1176}
1177
1178
1179/**
1180 * @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqCompleteNotify}
1181 */
1182static DECLCALLBACK(int) usbMsdLun0IoReqCompleteNotify(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
1183 void *pvIoReqAlloc, int rcReq)
1184{
1185 RT_NOREF1(hIoReq);
1186 PUSBMSD pThis = RT_FROM_MEMBER(pInterface, USBMSD, Lun0.IMediaExPort);
1187 PUSBMSDREQ pReq = (PUSBMSDREQ)pvIoReqAlloc;
1188
1189 usbMsdReqComplete(pThis, pReq, rcReq);
1190 return VINF_SUCCESS;
1191}
1192
1193
1194/**
1195 * @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqStateChanged}
1196 */
1197static DECLCALLBACK(void) usbMsdLun0IoReqStateChanged(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
1198 void *pvIoReqAlloc, PDMMEDIAEXIOREQSTATE enmState)
1199{
1200 RT_NOREF4(pInterface, hIoReq, pvIoReqAlloc, enmState);
1201 AssertLogRelMsgFailed(("This should not be hit because I/O requests should not be suspended\n"));
1202}
1203
1204
1205/**
1206 * @interface_method_impl{PDMIMEDIAEXPORT,pfnMediumEjected}
1207 */
1208static DECLCALLBACK(void) usbMsdLun0MediumEjected(PPDMIMEDIAEXPORT pInterface)
1209{
1210 RT_NOREF1(pInterface); /** @todo */
1211}
1212
1213
1214/**
1215 * @interface_method_impl{PDMIMEDIAPORT,pfnQueryDeviceLocation}
1216 */
1217static DECLCALLBACK(int) usbMsdLun0QueryDeviceLocation(PPDMIMEDIAPORT pInterface, const char **ppcszController,
1218 uint32_t *piInstance, uint32_t *piLUN)
1219{
1220 PUSBMSD pThis = RT_FROM_MEMBER(pInterface, USBMSD, Lun0.IMediaPort);
1221 PPDMUSBINS pUsbIns = pThis->pUsbIns;
1222
1223 AssertPtrReturn(ppcszController, VERR_INVALID_POINTER);
1224 AssertPtrReturn(piInstance, VERR_INVALID_POINTER);
1225 AssertPtrReturn(piLUN, VERR_INVALID_POINTER);
1226
1227 *ppcszController = pUsbIns->pReg->szName;
1228 *piInstance = pUsbIns->iInstance;
1229 *piLUN = 0;
1230
1231 return VINF_SUCCESS;
1232}
1233
1234
1235/**
1236 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
1237 */
1238static DECLCALLBACK(void *) usbMsdLun0QueryInterface(PPDMIBASE pInterface, const char *pszIID)
1239{
1240 PUSBMSD pThis = RT_FROM_MEMBER(pInterface, USBMSD, Lun0.IBase);
1241 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThis->Lun0.IBase);
1242 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIAPORT, &pThis->Lun0.IMediaPort);
1243 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIAEXPORT, &pThis->Lun0.IMediaExPort);
1244 return NULL;
1245}
1246
1247
1248/**
1249 * Checks if all asynchronous I/O is finished.
1250 *
1251 * Used by usbMsdVMReset, usbMsdVMSuspend and usbMsdVMPowerOff.
1252 *
1253 * @returns true if quiesced, false if busy.
1254 * @param pUsbIns The USB device instance.
1255 */
1256static bool usbMsdAllAsyncIOIsFinished(PPDMUSBINS pUsbIns)
1257{
1258 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1259
1260 if ( VALID_PTR(pThis->pReq)
1261 && pThis->pReq->enmState == USBMSDREQSTATE_EXECUTING)
1262 return false;
1263
1264 return true;
1265}
1266
1267/**
1268 * @callback_method_impl{FNPDMDEVASYNCNOTIFY,
1269 * Callback employed by usbMsdVMSuspend and usbMsdVMPowerOff.}
1270 */
1271static DECLCALLBACK(bool) usbMsdIsAsyncSuspendOrPowerOffDone(PPDMUSBINS pUsbIns)
1272{
1273 if (!usbMsdAllAsyncIOIsFinished(pUsbIns))
1274 return false;
1275
1276 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1277 ASMAtomicWriteBool(&pThis->fSignalIdle, false);
1278 return true;
1279}
1280
1281/**
1282 * Common worker for usbMsdVMSuspend and usbMsdVMPowerOff.
1283 */
1284static void usbMsdSuspendOrPowerOff(PPDMUSBINS pUsbIns)
1285{
1286 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1287
1288 ASMAtomicWriteBool(&pThis->fSignalIdle, true);
1289 if (!usbMsdAllAsyncIOIsFinished(pUsbIns))
1290 PDMUsbHlpSetAsyncNotification(pUsbIns, usbMsdIsAsyncSuspendOrPowerOffDone);
1291 else
1292 {
1293 ASMAtomicWriteBool(&pThis->fSignalIdle, false);
1294
1295 if (pThis->pReq)
1296 {
1297 usbMsdReqFree(pThis, pThis->pReq);
1298 pThis->pReq = NULL;
1299 }
1300 }
1301
1302 if (pThis->Lun0.pIMediaEx)
1303 pThis->Lun0.pIMediaEx->pfnNotifySuspend(pThis->Lun0.pIMediaEx);
1304}
1305
1306
1307/* -=-=-=-=- Saved State -=-=-=-=- */
1308
1309/**
1310 * @callback_method_impl{FNSSMUSBSAVEPREP}
1311 */
1312static DECLCALLBACK(int) usbMsdSavePrep(PPDMUSBINS pUsbIns, PSSMHANDLE pSSM)
1313{
1314 RT_NOREF(pSSM);
1315#ifdef VBOX_STRICT
1316 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1317 Assert(usbMsdAllAsyncIOIsFinished(pUsbIns));
1318 Assert(usbMsdQueueIsEmpty(&pThis->ToHostQueue));
1319 Assert(usbMsdQueueIsEmpty(&pThis->DoneQueue));
1320#else
1321 RT_NOREF(pUsbIns);
1322#endif
1323 return VINF_SUCCESS;
1324}
1325
1326/**
1327 * @callback_method_impl{FNSSMUSBLOADPREP}
1328 */
1329static DECLCALLBACK(int) usbMsdLoadPrep(PPDMUSBINS pUsbIns, PSSMHANDLE pSSM)
1330{
1331 RT_NOREF(pSSM);
1332#ifdef VBOX_STRICT
1333 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1334 Assert(usbMsdAllAsyncIOIsFinished(pUsbIns));
1335 Assert(usbMsdQueueIsEmpty(&pThis->ToHostQueue));
1336 Assert(usbMsdQueueIsEmpty(&pThis->DoneQueue));
1337#else
1338 RT_NOREF(pUsbIns);
1339#endif
1340 return VINF_SUCCESS;
1341}
1342
1343/**
1344 * @callback_method_impl{FNSSMUSBLIVEEXEC}
1345 */
1346static DECLCALLBACK(int) usbMsdLiveExec(PPDMUSBINS pUsbIns, PSSMHANDLE pSSM, uint32_t uPass)
1347{
1348 RT_NOREF(uPass);
1349 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1350
1351 /* config. */
1352 SSMR3PutBool(pSSM, pThis->Lun0.pIBase != NULL);
1353 return VINF_SSM_DONT_CALL_AGAIN;
1354}
1355
1356/**
1357 * @callback_method_impl{FNSSMUSBSAVEEXEC}
1358 */
1359static DECLCALLBACK(int) usbMsdSaveExec(PPDMUSBINS pUsbIns, PSSMHANDLE pSSM)
1360{
1361 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1362 int rc;
1363
1364 /* The config */
1365 rc = usbMsdLiveExec(pUsbIns, pSSM, SSM_PASS_FINAL);
1366 AssertRCReturn(rc, rc);
1367
1368 SSMR3PutU8(pSSM, pThis->bConfigurationValue);
1369 SSMR3PutBool(pSSM, pThis->aEps[0].fHalted);
1370 SSMR3PutBool(pSSM, pThis->aEps[1].fHalted);
1371 SSMR3PutBool(pSSM, pThis->aEps[2].fHalted);
1372 SSMR3PutBool(pSSM, pThis->pReq != NULL);
1373
1374 if (pThis->pReq)
1375 {
1376 PUSBMSDREQ pReq = pThis->pReq;
1377
1378 SSMR3PutU32(pSSM, pReq->enmState);
1379 SSMR3PutU32(pSSM, pReq->cbBuf);
1380 if (pReq->cbBuf)
1381 {
1382 AssertPtr(pReq->pbBuf);
1383 SSMR3PutMem(pSSM, pReq->pbBuf, pReq->cbBuf);
1384 }
1385
1386 SSMR3PutU32(pSSM, pReq->offBuf);
1387 SSMR3PutMem(pSSM, &pReq->Cbw, sizeof(pReq->Cbw));
1388 SSMR3PutU8(pSSM, pReq->iScsiReqStatus);
1389 }
1390
1391 return SSMR3PutU32(pSSM, UINT32_MAX); /* sanity/terminator */
1392}
1393
1394/**
1395 * @callback_method_impl{FNSSMUSBLOADEXEC}
1396 */
1397static DECLCALLBACK(int) usbMsdLoadExec(PPDMUSBINS pUsbIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
1398{
1399 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1400 uint32_t u32;
1401 int rc;
1402
1403 if (uVersion > USB_MSD_SAVED_STATE_VERSION)
1404 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
1405
1406 /* Verify config. */
1407 bool fInUse;
1408 rc = SSMR3GetBool(pSSM, &fInUse);
1409 AssertRCReturn(rc, rc);
1410 if (fInUse != (pThis->Lun0.pIBase != NULL))
1411 return SSMR3SetCfgError(pSSM, RT_SRC_POS,
1412 N_("The %s VM is missing a USB mass storage device. Please make sure the source and target VMs have compatible storage configurations"),
1413 fInUse ? "target" : "source");
1414
1415 if (uPass == SSM_PASS_FINAL)
1416 {
1417 /* Restore data. */
1418 Assert(!pThis->pReq);
1419
1420 SSMR3GetU8(pSSM, &pThis->bConfigurationValue);
1421 SSMR3GetBool(pSSM, &pThis->aEps[0].fHalted);
1422 SSMR3GetBool(pSSM, &pThis->aEps[1].fHalted);
1423 SSMR3GetBool(pSSM, &pThis->aEps[2].fHalted);
1424 bool fReqAlloc = false;
1425 rc = SSMR3GetBool(pSSM, &fReqAlloc);
1426 AssertRCReturn(rc, rc);
1427 if (fReqAlloc)
1428 {
1429 PUSBMSDREQ pReq = usbMsdReqAlloc(pThis);
1430 AssertReturn(pReq, VERR_NO_MEMORY);
1431 pThis->pReq = pReq;
1432
1433 SSMR3GetU32(pSSM, (uint32_t *)&pReq->enmState);
1434 uint32_t cbBuf = 0;
1435 rc = SSMR3GetU32(pSSM, &cbBuf);
1436 AssertRCReturn(rc, rc);
1437 if (cbBuf)
1438 {
1439 if (usbMsdReqEnsureBuffer(pThis, pReq, cbBuf))
1440 {
1441 AssertPtr(pReq->pbBuf);
1442 Assert(cbBuf == pReq->cbBuf);
1443 SSMR3GetMem(pSSM, pReq->pbBuf, pReq->cbBuf);
1444 }
1445 else
1446 return VERR_NO_MEMORY;
1447 }
1448
1449 SSMR3GetU32(pSSM, &pReq->offBuf);
1450 SSMR3GetMem(pSSM, &pReq->Cbw, sizeof(pReq->Cbw));
1451
1452 if (uVersion > USB_MSD_SAVED_STATE_VERSION_PRE_CLEANUP)
1453 rc = SSMR3GetU8(pSSM, &pReq->iScsiReqStatus);
1454 else
1455 {
1456 int32_t iScsiReqStatus;
1457
1458 /* Skip old fields which are unused now or can be determined from the CBW. */
1459 SSMR3Skip(pSSM, 4 * 4 + 64);
1460 rc = SSMR3GetS32(pSSM, &iScsiReqStatus);
1461 pReq->iScsiReqStatus = (uint8_t)iScsiReqStatus;
1462 }
1463 AssertRCReturn(rc, rc);
1464 }
1465
1466 rc = SSMR3GetU32(pSSM, &u32);
1467 AssertRCReturn(rc, rc);
1468 AssertMsgReturn(u32 == UINT32_MAX, ("%#x\n", u32), VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
1469 }
1470
1471 return VINF_SUCCESS;
1472}
1473
1474
1475/**
1476 * @interface_method_impl{PDMUSBREG,pfnUrbReap}
1477 */
1478static DECLCALLBACK(PVUSBURB) usbMsdUrbReap(PPDMUSBINS pUsbIns, RTMSINTERVAL cMillies)
1479{
1480 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1481 LogFlow(("usbMsdUrbReap/#%u: cMillies=%u\n", pUsbIns->iInstance, cMillies));
1482
1483 RTCritSectEnter(&pThis->CritSect);
1484
1485 PVUSBURB pUrb = usbMsdQueueRemoveHead(&pThis->DoneQueue);
1486 if (!pUrb && cMillies)
1487 {
1488 /* Wait */
1489 pThis->fHaveDoneQueueWaiter = true;
1490 RTCritSectLeave(&pThis->CritSect);
1491
1492 RTSemEventWait(pThis->hEvtDoneQueue, cMillies);
1493
1494 RTCritSectEnter(&pThis->CritSect);
1495 pThis->fHaveDoneQueueWaiter = false;
1496
1497 pUrb = usbMsdQueueRemoveHead(&pThis->DoneQueue);
1498 }
1499
1500 RTCritSectLeave(&pThis->CritSect);
1501
1502 if (pUrb)
1503 Log(("usbMsdUrbReap/#%u: pUrb=%p:%s\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc));
1504 return pUrb;
1505}
1506
1507
1508/**
1509 * @interface_method_impl{PDMUSBREG,pfnWakeup}
1510 */
1511static DECLCALLBACK(int) usbMsdWakeup(PPDMUSBINS pUsbIns)
1512{
1513 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1514 LogFlow(("usbMsdUrbReap/#%u:\n", pUsbIns->iInstance));
1515
1516 return RTSemEventSignal(pThis->hEvtDoneQueue);
1517}
1518
1519
1520/**
1521 * @interface_method_impl{PDMUSBREG,pfnUrbCancel}
1522 */
1523static DECLCALLBACK(int) usbMsdUrbCancel(PPDMUSBINS pUsbIns, PVUSBURB pUrb)
1524{
1525 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1526 LogFlow(("usbMsdUrbCancel/#%u: pUrb=%p:%s\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc));
1527 RTCritSectEnter(&pThis->CritSect);
1528
1529 /*
1530 * Remove the URB from the to-host queue and move it onto the done queue.
1531 */
1532 if (usbMsdQueueRemove(&pThis->ToHostQueue, pUrb))
1533 usbMsdLinkDone(pThis, pUrb);
1534
1535 RTCritSectLeave(&pThis->CritSect);
1536 return VINF_SUCCESS;
1537}
1538
1539
1540/**
1541 * Wrapper around PDMISCSICONNECTOR::pfnSCSIRequestSend that deals with
1542 * SCSI_REQUEST_SENSE.
1543 *
1544 * @returns VBox status code.
1545 * @param pThis The MSD instance data.
1546 * @param pReq The MSD request.
1547 * @param pszCaller Where we're called from.
1548 */
1549static int usbMsdSubmitScsiCommand(PUSBMSD pThis, PUSBMSDREQ pReq, const char *pszCaller)
1550{
1551 RT_NOREF(pszCaller);
1552 Log(("%s: Entering EXECUTING (dCBWTag=%#x).\n", pszCaller, pReq->Cbw.dCBWTag));
1553 Assert(pReq == pThis->pReq);
1554 pReq->enmState = USBMSDREQSTATE_EXECUTING;
1555
1556 PDMMEDIAEXIOREQSCSITXDIR enmTxDir = pReq->Cbw.dCBWDataTransferLength == 0
1557 ? PDMMEDIAEXIOREQSCSITXDIR_NONE
1558 : (pReq->Cbw.bmCBWFlags & USBCBW_DIR_MASK) == USBCBW_DIR_OUT
1559 ? PDMMEDIAEXIOREQSCSITXDIR_TO_DEVICE
1560 : PDMMEDIAEXIOREQSCSITXDIR_FROM_DEVICE;
1561
1562 return pThis->Lun0.pIMediaEx->pfnIoReqSendScsiCmd(pThis->Lun0.pIMediaEx, pReq->hIoReq, pReq->Cbw.bCBWLun,
1563 &pReq->Cbw.CBWCB[0], pReq->Cbw.bCBWCBLength, enmTxDir,
1564 pReq->Cbw.dCBWDataTransferLength, NULL, 0,
1565 &pReq->iScsiReqStatus, 20 * RT_MS_1SEC);
1566}
1567
1568
1569/**
1570 * Handle requests sent to the outbound (to device) bulk pipe.
1571 */
1572static int usbMsdHandleBulkHostToDev(PUSBMSD pThis, PUSBMSDEP pEp, PVUSBURB pUrb)
1573{
1574 /*
1575 * Stall the request if the pipe is halted.
1576 */
1577 if (RT_UNLIKELY(pEp->fHalted))
1578 return usbMsdCompleteStall(pThis, NULL, pUrb, "Halted pipe");
1579
1580 /*
1581 * Deal with the URB according to the current state.
1582 */
1583 PUSBMSDREQ pReq = pThis->pReq;
1584 USBMSDREQSTATE enmState = pReq ? pReq->enmState : USBMSDREQSTATE_READY;
1585 switch (enmState)
1586 {
1587 case USBMSDREQSTATE_STATUS:
1588 LogFlow(("usbMsdHandleBulkHostToDev: Skipping pending status.\n"));
1589 pReq->enmState = USBMSDREQSTATE_READY;
1590 RT_FALL_THRU();
1591
1592 /*
1593 * We're ready to receive a command. Start off by validating the
1594 * incoming request.
1595 */
1596 case USBMSDREQSTATE_READY:
1597 {
1598 PCUSBCBW pCbw = (PUSBCBW)&pUrb->abData[0];
1599 if (pUrb->cbData < RT_UOFFSETOF(USBCBW, CBWCB[1]))
1600 {
1601 Log(("usbMsd: Bad CBW: cbData=%#x < min=%#x\n", pUrb->cbData, RT_UOFFSETOF(USBCBW, CBWCB[1]) ));
1602 return usbMsdCompleteStall(pThis, NULL, pUrb, "BAD CBW");
1603 }
1604 if (pCbw->dCBWSignature != USBCBW_SIGNATURE)
1605 {
1606 Log(("usbMsd: CBW: Invalid dCBWSignature value: %#x\n", pCbw->dCBWSignature));
1607 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1608 }
1609 Log(("usbMsd: CBW: dCBWTag=%#x dCBWDataTransferLength=%#x bmCBWFlags=%#x bCBWLun=%#x bCBWCBLength=%#x cbData=%#x fShortNotOk=%RTbool\n",
1610 pCbw->dCBWTag, pCbw->dCBWDataTransferLength, pCbw->bmCBWFlags, pCbw->bCBWLun, pCbw->bCBWCBLength, pUrb->cbData, pUrb->fShortNotOk));
1611 if (pCbw->bmCBWFlags & ~USBCBW_DIR_MASK)
1612 {
1613 Log(("usbMsd: CBW: Bad bmCBWFlags value: %#x\n", pCbw->bmCBWFlags));
1614 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1615
1616 }
1617 if (pCbw->bCBWLun != 0)
1618 {
1619 Log(("usbMsd: CBW: Bad bCBWLun value: %#x\n", pCbw->bCBWLun));
1620 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1621 }
1622 if (pCbw->bCBWCBLength == 0)
1623 {
1624 Log(("usbMsd: CBW: Bad bCBWCBLength value: %#x\n", pCbw->bCBWCBLength));
1625 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1626 }
1627 if (pUrb->cbData < RT_UOFFSETOF_DYN(USBCBW, CBWCB[pCbw->bCBWCBLength]))
1628 {
1629 Log(("usbMsd: CBW: Mismatching cbData and bCBWCBLength values: %#x vs. %#x (%#x)\n",
1630 pUrb->cbData, RT_UOFFSETOF_DYN(USBCBW, CBWCB[pCbw->bCBWCBLength]), pCbw->bCBWCBLength));
1631 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1632 }
1633 if (pCbw->dCBWDataTransferLength > _1M)
1634 {
1635 Log(("usbMsd: CBW: dCBWDataTransferLength is too large: %#x (%u)\n",
1636 pCbw->dCBWDataTransferLength, pCbw->dCBWDataTransferLength));
1637 return usbMsdCompleteStall(pThis, NULL, pUrb, "Too big transfer");
1638 }
1639
1640 /*
1641 * Make sure we've got a request and a sufficient buffer space.
1642 *
1643 * Note! This will make sure the buffer is ZERO as well, thus
1644 * saving us the trouble of clearing the output buffer on
1645 * failure later.
1646 */
1647 if (!pReq)
1648 {
1649 pReq = usbMsdReqAlloc(pThis);
1650 if (!pReq)
1651 return usbMsdCompleteStall(pThis, NULL, pUrb, "Request allocation failure");
1652 pThis->pReq = pReq;
1653 }
1654 if (!usbMsdReqEnsureBuffer(pThis, pReq, pCbw->dCBWDataTransferLength))
1655 return usbMsdCompleteStall(pThis, NULL, pUrb, "Buffer allocation failure");
1656
1657 /*
1658 * Prepare the request. Kick it off right away if possible.
1659 */
1660 usbMsdReqPrepare(pReq, pCbw);
1661
1662 if ( pReq->Cbw.dCBWDataTransferLength == 0
1663 || (pReq->Cbw.bmCBWFlags & USBCBW_DIR_MASK) == USBCBW_DIR_IN)
1664 {
1665 int rc = usbMsdSubmitScsiCommand(pThis, pReq, "usbMsdHandleBulkHostToDev");
1666 if (RT_SUCCESS(rc) && rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
1667 usbMsdReqComplete(pThis, pReq, rc);
1668 else if (RT_FAILURE(rc))
1669 {
1670 Log(("usbMsd: Failed sending SCSI request to driver: %Rrc\n", rc));
1671 return usbMsdCompleteStall(pThis, NULL, pUrb, "SCSI Submit #1");
1672 }
1673 }
1674 else
1675 {
1676 Log(("usbMsdHandleBulkHostToDev: Entering DATA_FROM_HOST.\n"));
1677 pReq->enmState = USBMSDREQSTATE_DATA_FROM_HOST;
1678 }
1679
1680 return usbMsdCompleteOk(pThis, pUrb, pUrb->cbData);
1681 }
1682
1683 /*
1684 * Stuff the data into the buffer.
1685 */
1686 case USBMSDREQSTATE_DATA_FROM_HOST:
1687 {
1688 uint32_t cbData = pUrb->cbData;
1689 uint32_t cbLeft = pReq->Cbw.dCBWDataTransferLength - pReq->offBuf;
1690 if (cbData > cbLeft)
1691 {
1692 Log(("usbMsd: Too much data: cbData=%#x offBuf=%#x dCBWDataTransferLength=%#x cbLeft=%#x\n",
1693 cbData, pReq->offBuf, pReq->Cbw.dCBWDataTransferLength, cbLeft));
1694 return usbMsdCompleteStall(pThis, NULL, pUrb, "Too much data");
1695 }
1696 memcpy(&pReq->pbBuf[pReq->offBuf], &pUrb->abData[0], cbData);
1697 pReq->offBuf += cbData;
1698
1699 if (pReq->offBuf == pReq->Cbw.dCBWDataTransferLength)
1700 {
1701 int rc = usbMsdSubmitScsiCommand(pThis, pReq, "usbMsdHandleBulkHostToDev");
1702 if (RT_SUCCESS(rc) && rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
1703 usbMsdReqComplete(pThis, pReq, rc);
1704 else if (RT_FAILURE(rc))
1705 {
1706 Log(("usbMsd: Failed sending SCSI request to driver: %Rrc\n", rc));
1707 return usbMsdCompleteStall(pThis, NULL, pUrb, "SCSI Submit #2");
1708 }
1709 }
1710 return usbMsdCompleteOk(pThis, pUrb, cbData);
1711 }
1712
1713 /*
1714 * Bad state, stall.
1715 */
1716 case USBMSDREQSTATE_DATA_TO_HOST:
1717 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad state H2D: DATA_TO_HOST");
1718
1719 case USBMSDREQSTATE_EXECUTING:
1720 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad state H2D: EXECUTING");
1721
1722 default:
1723 AssertMsgFailed(("enmState=%d\n", enmState));
1724 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad state (H2D)");
1725 }
1726}
1727
1728
1729/**
1730 * Handle requests sent to the inbound (to host) bulk pipe.
1731 */
1732static int usbMsdHandleBulkDevToHost(PUSBMSD pThis, PUSBMSDEP pEp, PVUSBURB pUrb)
1733{
1734 /*
1735 * Stall the request if the pipe is halted OR if there is no
1736 * pending request yet.
1737 */
1738 PUSBMSDREQ pReq = pThis->pReq;
1739 if (RT_UNLIKELY(pEp->fHalted || !pReq))
1740 return usbMsdCompleteStall(pThis, NULL, pUrb, pEp->fHalted ? "Halted pipe" : "No request");
1741
1742 /*
1743 * Deal with the URB according to the state.
1744 */
1745 switch (pReq->enmState)
1746 {
1747 /*
1748 * We've data left to transfer to the host.
1749 */
1750 case USBMSDREQSTATE_DATA_TO_HOST:
1751 {
1752 uint32_t cbData = pUrb->cbData;
1753 uint32_t cbCopy = pReq->Cbw.dCBWDataTransferLength - pReq->offBuf;
1754 if (cbData <= cbCopy)
1755 cbCopy = cbData;
1756 else if (pUrb->fShortNotOk)
1757 {
1758 Log(("usbMsd: Requested more data that we've got; cbData=%#x offBuf=%#x dCBWDataTransferLength=%#x cbLeft=%#x\n",
1759 cbData, pReq->offBuf, pReq->Cbw.dCBWDataTransferLength, cbCopy));
1760 return usbMsdCompleteStall(pThis, NULL, pUrb, "Data underrun");
1761 }
1762 memcpy(&pUrb->abData[0], &pReq->pbBuf[pReq->offBuf], cbCopy);
1763 pReq->offBuf += cbCopy;
1764
1765 if (pReq->offBuf == pReq->Cbw.dCBWDataTransferLength)
1766 {
1767 Log(("usbMsdHandleBulkDevToHost: Entering STATUS\n"));
1768 pReq->enmState = USBMSDREQSTATE_STATUS;
1769 }
1770 return usbMsdCompleteOk(pThis, pUrb, cbCopy);
1771 }
1772
1773 /*
1774 * Status transfer.
1775 */
1776 case USBMSDREQSTATE_STATUS:
1777 {
1778 if ((pUrb->cbData < sizeof(USBCSW)) || (pUrb->cbData > sizeof(USBCSW) && pUrb->fShortNotOk))
1779 {
1780 Log(("usbMsd: Unexpected status request size: %#x (expected %#x), fShortNotOK=%RTbool\n", pUrb->cbData, sizeof(USBCSW), pUrb->fShortNotOk));
1781 return usbMsdCompleteStall(pThis, NULL, pUrb, "Invalid CSW size");
1782 }
1783
1784 /* Enter a CSW into the URB data buffer. */
1785 PUSBCSW pCsw = (PUSBCSW)&pUrb->abData[0];
1786 pCsw->dCSWSignature = USBCSW_SIGNATURE;
1787 pCsw->dCSWTag = pReq->Cbw.dCBWTag;
1788 pCsw->bCSWStatus = pReq->iScsiReqStatus == SCSI_STATUS_OK
1789 ? USBCSW_STATUS_OK
1790 : pReq->iScsiReqStatus < 0xff
1791 ? USBCSW_STATUS_FAILED
1792 : USBCSW_STATUS_PHASE_ERROR;
1793 /** @todo the following is not always accurate; VSCSI needs
1794 * to implement residual counts properly! */
1795 if ((pReq->Cbw.bmCBWFlags & USBCBW_DIR_MASK) == USBCBW_DIR_OUT)
1796 pCsw->dCSWDataResidue = pCsw->bCSWStatus == USBCSW_STATUS_OK
1797 ? 0
1798 : pReq->Cbw.dCBWDataTransferLength;
1799 else
1800 pCsw->dCSWDataResidue = pCsw->bCSWStatus == USBCSW_STATUS_OK
1801 ? 0
1802 : pReq->Cbw.dCBWDataTransferLength;
1803 Log(("usbMsd: CSW: dCSWTag=%#x bCSWStatus=%d dCSWDataResidue=%#x\n",
1804 pCsw->dCSWTag, pCsw->bCSWStatus, pCsw->dCSWDataResidue));
1805
1806 Log(("usbMsdHandleBulkDevToHost: Entering READY\n"));
1807 pReq->enmState = USBMSDREQSTATE_READY;
1808 return usbMsdCompleteOk(pThis, pUrb, sizeof(*pCsw));
1809 }
1810
1811 /*
1812 * Status request before we've received all (or even any) data.
1813 * Linux 2.4.31 does this sometimes. The recommended behavior is to
1814 * to accept the current data amount and execute the request. (The
1815 * alternative behavior is to stall.)
1816 */
1817 case USBMSDREQSTATE_DATA_FROM_HOST:
1818 {
1819 if (pUrb->cbData != sizeof(USBCSW))
1820 {
1821 Log(("usbMsdHandleBulkDevToHost: DATA_FROM_HOST; cbData=%#x -> stall\n", pUrb->cbData));
1822 return usbMsdCompleteStall(pThis, NULL, pUrb, "Invalid CSW size");
1823 }
1824
1825 int rc = usbMsdSubmitScsiCommand(pThis, pReq, "usbMsdHandleBulkDevToHost");
1826 if (RT_SUCCESS(rc) && rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
1827 usbMsdReqComplete(pThis, pReq, rc);
1828 else if (RT_FAILURE(rc))
1829 {
1830 Log(("usbMsd: Failed sending SCSI request to driver: %Rrc\n", rc));
1831 return usbMsdCompleteStall(pThis, NULL, pUrb, "SCSI Submit #3");
1832 }
1833 }
1834 RT_FALL_THRU();
1835
1836 /*
1837 * The SCSI command is still pending, queue the URB awaiting its
1838 * completion.
1839 */
1840 case USBMSDREQSTATE_EXECUTING:
1841 usbMsdQueueAddTail(&pThis->ToHostQueue, pUrb);
1842 LogFlow(("usbMsdHandleBulkDevToHost: Added %p:%s to the to-host queue\n", pUrb, pUrb->pszDesc));
1843 return VINF_SUCCESS;
1844
1845 /*
1846 * Bad states, stall.
1847 */
1848 case USBMSDREQSTATE_READY:
1849 Log(("usbMsdHandleBulkDevToHost: enmState=READ(%d) (cbData=%#x)\n", pReq->enmState, pUrb->cbData));
1850 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad state D2H: READY");
1851
1852 default:
1853 Log(("usbMsdHandleBulkDevToHost: enmState=%d cbData=%#x\n", pReq->enmState, pUrb->cbData));
1854 return usbMsdCompleteStall(pThis, NULL, pUrb, "Really bad state (D2H)!");
1855 }
1856}
1857
1858
1859/**
1860 * Handles request send to the default control pipe.
1861 */
1862static int usbMsdHandleDefaultPipe(PUSBMSD pThis, PUSBMSDEP pEp, PVUSBURB pUrb)
1863{
1864 PVUSBSETUP pSetup = (PVUSBSETUP)&pUrb->abData[0];
1865 AssertReturn(pUrb->cbData >= sizeof(*pSetup), VERR_VUSB_FAILED_TO_QUEUE_URB);
1866
1867 if ((pSetup->bmRequestType & VUSB_REQ_MASK) == VUSB_REQ_STANDARD)
1868 {
1869 switch (pSetup->bRequest)
1870 {
1871 case VUSB_REQ_GET_DESCRIPTOR:
1872 {
1873 if (pSetup->bmRequestType != (VUSB_TO_DEVICE | VUSB_REQ_STANDARD | VUSB_DIR_TO_HOST))
1874 {
1875 Log(("usbMsd: Bad GET_DESCRIPTOR req: bmRequestType=%#x\n", pSetup->bmRequestType));
1876 return usbMsdCompleteStall(pThis, pEp, pUrb, "Bad GET_DESCRIPTOR");
1877 }
1878
1879 switch (pSetup->wValue >> 8)
1880 {
1881 uint32_t cbCopy;
1882
1883 case VUSB_DT_STRING:
1884 Log(("usbMsd: GET_DESCRIPTOR DT_STRING wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1885 break;
1886 case VUSB_DT_DEVICE_QUALIFIER:
1887 Log(("usbMsd: GET_DESCRIPTOR DT_DEVICE_QUALIFIER wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1888 /* Returned data is written after the setup message. */
1889 cbCopy = pUrb->cbData - sizeof(*pSetup);
1890 cbCopy = RT_MIN(cbCopy, sizeof(g_UsbMsdDeviceQualifier));
1891 memcpy(&pUrb->abData[sizeof(*pSetup)], &g_UsbMsdDeviceQualifier, cbCopy);
1892 return usbMsdCompleteOk(pThis, pUrb, cbCopy + sizeof(*pSetup));
1893 case VUSB_DT_BOS:
1894 Log(("usbMsd: GET_DESCRIPTOR DT_BOS wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1895 /* Returned data is written after the setup message. */
1896 cbCopy = pUrb->cbData - sizeof(*pSetup);
1897 cbCopy = RT_MIN(cbCopy, sizeof(g_UsbMsdBOS));
1898 memcpy(&pUrb->abData[sizeof(*pSetup)], &g_UsbMsdBOS, cbCopy);
1899 return usbMsdCompleteOk(pThis, pUrb, cbCopy + sizeof(*pSetup));
1900 default:
1901 Log(("usbMsd: GET_DESCRIPTOR, huh? wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1902 break;
1903 }
1904 break;
1905 }
1906
1907 case VUSB_REQ_CLEAR_FEATURE:
1908 break;
1909 }
1910
1911 /** @todo implement this. */
1912 Log(("usbMsd: Implement standard request: bmRequestType=%#x bRequest=%#x wValue=%#x wIndex=%#x wLength=%#x\n",
1913 pSetup->bmRequestType, pSetup->bRequest, pSetup->wValue, pSetup->wIndex, pSetup->wLength));
1914
1915 usbMsdCompleteStall(pThis, pEp, pUrb, "TODO: standard request stuff");
1916 }
1917 /* 3.1 Bulk-Only Mass Storage Reset */
1918 else if ( pSetup->bmRequestType == (VUSB_REQ_CLASS | VUSB_TO_INTERFACE)
1919 && pSetup->bRequest == 0xff
1920 && !pSetup->wValue
1921 && !pSetup->wLength
1922 && pSetup->wIndex == 0)
1923 {
1924 Log(("usbMsdHandleDefaultPipe: Bulk-Only Mass Storage Reset\n"));
1925 return usbMsdResetWorker(pThis, pUrb, false /*fSetConfig*/);
1926 }
1927 /* 3.2 Get Max LUN, may stall if we like (but we don't). */
1928 else if ( pSetup->bmRequestType == (VUSB_REQ_CLASS | VUSB_TO_INTERFACE | VUSB_DIR_TO_HOST)
1929 && pSetup->bRequest == 0xfe
1930 && !pSetup->wValue
1931 && pSetup->wLength == 1
1932 && pSetup->wIndex == 0)
1933 {
1934 *(uint8_t *)(pSetup + 1) = 0; /* max lun is 0 */
1935 usbMsdCompleteOk(pThis, pUrb, 1);
1936 }
1937 else
1938 {
1939 Log(("usbMsd: Unknown control msg: bmRequestType=%#x bRequest=%#x wValue=%#x wIndex=%#x wLength=%#x\n",
1940 pSetup->bmRequestType, pSetup->bRequest, pSetup->wValue, pSetup->wIndex, pSetup->wLength));
1941 return usbMsdCompleteStall(pThis, pEp, pUrb, "Unknown control msg");
1942 }
1943
1944 return VINF_SUCCESS;
1945}
1946
1947
1948/**
1949 * @interface_method_impl{PDMUSBREG,pfnUrbQueue}
1950 */
1951static DECLCALLBACK(int) usbMsdQueue(PPDMUSBINS pUsbIns, PVUSBURB pUrb)
1952{
1953 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1954 LogFlow(("usbMsdQueue/#%u: pUrb=%p:%s EndPt=%#x\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc, pUrb->EndPt));
1955 RTCritSectEnter(&pThis->CritSect);
1956
1957 /*
1958 * Parse on a per end-point basis.
1959 */
1960 int rc;
1961 switch (pUrb->EndPt)
1962 {
1963 case 0:
1964 rc = usbMsdHandleDefaultPipe(pThis, &pThis->aEps[0], pUrb);
1965 break;
1966
1967 case 0x81:
1968 AssertFailed();
1969 RT_FALL_THRU();
1970 case 0x01:
1971 rc = usbMsdHandleBulkDevToHost(pThis, &pThis->aEps[1], pUrb);
1972 break;
1973
1974 case 0x02:
1975 rc = usbMsdHandleBulkHostToDev(pThis, &pThis->aEps[2], pUrb);
1976 break;
1977
1978 default:
1979 AssertMsgFailed(("EndPt=%d\n", pUrb->EndPt));
1980 rc = VERR_VUSB_FAILED_TO_QUEUE_URB;
1981 break;
1982 }
1983
1984 RTCritSectLeave(&pThis->CritSect);
1985 return rc;
1986}
1987
1988
1989/**
1990 * @interface_method_impl{PDMUSBREG,pfnUsbClearHaltedEndpoint}
1991 */
1992static DECLCALLBACK(int) usbMsdUsbClearHaltedEndpoint(PPDMUSBINS pUsbIns, unsigned uEndpoint)
1993{
1994 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1995 LogFlow(("usbMsdUsbClearHaltedEndpoint/#%u: uEndpoint=%#x\n", pUsbIns->iInstance, uEndpoint));
1996
1997 if ((uEndpoint & ~0x80) < RT_ELEMENTS(pThis->aEps))
1998 {
1999 RTCritSectEnter(&pThis->CritSect);
2000 pThis->aEps[(uEndpoint & ~0x80)].fHalted = false;
2001 RTCritSectLeave(&pThis->CritSect);
2002 }
2003
2004 return VINF_SUCCESS;
2005}
2006
2007
2008/**
2009 * @interface_method_impl{PDMUSBREG,pfnUsbSetInterface}
2010 */
2011static DECLCALLBACK(int) usbMsdUsbSetInterface(PPDMUSBINS pUsbIns, uint8_t bInterfaceNumber, uint8_t bAlternateSetting)
2012{
2013 RT_NOREF(pUsbIns, bInterfaceNumber, bAlternateSetting);
2014 LogFlow(("usbMsdUsbSetInterface/#%u: bInterfaceNumber=%u bAlternateSetting=%u\n", pUsbIns->iInstance, bInterfaceNumber, bAlternateSetting));
2015 Assert(bAlternateSetting == 0);
2016 return VINF_SUCCESS;
2017}
2018
2019
2020/**
2021 * @interface_method_impl{PDMUSBREG,pfnUsbSetConfiguration}
2022 */
2023static DECLCALLBACK(int) usbMsdUsbSetConfiguration(PPDMUSBINS pUsbIns, uint8_t bConfigurationValue,
2024 const void *pvOldCfgDesc, const void *pvOldIfState, const void *pvNewCfgDesc)
2025{
2026 RT_NOREF(pvOldCfgDesc, pvOldIfState, pvNewCfgDesc);
2027 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2028 LogFlow(("usbMsdUsbSetConfiguration/#%u: bConfigurationValue=%u\n", pUsbIns->iInstance, bConfigurationValue));
2029 Assert(bConfigurationValue == 1);
2030 RTCritSectEnter(&pThis->CritSect);
2031
2032 /*
2033 * If the same config is applied more than once, it's a kind of reset.
2034 */
2035 if (pThis->bConfigurationValue == bConfigurationValue)
2036 usbMsdResetWorker(pThis, NULL, true /*fSetConfig*/); /** @todo figure out the exact difference */
2037 pThis->bConfigurationValue = bConfigurationValue;
2038
2039 RTCritSectLeave(&pThis->CritSect);
2040 return VINF_SUCCESS;
2041}
2042
2043
2044/**
2045 * @interface_method_impl{PDMUSBREG,pfnUsbGetDescriptorCache}
2046 */
2047static DECLCALLBACK(PCPDMUSBDESCCACHE) usbMsdUsbGetDescriptorCache(PPDMUSBINS pUsbIns)
2048{
2049 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2050 LogFlow(("usbMsdUsbGetDescriptorCache/#%u:\n", pUsbIns->iInstance));
2051 if (pThis->pUsbIns->enmSpeed == VUSB_SPEED_SUPER)
2052 return pThis->fIsCdrom ? &g_UsbCdDescCacheSS : &g_UsbMsdDescCacheSS;
2053 else if (pThis->pUsbIns->enmSpeed == VUSB_SPEED_HIGH)
2054 return pThis->fIsCdrom ? &g_UsbCdDescCacheHS : &g_UsbMsdDescCacheHS;
2055 else
2056 return pThis->fIsCdrom ? &g_UsbCdDescCacheFS : &g_UsbMsdDescCacheFS;
2057}
2058
2059
2060/**
2061 * @interface_method_impl{PDMUSBREG,pfnUsbReset}
2062 */
2063static DECLCALLBACK(int) usbMsdUsbReset(PPDMUSBINS pUsbIns, bool fResetOnLinux)
2064{
2065 RT_NOREF(fResetOnLinux);
2066 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2067 LogFlow(("usbMsdUsbReset/#%u:\n", pUsbIns->iInstance));
2068 RTCritSectEnter(&pThis->CritSect);
2069
2070 int rc = usbMsdResetWorker(pThis, NULL, false /*fSetConfig*/);
2071
2072 RTCritSectLeave(&pThis->CritSect);
2073 return rc;
2074}
2075
2076
2077/**
2078 * @interface_method_impl{PDMUSBREG,pfnVMSuspend}
2079 */
2080static DECLCALLBACK(void) usbMsdVMSuspend(PPDMUSBINS pUsbIns)
2081{
2082 LogFlow(("usbMsdVMSuspend/#%u:\n", pUsbIns->iInstance));
2083 usbMsdSuspendOrPowerOff(pUsbIns);
2084}
2085
2086
2087/**
2088 * @interface_method_impl{PDMUSBREG,pfnVMSuspend}
2089 */
2090static DECLCALLBACK(void) usbMsdVMPowerOff(PPDMUSBINS pUsbIns)
2091{
2092 LogFlow(("usbMsdVMPowerOff/#%u:\n", pUsbIns->iInstance));
2093 usbMsdSuspendOrPowerOff(pUsbIns);
2094}
2095
2096
2097/**
2098 * @interface_method_impl{PDMUSBREG,pfnDriverAttach}
2099 */
2100static DECLCALLBACK(int) usbMsdDriverAttach(PPDMUSBINS pUsbIns, unsigned iLUN, uint32_t fFlags)
2101{
2102 RT_NOREF(fFlags);
2103 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2104
2105 LogFlow(("usbMsdDriverAttach/#%u:\n", pUsbIns->iInstance));
2106
2107 AssertMsg(iLUN == 0, ("UsbMsd: No other LUN than 0 is supported\n"));
2108 AssertMsg(fFlags & PDM_TACH_FLAGS_NOT_HOT_PLUG,
2109 ("UsbMsd: Device does not support hotplugging\n"));
2110
2111 /* the usual paranoia */
2112 AssertRelease(!pThis->Lun0.pIBase);
2113 AssertRelease(!pThis->Lun0.pIMedia);
2114 AssertRelease(!pThis->Lun0.pIMediaEx);
2115
2116 /*
2117 * Try attach the block device and get the interfaces,
2118 * required as well as optional.
2119 */
2120 int rc = PDMUsbHlpDriverAttach(pUsbIns, iLUN, &pThis->Lun0.IBase, &pThis->Lun0.pIBase, NULL);
2121 if (RT_SUCCESS(rc))
2122 {
2123 /* Get media and extended media interface. */
2124 pThis->Lun0.pIMedia = PDMIBASE_QUERY_INTERFACE(pThis->Lun0.pIBase, PDMIMEDIA);
2125 AssertMsgReturn(pThis->Lun0.pIMedia, ("Missing media interface below\n"), VERR_PDM_MISSING_INTERFACE);
2126 pThis->Lun0.pIMediaEx = PDMIBASE_QUERY_INTERFACE(pThis->Lun0.pIBase, PDMIMEDIAEX);
2127 AssertMsgReturn(pThis->Lun0.pIMediaEx, ("Missing extended media interface below\n"), VERR_PDM_MISSING_INTERFACE);
2128
2129 rc = pThis->Lun0.pIMediaEx->pfnIoReqAllocSizeSet(pThis->Lun0.pIMediaEx, sizeof(USBMSDREQ));
2130 AssertMsgRCReturn(rc, ("MSD failed to set I/O request size!\n"), VERR_PDM_MISSING_INTERFACE);
2131 }
2132 else
2133 AssertMsgFailed(("Failed to attach LUN#%d. rc=%Rrc\n", iLUN, rc));
2134
2135 if (RT_FAILURE(rc))
2136 {
2137 pThis->Lun0.pIBase = NULL;
2138 pThis->Lun0.pIMedia = NULL;
2139 pThis->Lun0.pIMediaEx = NULL;
2140 }
2141
2142 pThis->fIsCdrom = false;
2143 PDMMEDIATYPE enmType = pThis->Lun0.pIMedia->pfnGetType(pThis->Lun0.pIMedia);
2144 /* Anything else will be reported as a hard disk. */
2145 if (enmType == PDMMEDIATYPE_CDROM || enmType == PDMMEDIATYPE_DVD)
2146 pThis->fIsCdrom = true;
2147
2148 return rc;
2149}
2150
2151
2152/**
2153 * @interface_method_impl{PDMUSBREG,pfnDriverDetach}
2154 */
2155static DECLCALLBACK(void) usbMsdDriverDetach(PPDMUSBINS pUsbIns, unsigned iLUN, uint32_t fFlags)
2156{
2157 RT_NOREF(iLUN, fFlags);
2158 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2159
2160 LogFlow(("usbMsdDriverDetach/#%u:\n", pUsbIns->iInstance));
2161
2162 AssertMsg(iLUN == 0, ("UsbMsd: No other LUN than 0 is supported\n"));
2163 AssertMsg(fFlags & PDM_TACH_FLAGS_NOT_HOT_PLUG,
2164 ("UsbMsd: Device does not support hotplugging\n"));
2165
2166 if (pThis->pReq)
2167 {
2168 usbMsdReqFree(pThis, pThis->pReq);
2169 pThis->pReq = NULL;
2170 }
2171
2172 /*
2173 * Zero some important members.
2174 */
2175 pThis->Lun0.pIBase = NULL;
2176 pThis->Lun0.pIMedia = NULL;
2177 pThis->Lun0.pIMediaEx = NULL;
2178}
2179
2180
2181/**
2182 * @callback_method_impl{FNPDMDEVASYNCNOTIFY,
2183 * Callback employed by usbMsdVMReset.}
2184 */
2185static DECLCALLBACK(bool) usbMsdIsAsyncResetDone(PPDMUSBINS pUsbIns)
2186{
2187 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2188
2189 if (!usbMsdAllAsyncIOIsFinished(pUsbIns))
2190 return false;
2191 ASMAtomicWriteBool(&pThis->fSignalIdle, false);
2192
2193 int rc = usbMsdResetWorker(pThis, NULL, false /*fSetConfig*/);
2194 AssertRC(rc);
2195 return true;
2196}
2197
2198/**
2199 * @interface_method_impl{PDMDEVREG,pfnReset}
2200 */
2201static DECLCALLBACK(void) usbMsdVMReset(PPDMUSBINS pUsbIns)
2202{
2203 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2204
2205 ASMAtomicWriteBool(&pThis->fSignalIdle, true);
2206 if (!usbMsdAllAsyncIOIsFinished(pUsbIns))
2207 PDMUsbHlpSetAsyncNotification(pUsbIns, usbMsdIsAsyncResetDone);
2208 else
2209 {
2210 ASMAtomicWriteBool(&pThis->fSignalIdle, false);
2211 int rc = usbMsdResetWorker(pThis, NULL, false /*fSetConfig*/);
2212 AssertRC(rc);
2213 }
2214}
2215
2216
2217/**
2218 * @interface_method_impl{PDMUSBREG,pfnDestruct}
2219 */
2220static DECLCALLBACK(void) usbMsdDestruct(PPDMUSBINS pUsbIns)
2221{
2222 PDMUSB_CHECK_VERSIONS_RETURN_VOID(pUsbIns);
2223 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2224 LogFlow(("usbMsdDestruct/#%u:\n", pUsbIns->iInstance));
2225
2226 if (RTCritSectIsInitialized(&pThis->CritSect))
2227 {
2228 RTCritSectEnter(&pThis->CritSect);
2229 RTCritSectLeave(&pThis->CritSect);
2230 RTCritSectDelete(&pThis->CritSect);
2231 }
2232
2233 if (pThis->hEvtDoneQueue != NIL_RTSEMEVENT)
2234 {
2235 RTSemEventDestroy(pThis->hEvtDoneQueue);
2236 pThis->hEvtDoneQueue = NIL_RTSEMEVENT;
2237 }
2238
2239 if (pThis->hEvtReset != NIL_RTSEMEVENTMULTI)
2240 {
2241 RTSemEventMultiDestroy(pThis->hEvtReset);
2242 pThis->hEvtReset = NIL_RTSEMEVENTMULTI;
2243 }
2244}
2245
2246
2247/**
2248 * @interface_method_impl{PDMUSBREG,pfnConstruct}
2249 */
2250static DECLCALLBACK(int) usbMsdConstruct(PPDMUSBINS pUsbIns, int iInstance, PCFGMNODE pCfg, PCFGMNODE pCfgGlobal)
2251{
2252 RT_NOREF(pCfgGlobal);
2253 PDMUSB_CHECK_VERSIONS_RETURN(pUsbIns);
2254 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2255 Log(("usbMsdConstruct/#%u:\n", iInstance));
2256
2257 /*
2258 * Perform the basic structure initialization first so the destructor
2259 * will not misbehave.
2260 */
2261 pThis->pUsbIns = pUsbIns;
2262 pThis->hEvtDoneQueue = NIL_RTSEMEVENT;
2263 pThis->hEvtReset = NIL_RTSEMEVENTMULTI;
2264 pThis->Lun0.IBase.pfnQueryInterface = usbMsdLun0QueryInterface;
2265 pThis->Lun0.IMediaPort.pfnQueryDeviceLocation = usbMsdLun0QueryDeviceLocation;
2266 pThis->Lun0.IMediaExPort.pfnIoReqCompleteNotify = usbMsdLun0IoReqCompleteNotify;
2267 pThis->Lun0.IMediaExPort.pfnIoReqCopyFromBuf = usbMsdLun0IoReqCopyFromBuf;
2268 pThis->Lun0.IMediaExPort.pfnIoReqCopyToBuf = usbMsdLun0IoReqCopyToBuf;
2269 pThis->Lun0.IMediaExPort.pfnIoReqQueryDiscardRanges = NULL;
2270 pThis->Lun0.IMediaExPort.pfnIoReqStateChanged = usbMsdLun0IoReqStateChanged;
2271 pThis->Lun0.IMediaExPort.pfnMediumEjected = usbMsdLun0MediumEjected;
2272 usbMsdQueueInit(&pThis->ToHostQueue);
2273 usbMsdQueueInit(&pThis->DoneQueue);
2274
2275 int rc = RTCritSectInit(&pThis->CritSect);
2276 AssertRCReturn(rc, rc);
2277
2278 rc = RTSemEventCreate(&pThis->hEvtDoneQueue);
2279 AssertRCReturn(rc, rc);
2280
2281 rc = RTSemEventMultiCreate(&pThis->hEvtReset);
2282 AssertRCReturn(rc, rc);
2283
2284 /*
2285 * Validate and read the configuration.
2286 */
2287 rc = CFGMR3ValidateConfig(pCfg, "/", "", "", "UsbMsd", iInstance);
2288 if (RT_FAILURE(rc))
2289 return rc;
2290
2291 /*
2292 * Attach the SCSI driver.
2293 */
2294 rc = PDMUsbHlpDriverAttach(pUsbIns, 0 /*iLun*/, &pThis->Lun0.IBase, &pThis->Lun0.pIBase, "SCSI Port");
2295 if (RT_FAILURE(rc))
2296 return PDMUsbHlpVMSetError(pUsbIns, rc, RT_SRC_POS, N_("MSD failed to attach SCSI driver"));
2297 pThis->Lun0.pIMedia = PDMIBASE_QUERY_INTERFACE(pThis->Lun0.pIBase, PDMIMEDIA);
2298 if (!pThis->Lun0.pIMedia)
2299 return PDMUsbHlpVMSetError(pUsbIns, VERR_PDM_MISSING_INTERFACE_BELOW, RT_SRC_POS,
2300 N_("MSD failed to query the PDMIMEDIA from the driver below it"));
2301 pThis->Lun0.pIMediaEx = PDMIBASE_QUERY_INTERFACE(pThis->Lun0.pIBase, PDMIMEDIAEX);
2302 if (!pThis->Lun0.pIMediaEx)
2303 return PDMUsbHlpVMSetError(pUsbIns, VERR_PDM_MISSING_INTERFACE_BELOW, RT_SRC_POS,
2304 N_("MSD failed to query the PDMIMEDIAEX from the driver below it"));
2305
2306 /*
2307 * Find out what kind of device we are.
2308 */
2309 pThis->fIsCdrom = false;
2310 PDMMEDIATYPE enmType = pThis->Lun0.pIMedia->pfnGetType(pThis->Lun0.pIMedia);
2311 /* Anything else will be reported as a hard disk. */
2312 if (enmType == PDMMEDIATYPE_CDROM || enmType == PDMMEDIATYPE_DVD)
2313 pThis->fIsCdrom = true;
2314
2315 rc = pThis->Lun0.pIMediaEx->pfnIoReqAllocSizeSet(pThis->Lun0.pIMediaEx, sizeof(USBMSDREQ));
2316 if (RT_FAILURE(rc))
2317 return PDMUsbHlpVMSetError(pUsbIns, rc, RT_SRC_POS, N_("MSD failed to set I/O request size!"));
2318
2319 /*
2320 * Register the saved state data unit.
2321 */
2322 rc = PDMUsbHlpSSMRegister(pUsbIns, USB_MSD_SAVED_STATE_VERSION, sizeof(*pThis),
2323 NULL, usbMsdLiveExec, NULL,
2324 usbMsdSavePrep, usbMsdSaveExec, NULL,
2325 usbMsdLoadPrep, usbMsdLoadExec, NULL);
2326 if (RT_FAILURE(rc))
2327 return PDMUsbHlpVMSetError(pUsbIns, rc, RT_SRC_POS,
2328 N_("MSD failed to register SSM save state handlers"));
2329
2330 return VINF_SUCCESS;
2331}
2332
2333
2334/**
2335 * The USB Mass Storage Device (MSD) registration record.
2336 */
2337const PDMUSBREG g_UsbMsd =
2338{
2339 /* u32Version */
2340 PDM_USBREG_VERSION,
2341 /* szName */
2342 "Msd",
2343 /* pszDescription */
2344 "USB Mass Storage Device, one LUN.",
2345 /* fFlags */
2346 PDM_USBREG_HIGHSPEED_CAPABLE | PDM_USBREG_SUPERSPEED_CAPABLE
2347 | PDM_USBREG_SAVED_STATE_SUPPORTED,
2348 /* cMaxInstances */
2349 ~0U,
2350 /* cbInstance */
2351 sizeof(USBMSD),
2352 /* pfnConstruct */
2353 usbMsdConstruct,
2354 /* pfnDestruct */
2355 usbMsdDestruct,
2356 /* pfnVMInitComplete */
2357 NULL,
2358 /* pfnVMPowerOn */
2359 NULL,
2360 /* pfnVMReset */
2361 usbMsdVMReset,
2362 /* pfnVMSuspend */
2363 usbMsdVMSuspend,
2364 /* pfnVMResume */
2365 NULL,
2366 /* pfnVMPowerOff */
2367 usbMsdVMPowerOff,
2368 /* pfnHotPlugged */
2369 NULL,
2370 /* pfnHotUnplugged */
2371 NULL,
2372 /* pfnDriverAttach */
2373 usbMsdDriverAttach,
2374 /* pfnDriverDetach */
2375 usbMsdDriverDetach,
2376 /* pfnQueryInterface */
2377 NULL,
2378 /* pfnUsbReset */
2379 usbMsdUsbReset,
2380 /* pfnUsbGetCachedDescriptors */
2381 usbMsdUsbGetDescriptorCache,
2382 /* pfnUsbSetConfiguration */
2383 usbMsdUsbSetConfiguration,
2384 /* pfnUsbSetInterface */
2385 usbMsdUsbSetInterface,
2386 /* pfnUsbClearHaltedEndpoint */
2387 usbMsdUsbClearHaltedEndpoint,
2388 /* pfnUrbNew */
2389 NULL/*usbMsdUrbNew*/,
2390 /* pfnQueue */
2391 usbMsdQueue,
2392 /* pfnUrbCancel */
2393 usbMsdUrbCancel,
2394 /* pfnUrbReap */
2395 usbMsdUrbReap,
2396 /* pfnWakeup */
2397 usbMsdWakeup,
2398 /* u32TheEnd */
2399 PDM_USBREG_VERSION
2400};
2401
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