VirtualBox

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

Last change on this file since 90791 was 90791, checked in by vboxsync, 3 years ago

Devices: More VALID_PTR -> RT_VALID_PTR/AssertPtr.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 80.9 KB
Line 
1/* $Id: UsbMsd.cpp 90791 2021-08-23 10:28:24Z 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 uint8_t bCBWLen = RT_MIN(pCbw->bCBWCBLength, sizeof(pCbw->CBWCB));
890 size_t cbCopy = RT_UOFFSETOF_DYN(USBCBW, CBWCB[bCBWLen]);
891 memcpy(&pReq->Cbw, pCbw, cbCopy);
892 memset((uint8_t *)&pReq->Cbw + cbCopy, 0, sizeof(pReq->Cbw) - cbCopy);
893
894 /* Setup the SCSI request. */
895 pReq->offBuf = 0;
896 pReq->iScsiReqStatus = 0xff;
897}
898
899
900/**
901 * Makes sure that there is sufficient buffer space available.
902 *
903 * @returns Success indicator (true/false)
904 * @param pThis The MSD instance.
905 * @param pReq The request.
906 * @param cbBuf The required buffer space.
907 */
908static int usbMsdReqEnsureBuffer(PUSBMSD pThis, PUSBMSDREQ pReq, uint32_t cbBuf)
909{
910 if (RT_LIKELY(pReq->cbBuf >= cbBuf))
911 RT_BZERO(pReq->pbBuf, cbBuf);
912 else
913 {
914 PDMUsbHlpMMHeapFree(pThis->pUsbIns, pReq->pbBuf);
915 pReq->cbBuf = 0;
916
917 cbBuf = RT_ALIGN_Z(cbBuf, 0x1000);
918 pReq->pbBuf = (uint8_t *)PDMUsbHlpMMHeapAllocZ(pThis->pUsbIns, cbBuf);
919 if (!pReq->pbBuf)
920 return false;
921
922 pReq->cbBuf = cbBuf;
923 }
924 return true;
925}
926
927
928/**
929 * Completes the URB with a stalled state, halting the pipe.
930 */
931static int usbMsdCompleteStall(PUSBMSD pThis, PUSBMSDEP pEp, PVUSBURB pUrb, const char *pszWhy)
932{
933 RT_NOREF(pszWhy);
934 Log(("usbMsdCompleteStall/#%u: pUrb=%p:%s: %s\n", pThis->pUsbIns->iInstance, pUrb, pUrb->pszDesc, pszWhy));
935
936 pUrb->enmStatus = VUSBSTATUS_STALL;
937
938 /** @todo figure out if the stall is global or pipe-specific or both. */
939 if (pEp)
940 pEp->fHalted = true;
941 else
942 {
943 pThis->aEps[1].fHalted = true;
944 pThis->aEps[2].fHalted = true;
945 }
946
947 usbMsdLinkDone(pThis, pUrb);
948 return VINF_SUCCESS;
949}
950
951
952/**
953 * Completes the URB with a OK state.
954 */
955static int usbMsdCompleteOk(PUSBMSD pThis, PVUSBURB pUrb, size_t cbData)
956{
957 Log(("usbMsdCompleteOk/#%u: pUrb=%p:%s cbData=%#zx\n", pThis->pUsbIns->iInstance, pUrb, pUrb->pszDesc, cbData));
958
959 pUrb->enmStatus = VUSBSTATUS_OK;
960 pUrb->cbData = (uint32_t)cbData;
961
962 usbMsdLinkDone(pThis, pUrb);
963 return VINF_SUCCESS;
964}
965
966
967/**
968 * Reset worker for usbMsdUsbReset, usbMsdUsbSetConfiguration and
969 * usbMsdUrbHandleDefaultPipe.
970 *
971 * @returns VBox status code.
972 * @param pThis The MSD instance.
973 * @param pUrb Set when usbMsdUrbHandleDefaultPipe is the
974 * caller.
975 * @param fSetConfig Set when usbMsdUsbSetConfiguration is the
976 * caller.
977 */
978static int usbMsdResetWorker(PUSBMSD pThis, PVUSBURB pUrb, bool fSetConfig)
979{
980 /*
981 * Wait for the any command currently executing to complete before
982 * resetting. (We cannot cancel its execution.) How we do this depends
983 * on the reset method.
984 */
985 PUSBMSDREQ pReq = pThis->pReq;
986 if ( pReq
987 && pReq->enmState == USBMSDREQSTATE_EXECUTING)
988 {
989 /* Don't try to deal with the set config variant nor multiple build-only
990 mass storage resets. */
991 if (pThis->pResetUrb && (pUrb || fSetConfig))
992 {
993 Log(("usbMsdResetWorker: pResetUrb is already %p:%s - stalling\n", pThis->pResetUrb, pThis->pResetUrb->pszDesc));
994 return usbMsdCompleteStall(pThis, NULL, pUrb, "pResetUrb");
995 }
996
997 /* Bulk-Only Mass Storage Reset: Complete the reset on request completion. */
998 if (pUrb)
999 {
1000 pThis->pResetUrb = pUrb;
1001 Log(("usbMsdResetWorker: Setting pResetUrb to %p:%s\n", pThis->pResetUrb, pThis->pResetUrb->pszDesc));
1002 return VINF_SUCCESS;
1003 }
1004
1005 /* Device reset: Wait for up to 10 ms. If it doesn't work, ditch
1006 whole the request structure. We'll allocate a new one when needed. */
1007 Log(("usbMsdResetWorker: Waiting for completion...\n"));
1008 Assert(!pThis->fSignalResetSem);
1009 pThis->fSignalResetSem = true;
1010 RTSemEventMultiReset(pThis->hEvtReset);
1011 RTCritSectLeave(&pThis->CritSect);
1012
1013 int rc = RTSemEventMultiWait(pThis->hEvtReset, 10 /*ms*/);
1014
1015 RTCritSectEnter(&pThis->CritSect);
1016 pThis->fSignalResetSem = false;
1017 if ( RT_FAILURE(rc)
1018 || pReq->enmState == USBMSDREQSTATE_EXECUTING)
1019 {
1020 Log(("usbMsdResetWorker: Didn't complete, ditching the current request (%p)!\n", pReq));
1021 Assert(pReq == pThis->pReq);
1022 pReq->enmState = USBMSDREQSTATE_DESTROY_ON_COMPLETION;
1023 pThis->pReq = NULL;
1024 pReq = NULL;
1025 }
1026 }
1027
1028 /*
1029 * Reset the request and device state.
1030 */
1031 if (pReq)
1032 {
1033 pReq->enmState = USBMSDREQSTATE_READY;
1034 pReq->iScsiReqStatus = 0xff;
1035 }
1036
1037 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aEps); i++)
1038 pThis->aEps[i].fHalted = false;
1039
1040 if (!pUrb && !fSetConfig) /* (only device reset) */
1041 pThis->bConfigurationValue = 0; /* default */
1042
1043 /*
1044 * Ditch all pending URBs.
1045 */
1046 PVUSBURB pCurUrb;
1047 while ((pCurUrb = usbMsdQueueRemoveHead(&pThis->ToHostQueue)) != NULL)
1048 {
1049 pCurUrb->enmStatus = VUSBSTATUS_CRC;
1050 usbMsdLinkDone(pThis, pCurUrb);
1051 }
1052
1053 pCurUrb = pThis->pResetUrb;
1054 if (pCurUrb)
1055 {
1056 pThis->pResetUrb = NULL;
1057 pCurUrb->enmStatus = VUSBSTATUS_CRC;
1058 usbMsdLinkDone(pThis, pCurUrb);
1059 }
1060
1061 if (pUrb)
1062 return usbMsdCompleteOk(pThis, pUrb, 0);
1063 return VINF_SUCCESS;
1064}
1065
1066
1067/**
1068 * Process a completed request.
1069 *
1070 * @returns nothing.
1071 * @param pThis The MSD instance.
1072 * @param pReq The request.
1073 * @param rcReq The completion status.
1074 */
1075static void usbMsdReqComplete(PUSBMSD pThis, PUSBMSDREQ pReq, int rcReq)
1076{
1077 RT_NOREF1(rcReq);
1078
1079 Log(("usbMsdLun0IoReqCompleteNotify: pReq=%p dCBWTag=%#x iScsiReqStatus=%u \n", pReq, pReq->Cbw.dCBWTag, pReq->iScsiReqStatus));
1080 RTCritSectEnter(&pThis->CritSect);
1081
1082 if (pReq->enmState != USBMSDREQSTATE_DESTROY_ON_COMPLETION)
1083 {
1084 Assert(pReq->enmState == USBMSDREQSTATE_EXECUTING);
1085 Assert(pThis->pReq == pReq);
1086
1087 /*
1088 * Advance the state machine. The state machine is not affected by
1089 * SCSI errors.
1090 */
1091 if ((pReq->Cbw.bmCBWFlags & USBCBW_DIR_MASK) == USBCBW_DIR_OUT)
1092 {
1093 pReq->enmState = USBMSDREQSTATE_STATUS;
1094 Log(("usbMsdLun0IoReqCompleteNotify: Entering STATUS\n"));
1095 }
1096 else
1097 {
1098 pReq->enmState = USBMSDREQSTATE_DATA_TO_HOST;
1099 Log(("usbMsdLun0IoReqCompleteNotify: Entering DATA_TO_HOST\n"));
1100 }
1101
1102 /*
1103 * Deal with pending to-host URBs.
1104 */
1105 for (;;)
1106 {
1107 PVUSBURB pUrb = usbMsdQueueRemoveHead(&pThis->ToHostQueue);
1108 if (!pUrb)
1109 break;
1110
1111 /* Process it the normal way. */
1112 usbMsdHandleBulkDevToHost(pThis, &pThis->aEps[1], pUrb);
1113 }
1114 }
1115 else
1116 {
1117 Log(("usbMsdLun0IoReqCompleteNotify: freeing %p\n", pReq));
1118 usbMsdReqFree(pThis, pReq);
1119 }
1120
1121 if (pThis->fSignalResetSem)
1122 RTSemEventMultiSignal(pThis->hEvtReset);
1123
1124 if (pThis->pResetUrb)
1125 {
1126 pThis->pResetUrb = NULL;
1127 usbMsdResetWorker(pThis, pThis->pResetUrb, false /*fSetConfig*/);
1128 }
1129
1130 RTCritSectLeave(&pThis->CritSect);
1131}
1132
1133
1134/**
1135 * @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqCopyFromBuf}
1136 */
1137static DECLCALLBACK(int) usbMsdLun0IoReqCopyFromBuf(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
1138 void *pvIoReqAlloc, uint32_t offDst, PRTSGBUF pSgBuf,
1139 size_t cbCopy)
1140{
1141 RT_NOREF2(pInterface, hIoReq);
1142 int rc = VINF_SUCCESS;
1143 PUSBMSDREQ pReq = (PUSBMSDREQ)pvIoReqAlloc;
1144
1145 if (RT_UNLIKELY(offDst + cbCopy > pReq->cbBuf))
1146 rc = VERR_PDM_MEDIAEX_IOBUF_OVERFLOW;
1147 else
1148 {
1149 size_t cbCopied = RTSgBufCopyToBuf(pSgBuf, pReq->pbBuf + offDst, cbCopy);
1150 Assert(cbCopied == cbCopy); RT_NOREF(cbCopied);
1151 }
1152
1153 return rc;
1154}
1155
1156
1157/**
1158 * @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqCopyToBuf}
1159 */
1160static DECLCALLBACK(int) usbMsdLun0IoReqCopyToBuf(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
1161 void *pvIoReqAlloc, uint32_t offSrc, PRTSGBUF pSgBuf,
1162 size_t cbCopy)
1163{
1164 RT_NOREF2(pInterface, hIoReq);
1165 int rc = VINF_SUCCESS;
1166 PUSBMSDREQ pReq = (PUSBMSDREQ)pvIoReqAlloc;
1167
1168 if (RT_UNLIKELY(offSrc + cbCopy > pReq->cbBuf))
1169 rc = VERR_PDM_MEDIAEX_IOBUF_UNDERRUN;
1170 else
1171 {
1172 size_t cbCopied = RTSgBufCopyFromBuf(pSgBuf, pReq->pbBuf + offSrc, cbCopy);
1173 Assert(cbCopied == cbCopy); RT_NOREF(cbCopied);
1174 }
1175
1176 return rc;
1177}
1178
1179
1180/**
1181 * @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqCompleteNotify}
1182 */
1183static DECLCALLBACK(int) usbMsdLun0IoReqCompleteNotify(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
1184 void *pvIoReqAlloc, int rcReq)
1185{
1186 RT_NOREF1(hIoReq);
1187 PUSBMSD pThis = RT_FROM_MEMBER(pInterface, USBMSD, Lun0.IMediaExPort);
1188 PUSBMSDREQ pReq = (PUSBMSDREQ)pvIoReqAlloc;
1189
1190 usbMsdReqComplete(pThis, pReq, rcReq);
1191 return VINF_SUCCESS;
1192}
1193
1194
1195/**
1196 * @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqStateChanged}
1197 */
1198static DECLCALLBACK(void) usbMsdLun0IoReqStateChanged(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
1199 void *pvIoReqAlloc, PDMMEDIAEXIOREQSTATE enmState)
1200{
1201 RT_NOREF4(pInterface, hIoReq, pvIoReqAlloc, enmState);
1202 AssertLogRelMsgFailed(("This should not be hit because I/O requests should not be suspended\n"));
1203}
1204
1205
1206/**
1207 * @interface_method_impl{PDMIMEDIAEXPORT,pfnMediumEjected}
1208 */
1209static DECLCALLBACK(void) usbMsdLun0MediumEjected(PPDMIMEDIAEXPORT pInterface)
1210{
1211 RT_NOREF1(pInterface); /** @todo */
1212}
1213
1214
1215/**
1216 * @interface_method_impl{PDMIMEDIAPORT,pfnQueryDeviceLocation}
1217 */
1218static DECLCALLBACK(int) usbMsdLun0QueryDeviceLocation(PPDMIMEDIAPORT pInterface, const char **ppcszController,
1219 uint32_t *piInstance, uint32_t *piLUN)
1220{
1221 PUSBMSD pThis = RT_FROM_MEMBER(pInterface, USBMSD, Lun0.IMediaPort);
1222 PPDMUSBINS pUsbIns = pThis->pUsbIns;
1223
1224 AssertPtrReturn(ppcszController, VERR_INVALID_POINTER);
1225 AssertPtrReturn(piInstance, VERR_INVALID_POINTER);
1226 AssertPtrReturn(piLUN, VERR_INVALID_POINTER);
1227
1228 *ppcszController = pUsbIns->pReg->szName;
1229 *piInstance = pUsbIns->iInstance;
1230 *piLUN = 0;
1231
1232 return VINF_SUCCESS;
1233}
1234
1235
1236/**
1237 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
1238 */
1239static DECLCALLBACK(void *) usbMsdLun0QueryInterface(PPDMIBASE pInterface, const char *pszIID)
1240{
1241 PUSBMSD pThis = RT_FROM_MEMBER(pInterface, USBMSD, Lun0.IBase);
1242 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThis->Lun0.IBase);
1243 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIAPORT, &pThis->Lun0.IMediaPort);
1244 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIAEXPORT, &pThis->Lun0.IMediaExPort);
1245 return NULL;
1246}
1247
1248
1249/**
1250 * Checks if all asynchronous I/O is finished.
1251 *
1252 * Used by usbMsdVMReset, usbMsdVMSuspend and usbMsdVMPowerOff.
1253 *
1254 * @returns true if quiesced, false if busy.
1255 * @param pUsbIns The USB device instance.
1256 */
1257static bool usbMsdAllAsyncIOIsFinished(PPDMUSBINS pUsbIns)
1258{
1259 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1260
1261 if ( RT_VALID_PTR(pThis->pReq)
1262 && pThis->pReq->enmState == USBMSDREQSTATE_EXECUTING)
1263 return false;
1264
1265 return true;
1266}
1267
1268/**
1269 * @callback_method_impl{FNPDMDEVASYNCNOTIFY,
1270 * Callback employed by usbMsdVMSuspend and usbMsdVMPowerOff.}
1271 */
1272static DECLCALLBACK(bool) usbMsdIsAsyncSuspendOrPowerOffDone(PPDMUSBINS pUsbIns)
1273{
1274 if (!usbMsdAllAsyncIOIsFinished(pUsbIns))
1275 return false;
1276
1277 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1278 ASMAtomicWriteBool(&pThis->fSignalIdle, false);
1279 return true;
1280}
1281
1282/**
1283 * Common worker for usbMsdVMSuspend and usbMsdVMPowerOff.
1284 */
1285static void usbMsdSuspendOrPowerOff(PPDMUSBINS pUsbIns)
1286{
1287 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1288
1289 ASMAtomicWriteBool(&pThis->fSignalIdle, true);
1290 if (!usbMsdAllAsyncIOIsFinished(pUsbIns))
1291 PDMUsbHlpSetAsyncNotification(pUsbIns, usbMsdIsAsyncSuspendOrPowerOffDone);
1292 else
1293 {
1294 ASMAtomicWriteBool(&pThis->fSignalIdle, false);
1295
1296 if (pThis->pReq)
1297 {
1298 usbMsdReqFree(pThis, pThis->pReq);
1299 pThis->pReq = NULL;
1300 }
1301 }
1302
1303 if (pThis->Lun0.pIMediaEx)
1304 pThis->Lun0.pIMediaEx->pfnNotifySuspend(pThis->Lun0.pIMediaEx);
1305}
1306
1307
1308/* -=-=-=-=- Saved State -=-=-=-=- */
1309
1310/**
1311 * @callback_method_impl{FNSSMUSBSAVEPREP}
1312 */
1313static DECLCALLBACK(int) usbMsdSavePrep(PPDMUSBINS pUsbIns, PSSMHANDLE pSSM)
1314{
1315 RT_NOREF(pSSM);
1316#ifdef VBOX_STRICT
1317 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1318 Assert(usbMsdAllAsyncIOIsFinished(pUsbIns));
1319 Assert(usbMsdQueueIsEmpty(&pThis->ToHostQueue));
1320 Assert(usbMsdQueueIsEmpty(&pThis->DoneQueue));
1321#else
1322 RT_NOREF(pUsbIns);
1323#endif
1324 return VINF_SUCCESS;
1325}
1326
1327/**
1328 * @callback_method_impl{FNSSMUSBLOADPREP}
1329 */
1330static DECLCALLBACK(int) usbMsdLoadPrep(PPDMUSBINS pUsbIns, PSSMHANDLE pSSM)
1331{
1332 RT_NOREF(pSSM);
1333#ifdef VBOX_STRICT
1334 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1335 Assert(usbMsdAllAsyncIOIsFinished(pUsbIns));
1336 Assert(usbMsdQueueIsEmpty(&pThis->ToHostQueue));
1337 Assert(usbMsdQueueIsEmpty(&pThis->DoneQueue));
1338#else
1339 RT_NOREF(pUsbIns);
1340#endif
1341 return VINF_SUCCESS;
1342}
1343
1344/**
1345 * @callback_method_impl{FNSSMUSBLIVEEXEC}
1346 */
1347static DECLCALLBACK(int) usbMsdLiveExec(PPDMUSBINS pUsbIns, PSSMHANDLE pSSM, uint32_t uPass)
1348{
1349 RT_NOREF(uPass);
1350 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1351
1352 /* config. */
1353 SSMR3PutBool(pSSM, pThis->Lun0.pIBase != NULL);
1354 return VINF_SSM_DONT_CALL_AGAIN;
1355}
1356
1357/**
1358 * @callback_method_impl{FNSSMUSBSAVEEXEC}
1359 */
1360static DECLCALLBACK(int) usbMsdSaveExec(PPDMUSBINS pUsbIns, PSSMHANDLE pSSM)
1361{
1362 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1363 int rc;
1364
1365 /* The config */
1366 rc = usbMsdLiveExec(pUsbIns, pSSM, SSM_PASS_FINAL);
1367 AssertRCReturn(rc, rc);
1368
1369 SSMR3PutU8(pSSM, pThis->bConfigurationValue);
1370 SSMR3PutBool(pSSM, pThis->aEps[0].fHalted);
1371 SSMR3PutBool(pSSM, pThis->aEps[1].fHalted);
1372 SSMR3PutBool(pSSM, pThis->aEps[2].fHalted);
1373 SSMR3PutBool(pSSM, pThis->pReq != NULL);
1374
1375 if (pThis->pReq)
1376 {
1377 PUSBMSDREQ pReq = pThis->pReq;
1378
1379 SSMR3PutU32(pSSM, pReq->enmState);
1380 SSMR3PutU32(pSSM, pReq->cbBuf);
1381 if (pReq->cbBuf)
1382 {
1383 AssertPtr(pReq->pbBuf);
1384 SSMR3PutMem(pSSM, pReq->pbBuf, pReq->cbBuf);
1385 }
1386
1387 SSMR3PutU32(pSSM, pReq->offBuf);
1388 SSMR3PutMem(pSSM, &pReq->Cbw, sizeof(pReq->Cbw));
1389 SSMR3PutU8(pSSM, pReq->iScsiReqStatus);
1390 }
1391
1392 return SSMR3PutU32(pSSM, UINT32_MAX); /* sanity/terminator */
1393}
1394
1395/**
1396 * @callback_method_impl{FNSSMUSBLOADEXEC}
1397 */
1398static DECLCALLBACK(int) usbMsdLoadExec(PPDMUSBINS pUsbIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
1399{
1400 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1401 uint32_t u32;
1402 int rc;
1403
1404 if (uVersion > USB_MSD_SAVED_STATE_VERSION)
1405 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
1406
1407 /* Verify config. */
1408 bool fInUse;
1409 rc = SSMR3GetBool(pSSM, &fInUse);
1410 AssertRCReturn(rc, rc);
1411 if (fInUse != (pThis->Lun0.pIBase != NULL))
1412 return SSMR3SetCfgError(pSSM, RT_SRC_POS,
1413 N_("The %s VM is missing a USB mass storage device. Please make sure the source and target VMs have compatible storage configurations"),
1414 fInUse ? "target" : "source");
1415
1416 if (uPass == SSM_PASS_FINAL)
1417 {
1418 /* Restore data. */
1419 Assert(!pThis->pReq);
1420
1421 SSMR3GetU8(pSSM, &pThis->bConfigurationValue);
1422 SSMR3GetBool(pSSM, &pThis->aEps[0].fHalted);
1423 SSMR3GetBool(pSSM, &pThis->aEps[1].fHalted);
1424 SSMR3GetBool(pSSM, &pThis->aEps[2].fHalted);
1425 bool fReqAlloc = false;
1426 rc = SSMR3GetBool(pSSM, &fReqAlloc);
1427 AssertRCReturn(rc, rc);
1428 if (fReqAlloc)
1429 {
1430 PUSBMSDREQ pReq = usbMsdReqAlloc(pThis);
1431 AssertReturn(pReq, VERR_NO_MEMORY);
1432 pThis->pReq = pReq;
1433
1434 AssertCompile(sizeof(pReq->enmState) == sizeof(uint32_t));
1435 SSMR3GetU32(pSSM, (uint32_t *)&pReq->enmState);
1436
1437 uint32_t cbBuf = 0;
1438 rc = SSMR3GetU32(pSSM, &cbBuf);
1439 AssertRCReturn(rc, rc);
1440 if (cbBuf)
1441 {
1442 if (usbMsdReqEnsureBuffer(pThis, pReq, cbBuf))
1443 {
1444 AssertPtr(pReq->pbBuf);
1445 Assert(cbBuf == pReq->cbBuf);
1446 SSMR3GetMem(pSSM, pReq->pbBuf, pReq->cbBuf);
1447 }
1448 else
1449 return VERR_NO_MEMORY;
1450 }
1451
1452 SSMR3GetU32(pSSM, &pReq->offBuf);
1453 SSMR3GetMem(pSSM, &pReq->Cbw, sizeof(pReq->Cbw));
1454
1455 if (uVersion > USB_MSD_SAVED_STATE_VERSION_PRE_CLEANUP)
1456 rc = SSMR3GetU8(pSSM, &pReq->iScsiReqStatus);
1457 else
1458 {
1459 int32_t iScsiReqStatus;
1460
1461 /* Skip old fields which are unused now or can be determined from the CBW. */
1462 SSMR3Skip(pSSM, 4 * 4 + 64);
1463 rc = SSMR3GetS32(pSSM, &iScsiReqStatus);
1464 pReq->iScsiReqStatus = (uint8_t)iScsiReqStatus;
1465 }
1466 AssertRCReturn(rc, rc);
1467 }
1468
1469 rc = SSMR3GetU32(pSSM, &u32);
1470 AssertRCReturn(rc, rc);
1471 AssertMsgReturn(u32 == UINT32_MAX, ("%#x\n", u32), VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
1472 }
1473
1474 return VINF_SUCCESS;
1475}
1476
1477
1478/**
1479 * @interface_method_impl{PDMUSBREG,pfnUrbReap}
1480 */
1481static DECLCALLBACK(PVUSBURB) usbMsdUrbReap(PPDMUSBINS pUsbIns, RTMSINTERVAL cMillies)
1482{
1483 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1484 LogFlow(("usbMsdUrbReap/#%u: cMillies=%u\n", pUsbIns->iInstance, cMillies));
1485
1486 RTCritSectEnter(&pThis->CritSect);
1487
1488 PVUSBURB pUrb = usbMsdQueueRemoveHead(&pThis->DoneQueue);
1489 if (!pUrb && cMillies)
1490 {
1491 /* Wait */
1492 pThis->fHaveDoneQueueWaiter = true;
1493 RTCritSectLeave(&pThis->CritSect);
1494
1495 RTSemEventWait(pThis->hEvtDoneQueue, cMillies);
1496
1497 RTCritSectEnter(&pThis->CritSect);
1498 pThis->fHaveDoneQueueWaiter = false;
1499
1500 pUrb = usbMsdQueueRemoveHead(&pThis->DoneQueue);
1501 }
1502
1503 RTCritSectLeave(&pThis->CritSect);
1504
1505 if (pUrb)
1506 Log(("usbMsdUrbReap/#%u: pUrb=%p:%s\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc));
1507 return pUrb;
1508}
1509
1510
1511/**
1512 * @interface_method_impl{PDMUSBREG,pfnWakeup}
1513 */
1514static DECLCALLBACK(int) usbMsdWakeup(PPDMUSBINS pUsbIns)
1515{
1516 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1517 LogFlow(("usbMsdUrbReap/#%u:\n", pUsbIns->iInstance));
1518
1519 return RTSemEventSignal(pThis->hEvtDoneQueue);
1520}
1521
1522
1523/**
1524 * @interface_method_impl{PDMUSBREG,pfnUrbCancel}
1525 */
1526static DECLCALLBACK(int) usbMsdUrbCancel(PPDMUSBINS pUsbIns, PVUSBURB pUrb)
1527{
1528 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1529 LogFlow(("usbMsdUrbCancel/#%u: pUrb=%p:%s\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc));
1530 RTCritSectEnter(&pThis->CritSect);
1531
1532 /*
1533 * Remove the URB from the to-host queue and move it onto the done queue.
1534 */
1535 if (usbMsdQueueRemove(&pThis->ToHostQueue, pUrb))
1536 usbMsdLinkDone(pThis, pUrb);
1537
1538 RTCritSectLeave(&pThis->CritSect);
1539 return VINF_SUCCESS;
1540}
1541
1542
1543/**
1544 * Wrapper around PDMISCSICONNECTOR::pfnSCSIRequestSend that deals with
1545 * SCSI_REQUEST_SENSE.
1546 *
1547 * @returns VBox status code.
1548 * @param pThis The MSD instance data.
1549 * @param pReq The MSD request.
1550 * @param pszCaller Where we're called from.
1551 */
1552static int usbMsdSubmitScsiCommand(PUSBMSD pThis, PUSBMSDREQ pReq, const char *pszCaller)
1553{
1554 RT_NOREF(pszCaller);
1555 Log(("%s: Entering EXECUTING (dCBWTag=%#x).\n", pszCaller, pReq->Cbw.dCBWTag));
1556 Assert(pReq == pThis->pReq);
1557 pReq->enmState = USBMSDREQSTATE_EXECUTING;
1558
1559 PDMMEDIAEXIOREQSCSITXDIR enmTxDir = pReq->Cbw.dCBWDataTransferLength == 0
1560 ? PDMMEDIAEXIOREQSCSITXDIR_NONE
1561 : (pReq->Cbw.bmCBWFlags & USBCBW_DIR_MASK) == USBCBW_DIR_OUT
1562 ? PDMMEDIAEXIOREQSCSITXDIR_TO_DEVICE
1563 : PDMMEDIAEXIOREQSCSITXDIR_FROM_DEVICE;
1564
1565 return pThis->Lun0.pIMediaEx->pfnIoReqSendScsiCmd(pThis->Lun0.pIMediaEx, pReq->hIoReq, pReq->Cbw.bCBWLun,
1566 &pReq->Cbw.CBWCB[0], pReq->Cbw.bCBWCBLength, enmTxDir, NULL,
1567 pReq->Cbw.dCBWDataTransferLength, NULL, 0, NULL,
1568 &pReq->iScsiReqStatus, 20 * RT_MS_1SEC);
1569}
1570
1571
1572/**
1573 * Handle requests sent to the outbound (to device) bulk pipe.
1574 */
1575static int usbMsdHandleBulkHostToDev(PUSBMSD pThis, PUSBMSDEP pEp, PVUSBURB pUrb)
1576{
1577 /*
1578 * Stall the request if the pipe is halted.
1579 */
1580 if (RT_UNLIKELY(pEp->fHalted))
1581 return usbMsdCompleteStall(pThis, NULL, pUrb, "Halted pipe");
1582
1583 /*
1584 * Deal with the URB according to the current state.
1585 */
1586 PUSBMSDREQ pReq = pThis->pReq;
1587 USBMSDREQSTATE enmState = pReq ? pReq->enmState : USBMSDREQSTATE_READY;
1588 switch (enmState)
1589 {
1590 case USBMSDREQSTATE_STATUS:
1591 LogFlow(("usbMsdHandleBulkHostToDev: Skipping pending status.\n"));
1592 pReq->enmState = USBMSDREQSTATE_READY;
1593 RT_FALL_THRU();
1594
1595 /*
1596 * We're ready to receive a command. Start off by validating the
1597 * incoming request.
1598 */
1599 case USBMSDREQSTATE_READY:
1600 {
1601 PCUSBCBW pCbw = (PUSBCBW)&pUrb->abData[0];
1602 if (pUrb->cbData < RT_UOFFSETOF(USBCBW, CBWCB[1]))
1603 {
1604 Log(("usbMsd: Bad CBW: cbData=%#x < min=%#x\n", pUrb->cbData, RT_UOFFSETOF(USBCBW, CBWCB[1]) ));
1605 return usbMsdCompleteStall(pThis, NULL, pUrb, "BAD CBW");
1606 }
1607 if (pCbw->dCBWSignature != USBCBW_SIGNATURE)
1608 {
1609 Log(("usbMsd: CBW: Invalid dCBWSignature value: %#x\n", pCbw->dCBWSignature));
1610 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1611 }
1612 Log(("usbMsd: CBW: dCBWTag=%#x dCBWDataTransferLength=%#x bmCBWFlags=%#x bCBWLun=%#x bCBWCBLength=%#x cbData=%#x fShortNotOk=%RTbool\n",
1613 pCbw->dCBWTag, pCbw->dCBWDataTransferLength, pCbw->bmCBWFlags, pCbw->bCBWLun, pCbw->bCBWCBLength, pUrb->cbData, pUrb->fShortNotOk));
1614 if (pCbw->bmCBWFlags & ~USBCBW_DIR_MASK)
1615 {
1616 Log(("usbMsd: CBW: Bad bmCBWFlags value: %#x\n", pCbw->bmCBWFlags));
1617 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1618
1619 }
1620 if (pCbw->bCBWLun != 0)
1621 {
1622 Log(("usbMsd: CBW: Bad bCBWLun value: %#x\n", pCbw->bCBWLun));
1623 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1624 }
1625 if ((pCbw->bCBWCBLength == 0) || (pCbw->bCBWCBLength > sizeof(pCbw->CBWCB)))
1626 {
1627 Log(("usbMsd: CBW: Bad bCBWCBLength value: %#x\n", pCbw->bCBWCBLength));
1628 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1629 }
1630 if (pUrb->cbData < RT_UOFFSETOF_DYN(USBCBW, CBWCB[pCbw->bCBWCBLength]))
1631 {
1632 Log(("usbMsd: CBW: Mismatching cbData and bCBWCBLength values: %#x vs. %#x (%#x)\n",
1633 pUrb->cbData, RT_UOFFSETOF_DYN(USBCBW, CBWCB[pCbw->bCBWCBLength]), pCbw->bCBWCBLength));
1634 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad CBW");
1635 }
1636 if (pCbw->dCBWDataTransferLength > _1M)
1637 {
1638 Log(("usbMsd: CBW: dCBWDataTransferLength is too large: %#x (%u)\n",
1639 pCbw->dCBWDataTransferLength, pCbw->dCBWDataTransferLength));
1640 return usbMsdCompleteStall(pThis, NULL, pUrb, "Too big transfer");
1641 }
1642
1643 /*
1644 * Make sure we've got a request and a sufficient buffer space.
1645 *
1646 * Note! This will make sure the buffer is ZERO as well, thus
1647 * saving us the trouble of clearing the output buffer on
1648 * failure later.
1649 */
1650 if (!pReq)
1651 {
1652 pReq = usbMsdReqAlloc(pThis);
1653 if (!pReq)
1654 return usbMsdCompleteStall(pThis, NULL, pUrb, "Request allocation failure");
1655 pThis->pReq = pReq;
1656 }
1657 if (!usbMsdReqEnsureBuffer(pThis, pReq, pCbw->dCBWDataTransferLength))
1658 return usbMsdCompleteStall(pThis, NULL, pUrb, "Buffer allocation failure");
1659
1660 /*
1661 * Prepare the request. Kick it off right away if possible.
1662 */
1663 usbMsdReqPrepare(pReq, pCbw);
1664
1665 if ( pReq->Cbw.dCBWDataTransferLength == 0
1666 || (pReq->Cbw.bmCBWFlags & USBCBW_DIR_MASK) == USBCBW_DIR_IN)
1667 {
1668 int rc = usbMsdSubmitScsiCommand(pThis, pReq, "usbMsdHandleBulkHostToDev");
1669 if (RT_SUCCESS(rc) && rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
1670 usbMsdReqComplete(pThis, pReq, rc);
1671 else if (RT_FAILURE(rc))
1672 {
1673 Log(("usbMsd: Failed sending SCSI request to driver: %Rrc\n", rc));
1674 return usbMsdCompleteStall(pThis, NULL, pUrb, "SCSI Submit #1");
1675 }
1676 }
1677 else
1678 {
1679 Log(("usbMsdHandleBulkHostToDev: Entering DATA_FROM_HOST.\n"));
1680 pReq->enmState = USBMSDREQSTATE_DATA_FROM_HOST;
1681 }
1682
1683 return usbMsdCompleteOk(pThis, pUrb, pUrb->cbData);
1684 }
1685
1686 /*
1687 * Stuff the data into the buffer.
1688 */
1689 case USBMSDREQSTATE_DATA_FROM_HOST:
1690 {
1691 uint32_t cbData = pUrb->cbData;
1692 uint32_t cbLeft = pReq->Cbw.dCBWDataTransferLength - pReq->offBuf;
1693 if (cbData > cbLeft)
1694 {
1695 Log(("usbMsd: Too much data: cbData=%#x offBuf=%#x dCBWDataTransferLength=%#x cbLeft=%#x\n",
1696 cbData, pReq->offBuf, pReq->Cbw.dCBWDataTransferLength, cbLeft));
1697 return usbMsdCompleteStall(pThis, NULL, pUrb, "Too much data");
1698 }
1699 memcpy(&pReq->pbBuf[pReq->offBuf], &pUrb->abData[0], cbData);
1700 pReq->offBuf += cbData;
1701
1702 if (pReq->offBuf == pReq->Cbw.dCBWDataTransferLength)
1703 {
1704 int rc = usbMsdSubmitScsiCommand(pThis, pReq, "usbMsdHandleBulkHostToDev");
1705 if (RT_SUCCESS(rc) && rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
1706 usbMsdReqComplete(pThis, pReq, rc);
1707 else if (RT_FAILURE(rc))
1708 {
1709 Log(("usbMsd: Failed sending SCSI request to driver: %Rrc\n", rc));
1710 return usbMsdCompleteStall(pThis, NULL, pUrb, "SCSI Submit #2");
1711 }
1712 }
1713 return usbMsdCompleteOk(pThis, pUrb, cbData);
1714 }
1715
1716 /*
1717 * Bad state, stall.
1718 */
1719 case USBMSDREQSTATE_DATA_TO_HOST:
1720 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad state H2D: DATA_TO_HOST");
1721
1722 case USBMSDREQSTATE_EXECUTING:
1723 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad state H2D: EXECUTING");
1724
1725 default:
1726 AssertMsgFailed(("enmState=%d\n", enmState));
1727 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad state (H2D)");
1728 }
1729}
1730
1731
1732/**
1733 * Handle requests sent to the inbound (to host) bulk pipe.
1734 */
1735static int usbMsdHandleBulkDevToHost(PUSBMSD pThis, PUSBMSDEP pEp, PVUSBURB pUrb)
1736{
1737 /*
1738 * Stall the request if the pipe is halted OR if there is no
1739 * pending request yet.
1740 */
1741 PUSBMSDREQ pReq = pThis->pReq;
1742 if (RT_UNLIKELY(pEp->fHalted || !pReq))
1743 return usbMsdCompleteStall(pThis, NULL, pUrb, pEp->fHalted ? "Halted pipe" : "No request");
1744
1745 /*
1746 * Deal with the URB according to the state.
1747 */
1748 switch (pReq->enmState)
1749 {
1750 /*
1751 * We've data left to transfer to the host.
1752 */
1753 case USBMSDREQSTATE_DATA_TO_HOST:
1754 {
1755 uint32_t cbData = pUrb->cbData;
1756 uint32_t cbCopy = pReq->Cbw.dCBWDataTransferLength - pReq->offBuf;
1757 if (cbData <= cbCopy)
1758 cbCopy = cbData;
1759 else if (pUrb->fShortNotOk)
1760 {
1761 Log(("usbMsd: Requested more data that we've got; cbData=%#x offBuf=%#x dCBWDataTransferLength=%#x cbLeft=%#x\n",
1762 cbData, pReq->offBuf, pReq->Cbw.dCBWDataTransferLength, cbCopy));
1763 return usbMsdCompleteStall(pThis, NULL, pUrb, "Data underrun");
1764 }
1765 memcpy(&pUrb->abData[0], &pReq->pbBuf[pReq->offBuf], cbCopy);
1766 pReq->offBuf += cbCopy;
1767
1768 if (pReq->offBuf == pReq->Cbw.dCBWDataTransferLength)
1769 {
1770 Log(("usbMsdHandleBulkDevToHost: Entering STATUS\n"));
1771 pReq->enmState = USBMSDREQSTATE_STATUS;
1772 }
1773 return usbMsdCompleteOk(pThis, pUrb, cbCopy);
1774 }
1775
1776 /*
1777 * Status transfer.
1778 */
1779 case USBMSDREQSTATE_STATUS:
1780 {
1781 if ((pUrb->cbData < sizeof(USBCSW)) || (pUrb->cbData > sizeof(USBCSW) && pUrb->fShortNotOk))
1782 {
1783 Log(("usbMsd: Unexpected status request size: %#x (expected %#x), fShortNotOK=%RTbool\n", pUrb->cbData, sizeof(USBCSW), pUrb->fShortNotOk));
1784 return usbMsdCompleteStall(pThis, NULL, pUrb, "Invalid CSW size");
1785 }
1786
1787 /* Enter a CSW into the URB data buffer. */
1788 PUSBCSW pCsw = (PUSBCSW)&pUrb->abData[0];
1789 pCsw->dCSWSignature = USBCSW_SIGNATURE;
1790 pCsw->dCSWTag = pReq->Cbw.dCBWTag;
1791 pCsw->bCSWStatus = pReq->iScsiReqStatus == SCSI_STATUS_OK
1792 ? USBCSW_STATUS_OK
1793 : pReq->iScsiReqStatus < 0xff
1794 ? USBCSW_STATUS_FAILED
1795 : USBCSW_STATUS_PHASE_ERROR;
1796 /** @todo the following is not always accurate; VSCSI needs
1797 * to implement residual counts properly! */
1798 if ((pReq->Cbw.bmCBWFlags & USBCBW_DIR_MASK) == USBCBW_DIR_OUT)
1799 pCsw->dCSWDataResidue = pCsw->bCSWStatus == USBCSW_STATUS_OK
1800 ? 0
1801 : pReq->Cbw.dCBWDataTransferLength;
1802 else
1803 pCsw->dCSWDataResidue = pCsw->bCSWStatus == USBCSW_STATUS_OK
1804 ? 0
1805 : pReq->Cbw.dCBWDataTransferLength;
1806 Log(("usbMsd: CSW: dCSWTag=%#x bCSWStatus=%d dCSWDataResidue=%#x\n",
1807 pCsw->dCSWTag, pCsw->bCSWStatus, pCsw->dCSWDataResidue));
1808
1809 Log(("usbMsdHandleBulkDevToHost: Entering READY\n"));
1810 pReq->enmState = USBMSDREQSTATE_READY;
1811 return usbMsdCompleteOk(pThis, pUrb, sizeof(*pCsw));
1812 }
1813
1814 /*
1815 * Status request before we've received all (or even any) data.
1816 * Linux 2.4.31 does this sometimes. The recommended behavior is to
1817 * to accept the current data amount and execute the request. (The
1818 * alternative behavior is to stall.)
1819 */
1820 case USBMSDREQSTATE_DATA_FROM_HOST:
1821 {
1822 if (pUrb->cbData != sizeof(USBCSW))
1823 {
1824 Log(("usbMsdHandleBulkDevToHost: DATA_FROM_HOST; cbData=%#x -> stall\n", pUrb->cbData));
1825 return usbMsdCompleteStall(pThis, NULL, pUrb, "Invalid CSW size");
1826 }
1827
1828 int rc = usbMsdSubmitScsiCommand(pThis, pReq, "usbMsdHandleBulkDevToHost");
1829 if (RT_SUCCESS(rc) && rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
1830 usbMsdReqComplete(pThis, pReq, rc);
1831 else if (RT_FAILURE(rc))
1832 {
1833 Log(("usbMsd: Failed sending SCSI request to driver: %Rrc\n", rc));
1834 return usbMsdCompleteStall(pThis, NULL, pUrb, "SCSI Submit #3");
1835 }
1836 }
1837 RT_FALL_THRU();
1838
1839 /*
1840 * The SCSI command is still pending, queue the URB awaiting its
1841 * completion.
1842 */
1843 case USBMSDREQSTATE_EXECUTING:
1844 usbMsdQueueAddTail(&pThis->ToHostQueue, pUrb);
1845 LogFlow(("usbMsdHandleBulkDevToHost: Added %p:%s to the to-host queue\n", pUrb, pUrb->pszDesc));
1846 return VINF_SUCCESS;
1847
1848 /*
1849 * Bad states, stall.
1850 */
1851 case USBMSDREQSTATE_READY:
1852 Log(("usbMsdHandleBulkDevToHost: enmState=READ(%d) (cbData=%#x)\n", pReq->enmState, pUrb->cbData));
1853 return usbMsdCompleteStall(pThis, NULL, pUrb, "Bad state D2H: READY");
1854
1855 default:
1856 Log(("usbMsdHandleBulkDevToHost: enmState=%d cbData=%#x\n", pReq->enmState, pUrb->cbData));
1857 return usbMsdCompleteStall(pThis, NULL, pUrb, "Really bad state (D2H)!");
1858 }
1859}
1860
1861
1862/**
1863 * Handles request send to the default control pipe.
1864 */
1865static int usbMsdHandleDefaultPipe(PUSBMSD pThis, PUSBMSDEP pEp, PVUSBURB pUrb)
1866{
1867 PVUSBSETUP pSetup = (PVUSBSETUP)&pUrb->abData[0];
1868 AssertReturn(pUrb->cbData >= sizeof(*pSetup), VERR_VUSB_FAILED_TO_QUEUE_URB);
1869
1870 if ((pSetup->bmRequestType & VUSB_REQ_MASK) == VUSB_REQ_STANDARD)
1871 {
1872 switch (pSetup->bRequest)
1873 {
1874 case VUSB_REQ_GET_DESCRIPTOR:
1875 {
1876 if (pSetup->bmRequestType != (VUSB_TO_DEVICE | VUSB_REQ_STANDARD | VUSB_DIR_TO_HOST))
1877 {
1878 Log(("usbMsd: Bad GET_DESCRIPTOR req: bmRequestType=%#x\n", pSetup->bmRequestType));
1879 return usbMsdCompleteStall(pThis, pEp, pUrb, "Bad GET_DESCRIPTOR");
1880 }
1881
1882 switch (pSetup->wValue >> 8)
1883 {
1884 uint32_t cbCopy;
1885
1886 case VUSB_DT_STRING:
1887 Log(("usbMsd: GET_DESCRIPTOR DT_STRING wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1888 break;
1889 case VUSB_DT_DEVICE_QUALIFIER:
1890 Log(("usbMsd: GET_DESCRIPTOR DT_DEVICE_QUALIFIER wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1891 /* Returned data is written after the setup message. */
1892 cbCopy = pUrb->cbData - sizeof(*pSetup);
1893 cbCopy = RT_MIN(cbCopy, sizeof(g_UsbMsdDeviceQualifier));
1894 memcpy(&pUrb->abData[sizeof(*pSetup)], &g_UsbMsdDeviceQualifier, cbCopy);
1895 return usbMsdCompleteOk(pThis, pUrb, cbCopy + sizeof(*pSetup));
1896 case VUSB_DT_BOS:
1897 Log(("usbMsd: GET_DESCRIPTOR DT_BOS wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1898 /* Returned data is written after the setup message. */
1899 cbCopy = pUrb->cbData - sizeof(*pSetup);
1900 cbCopy = RT_MIN(cbCopy, sizeof(g_UsbMsdBOS));
1901 memcpy(&pUrb->abData[sizeof(*pSetup)], &g_UsbMsdBOS, cbCopy);
1902 return usbMsdCompleteOk(pThis, pUrb, cbCopy + sizeof(*pSetup));
1903 default:
1904 Log(("usbMsd: GET_DESCRIPTOR, huh? wValue=%#x wIndex=%#x\n", pSetup->wValue, pSetup->wIndex));
1905 break;
1906 }
1907 break;
1908 }
1909
1910 case VUSB_REQ_CLEAR_FEATURE:
1911 break;
1912 }
1913
1914 /** @todo implement this. */
1915 Log(("usbMsd: Implement standard request: bmRequestType=%#x bRequest=%#x wValue=%#x wIndex=%#x wLength=%#x\n",
1916 pSetup->bmRequestType, pSetup->bRequest, pSetup->wValue, pSetup->wIndex, pSetup->wLength));
1917
1918 usbMsdCompleteStall(pThis, pEp, pUrb, "TODO: standard request stuff");
1919 }
1920 /* 3.1 Bulk-Only Mass Storage Reset */
1921 else if ( pSetup->bmRequestType == (VUSB_REQ_CLASS | VUSB_TO_INTERFACE)
1922 && pSetup->bRequest == 0xff
1923 && !pSetup->wValue
1924 && !pSetup->wLength
1925 && pSetup->wIndex == 0)
1926 {
1927 Log(("usbMsdHandleDefaultPipe: Bulk-Only Mass Storage Reset\n"));
1928 return usbMsdResetWorker(pThis, pUrb, false /*fSetConfig*/);
1929 }
1930 /* 3.2 Get Max LUN, may stall if we like (but we don't). */
1931 else if ( pSetup->bmRequestType == (VUSB_REQ_CLASS | VUSB_TO_INTERFACE | VUSB_DIR_TO_HOST)
1932 && pSetup->bRequest == 0xfe
1933 && !pSetup->wValue
1934 && pSetup->wLength == 1
1935 && pSetup->wIndex == 0)
1936 {
1937 *(uint8_t *)(pSetup + 1) = 0; /* max lun is 0 */
1938 usbMsdCompleteOk(pThis, pUrb, 1);
1939 }
1940 else
1941 {
1942 Log(("usbMsd: Unknown control msg: bmRequestType=%#x bRequest=%#x wValue=%#x wIndex=%#x wLength=%#x\n",
1943 pSetup->bmRequestType, pSetup->bRequest, pSetup->wValue, pSetup->wIndex, pSetup->wLength));
1944 return usbMsdCompleteStall(pThis, pEp, pUrb, "Unknown control msg");
1945 }
1946
1947 return VINF_SUCCESS;
1948}
1949
1950
1951/**
1952 * @interface_method_impl{PDMUSBREG,pfnUrbQueue}
1953 */
1954static DECLCALLBACK(int) usbMsdQueue(PPDMUSBINS pUsbIns, PVUSBURB pUrb)
1955{
1956 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1957 LogFlow(("usbMsdQueue/#%u: pUrb=%p:%s EndPt=%#x\n", pUsbIns->iInstance, pUrb, pUrb->pszDesc, pUrb->EndPt));
1958 RTCritSectEnter(&pThis->CritSect);
1959
1960 /*
1961 * Parse on a per end-point basis.
1962 */
1963 int rc;
1964 switch (pUrb->EndPt)
1965 {
1966 case 0:
1967 rc = usbMsdHandleDefaultPipe(pThis, &pThis->aEps[0], pUrb);
1968 break;
1969
1970 case 0x81:
1971 AssertFailed();
1972 RT_FALL_THRU();
1973 case 0x01:
1974 rc = usbMsdHandleBulkDevToHost(pThis, &pThis->aEps[1], pUrb);
1975 break;
1976
1977 case 0x02:
1978 rc = usbMsdHandleBulkHostToDev(pThis, &pThis->aEps[2], pUrb);
1979 break;
1980
1981 default:
1982 AssertMsgFailed(("EndPt=%d\n", pUrb->EndPt));
1983 rc = VERR_VUSB_FAILED_TO_QUEUE_URB;
1984 break;
1985 }
1986
1987 RTCritSectLeave(&pThis->CritSect);
1988 return rc;
1989}
1990
1991
1992/**
1993 * @interface_method_impl{PDMUSBREG,pfnUsbClearHaltedEndpoint}
1994 */
1995static DECLCALLBACK(int) usbMsdUsbClearHaltedEndpoint(PPDMUSBINS pUsbIns, unsigned uEndpoint)
1996{
1997 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
1998 LogFlow(("usbMsdUsbClearHaltedEndpoint/#%u: uEndpoint=%#x\n", pUsbIns->iInstance, uEndpoint));
1999
2000 if ((uEndpoint & ~0x80) < RT_ELEMENTS(pThis->aEps))
2001 {
2002 RTCritSectEnter(&pThis->CritSect);
2003 pThis->aEps[(uEndpoint & ~0x80)].fHalted = false;
2004 RTCritSectLeave(&pThis->CritSect);
2005 }
2006
2007 return VINF_SUCCESS;
2008}
2009
2010
2011/**
2012 * @interface_method_impl{PDMUSBREG,pfnUsbSetInterface}
2013 */
2014static DECLCALLBACK(int) usbMsdUsbSetInterface(PPDMUSBINS pUsbIns, uint8_t bInterfaceNumber, uint8_t bAlternateSetting)
2015{
2016 RT_NOREF(pUsbIns, bInterfaceNumber, bAlternateSetting);
2017 LogFlow(("usbMsdUsbSetInterface/#%u: bInterfaceNumber=%u bAlternateSetting=%u\n", pUsbIns->iInstance, bInterfaceNumber, bAlternateSetting));
2018 Assert(bAlternateSetting == 0);
2019 return VINF_SUCCESS;
2020}
2021
2022
2023/**
2024 * @interface_method_impl{PDMUSBREG,pfnUsbSetConfiguration}
2025 */
2026static DECLCALLBACK(int) usbMsdUsbSetConfiguration(PPDMUSBINS pUsbIns, uint8_t bConfigurationValue,
2027 const void *pvOldCfgDesc, const void *pvOldIfState, const void *pvNewCfgDesc)
2028{
2029 RT_NOREF(pvOldCfgDesc, pvOldIfState, pvNewCfgDesc);
2030 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2031 LogFlow(("usbMsdUsbSetConfiguration/#%u: bConfigurationValue=%u\n", pUsbIns->iInstance, bConfigurationValue));
2032 Assert(bConfigurationValue == 1);
2033 RTCritSectEnter(&pThis->CritSect);
2034
2035 /*
2036 * If the same config is applied more than once, it's a kind of reset.
2037 */
2038 if (pThis->bConfigurationValue == bConfigurationValue)
2039 usbMsdResetWorker(pThis, NULL, true /*fSetConfig*/); /** @todo figure out the exact difference */
2040 pThis->bConfigurationValue = bConfigurationValue;
2041
2042 RTCritSectLeave(&pThis->CritSect);
2043 return VINF_SUCCESS;
2044}
2045
2046
2047/**
2048 * @interface_method_impl{PDMUSBREG,pfnUsbGetDescriptorCache}
2049 */
2050static DECLCALLBACK(PCPDMUSBDESCCACHE) usbMsdUsbGetDescriptorCache(PPDMUSBINS pUsbIns)
2051{
2052 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2053 LogFlow(("usbMsdUsbGetDescriptorCache/#%u:\n", pUsbIns->iInstance));
2054 if (pThis->pUsbIns->enmSpeed == VUSB_SPEED_SUPER)
2055 return pThis->fIsCdrom ? &g_UsbCdDescCacheSS : &g_UsbMsdDescCacheSS;
2056 else if (pThis->pUsbIns->enmSpeed == VUSB_SPEED_HIGH)
2057 return pThis->fIsCdrom ? &g_UsbCdDescCacheHS : &g_UsbMsdDescCacheHS;
2058 else
2059 return pThis->fIsCdrom ? &g_UsbCdDescCacheFS : &g_UsbMsdDescCacheFS;
2060}
2061
2062
2063/**
2064 * @interface_method_impl{PDMUSBREG,pfnUsbReset}
2065 */
2066static DECLCALLBACK(int) usbMsdUsbReset(PPDMUSBINS pUsbIns, bool fResetOnLinux)
2067{
2068 RT_NOREF(fResetOnLinux);
2069 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2070 LogFlow(("usbMsdUsbReset/#%u:\n", pUsbIns->iInstance));
2071 RTCritSectEnter(&pThis->CritSect);
2072
2073 int rc = usbMsdResetWorker(pThis, NULL, false /*fSetConfig*/);
2074
2075 RTCritSectLeave(&pThis->CritSect);
2076 return rc;
2077}
2078
2079
2080/**
2081 * @interface_method_impl{PDMUSBREG,pfnVMSuspend}
2082 */
2083static DECLCALLBACK(void) usbMsdVMSuspend(PPDMUSBINS pUsbIns)
2084{
2085 LogFlow(("usbMsdVMSuspend/#%u:\n", pUsbIns->iInstance));
2086 usbMsdSuspendOrPowerOff(pUsbIns);
2087}
2088
2089
2090/**
2091 * @interface_method_impl{PDMUSBREG,pfnVMSuspend}
2092 */
2093static DECLCALLBACK(void) usbMsdVMPowerOff(PPDMUSBINS pUsbIns)
2094{
2095 LogFlow(("usbMsdVMPowerOff/#%u:\n", pUsbIns->iInstance));
2096 usbMsdSuspendOrPowerOff(pUsbIns);
2097}
2098
2099
2100/**
2101 * @interface_method_impl{PDMUSBREG,pfnDriverAttach}
2102 */
2103static DECLCALLBACK(int) usbMsdDriverAttach(PPDMUSBINS pUsbIns, unsigned iLUN, uint32_t fFlags)
2104{
2105 RT_NOREF(fFlags);
2106 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2107
2108 LogFlow(("usbMsdDriverAttach/#%u:\n", pUsbIns->iInstance));
2109
2110 AssertMsg(iLUN == 0, ("UsbMsd: No other LUN than 0 is supported\n"));
2111 AssertMsg(fFlags & PDM_TACH_FLAGS_NOT_HOT_PLUG,
2112 ("UsbMsd: Device does not support hotplugging\n"));
2113
2114 /* the usual paranoia */
2115 AssertRelease(!pThis->Lun0.pIBase);
2116 AssertRelease(!pThis->Lun0.pIMedia);
2117 AssertRelease(!pThis->Lun0.pIMediaEx);
2118
2119 /*
2120 * Try attach the block device and get the interfaces,
2121 * required as well as optional.
2122 */
2123 int rc = PDMUsbHlpDriverAttach(pUsbIns, iLUN, &pThis->Lun0.IBase, &pThis->Lun0.pIBase, NULL);
2124 if (RT_SUCCESS(rc))
2125 {
2126 /* Get media and extended media interface. */
2127 pThis->Lun0.pIMedia = PDMIBASE_QUERY_INTERFACE(pThis->Lun0.pIBase, PDMIMEDIA);
2128 AssertMsgReturn(pThis->Lun0.pIMedia, ("Missing media interface below\n"), VERR_PDM_MISSING_INTERFACE);
2129 pThis->Lun0.pIMediaEx = PDMIBASE_QUERY_INTERFACE(pThis->Lun0.pIBase, PDMIMEDIAEX);
2130 AssertMsgReturn(pThis->Lun0.pIMediaEx, ("Missing extended media interface below\n"), VERR_PDM_MISSING_INTERFACE);
2131
2132 rc = pThis->Lun0.pIMediaEx->pfnIoReqAllocSizeSet(pThis->Lun0.pIMediaEx, sizeof(USBMSDREQ));
2133 AssertMsgRCReturn(rc, ("MSD failed to set I/O request size!\n"), VERR_PDM_MISSING_INTERFACE);
2134 }
2135 else
2136 AssertMsgFailed(("Failed to attach LUN#%d. rc=%Rrc\n", iLUN, rc));
2137
2138 if (RT_FAILURE(rc))
2139 {
2140 pThis->Lun0.pIBase = NULL;
2141 pThis->Lun0.pIMedia = NULL;
2142 pThis->Lun0.pIMediaEx = NULL;
2143 }
2144
2145 pThis->fIsCdrom = false;
2146 PDMMEDIATYPE enmType = pThis->Lun0.pIMedia->pfnGetType(pThis->Lun0.pIMedia);
2147 /* Anything else will be reported as a hard disk. */
2148 if (enmType == PDMMEDIATYPE_CDROM || enmType == PDMMEDIATYPE_DVD)
2149 pThis->fIsCdrom = true;
2150
2151 return rc;
2152}
2153
2154
2155/**
2156 * @interface_method_impl{PDMUSBREG,pfnDriverDetach}
2157 */
2158static DECLCALLBACK(void) usbMsdDriverDetach(PPDMUSBINS pUsbIns, unsigned iLUN, uint32_t fFlags)
2159{
2160 RT_NOREF(iLUN, fFlags);
2161 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2162
2163 LogFlow(("usbMsdDriverDetach/#%u:\n", pUsbIns->iInstance));
2164
2165 AssertMsg(iLUN == 0, ("UsbMsd: No other LUN than 0 is supported\n"));
2166 AssertMsg(fFlags & PDM_TACH_FLAGS_NOT_HOT_PLUG,
2167 ("UsbMsd: Device does not support hotplugging\n"));
2168
2169 if (pThis->pReq)
2170 {
2171 usbMsdReqFree(pThis, pThis->pReq);
2172 pThis->pReq = NULL;
2173 }
2174
2175 /*
2176 * Zero some important members.
2177 */
2178 pThis->Lun0.pIBase = NULL;
2179 pThis->Lun0.pIMedia = NULL;
2180 pThis->Lun0.pIMediaEx = NULL;
2181}
2182
2183
2184/**
2185 * @callback_method_impl{FNPDMDEVASYNCNOTIFY,
2186 * Callback employed by usbMsdVMReset.}
2187 */
2188static DECLCALLBACK(bool) usbMsdIsAsyncResetDone(PPDMUSBINS pUsbIns)
2189{
2190 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2191
2192 if (!usbMsdAllAsyncIOIsFinished(pUsbIns))
2193 return false;
2194 ASMAtomicWriteBool(&pThis->fSignalIdle, false);
2195
2196 int rc = usbMsdResetWorker(pThis, NULL, false /*fSetConfig*/);
2197 AssertRC(rc);
2198 return true;
2199}
2200
2201/**
2202 * @interface_method_impl{PDMUSBREG,pfnVMReset}
2203 */
2204static DECLCALLBACK(void) usbMsdVMReset(PPDMUSBINS pUsbIns)
2205{
2206 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2207
2208 ASMAtomicWriteBool(&pThis->fSignalIdle, true);
2209 if (!usbMsdAllAsyncIOIsFinished(pUsbIns))
2210 PDMUsbHlpSetAsyncNotification(pUsbIns, usbMsdIsAsyncResetDone);
2211 else
2212 {
2213 ASMAtomicWriteBool(&pThis->fSignalIdle, false);
2214 int rc = usbMsdResetWorker(pThis, NULL, false /*fSetConfig*/);
2215 AssertRC(rc);
2216 }
2217}
2218
2219
2220/**
2221 * @interface_method_impl{PDMUSBREG,pfnDestruct}
2222 */
2223static DECLCALLBACK(void) usbMsdDestruct(PPDMUSBINS pUsbIns)
2224{
2225 PDMUSB_CHECK_VERSIONS_RETURN_VOID(pUsbIns);
2226 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2227 LogFlow(("usbMsdDestruct/#%u:\n", pUsbIns->iInstance));
2228
2229 if (RTCritSectIsInitialized(&pThis->CritSect))
2230 {
2231 RTCritSectEnter(&pThis->CritSect);
2232 RTCritSectLeave(&pThis->CritSect);
2233 RTCritSectDelete(&pThis->CritSect);
2234 }
2235
2236 if (pThis->hEvtDoneQueue != NIL_RTSEMEVENT)
2237 {
2238 RTSemEventDestroy(pThis->hEvtDoneQueue);
2239 pThis->hEvtDoneQueue = NIL_RTSEMEVENT;
2240 }
2241
2242 if (pThis->hEvtReset != NIL_RTSEMEVENTMULTI)
2243 {
2244 RTSemEventMultiDestroy(pThis->hEvtReset);
2245 pThis->hEvtReset = NIL_RTSEMEVENTMULTI;
2246 }
2247}
2248
2249
2250/**
2251 * @interface_method_impl{PDMUSBREG,pfnConstruct}
2252 */
2253static DECLCALLBACK(int) usbMsdConstruct(PPDMUSBINS pUsbIns, int iInstance, PCFGMNODE pCfg, PCFGMNODE pCfgGlobal)
2254{
2255 RT_NOREF(pCfgGlobal);
2256 PDMUSB_CHECK_VERSIONS_RETURN(pUsbIns);
2257 PUSBMSD pThis = PDMINS_2_DATA(pUsbIns, PUSBMSD);
2258 Log(("usbMsdConstruct/#%u:\n", iInstance));
2259
2260 /*
2261 * Perform the basic structure initialization first so the destructor
2262 * will not misbehave.
2263 */
2264 pThis->pUsbIns = pUsbIns;
2265 pThis->hEvtDoneQueue = NIL_RTSEMEVENT;
2266 pThis->hEvtReset = NIL_RTSEMEVENTMULTI;
2267 pThis->Lun0.IBase.pfnQueryInterface = usbMsdLun0QueryInterface;
2268 pThis->Lun0.IMediaPort.pfnQueryDeviceLocation = usbMsdLun0QueryDeviceLocation;
2269 pThis->Lun0.IMediaExPort.pfnIoReqCompleteNotify = usbMsdLun0IoReqCompleteNotify;
2270 pThis->Lun0.IMediaExPort.pfnIoReqCopyFromBuf = usbMsdLun0IoReqCopyFromBuf;
2271 pThis->Lun0.IMediaExPort.pfnIoReqCopyToBuf = usbMsdLun0IoReqCopyToBuf;
2272 pThis->Lun0.IMediaExPort.pfnIoReqQueryDiscardRanges = NULL;
2273 pThis->Lun0.IMediaExPort.pfnIoReqStateChanged = usbMsdLun0IoReqStateChanged;
2274 pThis->Lun0.IMediaExPort.pfnMediumEjected = usbMsdLun0MediumEjected;
2275 usbMsdQueueInit(&pThis->ToHostQueue);
2276 usbMsdQueueInit(&pThis->DoneQueue);
2277
2278 int rc = RTCritSectInit(&pThis->CritSect);
2279 AssertRCReturn(rc, rc);
2280
2281 rc = RTSemEventCreate(&pThis->hEvtDoneQueue);
2282 AssertRCReturn(rc, rc);
2283
2284 rc = RTSemEventMultiCreate(&pThis->hEvtReset);
2285 AssertRCReturn(rc, rc);
2286
2287 /*
2288 * Validate and read the configuration.
2289 */
2290 rc = CFGMR3ValidateConfig(pCfg, "/", "", "", "UsbMsd", iInstance);
2291 if (RT_FAILURE(rc))
2292 return rc;
2293
2294 /*
2295 * Attach the SCSI driver.
2296 */
2297 rc = PDMUsbHlpDriverAttach(pUsbIns, 0 /*iLun*/, &pThis->Lun0.IBase, &pThis->Lun0.pIBase, "SCSI Port");
2298 if (RT_FAILURE(rc))
2299 return PDMUsbHlpVMSetError(pUsbIns, rc, RT_SRC_POS, N_("MSD failed to attach SCSI driver"));
2300 pThis->Lun0.pIMedia = PDMIBASE_QUERY_INTERFACE(pThis->Lun0.pIBase, PDMIMEDIA);
2301 if (!pThis->Lun0.pIMedia)
2302 return PDMUsbHlpVMSetError(pUsbIns, VERR_PDM_MISSING_INTERFACE_BELOW, RT_SRC_POS,
2303 N_("MSD failed to query the PDMIMEDIA from the driver below it"));
2304 pThis->Lun0.pIMediaEx = PDMIBASE_QUERY_INTERFACE(pThis->Lun0.pIBase, PDMIMEDIAEX);
2305 if (!pThis->Lun0.pIMediaEx)
2306 return PDMUsbHlpVMSetError(pUsbIns, VERR_PDM_MISSING_INTERFACE_BELOW, RT_SRC_POS,
2307 N_("MSD failed to query the PDMIMEDIAEX from the driver below it"));
2308
2309 /*
2310 * Find out what kind of device we are.
2311 */
2312 pThis->fIsCdrom = false;
2313 PDMMEDIATYPE enmType = pThis->Lun0.pIMedia->pfnGetType(pThis->Lun0.pIMedia);
2314 /* Anything else will be reported as a hard disk. */
2315 if (enmType == PDMMEDIATYPE_CDROM || enmType == PDMMEDIATYPE_DVD)
2316 pThis->fIsCdrom = true;
2317
2318 rc = pThis->Lun0.pIMediaEx->pfnIoReqAllocSizeSet(pThis->Lun0.pIMediaEx, sizeof(USBMSDREQ));
2319 if (RT_FAILURE(rc))
2320 return PDMUsbHlpVMSetError(pUsbIns, rc, RT_SRC_POS, N_("MSD failed to set I/O request size!"));
2321
2322 /*
2323 * Register the saved state data unit.
2324 */
2325 rc = PDMUsbHlpSSMRegister(pUsbIns, USB_MSD_SAVED_STATE_VERSION, sizeof(*pThis),
2326 NULL, usbMsdLiveExec, NULL,
2327 usbMsdSavePrep, usbMsdSaveExec, NULL,
2328 usbMsdLoadPrep, usbMsdLoadExec, NULL);
2329 if (RT_FAILURE(rc))
2330 return PDMUsbHlpVMSetError(pUsbIns, rc, RT_SRC_POS,
2331 N_("MSD failed to register SSM save state handlers"));
2332
2333 return VINF_SUCCESS;
2334}
2335
2336
2337/**
2338 * The USB Mass Storage Device (MSD) registration record.
2339 */
2340const PDMUSBREG g_UsbMsd =
2341{
2342 /* u32Version */
2343 PDM_USBREG_VERSION,
2344 /* szName */
2345 "Msd",
2346 /* pszDescription */
2347 "USB Mass Storage Device, one LUN.",
2348 /* fFlags */
2349 PDM_USBREG_HIGHSPEED_CAPABLE | PDM_USBREG_SUPERSPEED_CAPABLE
2350 | PDM_USBREG_SAVED_STATE_SUPPORTED,
2351 /* cMaxInstances */
2352 ~0U,
2353 /* cbInstance */
2354 sizeof(USBMSD),
2355 /* pfnConstruct */
2356 usbMsdConstruct,
2357 /* pfnDestruct */
2358 usbMsdDestruct,
2359 /* pfnVMInitComplete */
2360 NULL,
2361 /* pfnVMPowerOn */
2362 NULL,
2363 /* pfnVMReset */
2364 usbMsdVMReset,
2365 /* pfnVMSuspend */
2366 usbMsdVMSuspend,
2367 /* pfnVMResume */
2368 NULL,
2369 /* pfnVMPowerOff */
2370 usbMsdVMPowerOff,
2371 /* pfnHotPlugged */
2372 NULL,
2373 /* pfnHotUnplugged */
2374 NULL,
2375 /* pfnDriverAttach */
2376 usbMsdDriverAttach,
2377 /* pfnDriverDetach */
2378 usbMsdDriverDetach,
2379 /* pfnQueryInterface */
2380 NULL,
2381 /* pfnUsbReset */
2382 usbMsdUsbReset,
2383 /* pfnUsbGetCachedDescriptors */
2384 usbMsdUsbGetDescriptorCache,
2385 /* pfnUsbSetConfiguration */
2386 usbMsdUsbSetConfiguration,
2387 /* pfnUsbSetInterface */
2388 usbMsdUsbSetInterface,
2389 /* pfnUsbClearHaltedEndpoint */
2390 usbMsdUsbClearHaltedEndpoint,
2391 /* pfnUrbNew */
2392 NULL/*usbMsdUrbNew*/,
2393 /* pfnQueue */
2394 usbMsdQueue,
2395 /* pfnUrbCancel */
2396 usbMsdUrbCancel,
2397 /* pfnUrbReap */
2398 usbMsdUrbReap,
2399 /* pfnWakeup */
2400 usbMsdWakeup,
2401 /* u32TheEnd */
2402 PDM_USBREG_VERSION
2403};
2404
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