VirtualBox

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

Last change on this file since 84389 was 82968, checked in by vboxsync, 5 years ago

Copyright year updates by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 80.8 KB
Line 
1/* $Id: UsbMsd.cpp 82968 2020-02-04 10:35:17Z vboxsync $ */
2/** @file
3 * UsbMSD - USB Mass Storage Device Emulation.
4 */
5
6/*
7 * Copyright (C) 2007-2020 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 AssertCompile(sizeof(pReq->enmState) == sizeof(uint32_t));
1434 SSMR3GetU32(pSSM, (uint32_t *)&pReq->enmState);
1435
1436 uint32_t cbBuf = 0;
1437 rc = SSMR3GetU32(pSSM, &cbBuf);
1438 AssertRCReturn(rc, rc);
1439 if (cbBuf)
1440 {
1441 if (usbMsdReqEnsureBuffer(pThis, pReq, cbBuf))
1442 {
1443 AssertPtr(pReq->pbBuf);
1444 Assert(cbBuf == pReq->cbBuf);
1445 SSMR3GetMem(pSSM, pReq->pbBuf, pReq->cbBuf);
1446 }
1447 else
1448 return VERR_NO_MEMORY;
1449 }
1450
1451 SSMR3GetU32(pSSM, &pReq->offBuf);
1452 SSMR3GetMem(pSSM, &pReq->Cbw, sizeof(pReq->Cbw));
1453
1454 if (uVersion > USB_MSD_SAVED_STATE_VERSION_PRE_CLEANUP)
1455 rc = SSMR3GetU8(pSSM, &pReq->iScsiReqStatus);
1456 else
1457 {
1458 int32_t iScsiReqStatus;
1459
1460 /* Skip old fields which are unused now or can be determined from the CBW. */
1461 SSMR3Skip(pSSM, 4 * 4 + 64);
1462 rc = SSMR3GetS32(pSSM, &iScsiReqStatus);
1463 pReq->iScsiReqStatus = (uint8_t)iScsiReqStatus;
1464 }
1465 AssertRCReturn(rc, rc);
1466 }
1467
1468 rc = SSMR3GetU32(pSSM, &u32);
1469 AssertRCReturn(rc, rc);
1470 AssertMsgReturn(u32 == UINT32_MAX, ("%#x\n", u32), VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
1471 }
1472
1473 return VINF_SUCCESS;
1474}
1475
1476
1477/**
1478 * @interface_method_impl{PDMUSBREG,pfnUrbReap}
1479 */
1480static DECLCALLBACK(PVUSBURB) usbMsdUrbReap(PPDMUSBINS pUsbIns, RTMSINTERVAL cMillies)
1481{
1482 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1483 LogFlow(("usbMsdUrbReap/#%u: cMillies=%u\n", pUsbIns->iInstance, cMillies));
1484
1485 RTCritSectEnter(&pThis->CritSect);
1486
1487 PVUSBURB pUrb = usbMsdQueueRemoveHead(&pThis->DoneQueue);
1488 if (!pUrb && cMillies)
1489 {
1490 /* Wait */
1491 pThis->fHaveDoneQueueWaiter = true;
1492 RTCritSectLeave(&pThis->CritSect);
1493
1494 RTSemEventWait(pThis->hEvtDoneQueue, cMillies);
1495
1496 RTCritSectEnter(&pThis->CritSect);
1497 pThis->fHaveDoneQueueWaiter = false;
1498
1499 pUrb = usbMsdQueueRemoveHead(&pThis->DoneQueue);
1500 }
1501
1502 RTCritSectLeave(&pThis->CritSect);
1503
1504 if (pUrb)
1505 Log(("usbMsdUrbReap/#%u: pUrb=%p:%s\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc));
1506 return pUrb;
1507}
1508
1509
1510/**
1511 * @interface_method_impl{PDMUSBREG,pfnWakeup}
1512 */
1513static DECLCALLBACK(int) usbMsdWakeup(PPDMUSBINS pUsbIns)
1514{
1515 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1516 LogFlow(("usbMsdUrbReap/#%u:\n", pUsbIns->iInstance));
1517
1518 return RTSemEventSignal(pThis->hEvtDoneQueue);
1519}
1520
1521
1522/**
1523 * @interface_method_impl{PDMUSBREG,pfnUrbCancel}
1524 */
1525static DECLCALLBACK(int) usbMsdUrbCancel(PPDMUSBINS pUsbIns, PVUSBURB pUrb)
1526{
1527 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1528 LogFlow(("usbMsdUrbCancel/#%u: pUrb=%p:%s\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc));
1529 RTCritSectEnter(&pThis->CritSect);
1530
1531 /*
1532 * Remove the URB from the to-host queue and move it onto the done queue.
1533 */
1534 if (usbMsdQueueRemove(&pThis->ToHostQueue, pUrb))
1535 usbMsdLinkDone(pThis, pUrb);
1536
1537 RTCritSectLeave(&pThis->CritSect);
1538 return VINF_SUCCESS;
1539}
1540
1541
1542/**
1543 * Wrapper around PDMISCSICONNECTOR::pfnSCSIRequestSend that deals with
1544 * SCSI_REQUEST_SENSE.
1545 *
1546 * @returns VBox status code.
1547 * @param pThis The MSD instance data.
1548 * @param pReq The MSD request.
1549 * @param pszCaller Where we're called from.
1550 */
1551static int usbMsdSubmitScsiCommand(PUSBMSD pThis, PUSBMSDREQ pReq, const char *pszCaller)
1552{
1553 RT_NOREF(pszCaller);
1554 Log(("%s: Entering EXECUTING (dCBWTag=%#x).\n", pszCaller, pReq->Cbw.dCBWTag));
1555 Assert(pReq == pThis->pReq);
1556 pReq->enmState = USBMSDREQSTATE_EXECUTING;
1557
1558 PDMMEDIAEXIOREQSCSITXDIR enmTxDir = pReq->Cbw.dCBWDataTransferLength == 0
1559 ? PDMMEDIAEXIOREQSCSITXDIR_NONE
1560 : (pReq->Cbw.bmCBWFlags & USBCBW_DIR_MASK) == USBCBW_DIR_OUT
1561 ? PDMMEDIAEXIOREQSCSITXDIR_TO_DEVICE
1562 : PDMMEDIAEXIOREQSCSITXDIR_FROM_DEVICE;
1563
1564 return pThis->Lun0.pIMediaEx->pfnIoReqSendScsiCmd(pThis->Lun0.pIMediaEx, pReq->hIoReq, pReq->Cbw.bCBWLun,
1565 &pReq->Cbw.CBWCB[0], pReq->Cbw.bCBWCBLength, enmTxDir, NULL,
1566 pReq->Cbw.dCBWDataTransferLength, NULL, 0, NULL,
1567 &pReq->iScsiReqStatus, 20 * RT_MS_1SEC);
1568}
1569
1570
1571/**
1572 * Handle requests sent to the outbound (to device) bulk pipe.
1573 */
1574static int usbMsdHandleBulkHostToDev(PUSBMSD pThis, PUSBMSDEP pEp, PVUSBURB pUrb)
1575{
1576 /*
1577 * Stall the request if the pipe is halted.
1578 */
1579 if (RT_UNLIKELY(pEp->fHalted))
1580 return usbMsdCompleteStall(pThis, NULL, pUrb, "Halted pipe");
1581
1582 /*
1583 * Deal with the URB according to the current state.
1584 */
1585 PUSBMSDREQ pReq = pThis->pReq;
1586 USBMSDREQSTATE enmState = pReq ? pReq->enmState : USBMSDREQSTATE_READY;
1587 switch (enmState)
1588 {
1589 case USBMSDREQSTATE_STATUS:
1590 LogFlow(("usbMsdHandleBulkHostToDev: Skipping pending status.\n"));
1591 pReq->enmState = USBMSDREQSTATE_READY;
1592 RT_FALL_THRU();
1593
1594 /*
1595 * We're ready to receive a command. Start off by validating the
1596 * incoming request.
1597 */
1598 case USBMSDREQSTATE_READY:
1599 {
1600 PCUSBCBW pCbw = (PUSBCBW)&pUrb->abData[0];
1601 if (pUrb->cbData < RT_UOFFSETOF(USBCBW, CBWCB[1]))
1602 {
1603 Log(("usbMsd: Bad CBW: cbData=%#x < min=%#x\n", pUrb->cbData, RT_UOFFSETOF(USBCBW, CBWCB[1]) ));
1604 return usbMsdCompleteStall(pThis, NULL, pUrb, "BAD CBW");
1605 }
1606 if (pCbw->dCBWSignature != USBCBW_SIGNATURE)
1607 {
1608 Log(("usbMsd: CBW: Invalid dCBWSignature value: %#x\n", pCbw->dCBWSignature));
1609 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1610 }
1611 Log(("usbMsd: CBW: dCBWTag=%#x dCBWDataTransferLength=%#x bmCBWFlags=%#x bCBWLun=%#x bCBWCBLength=%#x cbData=%#x fShortNotOk=%RTbool\n",
1612 pCbw->dCBWTag, pCbw->dCBWDataTransferLength, pCbw->bmCBWFlags, pCbw->bCBWLun, pCbw->bCBWCBLength, pUrb->cbData, pUrb->fShortNotOk));
1613 if (pCbw->bmCBWFlags & ~USBCBW_DIR_MASK)
1614 {
1615 Log(("usbMsd: CBW: Bad bmCBWFlags value: %#x\n", pCbw->bmCBWFlags));
1616 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1617
1618 }
1619 if (pCbw->bCBWLun != 0)
1620 {
1621 Log(("usbMsd: CBW: Bad bCBWLun value: %#x\n", pCbw->bCBWLun));
1622 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1623 }
1624 if (pCbw->bCBWCBLength == 0)
1625 {
1626 Log(("usbMsd: CBW: Bad bCBWCBLength value: %#x\n", pCbw->bCBWCBLength));
1627 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1628 }
1629 if (pUrb->cbData < RT_UOFFSETOF_DYN(USBCBW, CBWCB[pCbw->bCBWCBLength]))
1630 {
1631 Log(("usbMsd: CBW: Mismatching cbData and bCBWCBLength values: %#x vs. %#x (%#x)\n",
1632 pUrb->cbData, RT_UOFFSETOF_DYN(USBCBW, CBWCB[pCbw->bCBWCBLength]), pCbw->bCBWCBLength));
1633 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1634 }
1635 if (pCbw->dCBWDataTransferLength > _1M)
1636 {
1637 Log(("usbMsd: CBW: dCBWDataTransferLength is too large: %#x (%u)\n",
1638 pCbw->dCBWDataTransferLength, pCbw->dCBWDataTransferLength));
1639 return usbMsdCompleteStall(pThis, NULL, pUrb, "Too big transfer");
1640 }
1641
1642 /*
1643 * Make sure we've got a request and a sufficient buffer space.
1644 *
1645 * Note! This will make sure the buffer is ZERO as well, thus
1646 * saving us the trouble of clearing the output buffer on
1647 * failure later.
1648 */
1649 if (!pReq)
1650 {
1651 pReq = usbMsdReqAlloc(pThis);
1652 if (!pReq)
1653 return usbMsdCompleteStall(pThis, NULL, pUrb, "Request allocation failure");
1654 pThis->pReq = pReq;
1655 }
1656 if (!usbMsdReqEnsureBuffer(pThis, pReq, pCbw->dCBWDataTransferLength))
1657 return usbMsdCompleteStall(pThis, NULL, pUrb, "Buffer allocation failure");
1658
1659 /*
1660 * Prepare the request. Kick it off right away if possible.
1661 */
1662 usbMsdReqPrepare(pReq, pCbw);
1663
1664 if ( pReq->Cbw.dCBWDataTransferLength == 0
1665 || (pReq->Cbw.bmCBWFlags & USBCBW_DIR_MASK) == USBCBW_DIR_IN)
1666 {
1667 int rc = usbMsdSubmitScsiCommand(pThis, pReq, "usbMsdHandleBulkHostToDev");
1668 if (RT_SUCCESS(rc) && rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
1669 usbMsdReqComplete(pThis, pReq, rc);
1670 else if (RT_FAILURE(rc))
1671 {
1672 Log(("usbMsd: Failed sending SCSI request to driver: %Rrc\n", rc));
1673 return usbMsdCompleteStall(pThis, NULL, pUrb, "SCSI Submit #1");
1674 }
1675 }
1676 else
1677 {
1678 Log(("usbMsdHandleBulkHostToDev: Entering DATA_FROM_HOST.\n"));
1679 pReq->enmState = USBMSDREQSTATE_DATA_FROM_HOST;
1680 }
1681
1682 return usbMsdCompleteOk(pThis, pUrb, pUrb->cbData);
1683 }
1684
1685 /*
1686 * Stuff the data into the buffer.
1687 */
1688 case USBMSDREQSTATE_DATA_FROM_HOST:
1689 {
1690 uint32_t cbData = pUrb->cbData;
1691 uint32_t cbLeft = pReq->Cbw.dCBWDataTransferLength - pReq->offBuf;
1692 if (cbData > cbLeft)
1693 {
1694 Log(("usbMsd: Too much data: cbData=%#x offBuf=%#x dCBWDataTransferLength=%#x cbLeft=%#x\n",
1695 cbData, pReq->offBuf, pReq->Cbw.dCBWDataTransferLength, cbLeft));
1696 return usbMsdCompleteStall(pThis, NULL, pUrb, "Too much data");
1697 }
1698 memcpy(&pReq->pbBuf[pReq->offBuf], &pUrb->abData[0], cbData);
1699 pReq->offBuf += cbData;
1700
1701 if (pReq->offBuf == pReq->Cbw.dCBWDataTransferLength)
1702 {
1703 int rc = usbMsdSubmitScsiCommand(pThis, pReq, "usbMsdHandleBulkHostToDev");
1704 if (RT_SUCCESS(rc) && rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
1705 usbMsdReqComplete(pThis, pReq, rc);
1706 else if (RT_FAILURE(rc))
1707 {
1708 Log(("usbMsd: Failed sending SCSI request to driver: %Rrc\n", rc));
1709 return usbMsdCompleteStall(pThis, NULL, pUrb, "SCSI Submit #2");
1710 }
1711 }
1712 return usbMsdCompleteOk(pThis, pUrb, cbData);
1713 }
1714
1715 /*
1716 * Bad state, stall.
1717 */
1718 case USBMSDREQSTATE_DATA_TO_HOST:
1719 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad state H2D: DATA_TO_HOST");
1720
1721 case USBMSDREQSTATE_EXECUTING:
1722 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad state H2D: EXECUTING");
1723
1724 default:
1725 AssertMsgFailed(("enmState=%d\n", enmState));
1726 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad state (H2D)");
1727 }
1728}
1729
1730
1731/**
1732 * Handle requests sent to the inbound (to host) bulk pipe.
1733 */
1734static int usbMsdHandleBulkDevToHost(PUSBMSD pThis, PUSBMSDEP pEp, PVUSBURB pUrb)
1735{
1736 /*
1737 * Stall the request if the pipe is halted OR if there is no
1738 * pending request yet.
1739 */
1740 PUSBMSDREQ pReq = pThis->pReq;
1741 if (RT_UNLIKELY(pEp->fHalted || !pReq))
1742 return usbMsdCompleteStall(pThis, NULL, pUrb, pEp->fHalted ? "Halted pipe" : "No request");
1743
1744 /*
1745 * Deal with the URB according to the state.
1746 */
1747 switch (pReq->enmState)
1748 {
1749 /*
1750 * We've data left to transfer to the host.
1751 */
1752 case USBMSDREQSTATE_DATA_TO_HOST:
1753 {
1754 uint32_t cbData = pUrb->cbData;
1755 uint32_t cbCopy = pReq->Cbw.dCBWDataTransferLength - pReq->offBuf;
1756 if (cbData <= cbCopy)
1757 cbCopy = cbData;
1758 else if (pUrb->fShortNotOk)
1759 {
1760 Log(("usbMsd: Requested more data that we've got; cbData=%#x offBuf=%#x dCBWDataTransferLength=%#x cbLeft=%#x\n",
1761 cbData, pReq->offBuf, pReq->Cbw.dCBWDataTransferLength, cbCopy));
1762 return usbMsdCompleteStall(pThis, NULL, pUrb, "Data underrun");
1763 }
1764 memcpy(&pUrb->abData[0], &pReq->pbBuf[pReq->offBuf], cbCopy);
1765 pReq->offBuf += cbCopy;
1766
1767 if (pReq->offBuf == pReq->Cbw.dCBWDataTransferLength)
1768 {
1769 Log(("usbMsdHandleBulkDevToHost: Entering STATUS\n"));
1770 pReq->enmState = USBMSDREQSTATE_STATUS;
1771 }
1772 return usbMsdCompleteOk(pThis, pUrb, cbCopy);
1773 }
1774
1775 /*
1776 * Status transfer.
1777 */
1778 case USBMSDREQSTATE_STATUS:
1779 {
1780 if ((pUrb->cbData < sizeof(USBCSW)) || (pUrb->cbData > sizeof(USBCSW) && pUrb->fShortNotOk))
1781 {
1782 Log(("usbMsd: Unexpected status request size: %#x (expected %#x), fShortNotOK=%RTbool\n", pUrb->cbData, sizeof(USBCSW), pUrb->fShortNotOk));
1783 return usbMsdCompleteStall(pThis, NULL, pUrb, "Invalid CSW size");
1784 }
1785
1786 /* Enter a CSW into the URB data buffer. */
1787 PUSBCSW pCsw = (PUSBCSW)&pUrb->abData[0];
1788 pCsw->dCSWSignature = USBCSW_SIGNATURE;
1789 pCsw->dCSWTag = pReq->Cbw.dCBWTag;
1790 pCsw->bCSWStatus = pReq->iScsiReqStatus == SCSI_STATUS_OK
1791 ? USBCSW_STATUS_OK
1792 : pReq->iScsiReqStatus < 0xff
1793 ? USBCSW_STATUS_FAILED
1794 : USBCSW_STATUS_PHASE_ERROR;
1795 /** @todo the following is not always accurate; VSCSI needs
1796 * to implement residual counts properly! */
1797 if ((pReq->Cbw.bmCBWFlags & USBCBW_DIR_MASK) == USBCBW_DIR_OUT)
1798 pCsw->dCSWDataResidue = pCsw->bCSWStatus == USBCSW_STATUS_OK
1799 ? 0
1800 : pReq->Cbw.dCBWDataTransferLength;
1801 else
1802 pCsw->dCSWDataResidue = pCsw->bCSWStatus == USBCSW_STATUS_OK
1803 ? 0
1804 : pReq->Cbw.dCBWDataTransferLength;
1805 Log(("usbMsd: CSW: dCSWTag=%#x bCSWStatus=%d dCSWDataResidue=%#x\n",
1806 pCsw->dCSWTag, pCsw->bCSWStatus, pCsw->dCSWDataResidue));
1807
1808 Log(("usbMsdHandleBulkDevToHost: Entering READY\n"));
1809 pReq->enmState = USBMSDREQSTATE_READY;
1810 return usbMsdCompleteOk(pThis, pUrb, sizeof(*pCsw));
1811 }
1812
1813 /*
1814 * Status request before we've received all (or even any) data.
1815 * Linux 2.4.31 does this sometimes. The recommended behavior is to
1816 * to accept the current data amount and execute the request. (The
1817 * alternative behavior is to stall.)
1818 */
1819 case USBMSDREQSTATE_DATA_FROM_HOST:
1820 {
1821 if (pUrb->cbData != sizeof(USBCSW))
1822 {
1823 Log(("usbMsdHandleBulkDevToHost: DATA_FROM_HOST; cbData=%#x -> stall\n", pUrb->cbData));
1824 return usbMsdCompleteStall(pThis, NULL, pUrb, "Invalid CSW size");
1825 }
1826
1827 int rc = usbMsdSubmitScsiCommand(pThis, pReq, "usbMsdHandleBulkDevToHost");
1828 if (RT_SUCCESS(rc) && rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
1829 usbMsdReqComplete(pThis, pReq, rc);
1830 else if (RT_FAILURE(rc))
1831 {
1832 Log(("usbMsd: Failed sending SCSI request to driver: %Rrc\n", rc));
1833 return usbMsdCompleteStall(pThis, NULL, pUrb, "SCSI Submit #3");
1834 }
1835 }
1836 RT_FALL_THRU();
1837
1838 /*
1839 * The SCSI command is still pending, queue the URB awaiting its
1840 * completion.
1841 */
1842 case USBMSDREQSTATE_EXECUTING:
1843 usbMsdQueueAddTail(&pThis->ToHostQueue, pUrb);
1844 LogFlow(("usbMsdHandleBulkDevToHost: Added %p:%s to the to-host queue\n", pUrb, pUrb->pszDesc));
1845 return VINF_SUCCESS;
1846
1847 /*
1848 * Bad states, stall.
1849 */
1850 case USBMSDREQSTATE_READY:
1851 Log(("usbMsdHandleBulkDevToHost: enmState=READ(%d) (cbData=%#x)\n", pReq->enmState, pUrb->cbData));
1852 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad state D2H: READY");
1853
1854 default:
1855 Log(("usbMsdHandleBulkDevToHost: enmState=%d cbData=%#x\n", pReq->enmState, pUrb->cbData));
1856 return usbMsdCompleteStall(pThis, NULL, pUrb, "Really bad state (D2H)!");
1857 }
1858}
1859
1860
1861/**
1862 * Handles request send to the default control pipe.
1863 */
1864static int usbMsdHandleDefaultPipe(PUSBMSD pThis, PUSBMSDEP pEp, PVUSBURB pUrb)
1865{
1866 PVUSBSETUP pSetup = (PVUSBSETUP)&pUrb->abData[0];
1867 AssertReturn(pUrb->cbData >= sizeof(*pSetup), VERR_VUSB_FAILED_TO_QUEUE_URB);
1868
1869 if ((pSetup->bmRequestType & VUSB_REQ_MASK) == VUSB_REQ_STANDARD)
1870 {
1871 switch (pSetup->bRequest)
1872 {
1873 case VUSB_REQ_GET_DESCRIPTOR:
1874 {
1875 if (pSetup->bmRequestType != (VUSB_TO_DEVICE | VUSB_REQ_STANDARD | VUSB_DIR_TO_HOST))
1876 {
1877 Log(("usbMsd: Bad GET_DESCRIPTOR req: bmRequestType=%#x\n", pSetup->bmRequestType));
1878 return usbMsdCompleteStall(pThis, pEp, pUrb, "Bad GET_DESCRIPTOR");
1879 }
1880
1881 switch (pSetup->wValue >> 8)
1882 {
1883 uint32_t cbCopy;
1884
1885 case VUSB_DT_STRING:
1886 Log(("usbMsd: GET_DESCRIPTOR DT_STRING wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1887 break;
1888 case VUSB_DT_DEVICE_QUALIFIER:
1889 Log(("usbMsd: GET_DESCRIPTOR DT_DEVICE_QUALIFIER wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1890 /* Returned data is written after the setup message. */
1891 cbCopy = pUrb->cbData - sizeof(*pSetup);
1892 cbCopy = RT_MIN(cbCopy, sizeof(g_UsbMsdDeviceQualifier));
1893 memcpy(&pUrb->abData[sizeof(*pSetup)], &g_UsbMsdDeviceQualifier, cbCopy);
1894 return usbMsdCompleteOk(pThis, pUrb, cbCopy + sizeof(*pSetup));
1895 case VUSB_DT_BOS:
1896 Log(("usbMsd: GET_DESCRIPTOR DT_BOS wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1897 /* Returned data is written after the setup message. */
1898 cbCopy = pUrb->cbData - sizeof(*pSetup);
1899 cbCopy = RT_MIN(cbCopy, sizeof(g_UsbMsdBOS));
1900 memcpy(&pUrb->abData[sizeof(*pSetup)], &g_UsbMsdBOS, cbCopy);
1901 return usbMsdCompleteOk(pThis, pUrb, cbCopy + sizeof(*pSetup));
1902 default:
1903 Log(("usbMsd: GET_DESCRIPTOR, huh? wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1904 break;
1905 }
1906 break;
1907 }
1908
1909 case VUSB_REQ_CLEAR_FEATURE:
1910 break;
1911 }
1912
1913 /** @todo implement this. */
1914 Log(("usbMsd: Implement standard request: bmRequestType=%#x bRequest=%#x wValue=%#x wIndex=%#x wLength=%#x\n",
1915 pSetup->bmRequestType, pSetup->bRequest, pSetup->wValue, pSetup->wIndex, pSetup->wLength));
1916
1917 usbMsdCompleteStall(pThis, pEp, pUrb, "TODO: standard request stuff");
1918 }
1919 /* 3.1 Bulk-Only Mass Storage Reset */
1920 else if ( pSetup->bmRequestType == (VUSB_REQ_CLASS | VUSB_TO_INTERFACE)
1921 && pSetup->bRequest == 0xff
1922 && !pSetup->wValue
1923 && !pSetup->wLength
1924 && pSetup->wIndex == 0)
1925 {
1926 Log(("usbMsdHandleDefaultPipe: Bulk-Only Mass Storage Reset\n"));
1927 return usbMsdResetWorker(pThis, pUrb, false /*fSetConfig*/);
1928 }
1929 /* 3.2 Get Max LUN, may stall if we like (but we don't). */
1930 else if ( pSetup->bmRequestType == (VUSB_REQ_CLASS | VUSB_TO_INTERFACE | VUSB_DIR_TO_HOST)
1931 && pSetup->bRequest == 0xfe
1932 && !pSetup->wValue
1933 && pSetup->wLength == 1
1934 && pSetup->wIndex == 0)
1935 {
1936 *(uint8_t *)(pSetup + 1) = 0; /* max lun is 0 */
1937 usbMsdCompleteOk(pThis, pUrb, 1);
1938 }
1939 else
1940 {
1941 Log(("usbMsd: Unknown control msg: bmRequestType=%#x bRequest=%#x wValue=%#x wIndex=%#x wLength=%#x\n",
1942 pSetup->bmRequestType, pSetup->bRequest, pSetup->wValue, pSetup->wIndex, pSetup->wLength));
1943 return usbMsdCompleteStall(pThis, pEp, pUrb, "Unknown control msg");
1944 }
1945
1946 return VINF_SUCCESS;
1947}
1948
1949
1950/**
1951 * @interface_method_impl{PDMUSBREG,pfnUrbQueue}
1952 */
1953static DECLCALLBACK(int) usbMsdQueue(PPDMUSBINS pUsbIns, PVUSBURB pUrb)
1954{
1955 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1956 LogFlow(("usbMsdQueue/#%u: pUrb=%p:%s EndPt=%#x\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc, pUrb->EndPt));
1957 RTCritSectEnter(&pThis->CritSect);
1958
1959 /*
1960 * Parse on a per end-point basis.
1961 */
1962 int rc;
1963 switch (pUrb->EndPt)
1964 {
1965 case 0:
1966 rc = usbMsdHandleDefaultPipe(pThis, &pThis->aEps[0], pUrb);
1967 break;
1968
1969 case 0x81:
1970 AssertFailed();
1971 RT_FALL_THRU();
1972 case 0x01:
1973 rc = usbMsdHandleBulkDevToHost(pThis, &pThis->aEps[1], pUrb);
1974 break;
1975
1976 case 0x02:
1977 rc = usbMsdHandleBulkHostToDev(pThis, &pThis->aEps[2], pUrb);
1978 break;
1979
1980 default:
1981 AssertMsgFailed(("EndPt=%d\n", pUrb->EndPt));
1982 rc = VERR_VUSB_FAILED_TO_QUEUE_URB;
1983 break;
1984 }
1985
1986 RTCritSectLeave(&pThis->CritSect);
1987 return rc;
1988}
1989
1990
1991/**
1992 * @interface_method_impl{PDMUSBREG,pfnUsbClearHaltedEndpoint}
1993 */
1994static DECLCALLBACK(int) usbMsdUsbClearHaltedEndpoint(PPDMUSBINS pUsbIns, unsigned uEndpoint)
1995{
1996 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1997 LogFlow(("usbMsdUsbClearHaltedEndpoint/#%u: uEndpoint=%#x\n", pUsbIns->iInstance, uEndpoint));
1998
1999 if ((uEndpoint & ~0x80) < RT_ELEMENTS(pThis->aEps))
2000 {
2001 RTCritSectEnter(&pThis->CritSect);
2002 pThis->aEps[(uEndpoint & ~0x80)].fHalted = false;
2003 RTCritSectLeave(&pThis->CritSect);
2004 }
2005
2006 return VINF_SUCCESS;
2007}
2008
2009
2010/**
2011 * @interface_method_impl{PDMUSBREG,pfnUsbSetInterface}
2012 */
2013static DECLCALLBACK(int) usbMsdUsbSetInterface(PPDMUSBINS pUsbIns, uint8_t bInterfaceNumber, uint8_t bAlternateSetting)
2014{
2015 RT_NOREF(pUsbIns, bInterfaceNumber, bAlternateSetting);
2016 LogFlow(("usbMsdUsbSetInterface/#%u: bInterfaceNumber=%u bAlternateSetting=%u\n", pUsbIns->iInstance, bInterfaceNumber, bAlternateSetting));
2017 Assert(bAlternateSetting == 0);
2018 return VINF_SUCCESS;
2019}
2020
2021
2022/**
2023 * @interface_method_impl{PDMUSBREG,pfnUsbSetConfiguration}
2024 */
2025static DECLCALLBACK(int) usbMsdUsbSetConfiguration(PPDMUSBINS pUsbIns, uint8_t bConfigurationValue,
2026 const void *pvOldCfgDesc, const void *pvOldIfState, const void *pvNewCfgDesc)
2027{
2028 RT_NOREF(pvOldCfgDesc, pvOldIfState, pvNewCfgDesc);
2029 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2030 LogFlow(("usbMsdUsbSetConfiguration/#%u: bConfigurationValue=%u\n", pUsbIns->iInstance, bConfigurationValue));
2031 Assert(bConfigurationValue == 1);
2032 RTCritSectEnter(&pThis->CritSect);
2033
2034 /*
2035 * If the same config is applied more than once, it's a kind of reset.
2036 */
2037 if (pThis->bConfigurationValue == bConfigurationValue)
2038 usbMsdResetWorker(pThis, NULL, true /*fSetConfig*/); /** @todo figure out the exact difference */
2039 pThis->bConfigurationValue = bConfigurationValue;
2040
2041 RTCritSectLeave(&pThis->CritSect);
2042 return VINF_SUCCESS;
2043}
2044
2045
2046/**
2047 * @interface_method_impl{PDMUSBREG,pfnUsbGetDescriptorCache}
2048 */
2049static DECLCALLBACK(PCPDMUSBDESCCACHE) usbMsdUsbGetDescriptorCache(PPDMUSBINS pUsbIns)
2050{
2051 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2052 LogFlow(("usbMsdUsbGetDescriptorCache/#%u:\n", pUsbIns->iInstance));
2053 if (pThis->pUsbIns->enmSpeed == VUSB_SPEED_SUPER)
2054 return pThis->fIsCdrom ? &g_UsbCdDescCacheSS : &g_UsbMsdDescCacheSS;
2055 else if (pThis->pUsbIns->enmSpeed == VUSB_SPEED_HIGH)
2056 return pThis->fIsCdrom ? &g_UsbCdDescCacheHS : &g_UsbMsdDescCacheHS;
2057 else
2058 return pThis->fIsCdrom ? &g_UsbCdDescCacheFS : &g_UsbMsdDescCacheFS;
2059}
2060
2061
2062/**
2063 * @interface_method_impl{PDMUSBREG,pfnUsbReset}
2064 */
2065static DECLCALLBACK(int) usbMsdUsbReset(PPDMUSBINS pUsbIns, bool fResetOnLinux)
2066{
2067 RT_NOREF(fResetOnLinux);
2068 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2069 LogFlow(("usbMsdUsbReset/#%u:\n", pUsbIns->iInstance));
2070 RTCritSectEnter(&pThis->CritSect);
2071
2072 int rc = usbMsdResetWorker(pThis, NULL, false /*fSetConfig*/);
2073
2074 RTCritSectLeave(&pThis->CritSect);
2075 return rc;
2076}
2077
2078
2079/**
2080 * @interface_method_impl{PDMUSBREG,pfnVMSuspend}
2081 */
2082static DECLCALLBACK(void) usbMsdVMSuspend(PPDMUSBINS pUsbIns)
2083{
2084 LogFlow(("usbMsdVMSuspend/#%u:\n", pUsbIns->iInstance));
2085 usbMsdSuspendOrPowerOff(pUsbIns);
2086}
2087
2088
2089/**
2090 * @interface_method_impl{PDMUSBREG,pfnVMSuspend}
2091 */
2092static DECLCALLBACK(void) usbMsdVMPowerOff(PPDMUSBINS pUsbIns)
2093{
2094 LogFlow(("usbMsdVMPowerOff/#%u:\n", pUsbIns->iInstance));
2095 usbMsdSuspendOrPowerOff(pUsbIns);
2096}
2097
2098
2099/**
2100 * @interface_method_impl{PDMUSBREG,pfnDriverAttach}
2101 */
2102static DECLCALLBACK(int) usbMsdDriverAttach(PPDMUSBINS pUsbIns, unsigned iLUN, uint32_t fFlags)
2103{
2104 RT_NOREF(fFlags);
2105 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2106
2107 LogFlow(("usbMsdDriverAttach/#%u:\n", pUsbIns->iInstance));
2108
2109 AssertMsg(iLUN == 0, ("UsbMsd: No other LUN than 0 is supported\n"));
2110 AssertMsg(fFlags & PDM_TACH_FLAGS_NOT_HOT_PLUG,
2111 ("UsbMsd: Device does not support hotplugging\n"));
2112
2113 /* the usual paranoia */
2114 AssertRelease(!pThis->Lun0.pIBase);
2115 AssertRelease(!pThis->Lun0.pIMedia);
2116 AssertRelease(!pThis->Lun0.pIMediaEx);
2117
2118 /*
2119 * Try attach the block device and get the interfaces,
2120 * required as well as optional.
2121 */
2122 int rc = PDMUsbHlpDriverAttach(pUsbIns, iLUN, &pThis->Lun0.IBase, &pThis->Lun0.pIBase, NULL);
2123 if (RT_SUCCESS(rc))
2124 {
2125 /* Get media and extended media interface. */
2126 pThis->Lun0.pIMedia = PDMIBASE_QUERY_INTERFACE(pThis->Lun0.pIBase, PDMIMEDIA);
2127 AssertMsgReturn(pThis->Lun0.pIMedia, ("Missing media interface below\n"), VERR_PDM_MISSING_INTERFACE);
2128 pThis->Lun0.pIMediaEx = PDMIBASE_QUERY_INTERFACE(pThis->Lun0.pIBase, PDMIMEDIAEX);
2129 AssertMsgReturn(pThis->Lun0.pIMediaEx, ("Missing extended media interface below\n"), VERR_PDM_MISSING_INTERFACE);
2130
2131 rc = pThis->Lun0.pIMediaEx->pfnIoReqAllocSizeSet(pThis->Lun0.pIMediaEx, sizeof(USBMSDREQ));
2132 AssertMsgRCReturn(rc, ("MSD failed to set I/O request size!\n"), VERR_PDM_MISSING_INTERFACE);
2133 }
2134 else
2135 AssertMsgFailed(("Failed to attach LUN#%d. rc=%Rrc\n", iLUN, rc));
2136
2137 if (RT_FAILURE(rc))
2138 {
2139 pThis->Lun0.pIBase = NULL;
2140 pThis->Lun0.pIMedia = NULL;
2141 pThis->Lun0.pIMediaEx = NULL;
2142 }
2143
2144 pThis->fIsCdrom = false;
2145 PDMMEDIATYPE enmType = pThis->Lun0.pIMedia->pfnGetType(pThis->Lun0.pIMedia);
2146 /* Anything else will be reported as a hard disk. */
2147 if (enmType == PDMMEDIATYPE_CDROM || enmType == PDMMEDIATYPE_DVD)
2148 pThis->fIsCdrom = true;
2149
2150 return rc;
2151}
2152
2153
2154/**
2155 * @interface_method_impl{PDMUSBREG,pfnDriverDetach}
2156 */
2157static DECLCALLBACK(void) usbMsdDriverDetach(PPDMUSBINS pUsbIns, unsigned iLUN, uint32_t fFlags)
2158{
2159 RT_NOREF(iLUN, fFlags);
2160 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2161
2162 LogFlow(("usbMsdDriverDetach/#%u:\n", pUsbIns->iInstance));
2163
2164 AssertMsg(iLUN == 0, ("UsbMsd: No other LUN than 0 is supported\n"));
2165 AssertMsg(fFlags & PDM_TACH_FLAGS_NOT_HOT_PLUG,
2166 ("UsbMsd: Device does not support hotplugging\n"));
2167
2168 if (pThis->pReq)
2169 {
2170 usbMsdReqFree(pThis, pThis->pReq);
2171 pThis->pReq = NULL;
2172 }
2173
2174 /*
2175 * Zero some important members.
2176 */
2177 pThis->Lun0.pIBase = NULL;
2178 pThis->Lun0.pIMedia = NULL;
2179 pThis->Lun0.pIMediaEx = NULL;
2180}
2181
2182
2183/**
2184 * @callback_method_impl{FNPDMDEVASYNCNOTIFY,
2185 * Callback employed by usbMsdVMReset.}
2186 */
2187static DECLCALLBACK(bool) usbMsdIsAsyncResetDone(PPDMUSBINS pUsbIns)
2188{
2189 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2190
2191 if (!usbMsdAllAsyncIOIsFinished(pUsbIns))
2192 return false;
2193 ASMAtomicWriteBool(&pThis->fSignalIdle, false);
2194
2195 int rc = usbMsdResetWorker(pThis, NULL, false /*fSetConfig*/);
2196 AssertRC(rc);
2197 return true;
2198}
2199
2200/**
2201 * @interface_method_impl{PDMUSBREG,pfnVMReset}
2202 */
2203static DECLCALLBACK(void) usbMsdVMReset(PPDMUSBINS pUsbIns)
2204{
2205 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2206
2207 ASMAtomicWriteBool(&pThis->fSignalIdle, true);
2208 if (!usbMsdAllAsyncIOIsFinished(pUsbIns))
2209 PDMUsbHlpSetAsyncNotification(pUsbIns, usbMsdIsAsyncResetDone);
2210 else
2211 {
2212 ASMAtomicWriteBool(&pThis->fSignalIdle, false);
2213 int rc = usbMsdResetWorker(pThis, NULL, false /*fSetConfig*/);
2214 AssertRC(rc);
2215 }
2216}
2217
2218
2219/**
2220 * @interface_method_impl{PDMUSBREG,pfnDestruct}
2221 */
2222static DECLCALLBACK(void) usbMsdDestruct(PPDMUSBINS pUsbIns)
2223{
2224 PDMUSB_CHECK_VERSIONS_RETURN_VOID(pUsbIns);
2225 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2226 LogFlow(("usbMsdDestruct/#%u:\n", pUsbIns->iInstance));
2227
2228 if (RTCritSectIsInitialized(&pThis->CritSect))
2229 {
2230 RTCritSectEnter(&pThis->CritSect);
2231 RTCritSectLeave(&pThis->CritSect);
2232 RTCritSectDelete(&pThis->CritSect);
2233 }
2234
2235 if (pThis->hEvtDoneQueue != NIL_RTSEMEVENT)
2236 {
2237 RTSemEventDestroy(pThis->hEvtDoneQueue);
2238 pThis->hEvtDoneQueue = NIL_RTSEMEVENT;
2239 }
2240
2241 if (pThis->hEvtReset != NIL_RTSEMEVENTMULTI)
2242 {
2243 RTSemEventMultiDestroy(pThis->hEvtReset);
2244 pThis->hEvtReset = NIL_RTSEMEVENTMULTI;
2245 }
2246}
2247
2248
2249/**
2250 * @interface_method_impl{PDMUSBREG,pfnConstruct}
2251 */
2252static DECLCALLBACK(int) usbMsdConstruct(PPDMUSBINS pUsbIns, int iInstance, PCFGMNODE pCfg, PCFGMNODE pCfgGlobal)
2253{
2254 RT_NOREF(pCfgGlobal);
2255 PDMUSB_CHECK_VERSIONS_RETURN(pUsbIns);
2256 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2257 Log(("usbMsdConstruct/#%u:\n", iInstance));
2258
2259 /*
2260 * Perform the basic structure initialization first so the destructor
2261 * will not misbehave.
2262 */
2263 pThis->pUsbIns = pUsbIns;
2264 pThis->hEvtDoneQueue = NIL_RTSEMEVENT;
2265 pThis->hEvtReset = NIL_RTSEMEVENTMULTI;
2266 pThis->Lun0.IBase.pfnQueryInterface = usbMsdLun0QueryInterface;
2267 pThis->Lun0.IMediaPort.pfnQueryDeviceLocation = usbMsdLun0QueryDeviceLocation;
2268 pThis->Lun0.IMediaExPort.pfnIoReqCompleteNotify = usbMsdLun0IoReqCompleteNotify;
2269 pThis->Lun0.IMediaExPort.pfnIoReqCopyFromBuf = usbMsdLun0IoReqCopyFromBuf;
2270 pThis->Lun0.IMediaExPort.pfnIoReqCopyToBuf = usbMsdLun0IoReqCopyToBuf;
2271 pThis->Lun0.IMediaExPort.pfnIoReqQueryDiscardRanges = NULL;
2272 pThis->Lun0.IMediaExPort.pfnIoReqStateChanged = usbMsdLun0IoReqStateChanged;
2273 pThis->Lun0.IMediaExPort.pfnMediumEjected = usbMsdLun0MediumEjected;
2274 usbMsdQueueInit(&pThis->ToHostQueue);
2275 usbMsdQueueInit(&pThis->DoneQueue);
2276
2277 int rc = RTCritSectInit(&pThis->CritSect);
2278 AssertRCReturn(rc, rc);
2279
2280 rc = RTSemEventCreate(&pThis->hEvtDoneQueue);
2281 AssertRCReturn(rc, rc);
2282
2283 rc = RTSemEventMultiCreate(&pThis->hEvtReset);
2284 AssertRCReturn(rc, rc);
2285
2286 /*
2287 * Validate and read the configuration.
2288 */
2289 rc = CFGMR3ValidateConfig(pCfg, "/", "", "", "UsbMsd", iInstance);
2290 if (RT_FAILURE(rc))
2291 return rc;
2292
2293 /*
2294 * Attach the SCSI driver.
2295 */
2296 rc = PDMUsbHlpDriverAttach(pUsbIns, 0 /*iLun*/, &pThis->Lun0.IBase, &pThis->Lun0.pIBase, "SCSI Port");
2297 if (RT_FAILURE(rc))
2298 return PDMUsbHlpVMSetError(pUsbIns, rc, RT_SRC_POS, N_("MSD failed to attach SCSI driver"));
2299 pThis->Lun0.pIMedia = PDMIBASE_QUERY_INTERFACE(pThis->Lun0.pIBase, PDMIMEDIA);
2300 if (!pThis->Lun0.pIMedia)
2301 return PDMUsbHlpVMSetError(pUsbIns, VERR_PDM_MISSING_INTERFACE_BELOW, RT_SRC_POS,
2302 N_("MSD failed to query the PDMIMEDIA from the driver below it"));
2303 pThis->Lun0.pIMediaEx = PDMIBASE_QUERY_INTERFACE(pThis->Lun0.pIBase, PDMIMEDIAEX);
2304 if (!pThis->Lun0.pIMediaEx)
2305 return PDMUsbHlpVMSetError(pUsbIns, VERR_PDM_MISSING_INTERFACE_BELOW, RT_SRC_POS,
2306 N_("MSD failed to query the PDMIMEDIAEX from the driver below it"));
2307
2308 /*
2309 * Find out what kind of device we are.
2310 */
2311 pThis->fIsCdrom = false;
2312 PDMMEDIATYPE enmType = pThis->Lun0.pIMedia->pfnGetType(pThis->Lun0.pIMedia);
2313 /* Anything else will be reported as a hard disk. */
2314 if (enmType == PDMMEDIATYPE_CDROM || enmType == PDMMEDIATYPE_DVD)
2315 pThis->fIsCdrom = true;
2316
2317 rc = pThis->Lun0.pIMediaEx->pfnIoReqAllocSizeSet(pThis->Lun0.pIMediaEx, sizeof(USBMSDREQ));
2318 if (RT_FAILURE(rc))
2319 return PDMUsbHlpVMSetError(pUsbIns, rc, RT_SRC_POS, N_("MSD failed to set I/O request size!"));
2320
2321 /*
2322 * Register the saved state data unit.
2323 */
2324 rc = PDMUsbHlpSSMRegister(pUsbIns, USB_MSD_SAVED_STATE_VERSION, sizeof(*pThis),
2325 NULL, usbMsdLiveExec, NULL,
2326 usbMsdSavePrep, usbMsdSaveExec, NULL,
2327 usbMsdLoadPrep, usbMsdLoadExec, NULL);
2328 if (RT_FAILURE(rc))
2329 return PDMUsbHlpVMSetError(pUsbIns, rc, RT_SRC_POS,
2330 N_("MSD failed to register SSM save state handlers"));
2331
2332 return VINF_SUCCESS;
2333}
2334
2335
2336/**
2337 * The USB Mass Storage Device (MSD) registration record.
2338 */
2339const PDMUSBREG g_UsbMsd =
2340{
2341 /* u32Version */
2342 PDM_USBREG_VERSION,
2343 /* szName */
2344 "Msd",
2345 /* pszDescription */
2346 "USB Mass Storage Device, one LUN.",
2347 /* fFlags */
2348 PDM_USBREG_HIGHSPEED_CAPABLE | PDM_USBREG_SUPERSPEED_CAPABLE
2349 | PDM_USBREG_SAVED_STATE_SUPPORTED,
2350 /* cMaxInstances */
2351 ~0U,
2352 /* cbInstance */
2353 sizeof(USBMSD),
2354 /* pfnConstruct */
2355 usbMsdConstruct,
2356 /* pfnDestruct */
2357 usbMsdDestruct,
2358 /* pfnVMInitComplete */
2359 NULL,
2360 /* pfnVMPowerOn */
2361 NULL,
2362 /* pfnVMReset */
2363 usbMsdVMReset,
2364 /* pfnVMSuspend */
2365 usbMsdVMSuspend,
2366 /* pfnVMResume */
2367 NULL,
2368 /* pfnVMPowerOff */
2369 usbMsdVMPowerOff,
2370 /* pfnHotPlugged */
2371 NULL,
2372 /* pfnHotUnplugged */
2373 NULL,
2374 /* pfnDriverAttach */
2375 usbMsdDriverAttach,
2376 /* pfnDriverDetach */
2377 usbMsdDriverDetach,
2378 /* pfnQueryInterface */
2379 NULL,
2380 /* pfnUsbReset */
2381 usbMsdUsbReset,
2382 /* pfnUsbGetCachedDescriptors */
2383 usbMsdUsbGetDescriptorCache,
2384 /* pfnUsbSetConfiguration */
2385 usbMsdUsbSetConfiguration,
2386 /* pfnUsbSetInterface */
2387 usbMsdUsbSetInterface,
2388 /* pfnUsbClearHaltedEndpoint */
2389 usbMsdUsbClearHaltedEndpoint,
2390 /* pfnUrbNew */
2391 NULL/*usbMsdUrbNew*/,
2392 /* pfnQueue */
2393 usbMsdQueue,
2394 /* pfnUrbCancel */
2395 usbMsdUrbCancel,
2396 /* pfnUrbReap */
2397 usbMsdUrbReap,
2398 /* pfnWakeup */
2399 usbMsdWakeup,
2400 /* u32TheEnd */
2401 PDM_USBREG_VERSION
2402};
2403
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