VirtualBox

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

Last change on this file since 99739 was 99739, checked in by vboxsync, 19 months ago

*: doxygen corrections (mostly about removing @returns from functions returning void).

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