VirtualBox

source: vbox/trunk/src/VBox/Devices/Storage/DevVirtioSCSI.cpp@ 83967

Last change on this file since 83967 was 83913, checked in by vboxsync, 5 years ago

Network/DevVirtioNet_1_0.cpp: Various fixes and improvements, most notably: Implemented SSM (save, restore, pause, resume, stop) all tested, implemented STAM similarly to DevVirtioNet.cpp, verified, added support for VIRTIO_F_EVENT_IDX feature, improved internal handling of Rx/Tx queue pair mgt (will facility multiqueue (MQ) feature better), fixed various @todo's added by bird

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 117.1 KB
Line 
1/* $Id: DevVirtioSCSI.cpp 83913 2020-04-22 04:52:12Z vboxsync $ */
2/** @file
3 * VBox storage devices - Virtio SCSI Driver
4 *
5 * Log-levels used:
6 * - Level 1: The most important (but usually rare) things to note
7 * - Level 2: SCSI command logging
8 * - Level 3: Vector and I/O transfer summary (shows what client sent an expects and fulfillment)
9 * - Level 6: Device <-> Guest Driver negotation, traffic, notifications and state handling
10 * - Level 12: Brief formatted hex dumps of I/O data
11 */
12
13/*
14 * Copyright (C) 2006-2020 Oracle Corporation
15 *
16 * This file is part of VirtualBox Open Source Edition (OSE), as
17 * available from http://www.virtualbox.org. This file is free software;
18 * you can redistribute it and/or modify it under the terms of the GNU
19 * General Public License (GPL) as published by the Free Software
20 * Foundation, in version 2 as it comes in the "COPYING" file of the
21 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
22 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
23 */
24
25
26/*********************************************************************************************************************************
27* Header Files *
28*********************************************************************************************************************************/
29//#define LOG_GROUP LOG_GROUP_DRV_SCSI
30#define LOG_GROUP LOG_GROUP_DEV_VIRTIO
31
32#include <VBox/vmm/pdmdev.h>
33#include <VBox/vmm/pdmstorageifs.h>
34#include <VBox/vmm/pdmcritsect.h>
35#include <VBox/AssertGuest.h>
36#include <VBox/msi.h>
37#include <VBox/version.h>
38#include <VBox/log.h>
39#include <iprt/errcore.h>
40#include <iprt/assert.h>
41#include <iprt/string.h>
42#include <VBox/sup.h>
43#include "../build/VBoxDD.h"
44#include <VBox/scsi.h>
45#ifdef IN_RING3
46# include <iprt/alloc.h>
47# include <iprt/memcache.h>
48# include <iprt/semaphore.h>
49# include <iprt/sg.h>
50# include <iprt/param.h>
51# include <iprt/uuid.h>
52#endif
53#include "../VirtIO/Virtio_1_0.h"
54
55#include "VBoxSCSI.h"
56#include "VBoxDD.h"
57
58
59/*********************************************************************************************************************************
60* Defined Constants And Macros *
61*********************************************************************************************************************************/
62/** The current saved state version. */
63#define VIRTIOSCSI_SAVED_STATE_VERSION UINT32_C(1)
64
65
66#define LUN0 0
67/** @name VirtIO 1.0 SCSI Host feature bits (See VirtIO 1.0 specification, Section 5.6.3)
68 * @{ */
69#define VIRTIO_SCSI_F_INOUT RT_BIT_64(0) /** Request is device readable AND writeable */
70#define VIRTIO_SCSI_F_HOTPLUG RT_BIT_64(1) /** Host allows hotplugging SCSI LUNs & targets */
71#define VIRTIO_SCSI_F_CHANGE RT_BIT_64(2) /** Host LUNs chgs via VIRTIOSCSI_T_PARAM_CHANGE evt */
72#define VIRTIO_SCSI_F_T10_PI RT_BIT_64(3) /** Add T10 port info (DIF/DIX) in SCSI req hdr */
73/** @} */
74
75
76#define VIRTIOSCSI_HOST_SCSI_FEATURES_ALL \
77 (VIRTIO_SCSI_F_INOUT | VIRTIO_SCSI_F_HOTPLUG | VIRTIO_SCSI_F_CHANGE | VIRTIO_SCSI_F_T10_PI)
78
79#define VIRTIOSCSI_HOST_SCSI_FEATURES_NONE 0
80
81#define VIRTIOSCSI_HOST_SCSI_FEATURES_OFFERED VIRTIOSCSI_HOST_SCSI_FEATURES_NONE
82
83#define VIRTIOSCSI_REQ_QUEUE_CNT 4 /**< T.B.D. Consider increasing */
84#define VIRTIOSCSI_QUEUE_CNT (VIRTIOSCSI_REQ_QUEUE_CNT + 2)
85#define VIRTIOSCSI_MAX_TARGETS 256 /**< T.B.D. Figure out a a good value for this. */
86#define VIRTIOSCSI_MAX_LUN 256 /**< VirtIO specification, section 5.6.4 */
87#define VIRTIOSCSI_MAX_COMMANDS_PER_LUN 128 /**< T.B.D. What is a good value for this? */
88#define VIRTIOSCSI_MAX_SEG_COUNT 126 /**< T.B.D. What is a good value for this? */
89#define VIRTIOSCSI_MAX_SECTORS_HINT 0x10000 /**< VirtIO specification, section 5.6.4 */
90#define VIRTIOSCSI_MAX_CHANNEL_HINT 0 /**< VirtIO specification, section 5.6.4 should be 0 */
91
92#define PCI_DEVICE_ID_VIRTIOSCSI_HOST 0x1048 /**< Informs guest driver of type of VirtIO device */
93#define PCI_CLASS_BASE_MASS_STORAGE 0x01 /**< PCI Mass Storage device class */
94#define PCI_CLASS_SUB_SCSI_STORAGE_CONTROLLER 0x00 /**< PCI SCSI Controller subclass */
95#define PCI_CLASS_PROG_UNSPECIFIED 0x00 /**< Programming interface. N/A. */
96#define VIRTIOSCSI_PCI_CLASS 0x01 /**< Base class Mass Storage? */
97
98#define VIRTIOSCSI_SENSE_SIZE_DEFAULT 96 /**< VirtIO 1.0: 96 on reset, guest can change */
99#define VIRTIOSCSI_SENSE_SIZE_MAX 4096 /**< Picked out of thin air by bird. */
100#define VIRTIOSCSI_CDB_SIZE_DEFAULT 32 /**< VirtIO 1.0: 32 on reset, guest can change */
101#define VIRTIOSCSI_CDB_SIZE_MAX 255 /**< Picked out of thin air by bird. */
102#define VIRTIOSCSI_PI_BYTES_IN 1 /**< Value TBD (see section 5.6.6.1) */
103#define VIRTIOSCSI_PI_BYTES_OUT 1 /**< Value TBD (see section 5.6.6.1) */
104#define VIRTIOSCSI_DATA_OUT 512 /**< Value TBD (see section 5.6.6.1) */
105
106/**
107 * VirtIO SCSI Host Device device-specific queue indicies.
108 * (Note: # of request queues is determined by virtio_scsi_config.num_queues. VirtIO 1.0, 5.6.4)
109 */
110#define CONTROLQ_IDX 0 /**< Spec-defined Index of control queue */
111#define EVENTQ_IDX 1 /**< Spec-defined Index of event queue */
112#define VIRTQ_REQ_BASE 2 /**< Spec-defined base index of request queues */
113
114#define VIRTQNAME(qIdx) (pThis->aszVirtqNames[qIdx]) /**< Macro to get queue name from its index */
115#define CBVIRTQNAME(qIdx) RTStrNLen(VIRTQNAME(qIdx), sizeof(VIRTQNAME(qIdx)))
116
117#define IS_REQ_QUEUE(qIdx) (qIdx >= VIRTQ_REQ_BASE && qIdx < VIRTIOSCSI_QUEUE_CNT)
118
119#define VIRTIO_IS_IN_DIRECTION(pMediaExTxDirEnumValue) \
120 ((pMediaExTxDirEnumValue) == PDMMEDIAEXIOREQSCSITXDIR_FROM_DEVICE)
121
122#define VIRTIO_IS_OUT_DIRECTION(pMediaExTxDirEnumValue) \
123 ((pMediaExTxDirEnumValue) == PDMMEDIAEXIOREQSCSITXDIR_TO_DEVICE)
124
125
126/*********************************************************************************************************************************
127* Structures and Typedefs *
128*********************************************************************************************************************************/
129/**
130 * VirtIO SCSI Host Device device-specific configuration (see VirtIO 1.0, section 5.6.4)
131 * VBox VirtIO core issues callback to this VirtIO device-specific implementation to handle
132 * MMIO accesses to device-specific configuration parameters.
133 */
134typedef struct virtio_scsi_config
135{
136 uint32_t uNumQueues; /**< num_queues \# of req q's exposed by dev */
137 uint32_t uSegMax; /**< seg_max Max \# of segs allowed in cmd */
138 uint32_t uMaxSectors; /**< max_sectors Hint to guest max xfer to use */
139 uint32_t uCmdPerLun; /**< cmd_per_lun Max \# of link cmd sent per lun */
140 uint32_t uEventInfoSize; /**< event_info_size Fill max, evtq bufs */
141 uint32_t uSenseSize; /**< sense_size Max sense data size dev writes */
142 uint32_t uCdbSize; /**< cdb_size Max CDB size driver writes */
143 uint16_t uMaxChannel; /**< max_channel Hint to guest driver */
144 uint16_t uMaxTarget; /**< max_target Hint to guest driver */
145 uint32_t uMaxLun; /**< max_lun Hint to guest driver */
146} VIRTIOSCSI_CONFIG_T, PVIRTIOSCSI_CONFIG_T;
147
148/** @name VirtIO 1.0 SCSI Host Device device specific control types
149 * @{ */
150#define VIRTIOSCSI_T_NO_EVENT 0
151#define VIRTIOSCSI_T_TRANSPORT_RESET 1
152#define VIRTIOSCSI_T_ASYNC_NOTIFY 2 /**< Asynchronous notification */
153#define VIRTIOSCSI_T_PARAM_CHANGE 3
154/** @} */
155
156/**
157 * Device operation: eventq
158 */
159#define VIRTIOSCSI_T_EVENTS_MISSED UINT32_C(0x80000000)
160typedef struct virtio_scsi_event
161{
162 // Device-writable part
163 uint32_t uEvent; /**< event */
164 uint8_t abVirtioLun[8]; /**< lun */
165 uint32_t uReason; /**< reason */
166} VIRTIOSCSI_EVENT_T, *PVIRTIOSCSI_EVENT_T;
167
168/** @name VirtIO 1.0 SCSI Host Device device specific event types
169 * @{ */
170#define VIRTIOSCSI_EVT_RESET_HARD 0 /**< */
171#define VIRTIOSCSI_EVT_RESET_RESCAN 1 /**< */
172#define VIRTIOSCSI_EVT_RESET_REMOVED 2 /**< */
173/** @} */
174
175/**
176 * Device operation: reqestq
177 */
178#pragma pack(1)
179typedef struct REQ_CMD_HDR_T
180{
181 uint8_t abVirtioLun[8]; /**< lun */
182 uint64_t uId; /**< id */
183 uint8_t uTaskAttr; /**< task_attr */
184 uint8_t uPrio; /**< prio */
185 uint8_t uCrn; /**< crn */
186} REQ_CMD_HDR_T;
187#pragma pack()
188AssertCompileSize(REQ_CMD_HDR_T, 19);
189
190typedef struct REQ_CMD_PI_T
191{
192 uint32_t uPiBytesOut; /**< pi_bytesout */
193 uint32_t uPiBytesIn; /**< pi_bytesin */
194} REQ_CMD_PI_T;
195AssertCompileSize(REQ_CMD_PI_T, 8);
196
197typedef struct REQ_RESP_HDR_T
198{
199 uint32_t cbSenseLen; /**< sense_len */
200 uint32_t uResidual; /**< residual */
201 uint16_t uStatusQualifier; /**< status_qualifier */
202 uint8_t uStatus; /**< status SCSI status code */
203 uint8_t uResponse; /**< response */
204} REQ_RESP_HDR_T;
205AssertCompileSize(REQ_RESP_HDR_T, 12);
206
207#pragma pack(1)
208typedef struct VIRTIOSCSI_REQ_CMD_T
209{
210 /** Device-readable section
211 * @{ */
212 REQ_CMD_HDR_T ReqHdr;
213 uint8_t uCdb[1]; /**< cdb */
214
215 REQ_CMD_PI_T piHdr; /**< T10 Pi block integrity (optional feature) */
216 uint8_t uPiOut[1]; /**< pi_out[] T10 pi block integrity */
217 uint8_t uDataOut[1]; /**< dataout */
218 /** @} */
219
220 /** @name Device writable section
221 * @{ */
222 REQ_RESP_HDR_T respHdr;
223 uint8_t uSense[1]; /**< sense */
224 uint8_t uPiIn[1]; /**< pi_in[] T10 Pi block integrity */
225 uint8_t uDataIn[1]; /**< detain; */
226 /** @} */
227} VIRTIOSCSI_REQ_CMD_T, *PVIRTIOSCSI_REQ_CMD_T;
228#pragma pack()
229AssertCompileSize(VIRTIOSCSI_REQ_CMD_T, 19+8+12+6);
230
231/** @name VirtIO 1.0 SCSI Host Device Req command-specific response values
232 * @{ */
233#define VIRTIOSCSI_S_OK 0 /**< control, command */
234#define VIRTIOSCSI_S_OVERRUN 1 /**< control */
235#define VIRTIOSCSI_S_ABORTED 2 /**< control */
236#define VIRTIOSCSI_S_BAD_TARGET 3 /**< control, command */
237#define VIRTIOSCSI_S_RESET 4 /**< control */
238#define VIRTIOSCSI_S_BUSY 5 /**< control, command */
239#define VIRTIOSCSI_S_TRANSPORT_FAILURE 6 /**< control, command */
240#define VIRTIOSCSI_S_TARGET_FAILURE 7 /**< control, command */
241#define VIRTIOSCSI_S_NEXUS_FAILURE 8 /**< control, command */
242#define VIRTIOSCSI_S_FAILURE 9 /**< control, command */
243#define VIRTIOSCSI_S_INCORRECT_LUN 12 /**< command */
244/** @} */
245
246/** @name VirtIO 1.0 SCSI Host Device command-specific task_attr values
247 * @{ */
248#define VIRTIOSCSI_S_SIMPLE 0 /**< */
249#define VIRTIOSCSI_S_ORDERED 1 /**< */
250#define VIRTIOSCSI_S_HEAD 2 /**< */
251#define VIRTIOSCSI_S_ACA 3 /**< */
252/** @} */
253
254/**
255 * VirtIO 1.0 SCSI Host Device Control command before we know type (5.6.6.2)
256 */
257typedef struct VIRTIOSCSI_CTRL_T
258{
259 uint32_t uType;
260} VIRTIOSCSI_CTRL_T, *PVIRTIOSCSI_CTRL_T;
261
262/** @name VirtIO 1.0 SCSI Host Device command-specific TMF values
263 * @{ */
264#define VIRTIOSCSI_T_TMF 0 /**< */
265#define VIRTIOSCSI_T_TMF_ABORT_TASK 0 /**< */
266#define VIRTIOSCSI_T_TMF_ABORT_TASK_SET 1 /**< */
267#define VIRTIOSCSI_T_TMF_CLEAR_ACA 2 /**< */
268#define VIRTIOSCSI_T_TMF_CLEAR_TASK_SET 3 /**< */
269#define VIRTIOSCSI_T_TMF_I_T_NEXUS_RESET 4 /**< */
270#define VIRTIOSCSI_T_TMF_LOGICAL_UNIT_RESET 5 /**< */
271#define VIRTIOSCSI_T_TMF_QUERY_TASK 6 /**< */
272#define VIRTIOSCSI_T_TMF_QUERY_TASK_SET 7 /**< */
273/** @} */
274
275#pragma pack(1)
276typedef struct VIRTIOSCSI_CTRL_TMF_T
277{
278 uint32_t uType; /**< type */
279 uint32_t uSubtype; /**< subtype */
280 uint8_t abScsiLun[8]; /**< lun */
281 uint64_t uId; /**< id */
282} VIRTIOSCSI_CTRL_TMF_T, *PVIRTIOSCSI_CTRL_TMF_T;
283#pragma pack()
284AssertCompileSize(VIRTIOSCSI_CTRL_TMF_T, 24);
285
286/** VirtIO 1.0 section 5.6.6.2, CTRL TMF response is an 8-bit status */
287
288/** @name VirtIO 1.0 SCSI Host Device device specific tmf control response values
289 * @{ */
290#define VIRTIOSCSI_S_FUNCTION_COMPLETE 0 /**< */
291#define VIRTIOSCSI_S_FUNCTION_SUCCEEDED 10 /**< */
292#define VIRTIOSCSI_S_FUNCTION_REJECTED 11 /**< */
293/** @} */
294
295#define VIRTIOSCSI_T_AN_QUERY 1 /**< Asynchronous notification query */
296#define VIRTIOSCSI_T_AN_SUBSCRIBE 2 /**< Asynchronous notification subscription */
297
298#pragma pack(1)
299typedef struct VIRTIOSCSI_CTRL_AN_T
300{
301 uint32_t uType; /**< type */
302 uint8_t abScsiLun[8]; /**< lun */
303 uint32_t fEventsRequested; /**< event_requested */
304} VIRTIOSCSI_CTRL_AN_T, *PVIRTIOSCSI_CTRL_AN_T;
305#pragma pack()
306AssertCompileSize(VIRTIOSCSI_CTRL_AN_T, 16);
307
308/** VirtIO 1.0, Section 5.6.6.2, CTRL AN response is 4-byte evt mask + 8-bit status */
309
310typedef union VIRTIO_SCSI_CTRL_UNION_T
311{
312 VIRTIOSCSI_CTRL_T Type;
313 VIRTIOSCSI_CTRL_TMF_T Tmf;
314 VIRTIOSCSI_CTRL_AN_T AsyncNotify;
315 uint8_t ab[24];
316} VIRTIO_SCSI_CTRL_UNION_T, *PVIRTIO_SCSI_CTRL_UNION_T;
317AssertCompile(sizeof(VIRTIO_SCSI_CTRL_UNION_T) == 24); /* VIRTIOSCSI_CTRL_T forces 4 byte alignment, the other two are byte packed. */
318
319/** @name VirtIO 1.0 SCSI Host Device device specific tmf control response values
320 * @{ */
321#define VIRTIOSCSI_EVT_ASYNC_OPERATIONAL_CHANGE 2 /**< */
322#define VIRTIOSCSI_EVT_ASYNC_POWER_MGMT 4 /**< */
323#define VIRTIOSCSI_EVT_ASYNC_EXTERNAL_REQUEST 8 /**< */
324#define VIRTIOSCSI_EVT_ASYNC_MEDIA_CHANGE 16 /**< */
325#define VIRTIOSCSI_EVT_ASYNC_MULTI_HOST 32 /**< */
326#define VIRTIOSCSI_EVT_ASYNC_DEVICE_BUSY 64 /**< */
327/** @} */
328
329#define SUBSCRIBABLE_EVENTS \
330 ( VIRTIOSCSI_EVT_ASYNC_OPERATIONAL_CHANGE \
331 | VIRTIOSCSI_EVT_ASYNC_POWER_MGMT \
332 | VIRTIOSCSI_EVT_ASYNC_EXTERNAL_REQUEST \
333 | VIRTIOSCSI_EVT_ASYNC_MEDIA_CHANGE \
334 | VIRTIOSCSI_EVT_ASYNC_MULTI_HOST \
335 | VIRTIOSCSI_EVT_ASYNC_DEVICE_BUSY )
336
337#define SUPPORTED_EVENTS 0 /* TBD */
338
339/**
340 * Worker thread context, shared state.
341 */
342typedef struct VIRTIOSCSIWORKER
343{
344 SUPSEMEVENT hEvtProcess; /**< handle of associated sleep/wake-up semaphore */
345} VIRTIOSCSIWORKER;
346/** Pointer to a VirtIO SCSI worker. */
347typedef VIRTIOSCSIWORKER *PVIRTIOSCSIWORKER;
348
349/**
350 * Worker thread context, ring-3 state.
351 */
352typedef struct VIRTIOSCSIWORKERR3
353{
354 R3PTRTYPE(PPDMTHREAD) pThread; /**< pointer to worker thread's handle */
355 bool volatile fSleeping; /**< Flags whether worker thread is sleeping or not */
356 bool volatile fNotified; /**< Flags whether worker thread notified */
357 uint16_t auRedoDescs[VIRTQ_MAX_SIZE];/**< List of previously suspended reqs to re-submit */
358 uint16_t cRedoDescs; /**< Number of redo desc chain head desc idxes in list */
359} VIRTIOSCSIWORKERR3;
360/** Pointer to a VirtIO SCSI worker. */
361typedef VIRTIOSCSIWORKERR3 *PVIRTIOSCSIWORKERR3;
362
363/**
364 * State of a target attached to the VirtIO SCSI Host
365 */
366typedef struct VIRTIOSCSITARGET
367{
368 /** The ring-3 device instance so we can easily get our bearings. */
369 PPDMDEVINSR3 pDevIns;
370
371 /** Pointer to attached driver's base interface. */
372 R3PTRTYPE(PPDMIBASE) pDrvBase;
373
374 /** Target number (PDM LUN) */
375 uint32_t uTarget;
376
377 /** Target Description */
378 R3PTRTYPE(char *) pszTargetName;
379
380 /** Target base interface. */
381 PDMIBASE IBase;
382
383 /** Flag whether device is present. */
384 bool fPresent;
385
386 /** Media port interface. */
387 PDMIMEDIAPORT IMediaPort;
388
389 /** Pointer to the attached driver's media interface. */
390 R3PTRTYPE(PPDMIMEDIA) pDrvMedia;
391
392 /** Extended media port interface. */
393 PDMIMEDIAEXPORT IMediaExPort;
394
395 /** Pointer to the attached driver's extended media interface. */
396 R3PTRTYPE(PPDMIMEDIAEX) pDrvMediaEx;
397
398 /** Status LED interface */
399 PDMILEDPORTS ILed;
400
401 /** The status LED state for this device. */
402 PDMLED led;
403
404} VIRTIOSCSITARGET, *PVIRTIOSCSITARGET;
405
406/**
407 * VirtIO Host SCSI device state, shared edition.
408 *
409 * @extends VIRTIOCORE
410 */
411typedef struct VIRTIOSCSI
412{
413 /** The core virtio state. */
414 VIRTIOCORE Virtio;
415
416 /** VirtIO Host SCSI device runtime configuration parameters */
417 VIRTIOSCSI_CONFIG_T virtioScsiConfig;
418
419 bool fBootable;
420 bool afPadding0[3];
421
422 /** Number of targets in paTargetInstances. */
423 uint32_t cTargets;
424
425 /** Per device-bound virtq worker-thread contexts (eventq slot unused) */
426 VIRTIOSCSIWORKER aWorkers[VIRTIOSCSI_QUEUE_CNT];
427
428 /** Instance name */
429 char szInstance[16];
430
431 /** Device-specific spec-based VirtIO VIRTQNAMEs */
432 char aszVirtqNames[VIRTIOSCSI_QUEUE_CNT][VIRTIO_MAX_QUEUE_NAME_SIZE];
433
434 /** Track which VirtIO queues we've attached to */
435 bool afQueueAttached[VIRTIOSCSI_QUEUE_CNT];
436
437 /** Set if events missed due to lack of bufs avail on eventq */
438 bool fEventsMissed;
439
440 /** Explicit alignment padding. */
441 bool afPadding1[2];
442
443 /** Mask of VirtIO Async Event types this device will deliver */
444 uint32_t fAsyncEvtsEnabled;
445
446 /** Total number of requests active across all targets */
447 volatile uint32_t cActiveReqs;
448
449
450 /** True if the guest/driver and VirtIO framework are in the ready state */
451 uint32_t fVirtioReady;
452
453 /** True if VIRTIO_SCSI_F_T10_PI was negotiated */
454 uint32_t fHasT10pi;
455
456 /** True if VIRTIO_SCSI_F_T10_PI was negotiated */
457 uint32_t fHasHotplug;
458
459 /** True if VIRTIO_SCSI_F_T10_PI was negotiated */
460 uint32_t fHasInOutBufs;
461
462 /** True if VIRTIO_SCSI_F_T10_PI was negotiated */
463 uint32_t fHasLunChange;
464
465 /** True if in the process of resetting */
466 uint32_t fResetting;
467
468} VIRTIOSCSI;
469/** Pointer to the shared state of the VirtIO Host SCSI device. */
470typedef VIRTIOSCSI *PVIRTIOSCSI;
471
472
473/**
474 * VirtIO Host SCSI device state, ring-3 edition.
475 *
476 * @extends VIRTIOCORER3
477 */
478typedef struct VIRTIOSCSIR3
479{
480 /** The core virtio ring-3 state. */
481 VIRTIOCORER3 Virtio;
482
483 /** Array of per-target data. */
484 R3PTRTYPE(PVIRTIOSCSITARGET) paTargetInstances;
485
486 /** Per device-bound virtq worker-thread contexts (eventq slot unused) */
487 VIRTIOSCSIWORKERR3 aWorkers[VIRTIOSCSI_QUEUE_CNT];
488
489 /** Device base interface. */
490 PDMIBASE IBase;
491
492 /** Pointer to the device instance.
493 * @note Only used in interface callbacks. */
494 PPDMDEVINSR3 pDevIns;
495
496 /** Status Target: LEDs port interface. */
497 PDMILEDPORTS ILeds;
498
499 /** IMediaExPort: Media ejection notification */
500 R3PTRTYPE(PPDMIMEDIANOTIFY) pMediaNotify;
501
502 /** Queue to send tasks to R3. - HC ptr */
503 R3PTRTYPE(PPDMQUEUE) pNotifierQueueR3;
504
505 /** True if in the process of quiescing I/O */
506 uint32_t fQuiescing;
507
508 /** For which purpose we're quiescing. */
509 VIRTIOVMSTATECHANGED enmQuiescingFor;
510
511} VIRTIOSCSIR3;
512/** Pointer to the ring-3 state of the VirtIO Host SCSI device. */
513typedef VIRTIOSCSIR3 *PVIRTIOSCSIR3;
514
515
516/**
517 * VirtIO Host SCSI device state, ring-0 edition.
518 */
519typedef struct VIRTIOSCSIR0
520{
521 /** The core virtio ring-0 state. */
522 VIRTIOCORER0 Virtio;
523} VIRTIOSCSIR0;
524/** Pointer to the ring-0 state of the VirtIO Host SCSI device. */
525typedef VIRTIOSCSIR0 *PVIRTIOSCSIR0;
526
527
528/**
529 * VirtIO Host SCSI device state, raw-mode edition.
530 */
531typedef struct VIRTIOSCSIRC
532{
533 /** The core virtio raw-mode state. */
534 VIRTIOCORERC Virtio;
535} VIRTIOSCSIRC;
536/** Pointer to the ring-0 state of the VirtIO Host SCSI device. */
537typedef VIRTIOSCSIRC *PVIRTIOSCSIRC;
538
539
540/** @typedef VIRTIOSCSICC
541 * The instance data for the current context. */
542typedef CTX_SUFF(VIRTIOSCSI) VIRTIOSCSICC;
543/** @typedef PVIRTIOSCSICC
544 * Pointer to the instance data for the current context. */
545typedef CTX_SUFF(PVIRTIOSCSI) PVIRTIOSCSICC;
546
547
548/**
549 * Request structure for IMediaEx (Associated Interfaces implemented by DrvSCSI)
550 * @note cbIn, cbOUt, cbDataOut mostly for debugging
551 */
552typedef struct VIRTIOSCSIREQ
553{
554 PDMMEDIAEXIOREQ hIoReq; /**< Handle of I/O request */
555 PVIRTIOSCSITARGET pTarget; /**< Target */
556 uint16_t qIdx; /**< Index of queue this request arrived on */
557 PVIRTIO_DESC_CHAIN_T pDescChain; /**< Prepared desc chain pulled from virtq avail ring */
558 uint32_t cbDataIn; /**< size of dataout buffer */
559 uint32_t cbDataOut; /**< size of dataout buffer */
560 uint16_t uDataInOff; /**< Fixed size of respHdr + sense (precede datain) */
561 uint16_t uDataOutOff; /**< Fixed size of respHdr + sense (precede datain) */
562 uint32_t cbSenseAlloc; /**< Size of sense buffer */
563 size_t cbSenseLen; /**< Receives \# bytes written into sense buffer */
564 uint8_t *pbSense; /**< Pointer to R3 sense buffer */
565 PDMMEDIAEXIOREQSCSITXDIR enmTxDir; /**< Receives transfer direction of I/O req */
566 uint8_t uStatus; /**< SCSI status code */
567} VIRTIOSCSIREQ;
568typedef VIRTIOSCSIREQ *PVIRTIOSCSIREQ;
569
570
571#ifdef IN_RING3 /* spans most of the file, at the moment. */
572
573
574DECLINLINE(void) virtioScsiSetVirtqNames(PVIRTIOSCSI pThis)
575{
576 RTStrCopy(pThis->aszVirtqNames[CONTROLQ_IDX], VIRTIO_MAX_QUEUE_NAME_SIZE, "controlq");
577 RTStrCopy(pThis->aszVirtqNames[EVENTQ_IDX], VIRTIO_MAX_QUEUE_NAME_SIZE, "eventq");
578 for (uint16_t qIdx = VIRTQ_REQ_BASE; qIdx < VIRTQ_REQ_BASE + VIRTIOSCSI_REQ_QUEUE_CNT; qIdx++)
579 RTStrPrintf(pThis->aszVirtqNames[qIdx], VIRTIO_MAX_QUEUE_NAME_SIZE,
580 "requestq<%d>", qIdx - VIRTQ_REQ_BASE);
581}
582
583#ifdef LOG_ENABLED
584
585
586DECLINLINE(const char *) virtioGetTxDirText(uint32_t enmTxDir)
587{
588 switch (enmTxDir)
589 {
590 case PDMMEDIAEXIOREQSCSITXDIR_UNKNOWN: return "<UNKNOWN>";
591 case PDMMEDIAEXIOREQSCSITXDIR_FROM_DEVICE: return "<DEV-TO-GUEST>";
592 case PDMMEDIAEXIOREQSCSITXDIR_TO_DEVICE: return "<GUEST-TO-DEV>";
593 case PDMMEDIAEXIOREQSCSITXDIR_NONE: return "<NONE>";
594 default: return "<BAD ENUM>";
595 }
596}
597
598DECLINLINE(const char *) virtioGetTMFTypeText(uint32_t uSubType)
599{
600 switch (uSubType)
601 {
602 case VIRTIOSCSI_T_TMF_ABORT_TASK: return "ABORT TASK";
603 case VIRTIOSCSI_T_TMF_ABORT_TASK_SET: return "ABORT TASK SET";
604 case VIRTIOSCSI_T_TMF_CLEAR_ACA: return "CLEAR ACA";
605 case VIRTIOSCSI_T_TMF_CLEAR_TASK_SET: return "CLEAR TASK SET";
606 case VIRTIOSCSI_T_TMF_I_T_NEXUS_RESET: return "I T NEXUS RESET";
607 case VIRTIOSCSI_T_TMF_LOGICAL_UNIT_RESET: return "LOGICAL UNIT RESET";
608 case VIRTIOSCSI_T_TMF_QUERY_TASK: return "QUERY TASK";
609 case VIRTIOSCSI_T_TMF_QUERY_TASK_SET: return "QUERY TASK SET";
610 default: return "<unknown>";
611 }
612}
613
614DECLINLINE(const char *) virtioGetReqRespText(uint32_t vboxRc)
615{
616 switch (vboxRc)
617 {
618 case VIRTIOSCSI_S_OK: return "OK/COMPLETE";
619 case VIRTIOSCSI_S_OVERRUN: return "OVERRRUN";
620 case VIRTIOSCSI_S_ABORTED: return "ABORTED";
621 case VIRTIOSCSI_S_BAD_TARGET: return "BAD TARGET";
622 case VIRTIOSCSI_S_RESET: return "RESET";
623 case VIRTIOSCSI_S_TRANSPORT_FAILURE: return "TRANSPORT FAILURE";
624 case VIRTIOSCSI_S_TARGET_FAILURE: return "TARGET FAILURE";
625 case VIRTIOSCSI_S_NEXUS_FAILURE: return "NEXUS FAILURE";
626 case VIRTIOSCSI_S_BUSY: return "BUSY";
627 case VIRTIOSCSI_S_FAILURE: return "FAILURE";
628 case VIRTIOSCSI_S_INCORRECT_LUN: return "INCORRECT LUN";
629 case VIRTIOSCSI_S_FUNCTION_SUCCEEDED: return "FUNCTION SUCCEEDED";
630 case VIRTIOSCSI_S_FUNCTION_REJECTED: return "FUNCTION REJECTED";
631 default: return "<unknown>";
632 }
633}
634
635DECLINLINE(void) virtioGetControlAsyncMaskText(char *pszOutput, uint32_t cbOutput, uint32_t fAsyncTypesMask)
636{
637 RTStrPrintf(pszOutput, cbOutput, "%s%s%s%s%s%s",
638 fAsyncTypesMask & VIRTIOSCSI_EVT_ASYNC_OPERATIONAL_CHANGE ? "CHANGE_OPERATION " : "",
639 fAsyncTypesMask & VIRTIOSCSI_EVT_ASYNC_POWER_MGMT ? "POWER_MGMT " : "",
640 fAsyncTypesMask & VIRTIOSCSI_EVT_ASYNC_EXTERNAL_REQUEST ? "EXTERNAL_REQ " : "",
641 fAsyncTypesMask & VIRTIOSCSI_EVT_ASYNC_MEDIA_CHANGE ? "MEDIA_CHANGE " : "",
642 fAsyncTypesMask & VIRTIOSCSI_EVT_ASYNC_MULTI_HOST ? "MULTI_HOST " : "",
643 fAsyncTypesMask & VIRTIOSCSI_EVT_ASYNC_DEVICE_BUSY ? "DEVICE_BUSY " : "");
644}
645
646static uint8_t virtioScsiEstimateCdbLen(uint8_t uCmd, uint8_t cbMax)
647{
648 if (uCmd < 0x1f)
649 return RT_MIN(6, cbMax);
650 if (uCmd >= 0x20 && uCmd < 0x60)
651 return RT_MIN(10, cbMax);
652 if (uCmd >= 0x60 && uCmd < 0x80)
653 return cbMax;
654 if (uCmd >= 0x80 && uCmd < 0xa0)
655 return RT_MIN(16, cbMax);
656 if (uCmd >= 0xa0 && uCmd < 0xc0)
657 return RT_MIN(12, cbMax);
658 return cbMax;
659}
660
661#endif /* LOG_ENABLED */
662
663static int virtioScsiR3SendEvent(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget, uint32_t uEventType, uint32_t uReason)
664{
665 switch (uEventType)
666 {
667 case VIRTIOSCSI_T_NO_EVENT:
668 Log6Func(("(target=%d, LUN=%d): Warning event info guest queued is shorter than configured\n", uTarget, LUN0));
669 break;
670 case VIRTIOSCSI_T_NO_EVENT | VIRTIOSCSI_T_EVENTS_MISSED:
671 Log6Func(("(target=%d, LUN=%d): Warning driver that events were missed\n", uTarget, LUN0));
672 break;
673 case VIRTIOSCSI_T_TRANSPORT_RESET:
674 switch (uReason)
675 {
676 case VIRTIOSCSI_EVT_RESET_REMOVED:
677 Log6Func(("(target=%d, LUN=%d): Target or LUN removed\n", uTarget, LUN0));
678 break;
679 case VIRTIOSCSI_EVT_RESET_RESCAN:
680 Log6Func(("(target=%d, LUN=%d): Target or LUN added\n", uTarget, LUN0));
681 break;
682 case VIRTIOSCSI_EVT_RESET_HARD:
683 Log6Func(("(target=%d, LUN=%d): Target was reset\n", uTarget, LUN0));
684 break;
685 }
686 break;
687 case VIRTIOSCSI_T_ASYNC_NOTIFY:
688 {
689#ifdef LOG_ENABLED
690 char szTypeText[128];
691 virtioGetControlAsyncMaskText(szTypeText, sizeof(szTypeText), uReason);
692 Log6Func(("(target=%d, LUN=%d): Delivering subscribed async notification %s\n", uTarget, LUN0, szTypeText));
693#endif
694 break;
695 }
696 case VIRTIOSCSI_T_PARAM_CHANGE:
697 LogFunc(("(target=%d, LUN=%d): PARAM_CHANGE sense code: 0x%x sense qualifier: 0x%x\n",
698 uTarget, LUN0, uReason & 0xff, (uReason >> 8) & 0xff));
699 break;
700 default:
701 Log6Func(("(target=%d, LUN=%d): Unknown event type: %d, ignoring\n", uTarget, LUN0, uEventType));
702 return VINF_SUCCESS;
703 }
704
705 PVIRTIO_DESC_CHAIN_T pDescChain = NULL;
706 int rc = virtioCoreR3QueueGet(pDevIns, &pThis->Virtio, EVENTQ_IDX, &pDescChain, true);
707 if (rc == VERR_NOT_AVAILABLE)
708 {
709 LogFunc(("eventq is empty, events missed (driver didn't preload queue)!\n"));
710 ASMAtomicWriteBool(&pThis->fEventsMissed, true);
711 return VINF_SUCCESS;
712 }
713 AssertRCReturn(rc, rc);
714
715 VIRTIOSCSI_EVENT_T Event;
716 Event.uEvent = uEventType;
717 Event.uReason = uReason;
718 Event.abVirtioLun[0] = 1;
719 Event.abVirtioLun[1] = uTarget;
720 Event.abVirtioLun[2] = (LUN0 >> 8) & 0x40;
721 Event.abVirtioLun[3] = LUN0 & 0xff;
722 Event.abVirtioLun[4] = 0;
723 Event.abVirtioLun[5] = 0;
724 Event.abVirtioLun[6] = 0;
725 Event.abVirtioLun[7] = 0;
726
727 RTSGSEG aReqSegs[1];
728 aReqSegs[0].pvSeg = &Event;
729 aReqSegs[0].cbSeg = sizeof(Event);
730
731 RTSGBUF ReqSgBuf;
732 RTSgBufInit(&ReqSgBuf, aReqSegs, RT_ELEMENTS(aReqSegs));
733
734 rc = virtioCoreR3QueuePut(pDevIns, &pThis->Virtio, EVENTQ_IDX, &ReqSgBuf, pDescChain, true /*fFence*/);
735 if (rc == VINF_SUCCESS)
736 virtioCoreQueueSync(pDevIns, &pThis->Virtio, EVENTQ_IDX, false);
737 else
738 LogRel(("Error writing control message to guest\n"));
739 virtioCoreR3DescChainRelease(&pThis->Virtio, pDescChain);
740
741 return rc;
742}
743
744/** Internal worker. */
745static void virtioScsiR3FreeReq(PVIRTIOSCSITARGET pTarget, PVIRTIOSCSIREQ pReq)
746{
747 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pTarget->pDevIns, PVIRTIOSCSI);
748 RTMemFree(pReq->pbSense);
749 pReq->pbSense = NULL;
750 virtioCoreR3DescChainRelease(&pThis->Virtio, pReq->pDescChain);
751 pReq->pDescChain = NULL;
752 pTarget->pDrvMediaEx->pfnIoReqFree(pTarget->pDrvMediaEx, pReq->hIoReq);
753}
754
755/**
756 * This is called to complete a request immediately
757 *
758 * @param pDevIns The device instance.
759 * @param pThis VirtIO SCSI shared instance data.
760 * @param pThisCC VirtIO SCSI ring-3 instance data.
761 * @param qIdx Queue index
762 * @param pDescChain Pointer to pre-processed descriptor chain pulled from virtq
763 * @param pRespHdr Response header
764 * @param pbSense Pointer to sense buffer or NULL if none.
765 * @param cbSenseCfg The configured sense buffer size.
766 *
767 * @returns VINF_SUCCESS
768 */
769static int virtioScsiR3ReqErr(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, PVIRTIOSCSICC pThisCC, uint16_t qIdx,
770 PVIRTIO_DESC_CHAIN_T pDescChain, REQ_RESP_HDR_T *pRespHdr, uint8_t *pbSense,
771 uint32_t cbSenseCfg)
772{
773 Log2Func((" status: %s response: %s\n",
774 SCSIStatusText(pRespHdr->uStatus), virtioGetReqRespText(pRespHdr->uResponse)));
775
776 RTSGSEG aReqSegs[2];
777
778 /* Segment #1: Request header*/
779 aReqSegs[0].pvSeg = pRespHdr;
780 aReqSegs[0].cbSeg = sizeof(*pRespHdr);
781
782 /* Segment #2: Sense data. */
783 uint8_t abSenseBuf[VIRTIOSCSI_SENSE_SIZE_MAX];
784 AssertCompile(VIRTIOSCSI_SENSE_SIZE_MAX <= 4096);
785 Assert(cbSenseCfg <= sizeof(abSenseBuf));
786
787 RT_ZERO(abSenseBuf);
788 if (pbSense && pRespHdr->cbSenseLen)
789 memcpy(abSenseBuf, pbSense, RT_MIN(pRespHdr->cbSenseLen, sizeof(abSenseBuf)));
790 else
791 pRespHdr->cbSenseLen = 0;
792
793 aReqSegs[1].pvSeg = abSenseBuf;
794 aReqSegs[1].cbSeg = cbSenseCfg;
795
796 /* Init S/G buffer. */
797 RTSGBUF ReqSgBuf;
798 RTSgBufInit(&ReqSgBuf, aReqSegs, RT_ELEMENTS(aReqSegs));
799
800 if (pThis->fResetting)
801 pRespHdr->uResponse = VIRTIOSCSI_S_RESET;
802
803 virtioCoreR3QueuePut(pDevIns, &pThis->Virtio, qIdx, &ReqSgBuf, pDescChain, true /* fFence */);
804 virtioCoreQueueSync(pDevIns, &pThis->Virtio, qIdx, false);
805
806 if (!ASMAtomicDecU32(&pThis->cActiveReqs) && pThisCC->fQuiescing)
807 PDMDevHlpAsyncNotificationCompleted(pDevIns);
808
809 Log2(("---------------------------------------------------------------------------------\n"));
810
811 return VINF_SUCCESS;
812}
813
814
815/**
816 * Variant of virtioScsiR3ReqErr that takes four (4) REQ_RESP_HDR_T member
817 * fields rather than a pointer to an initialized structure.
818 *
819 * @param pDevIns The device instance.
820 * @param pThis VirtIO SCSI shared instance data.
821 * @param pThisCC VirtIO SCSI ring-3 instance data.
822 * @param qIdx Queue index
823 * @param pDescChain Pointer to pre-processed descriptor chain pulled from virtq
824 * @param cbResidual The number of residual bytes or something like that.
825 * @param bStatus The SCSI status code.
826 * @param bResponse The virtio SCSI response code.
827 * @param pbSense Pointer to sense buffer or NULL if none.
828 * @param cbSense The number of bytes of sense data. Zero if none.
829 * @param cbSenseCfg The configured sense buffer size.
830 *
831 * @returns VINF_SUCCESS
832 */
833static int virtioScsiR3ReqErr4(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, PVIRTIOSCSICC pThisCC, uint16_t qIdx,
834 PVIRTIO_DESC_CHAIN_T pDescChain, uint32_t cbResidual, uint8_t bStatus, uint8_t bResponse,
835 uint8_t *pbSense, uint32_t cbSense, uint32_t cbSenseCfg)
836{
837 REQ_RESP_HDR_T RespHdr;
838 RespHdr.cbSenseLen = cbSense;
839 RespHdr.uResidual = cbResidual;
840 RespHdr.uStatusQualifier = 0;
841 RespHdr.uStatus = bStatus;
842 RespHdr.uResponse = bResponse;
843
844 return virtioScsiR3ReqErr(pDevIns, pThis, pThisCC, qIdx, pDescChain, &RespHdr, pbSense, cbSenseCfg);
845}
846
847static void virtioScsiR3SenseKeyToVirtioResp(REQ_RESP_HDR_T *respHdr, uint8_t uSenseKey)
848{
849 switch (uSenseKey)
850 {
851 case SCSI_SENSE_ABORTED_COMMAND:
852 respHdr->uResponse = VIRTIOSCSI_S_ABORTED;
853 break;
854 case SCSI_SENSE_COPY_ABORTED:
855 respHdr->uResponse = VIRTIOSCSI_S_ABORTED;
856 break;
857 case SCSI_SENSE_UNIT_ATTENTION:
858 respHdr->uResponse = VIRTIOSCSI_S_TARGET_FAILURE;
859 break;
860 case SCSI_SENSE_HARDWARE_ERROR:
861 respHdr->uResponse = VIRTIOSCSI_S_TARGET_FAILURE;
862 break;
863 case SCSI_SENSE_NOT_READY:
864 /* Not sure what to return for this. See choices at VirtIO 1.0, 5.6.6.1.1 */
865 respHdr->uResponse = VIRTIOSCSI_S_FAILURE;
866 /* respHdr->uResponse = VIRTIOSCSI_S_BUSY; */ /* BUSY is VirtIO's 'retryable' response */
867 break;
868 default:
869 respHdr->uResponse = VIRTIOSCSI_S_FAILURE;
870 break;
871 }
872}
873
874/**
875 * @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqCompleteNotify}
876 */
877static DECLCALLBACK(int) virtioScsiR3IoReqFinish(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
878 void *pvIoReqAlloc, int rcReq)
879{
880 PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaExPort);
881 PPDMDEVINS pDevIns = pTarget->pDevIns;
882 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
883 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
884 PPDMIMEDIAEX pIMediaEx = pTarget->pDrvMediaEx;
885 PVIRTIOSCSIREQ pReq = (PVIRTIOSCSIREQ)pvIoReqAlloc;
886
887 size_t cbResidual = 0;
888 int rc = pIMediaEx->pfnIoReqQueryResidual(pIMediaEx, hIoReq, &cbResidual);
889 AssertRC(rc);
890
891 size_t cbXfer = 0;
892 rc = pIMediaEx->pfnIoReqQueryXferSize(pIMediaEx, hIoReq, &cbXfer);
893 AssertRC(rc);
894
895 /* Masking deals with data type size discrepancies between
896 * The APIs (virtio and VBox). Windows C-compiler complains otherwise */
897 Assert(!(cbXfer & 0xffffffff00000000));
898 uint32_t cbXfer32 = cbXfer & 0xffffffff;
899 REQ_RESP_HDR_T respHdr = { 0 };
900 respHdr.cbSenseLen = pReq->pbSense[2] == SCSI_SENSE_NONE ? 0 : (uint32_t)pReq->cbSenseLen;
901 AssertMsg(!(cbResidual & 0xffffffff00000000),
902 ("WARNING: Residual size larger than sizeof(uint32_t), truncating"));
903 respHdr.uResidual = (uint32_t)(cbResidual & 0xffffffff);
904 respHdr.uStatus = pReq->uStatus;
905
906 /* VirtIO 1.0 spec 5.6.6.1.1 says device MUST return a VirtIO response byte value.
907 * Some are returned during the submit phase, and a few are not mapped at all,
908 * wherein anything that can't map specifically gets mapped to VIRTIOSCSI_S_FAILURE
909 */
910 if (pThis->fResetting)
911 respHdr.uResponse = VIRTIOSCSI_S_RESET;
912 else
913 {
914 switch (rcReq)
915 {
916 case SCSI_STATUS_OK:
917 {
918 if (pReq->uStatus != SCSI_STATUS_CHECK_CONDITION)
919 respHdr.uResponse = VIRTIOSCSI_S_OK;
920 else
921 virtioScsiR3SenseKeyToVirtioResp(&respHdr, pReq->pbSense[2]);
922 break;
923 }
924 case SCSI_STATUS_CHECK_CONDITION:
925 virtioScsiR3SenseKeyToVirtioResp(&respHdr, pReq->pbSense[2]);
926 break;
927
928 default:
929 respHdr.uResponse = VIRTIOSCSI_S_FAILURE;
930 break;
931 }
932 }
933
934 Log2Func(("status: (%d) %s, response: (%d) %s\n", pReq->uStatus, SCSIStatusText(pReq->uStatus),
935 respHdr.uResponse, virtioGetReqRespText(respHdr.uResponse)));
936
937 if (RT_FAILURE(rcReq))
938 Log2Func(("rcReq: %s\n", RTErrGetDefine(rcReq)));
939
940 if (LogIs3Enabled())
941 {
942 LogFunc(("cbDataIn = %u, cbDataOut = %u (cbIn = %u, cbOut = %u)\n",
943 pReq->cbDataIn, pReq->cbDataOut, pReq->pDescChain->cbPhysReturn, pReq->pDescChain->cbPhysSend));
944 LogFunc(("xfer = %lu, residual = %u\n", cbXfer, cbResidual));
945 LogFunc(("xfer direction: %s, sense written = %d, sense size = %d\n",
946 virtioGetTxDirText(pReq->enmTxDir), respHdr.cbSenseLen, pThis->virtioScsiConfig.uSenseSize));
947 }
948
949 if (respHdr.cbSenseLen && LogIs2Enabled())
950 {
951 LogFunc(("Sense: %s\n", SCSISenseText(pReq->pbSense[2])));
952 LogFunc(("Sense Ext3: %s\n", SCSISenseExtText(pReq->pbSense[12], pReq->pbSense[13])));
953 }
954
955 if ( (VIRTIO_IS_IN_DIRECTION(pReq->enmTxDir) && cbXfer32 > pReq->cbDataIn)
956 || (VIRTIO_IS_OUT_DIRECTION(pReq->enmTxDir) && cbXfer32 > pReq->cbDataOut))
957 {
958 Log2Func((" * * * * Data overrun, returning sense\n"));
959 uint8_t abSense[] = { RT_BIT(7) | SCSI_SENSE_RESPONSE_CODE_CURR_FIXED,
960 0, SCSI_SENSE_ILLEGAL_REQUEST, 0, 0, 0, 0, 10, 0, 0, 0 };
961 respHdr.cbSenseLen = sizeof(abSense);
962 respHdr.uStatus = SCSI_STATUS_CHECK_CONDITION;
963 respHdr.uResponse = VIRTIOSCSI_S_OVERRUN;
964 respHdr.uResidual = pReq->cbDataIn;
965
966 virtioScsiR3ReqErr(pDevIns, pThis, pThisCC, pReq->qIdx, pReq->pDescChain, &respHdr, abSense,
967 RT_MIN(pThis->virtioScsiConfig.uSenseSize, VIRTIOSCSI_SENSE_SIZE_MAX));
968 }
969 else
970 {
971 Assert(pReq->pbSense != NULL);
972
973 /* req datain bytes already in guest phys mem. via virtioScsiIoReqCopyFromBuf() */
974 RTSGSEG aReqSegs[2];
975
976 aReqSegs[0].pvSeg = &respHdr;
977 aReqSegs[0].cbSeg = sizeof(respHdr);
978
979 aReqSegs[1].pvSeg = pReq->pbSense;
980 aReqSegs[1].cbSeg = pReq->cbSenseAlloc; /* VirtIO 1.0 spec 5.6.4/5.6.6.1 */
981
982 RTSGBUF ReqSgBuf;
983 RTSgBufInit(&ReqSgBuf, aReqSegs, RT_ELEMENTS(aReqSegs));
984
985 size_t cbReqSgBuf = RTSgBufCalcTotalLength(&ReqSgBuf);
986 /** @todo r=bird: Returning here looks a little bogus... */
987 AssertMsgReturn(cbReqSgBuf <= pReq->pDescChain->cbPhysReturn,
988 ("Guest expected less req data (space needed: %zu, avail: %u)\n",
989 cbReqSgBuf, pReq->pDescChain->cbPhysReturn),
990 VERR_BUFFER_OVERFLOW);
991
992 virtioCoreR3QueuePut(pDevIns, &pThis->Virtio, pReq->qIdx, &ReqSgBuf, pReq->pDescChain, true /* fFence TBD */);
993 virtioCoreQueueSync(pDevIns, &pThis->Virtio, pReq->qIdx, false);
994
995 Log2(("-----------------------------------------------------------------------------------------\n"));
996 }
997
998 virtioScsiR3FreeReq(pTarget, pReq);
999
1000 if (!ASMAtomicDecU32(&pThis->cActiveReqs) && pThisCC->fQuiescing)
1001 PDMDevHlpAsyncNotificationCompleted(pDevIns);
1002
1003 return rc;
1004}
1005
1006/**
1007 * @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqCopyFromBuf}
1008 *
1009 * Copy virtual memory from VSCSI layer to guest physical memory
1010 */
1011static DECLCALLBACK(int) virtioScsiR3IoReqCopyFromBuf(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
1012 void *pvIoReqAlloc, uint32_t offDst, PRTSGBUF pSgBuf, size_t cbCopy)
1013{
1014 PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaExPort);
1015 PPDMDEVINS pDevIns = pTarget->pDevIns;
1016 PVIRTIOSCSIREQ pReq = (PVIRTIOSCSIREQ)pvIoReqAlloc;
1017 RT_NOREF(hIoReq, cbCopy);
1018
1019 if (!pReq->cbDataIn)
1020 return VINF_SUCCESS;
1021
1022 AssertReturn(pReq->pDescChain, VERR_INVALID_PARAMETER);
1023
1024 PVIRTIOSGBUF pSgPhysReturn = pReq->pDescChain->pSgPhysReturn;
1025 virtioCoreSgBufAdvance(pSgPhysReturn, offDst);
1026
1027 size_t cbCopied = 0;
1028 size_t cbRemain = pReq->cbDataIn;
1029
1030 /* Skip past the REQ_RESP_HDR_T and sense code if we're at the start of the buffer. */
1031 if (!pSgPhysReturn->idxSeg && pSgPhysReturn->cbSegLeft == pSgPhysReturn->paSegs[0].cbSeg)
1032 virtioCoreSgBufAdvance(pSgPhysReturn, pReq->uDataInOff);
1033
1034 while (cbRemain)
1035 {
1036 cbCopied = RT_MIN(pSgBuf->cbSegLeft, pSgPhysReturn->cbSegLeft);
1037 Assert(cbCopied > 0);
1038 PDMDevHlpPCIPhysWrite(pDevIns, pSgPhysReturn->gcPhysCur, pSgBuf->pvSegCur, cbCopied);
1039 RTSgBufAdvance(pSgBuf, cbCopied);
1040 virtioCoreSgBufAdvance(pSgPhysReturn, cbCopied);
1041 cbRemain -= cbCopied;
1042 }
1043 RT_UNTRUSTED_NONVOLATILE_COPY_FENCE(); /* needed? */
1044
1045 Log3Func((".... Copied %lu bytes from %lu byte guest buffer, residual=%lu\n",
1046 cbCopy, pReq->pDescChain->cbPhysReturn, pReq->pDescChain->cbPhysReturn - cbCopy));
1047
1048 return VINF_SUCCESS;
1049}
1050
1051/**
1052 * @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqCopyToBuf}
1053 *
1054 * Copy guest physical memory to VSCSI layer virtual memory
1055 */
1056static DECLCALLBACK(int) virtioScsiR3IoReqCopyToBuf(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
1057 void *pvIoReqAlloc, uint32_t offSrc, PRTSGBUF pSgBuf, size_t cbCopy)
1058{
1059 PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaExPort);
1060 PPDMDEVINS pDevIns = pTarget->pDevIns;
1061 PVIRTIOSCSIREQ pReq = (PVIRTIOSCSIREQ)pvIoReqAlloc;
1062 RT_NOREF(hIoReq, cbCopy);
1063
1064 if (!pReq->cbDataOut)
1065 return VINF_SUCCESS;
1066
1067 PVIRTIOSGBUF pSgPhysSend = pReq->pDescChain->pSgPhysSend;
1068 virtioCoreSgBufAdvance(pSgPhysSend, offSrc);
1069
1070 size_t cbCopied = 0;
1071 size_t cbRemain = pReq->cbDataOut;
1072 while (cbRemain)
1073 {
1074 cbCopied = RT_MIN(pSgBuf->cbSegLeft, pSgPhysSend->cbSegLeft);
1075 Assert(cbCopied > 0);
1076 PDMDevHlpPCIPhysRead(pDevIns, pSgPhysSend->gcPhysCur, pSgBuf->pvSegCur, cbCopied);
1077 RTSgBufAdvance(pSgBuf, cbCopied);
1078 virtioCoreSgBufAdvance(pSgPhysSend, cbCopied);
1079 cbRemain -= cbCopied;
1080 }
1081
1082 Log2Func((".... Copied %lu bytes to %lu byte guest buffer, residual=%lu\n",
1083 cbCopy, pReq->pDescChain->cbPhysReturn, pReq->pDescChain->cbPhysReturn - cbCopy));
1084
1085 return VINF_SUCCESS;
1086}
1087
1088/**
1089 * Handles request queues for/on a worker thread.
1090 *
1091 * @returns VBox status code (logged by caller).
1092 */
1093static int virtioScsiR3ReqSubmit(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, PVIRTIOSCSICC pThisCC,
1094 uint16_t qIdx, PVIRTIO_DESC_CHAIN_T pDescChain)
1095{
1096
1097 ASMAtomicIncU32(&pThis->cActiveReqs);
1098
1099 /*
1100 * Validate configuration values we use here before we start.
1101 */
1102 uint32_t const cbCdb = pThis->virtioScsiConfig.uCdbSize;
1103 uint32_t const cbSenseCfg = pThis->virtioScsiConfig.uSenseSize;
1104 /** @todo Report these as errors to the guest or does the caller do that? */
1105 ASSERT_GUEST_LOGREL_MSG_RETURN(cbCdb <= VIRTIOSCSI_CDB_SIZE_MAX, ("cbCdb=%#x\n", cbCdb), VERR_OUT_OF_RANGE);
1106 ASSERT_GUEST_LOGREL_MSG_RETURN(cbSenseCfg <= VIRTIOSCSI_SENSE_SIZE_MAX, ("cbSenseCfg=%#x\n", cbSenseCfg), VERR_OUT_OF_RANGE);
1107
1108 /*
1109 * Extract command header and CDB from guest physical memory
1110 * The max size is rather small here (19 + 255 = 274), so put
1111 * it on the stack.
1112 */
1113 size_t const cbReqHdr = sizeof(REQ_CMD_HDR_T) + cbCdb;
1114 AssertReturn(pDescChain->cbPhysSend >= cbReqHdr, VERR_INVALID_PARAMETER);
1115
1116 AssertCompile(VIRTIOSCSI_CDB_SIZE_MAX < 4096);
1117 union
1118 {
1119 RT_GCC_EXTENSION struct
1120 {
1121 REQ_CMD_HDR_T ReqHdr;
1122 uint8_t abCdb[VIRTIOSCSI_CDB_SIZE_MAX];
1123 } ;
1124 uint8_t ab[sizeof(REQ_CMD_HDR_T) + VIRTIOSCSI_CDB_SIZE_MAX];
1125 uint64_t au64Align[(sizeof(REQ_CMD_HDR_T) + VIRTIOSCSI_CDB_SIZE_MAX) / sizeof(uint64_t)];
1126 } VirtqReq;
1127 RT_ZERO(VirtqReq);
1128
1129 for (size_t offReq = 0; offReq < cbReqHdr; )
1130 {
1131 size_t cbSeg = cbReqHdr - offReq;
1132 RTGCPHYS GCPhys = virtioCoreSgBufGetNextSegment(pDescChain->pSgPhysSend, &cbSeg);
1133 PDMDevHlpPCIPhysRead(pDevIns, GCPhys, &VirtqReq.ab[offReq], cbSeg);
1134 offReq += cbSeg;
1135 }
1136
1137 uint8_t const uType = VirtqReq.ReqHdr.abVirtioLun[0];
1138 uint8_t const uTarget = VirtqReq.ReqHdr.abVirtioLun[1];
1139 uint32_t uScsiLun = RT_MAKE_U16(VirtqReq.ReqHdr.abVirtioLun[3], VirtqReq.ReqHdr.abVirtioLun[2]) & 0x3fff;
1140
1141 bool fBadLUNFormat = false;
1142 if (uType == 0xc1 && uTarget == 0x01)
1143 {
1144 LogRel(("* * * REPORT LUNS LU ACCESSED * * * "));
1145 /* Force rejection. */ /** @todo figure out right way to handle. Note this is a very
1146 * vague and confusing part of the VirtIO spec (which deviates from the SCSI standard).
1147 * I have not been able to determine how to implement this properly. I've checked the
1148 * source code of Guest drivers, so far, and none I've found use it. If logs show
1149 * this warning implementing it can be re-visited */
1150 uScsiLun = 0xff;
1151 }
1152 else
1153 if (uType != 1)
1154 fBadLUNFormat = true;
1155
1156 LogFunc(("[%s] (Target: %d LUN: %d) CDB: %.*Rhxs\n",
1157 SCSICmdText(VirtqReq.abCdb[0]), uTarget, uScsiLun,
1158 virtioScsiEstimateCdbLen(VirtqReq.abCdb[0], cbCdb), &VirtqReq.abCdb[0]));
1159
1160 Log3Func(("cmd id: %RX64, attr: %x, prio: %d, crn: %x\n",
1161 VirtqReq.ReqHdr.uId, VirtqReq.ReqHdr.uTaskAttr, VirtqReq.ReqHdr.uPrio, VirtqReq.ReqHdr.uCrn));
1162
1163 /*
1164 * Calculate request offsets and data sizes.
1165 */
1166 uint32_t const offDataOut = sizeof(REQ_CMD_HDR_T) + cbCdb;
1167 uint32_t const offDataIn = sizeof(REQ_RESP_HDR_T) + cbSenseCfg;
1168 uint32_t const cbDataOut = pDescChain->cbPhysSend - offDataOut;
1169 /** @todo r=bird: Validate cbPhysReturn properly? I've just RT_MAX'ed it for now. */
1170 uint32_t const cbDataIn = RT_MAX(pDescChain->cbPhysReturn, offDataIn) - offDataIn;
1171 Assert(offDataOut <= UINT16_MAX);
1172 Assert(offDataIn <= UINT16_MAX);
1173
1174 /*
1175 * Handle submission errors
1176 */
1177 if (RT_LIKELY(!fBadLUNFormat))
1178 { /* likely */ }
1179 else
1180 {
1181 Log2Func(("Error submitting request, bad LUN format\n"));
1182 return virtioScsiR3ReqErr4(pDevIns, pThis, pThisCC, qIdx, pDescChain, cbDataIn + cbDataOut, 0 /*bStatus*/,
1183 VIRTIOSCSI_S_FAILURE, NULL /*pbSense*/, 0 /*cbSense*/, cbSenseCfg);
1184 }
1185
1186 PVIRTIOSCSITARGET const pTarget = &pThisCC->paTargetInstances[uTarget];
1187 if (RT_LIKELY( uTarget < pThis->cTargets
1188 && pTarget->fPresent
1189 && pTarget->pDrvMediaEx))
1190 { /* likely */ }
1191 else
1192 {
1193 Log2Func(("Error submitting request to bad target (%d) or bad LUN (%d)\n", uTarget, uScsiLun));
1194 uint8_t abSense[] = { RT_BIT(7) | SCSI_SENSE_RESPONSE_CODE_CURR_FIXED,
1195 0, SCSI_SENSE_ILLEGAL_REQUEST,
1196 0, 0, 0, 0, 10, SCSI_ASC_LOGICAL_UNIT_NOT_SUPPORTED, 0, 0 };
1197 return virtioScsiR3ReqErr4(pDevIns, pThis, pThisCC, qIdx, pDescChain, cbDataIn + cbDataOut, SCSI_STATUS_CHECK_CONDITION,
1198 VIRTIOSCSI_S_BAD_TARGET, abSense, sizeof(abSense), cbSenseCfg);
1199 }
1200 if (RT_LIKELY(uScsiLun == 0))
1201 { /* likely */ }
1202 else
1203 {
1204 Log2Func(("Error submitting request to bad target (%d) or bad LUN (%d)\n", uTarget, uScsiLun));
1205 uint8_t abSense[] = { RT_BIT(7) | SCSI_SENSE_RESPONSE_CODE_CURR_FIXED,
1206 0, SCSI_SENSE_ILLEGAL_REQUEST,
1207 0, 0, 0, 0, 10, SCSI_ASC_LOGICAL_UNIT_NOT_SUPPORTED, 0, 0 };
1208 return virtioScsiR3ReqErr4(pDevIns, pThis, pThisCC, qIdx, pDescChain, cbDataIn + cbDataOut, SCSI_STATUS_CHECK_CONDITION,
1209 VIRTIOSCSI_S_OK, abSense, sizeof(abSense), cbSenseCfg);
1210 }
1211 if (RT_LIKELY(!pThis->fResetting))
1212 { /* likely */ }
1213 else
1214 {
1215 Log2Func(("Aborting req submission because reset is in progress\n"));
1216 return virtioScsiR3ReqErr4(pDevIns, pThis, pThisCC, qIdx, pDescChain, cbDataIn + cbDataOut, SCSI_STATUS_OK,
1217 VIRTIOSCSI_S_RESET, NULL /*pbSense*/, 0 /*cbSense*/, cbSenseCfg);
1218 }
1219
1220 if (RT_LIKELY(!cbDataIn || !cbDataOut || pThis->fHasInOutBufs)) /* VirtIO 1.0, 5.6.6.1.1 */
1221 { /* likely */ }
1222 else
1223 {
1224 Log2Func(("Error submitting request, got datain & dataout bufs w/o INOUT feature negotated\n"));
1225 uint8_t abSense[] = { RT_BIT(7) | SCSI_SENSE_RESPONSE_CODE_CURR_FIXED,
1226 0, SCSI_SENSE_ILLEGAL_REQUEST, 0, 0, 0, 0, 10, 0, 0, 0 };
1227 return virtioScsiR3ReqErr4(pDevIns, pThis, pThisCC, qIdx, pDescChain, cbDataIn + cbDataOut, SCSI_STATUS_CHECK_CONDITION,
1228 VIRTIOSCSI_S_FAILURE, abSense, sizeof(abSense), cbSenseCfg);
1229 }
1230
1231 /*
1232 * Have underlying driver allocate a req of size set during initialization of this device.
1233 */
1234 PDMMEDIAEXIOREQ hIoReq = NULL;
1235 PVIRTIOSCSIREQ pReq = NULL;
1236 PPDMIMEDIAEX pIMediaEx = pTarget->pDrvMediaEx;
1237
1238 int rc = pIMediaEx->pfnIoReqAlloc(pIMediaEx, &hIoReq, (void **)&pReq, 0 /* uIoReqId */,
1239 PDMIMEDIAEX_F_SUSPEND_ON_RECOVERABLE_ERR);
1240
1241 AssertMsgRCReturn(rc, ("Failed to allocate I/O request, rc=%Rrc\n", rc), rc);
1242
1243 pReq->hIoReq = hIoReq;
1244 pReq->pTarget = pTarget;
1245 pReq->qIdx = qIdx;
1246 pReq->cbDataIn = cbDataIn;
1247 pReq->cbDataOut = cbDataOut;
1248 pReq->pDescChain = pDescChain;
1249 virtioCoreR3DescChainRetain(pDescChain); /* (For pReq->pDescChain. Released by virtioScsiR3FreeReq.) */
1250 pReq->uDataInOff = offDataIn;
1251 pReq->uDataOutOff = offDataOut;
1252
1253 pReq->cbSenseAlloc = cbSenseCfg;
1254 pReq->pbSense = (uint8_t *)RTMemAllocZ(pReq->cbSenseAlloc);
1255 AssertMsgReturnStmt(pReq->pbSense, ("Out of memory allocating sense buffer"),
1256 virtioScsiR3FreeReq(pTarget, pReq);, VERR_NO_MEMORY);
1257
1258 /* Note: DrvSCSI allocates one virtual memory buffer for input and output phases of the request */
1259 rc = pIMediaEx->pfnIoReqSendScsiCmd(pIMediaEx, pReq->hIoReq, uScsiLun,
1260 &VirtqReq.abCdb[0], cbCdb,
1261 PDMMEDIAEXIOREQSCSITXDIR_UNKNOWN, &pReq->enmTxDir,
1262 RT_MAX(cbDataIn, cbDataOut),
1263 pReq->pbSense, pReq->cbSenseAlloc, &pReq->cbSenseLen,
1264 &pReq->uStatus, RT_MS_30SEC);
1265
1266 if (rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
1267 {
1268 /*
1269 * Getting here means the request failed in early in the submission to the lower level driver,
1270 * and there will be no callback to the finished/completion function for this request
1271 */
1272 Assert(RT_FAILURE_NP(rc));
1273 Log2Func(("Request submission error from lower-level driver\n"));
1274 uint8_t uASC, uASCQ = 0;
1275 switch (rc)
1276 {
1277 case VERR_NO_MEMORY:
1278 uASC = SCSI_ASC_SYSTEM_RESOURCE_FAILURE;
1279 break;
1280 default:
1281 uASC = SCSI_ASC_INTERNAL_TARGET_FAILURE;
1282 break;
1283 }
1284 uint8_t abSense[] = { RT_BIT(7) | SCSI_SENSE_RESPONSE_CODE_CURR_FIXED,
1285 0, SCSI_SENSE_VENDOR_SPECIFIC,
1286 0, 0, 0, 0, 10, uASC, uASCQ, 0 };
1287 REQ_RESP_HDR_T respHdr = { 0 };
1288 respHdr.cbSenseLen = sizeof(abSense);
1289 respHdr.uStatus = SCSI_STATUS_CHECK_CONDITION;
1290 respHdr.uResponse = VIRTIOSCSI_S_FAILURE;
1291 respHdr.uResidual = cbDataIn + cbDataOut;
1292 virtioScsiR3ReqErr(pDevIns, pThis, pThisCC, qIdx, pDescChain, &respHdr, abSense, cbSenseCfg);
1293 virtioScsiR3FreeReq(pTarget, pReq);
1294 }
1295
1296 return VINF_SUCCESS;
1297}
1298
1299/**
1300 * Handles control transfers for/on a worker thread.
1301 *
1302 * @returns VBox status code (ignored by the caller).
1303 * @param pDevIns The device instance.
1304 * @param pThis VirtIO SCSI shared instance data.
1305 * @param pThisCC VirtIO SCSI ring-3 instance data.
1306 * @param qIdx CONTROLQ_IDX
1307 * @param pDescChain Descriptor chain to process.
1308 */
1309static int virtioScsiR3Ctrl(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, PVIRTIOSCSICC pThisCC,
1310 uint16_t qIdx, PVIRTIO_DESC_CHAIN_T pDescChain)
1311{
1312 AssertReturn(pDescChain->cbPhysSend >= RT_MIN(sizeof(VIRTIOSCSI_CTRL_AN_T),
1313 sizeof(VIRTIOSCSI_CTRL_TMF_T)), 0);
1314
1315 /*
1316 * Allocate buffer and read in the control command
1317 */
1318 VIRTIO_SCSI_CTRL_UNION_T ScsiCtrlUnion;
1319 RT_ZERO(ScsiCtrlUnion);
1320
1321 size_t const cbCtrl = RT_MIN(pDescChain->cbPhysSend, sizeof(VIRTIO_SCSI_CTRL_UNION_T));
1322 for (size_t offCtrl = 0; offCtrl < cbCtrl; )
1323 {
1324 size_t cbSeg = cbCtrl - offCtrl;
1325 RTGCPHYS GCPhys = virtioCoreSgBufGetNextSegment(pDescChain->pSgPhysSend, &cbSeg);
1326 PDMDevHlpPCIPhysRead(pDevIns, GCPhys, &ScsiCtrlUnion.ab[offCtrl], cbSeg);
1327 offCtrl += cbSeg;
1328 }
1329
1330 AssertReturn( (ScsiCtrlUnion.Type.uType == VIRTIOSCSI_T_TMF
1331 && pDescChain->cbPhysSend >= sizeof(VIRTIOSCSI_CTRL_TMF_T))
1332 || ( ( ScsiCtrlUnion.Type.uType == VIRTIOSCSI_T_AN_QUERY
1333 || ScsiCtrlUnion.Type.uType == VIRTIOSCSI_T_AN_SUBSCRIBE)
1334 && pDescChain->cbPhysSend >= sizeof(VIRTIOSCSI_CTRL_AN_T)),
1335 0 /** @todo r=bird: what kind of status is '0' here? */);
1336
1337 union
1338 {
1339 uint32_t fSupportedEvents;
1340 } uData;
1341 uint8_t bResponse = VIRTIOSCSI_S_OK;
1342 uint8_t cSegs;
1343 RTSGSEG aReqSegs[2];
1344 switch (ScsiCtrlUnion.Type.uType)
1345 {
1346 case VIRTIOSCSI_T_TMF: /* Task Management Functions */
1347 {
1348 uint8_t uTarget = ScsiCtrlUnion.Tmf.abScsiLun[1];
1349 uint32_t uScsiLun = RT_MAKE_U16(ScsiCtrlUnion.Tmf.abScsiLun[3], ScsiCtrlUnion.Tmf.abScsiLun[2]) & 0x3fff;
1350 Log2Func(("[%s] (Target: %d LUN: %d) Task Mgt Function: %s\n",
1351 VIRTQNAME(qIdx), uTarget, uScsiLun, virtioGetTMFTypeText(ScsiCtrlUnion.Tmf.uSubtype)));
1352
1353 if (uTarget >= pThis->cTargets || !pThisCC->paTargetInstances[uTarget].fPresent)
1354 bResponse = VIRTIOSCSI_S_BAD_TARGET;
1355 else
1356 if (uScsiLun != 0)
1357 bResponse = VIRTIOSCSI_S_INCORRECT_LUN;
1358 else
1359 switch (ScsiCtrlUnion.Tmf.uSubtype)
1360 {
1361 case VIRTIOSCSI_T_TMF_ABORT_TASK:
1362 bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
1363 break;
1364 case VIRTIOSCSI_T_TMF_ABORT_TASK_SET:
1365 bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
1366 break;
1367 case VIRTIOSCSI_T_TMF_CLEAR_ACA:
1368 bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
1369 break;
1370 case VIRTIOSCSI_T_TMF_CLEAR_TASK_SET:
1371 bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
1372 break;
1373 case VIRTIOSCSI_T_TMF_I_T_NEXUS_RESET:
1374 bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
1375 break;
1376 case VIRTIOSCSI_T_TMF_LOGICAL_UNIT_RESET:
1377 bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
1378 break;
1379 case VIRTIOSCSI_T_TMF_QUERY_TASK:
1380 bResponse = VIRTIOSCSI_S_FUNCTION_REJECTED;
1381 break;
1382 case VIRTIOSCSI_T_TMF_QUERY_TASK_SET:
1383 bResponse = VIRTIOSCSI_S_FUNCTION_REJECTED;
1384 break;
1385 default:
1386 LogFunc(("Unknown TMF type\n"));
1387 bResponse = VIRTIOSCSI_S_FAILURE;
1388 }
1389 cSegs = 0; /* only bResponse */
1390 break;
1391 }
1392 case VIRTIOSCSI_T_AN_QUERY: /* Guest SCSI driver is querying supported async event notifications */
1393 {
1394 uint8_t uTarget = ScsiCtrlUnion.AsyncNotify.abScsiLun[1];
1395 uint32_t uScsiLun = RT_MAKE_U16(ScsiCtrlUnion.AsyncNotify.abScsiLun[3],
1396 ScsiCtrlUnion.AsyncNotify.abScsiLun[2]) & 0x3fff;
1397
1398 if (uTarget >= pThis->cTargets || !pThisCC->paTargetInstances[uTarget].fPresent)
1399 bResponse = VIRTIOSCSI_S_BAD_TARGET;
1400 else
1401 if (uScsiLun != 0)
1402 bResponse = VIRTIOSCSI_S_INCORRECT_LUN;
1403 else
1404 bResponse = VIRTIOSCSI_S_FUNCTION_COMPLETE;
1405
1406#ifdef LOG_ENABLED
1407 if (LogIs2Enabled())
1408 {
1409 char szTypeText[128];
1410 virtioGetControlAsyncMaskText(szTypeText, sizeof(szTypeText), ScsiCtrlUnion.AsyncNotify.fEventsRequested);
1411 Log2Func(("[%s] (Target: %d LUN: %d) Async. Notification Query: %s\n",
1412 VIRTQNAME(qIdx), uTarget, uScsiLun, szTypeText));
1413 }
1414#endif
1415 uData.fSupportedEvents = SUPPORTED_EVENTS;
1416 aReqSegs[0].pvSeg = &uData.fSupportedEvents;
1417 aReqSegs[0].cbSeg = sizeof(uData.fSupportedEvents);
1418 cSegs = 1;
1419 break;
1420 }
1421 case VIRTIOSCSI_T_AN_SUBSCRIBE: /* Guest SCSI driver is subscribing to async event notification(s) */
1422 {
1423 if (ScsiCtrlUnion.AsyncNotify.fEventsRequested & ~SUBSCRIBABLE_EVENTS)
1424 LogFunc(("Unsupported bits in event subscription event mask: %#x\n",
1425 ScsiCtrlUnion.AsyncNotify.fEventsRequested));
1426
1427 uint8_t uTarget = ScsiCtrlUnion.AsyncNotify.abScsiLun[1];
1428 uint32_t uScsiLun = RT_MAKE_U16(ScsiCtrlUnion.AsyncNotify.abScsiLun[3],
1429 ScsiCtrlUnion.AsyncNotify.abScsiLun[2]) & 0x3fff;
1430
1431#ifdef LOG_ENABLED
1432 if (LogIs2Enabled())
1433 {
1434 char szTypeText[128];
1435 virtioGetControlAsyncMaskText(szTypeText, sizeof(szTypeText), ScsiCtrlUnion.AsyncNotify.fEventsRequested);
1436 Log2Func(("[%s] (Target: %d LUN: %d) Async. Notification Subscribe: %s\n",
1437 VIRTQNAME(qIdx), uTarget, uScsiLun, szTypeText));
1438 }
1439#endif
1440 if (uTarget >= pThis->cTargets || !pThisCC->paTargetInstances[uTarget].fPresent)
1441 bResponse = VIRTIOSCSI_S_BAD_TARGET;
1442 else
1443 if (uScsiLun != 0)
1444 bResponse = VIRTIOSCSI_S_INCORRECT_LUN;
1445 else
1446 {
1447 bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED; /* or VIRTIOSCSI_S_FUNCTION_COMPLETE? */
1448 pThis->fAsyncEvtsEnabled = SUPPORTED_EVENTS & ScsiCtrlUnion.AsyncNotify.fEventsRequested;
1449 }
1450
1451 aReqSegs[0].pvSeg = &pThis->fAsyncEvtsEnabled;
1452 aReqSegs[0].cbSeg = sizeof(pThis->fAsyncEvtsEnabled);
1453 cSegs = 1;
1454 break;
1455 }
1456 default:
1457 {
1458 LogFunc(("Unknown control type extracted from %s: %u\n", VIRTQNAME(qIdx), ScsiCtrlUnion.Type.uType));
1459
1460 bResponse = VIRTIOSCSI_S_FAILURE;
1461 cSegs = 0; /* only bResponse */
1462 break;
1463 }
1464 }
1465
1466 /* Add the response code: */
1467 aReqSegs[cSegs].pvSeg = &bResponse;
1468 aReqSegs[cSegs].cbSeg = sizeof(bResponse);
1469 cSegs++;
1470 Assert(cSegs <= RT_ELEMENTS(aReqSegs));
1471
1472 LogFunc(("Response code: %s\n", virtioGetReqRespText(bResponse)));
1473
1474 RTSGBUF ReqSgBuf;
1475 RTSgBufInit(&ReqSgBuf, aReqSegs, cSegs);
1476
1477 virtioCoreR3QueuePut(pDevIns, &pThis->Virtio, qIdx, &ReqSgBuf, pDescChain, true /*fFence*/);
1478 virtioCoreQueueSync(pDevIns, &pThis->Virtio, qIdx, false);
1479
1480 return VINF_SUCCESS;
1481}
1482
1483/**
1484 * @callback_method_impl{FNPDMTHREADWAKEUPDEV}
1485 */
1486static DECLCALLBACK(int) virtioScsiR3WorkerWakeUp(PPDMDEVINS pDevIns, PPDMTHREAD pThread)
1487{
1488 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
1489 return PDMDevHlpSUPSemEventSignal(pDevIns, pThis->aWorkers[(uintptr_t)pThread->pvUser].hEvtProcess);
1490}
1491
1492/**
1493 * @callback_method_impl{FNPDMTHREADDEV}
1494 */
1495static DECLCALLBACK(int) virtioScsiR3WorkerThread(PPDMDEVINS pDevIns, PPDMTHREAD pThread)
1496{
1497 uint16_t const qIdx = (uint16_t)(uintptr_t)pThread->pvUser;
1498 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
1499 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
1500 PVIRTIOSCSIWORKER pWorker = &pThis->aWorkers[qIdx];
1501 PVIRTIOSCSIWORKERR3 pWorkerR3 = &pThisCC->aWorkers[qIdx];
1502
1503 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
1504 return VINF_SUCCESS;
1505
1506 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
1507 {
1508 if (!pWorkerR3->cRedoDescs && virtioCoreQueueIsEmpty(pDevIns, &pThis->Virtio, qIdx))
1509 {
1510 /* Atomic interlocks avoid missing alarm while going to sleep & notifier waking the awoken */
1511 ASMAtomicWriteBool(&pWorkerR3->fSleeping, true);
1512 bool fNotificationSent = ASMAtomicXchgBool(&pWorkerR3->fNotified, false);
1513 if (!fNotificationSent)
1514 {
1515 Log6Func(("%s worker sleeping...\n", VIRTQNAME(qIdx)));
1516 Assert(ASMAtomicReadBool(&pWorkerR3->fSleeping));
1517 int rc = PDMDevHlpSUPSemEventWaitNoResume(pDevIns, pWorker->hEvtProcess, RT_INDEFINITE_WAIT);
1518 AssertLogRelMsgReturn(RT_SUCCESS(rc) || rc == VERR_INTERRUPTED, ("%Rrc\n", rc), rc);
1519 if (RT_UNLIKELY(pThread->enmState != PDMTHREADSTATE_RUNNING))
1520 return VINF_SUCCESS;
1521 if (rc == VERR_INTERRUPTED)
1522 continue;
1523 Log6Func(("%s worker woken\n", VIRTQNAME(qIdx)));
1524 ASMAtomicWriteBool(&pWorkerR3->fNotified, false);
1525 }
1526 ASMAtomicWriteBool(&pWorkerR3->fSleeping, false);
1527 }
1528
1529 if (!pThis->afQueueAttached[qIdx])
1530 {
1531 LogFunc(("%s queue not attached, worker aborting...\n", VIRTQNAME(qIdx)));
1532 break;
1533 }
1534 if (!pThisCC->fQuiescing)
1535 {
1536 /* Process any reqs that were suspended saved to the redo queue in save exec. */
1537 for (int i = 0; i < pWorkerR3->cRedoDescs; i++)
1538 {
1539 PVIRTIO_DESC_CHAIN_T pDescChain;
1540 int rc = virtioCoreR3DescChainGet(pDevIns, &pThis->Virtio, qIdx,
1541 pWorkerR3->auRedoDescs[i], &pDescChain);
1542 if (RT_FAILURE(rc))
1543 LogRel(("Error fetching desc chain to redo, %Rrc", rc));
1544
1545 rc = virtioScsiR3ReqSubmit(pDevIns, pThis, pThisCC, qIdx, pDescChain);
1546 if (RT_FAILURE(rc))
1547 LogRel(("Error submitting req packet, resetting %Rrc", rc));
1548
1549 virtioCoreR3DescChainRelease(&pThis->Virtio, pDescChain);
1550 }
1551 pWorkerR3->cRedoDescs = 0;
1552
1553 Log6Func(("fetching next descriptor chain from %s\n", VIRTQNAME(qIdx)));
1554 PVIRTIO_DESC_CHAIN_T pDescChain = NULL;
1555 int rc = virtioCoreR3QueueGet(pDevIns, &pThis->Virtio, qIdx, &pDescChain, true);
1556 if (rc == VERR_NOT_AVAILABLE)
1557 {
1558 Log6Func(("Nothing found in %s\n", VIRTQNAME(qIdx)));
1559 continue;
1560 }
1561
1562 AssertRC(rc);
1563 if (qIdx == CONTROLQ_IDX)
1564 virtioScsiR3Ctrl(pDevIns, pThis, pThisCC, qIdx, pDescChain);
1565 else /* request queue index */
1566 {
1567 rc = virtioScsiR3ReqSubmit(pDevIns, pThis, pThisCC, qIdx, pDescChain);
1568 if (RT_FAILURE(rc))
1569 LogRel(("Error submitting req packet, resetting %Rrc", rc));
1570 }
1571
1572 virtioCoreR3DescChainRelease(&pThis->Virtio, pDescChain);
1573 }
1574 }
1575 return VINF_SUCCESS;
1576}
1577
1578
1579/*********************************************************************************************************************************
1580* Sending evnets
1581*********************************************************************************************************************************/
1582
1583DECLINLINE(void) virtioScsiR3ReportEventsMissed(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget)
1584{
1585 virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_NO_EVENT | VIRTIOSCSI_T_EVENTS_MISSED, 0);
1586}
1587
1588
1589#if 0
1590/* SUBSCRIBABLE EVENT - not sure when to call this or how to detect when media is added or removed
1591 * via the VBox GUI */
1592DECLINLINE(void) virtioScsiR3ReportMediaChange(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget)
1593{
1594 if (pThis->fAsyncEvtsEnabled & VIRTIOSCSI_EVT_ASYNC_MEDIA_CHANGE)
1595 virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_ASYNC_NOTIFY, VIRTIOSCSI_EVT_ASYNC_MEDIA_CHANGE);
1596}
1597
1598/* ESSENTIAL (NON-SUBSCRIBABLE) EVENT TYPES (most guest virtio-scsi drivers ignore?) */
1599
1600DECLINLINE(void) virtioScsiR3ReportTransportReset(PDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget)
1601{
1602 virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_TRANSPORT_RESET, VIRTIOSCSI_EVT_RESET_HARD);
1603}
1604
1605DECLINLINE(void) virtioScsiR3ReportParamChange(PDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget,
1606 uint32_t uSenseCode, uint32_t uSenseQualifier)
1607{
1608 uint32_t uReason = uSenseQualifier << 8 | uSenseCode;
1609 virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_PARAM_CHANGE, uReason);
1610
1611}
1612
1613DECLINLINE(void) virtioScsiR3ReportTargetRemoved(PDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget)
1614{
1615 if (pThis->fHasHotplug)
1616 virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_TRANSPORT_RESET, VIRTIOSCSI_EVT_RESET_REMOVED);
1617}
1618
1619DECLINLINE(void) virtioScsiR3ReportTargetAdded(PDMDEVINS pDevInsPVIRTIOSCSI pThis, uint16_t uTarget)
1620{
1621 if (pThis->fHasHotplug)
1622 virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_TRANSPORT_RESET, VIRTIOSCSI_EVT_RESET_RESCAN);
1623}
1624
1625#endif
1626
1627/**
1628 * @callback_method_impl{VIRTIOCORER3,pfnQueueNotified}
1629 */
1630static DECLCALLBACK(void) virtioScsiR3Notified(PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC, uint16_t qIdx)
1631{
1632 PVIRTIOSCSI pThis = RT_FROM_MEMBER(pVirtio, VIRTIOSCSI, Virtio);
1633 PVIRTIOSCSICC pThisCC = RT_FROM_MEMBER(pVirtioCC, VIRTIOSCSICC, Virtio);
1634 PPDMDEVINS pDevIns = pThisCC->pDevIns;
1635 AssertReturnVoid(qIdx < VIRTIOSCSI_QUEUE_CNT);
1636 PVIRTIOSCSIWORKER pWorker = &pThis->aWorkers[qIdx];
1637 PVIRTIOSCSIWORKERR3 pWorkerR3 = &pThisCC->aWorkers[qIdx];
1638
1639#ifdef LOG_ENABLED
1640 RTLogFlush(NULL);
1641#endif
1642
1643 if (qIdx == CONTROLQ_IDX || IS_REQ_QUEUE(qIdx))
1644 {
1645 Log6Func(("%s has available data\n", VIRTQNAME(qIdx)));
1646 /* Wake queue's worker thread up if sleeping */
1647 if (!ASMAtomicXchgBool(&pWorkerR3->fNotified, true))
1648 {
1649 if (ASMAtomicReadBool(&pWorkerR3->fSleeping))
1650 {
1651 Log6Func(("waking %s worker.\n", VIRTQNAME(qIdx)));
1652 int rc = PDMDevHlpSUPSemEventSignal(pDevIns, pWorker->hEvtProcess);
1653 AssertRC(rc);
1654 }
1655 }
1656 }
1657 else if (qIdx == EVENTQ_IDX)
1658 {
1659 Log3Func(("Driver queued buffer(s) to %s\n", VIRTQNAME(qIdx)));
1660 if (ASMAtomicXchgBool(&pThis->fEventsMissed, false))
1661 virtioScsiR3ReportEventsMissed(pDevIns, pThis, 0);
1662 }
1663 else
1664 LogFunc(("Unexpected queue idx (ignoring): %d\n", qIdx));
1665}
1666
1667/**
1668 * @callback_method_impl{VIRTIOCORER3,pfnStatusChanged}
1669 */
1670static DECLCALLBACK(void) virtioScsiR3StatusChanged(PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC, uint32_t fVirtioReady)
1671{
1672 PVIRTIOSCSI pThis = RT_FROM_MEMBER(pVirtio, VIRTIOSCSI, Virtio);
1673 PVIRTIOSCSICC pThisCC = RT_FROM_MEMBER(pVirtioCC, VIRTIOSCSICC, Virtio);
1674
1675 pThis->fVirtioReady = fVirtioReady;
1676
1677 if (fVirtioReady)
1678 {
1679 LogFunc(("VirtIO ready\n-----------------------------------------------------------------------------------------\n"));
1680 uint64_t fFeatures = virtioCoreGetNegotiatedFeatures(&pThis->Virtio);
1681 pThis->fHasT10pi = fFeatures & VIRTIO_SCSI_F_T10_PI;
1682 pThis->fHasHotplug = fFeatures & VIRTIO_SCSI_F_HOTPLUG;
1683 pThis->fHasInOutBufs = fFeatures & VIRTIO_SCSI_F_INOUT;
1684 pThis->fHasLunChange = fFeatures & VIRTIO_SCSI_F_CHANGE;
1685 pThis->fResetting = false;
1686 pThisCC->fQuiescing = false;
1687
1688 for (unsigned i = 0; i < VIRTIOSCSI_QUEUE_CNT; i++)
1689 pThis->afQueueAttached[i] = true;
1690 }
1691 else
1692 {
1693 LogFunc(("VirtIO is resetting\n"));
1694 for (unsigned i = 0; i < VIRTIOSCSI_QUEUE_CNT; i++)
1695 pThis->afQueueAttached[i] = false;
1696 }
1697}
1698
1699
1700/*********************************************************************************************************************************
1701* LEDs *
1702*********************************************************************************************************************************/
1703
1704/**
1705 * @interface_method_impl{PDMILEDPORTS,pfnQueryStatusLed, Target level.}
1706 */
1707static DECLCALLBACK(int) virtioScsiR3TargetQueryStatusLed(PPDMILEDPORTS pInterface, unsigned iLUN, PPDMLED *ppLed)
1708{
1709 PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, ILed);
1710 if (iLUN == 0)
1711 {
1712 *ppLed = &pTarget->led;
1713 Assert((*ppLed)->u32Magic == PDMLED_MAGIC);
1714 return VINF_SUCCESS;
1715 }
1716 return VERR_PDM_LUN_NOT_FOUND;
1717}
1718/**
1719 * @interface_method_impl{PDMILEDPORTS,pfnQueryStatusLed, Device level.}
1720 */
1721static DECLCALLBACK(int) virtioScsiR3DeviceQueryStatusLed(PPDMILEDPORTS pInterface, unsigned iLUN, PPDMLED *ppLed)
1722{
1723 PVIRTIOSCSICC pThisCC = RT_FROM_MEMBER(pInterface, VIRTIOSCSICC, ILeds);
1724 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pThisCC->pDevIns, PVIRTIOSCSI);
1725 if (iLUN < pThis->cTargets)
1726 {
1727 *ppLed = &pThisCC->paTargetInstances[iLUN].led;
1728 Assert((*ppLed)->u32Magic == PDMLED_MAGIC);
1729 return VINF_SUCCESS;
1730 }
1731 return VERR_PDM_LUN_NOT_FOUND;
1732}
1733
1734
1735/*********************************************************************************************************************************
1736* PDMIMEDIAPORT (target) *
1737*********************************************************************************************************************************/
1738
1739/**
1740 * @interface_method_impl{PDMIMEDIAPORT,pfnQueryDeviceLocation, Target level.}
1741 */
1742static DECLCALLBACK(int) virtioScsiR3QueryDeviceLocation(PPDMIMEDIAPORT pInterface, const char **ppcszController,
1743 uint32_t *piInstance, uint32_t *piLUN)
1744{
1745 PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaPort);
1746 PPDMDEVINS pDevIns = pTarget->pDevIns;
1747
1748 AssertPtrReturn(ppcszController, VERR_INVALID_POINTER);
1749 AssertPtrReturn(piInstance, VERR_INVALID_POINTER);
1750 AssertPtrReturn(piLUN, VERR_INVALID_POINTER);
1751
1752 *ppcszController = pDevIns->pReg->szName;
1753 *piInstance = pDevIns->iInstance;
1754 *piLUN = pTarget->uTarget;
1755
1756 return VINF_SUCCESS;
1757}
1758
1759
1760/*********************************************************************************************************************************
1761* Virtio config. *
1762*********************************************************************************************************************************/
1763
1764/**
1765 * Resolves to boolean true if uOffset matches a field offset and size exactly,
1766 * (or if 64-bit field, if it accesses either 32-bit part as a 32-bit access)
1767 * Assumption is this critereon is mandated by VirtIO 1.0, Section 4.1.3.1)
1768 * (Easily re-written to allow unaligned bounded access to a field).
1769 *
1770 * @param member - Member of VIRTIO_PCI_COMMON_CFG_T
1771 * @result - true or false
1772 */
1773#define MATCH_SCSI_CONFIG(member) \
1774 ( ( RT_SIZEOFMEMB(VIRTIOSCSI_CONFIG_T, member) == 8 \
1775 && ( offConfig == RT_UOFFSETOF(VIRTIOSCSI_CONFIG_T, member) \
1776 || offConfig == RT_UOFFSETOF(VIRTIOSCSI_CONFIG_T, member) + sizeof(uint32_t)) \
1777 && cb == sizeof(uint32_t)) \
1778 || ( offConfig == RT_UOFFSETOF(VIRTIOSCSI_CONFIG_T, member) \
1779 && cb == RT_SIZEOFMEMB(VIRTIOSCSI_CONFIG_T, member)) )
1780
1781#ifdef LOG_ENABLED
1782# define LOG_SCSI_CONFIG_ACCESSOR(member) \
1783 virtioCoreLogMappedIoValue(__FUNCTION__, #member, RT_SIZEOFMEMB(VIRTIOSCSI_CONFIG_T, member), \
1784 pv, cb, offIntra, fWrite, false, 0);
1785#else
1786# define LOG_SCSI_CONFIG_ACCESSOR(member) do { } while (0)
1787#endif
1788
1789#define SCSI_CONFIG_ACCESSOR(member) \
1790 do \
1791 { \
1792 uint32_t offIntra = offConfig - RT_UOFFSETOF(VIRTIOSCSI_CONFIG_T, member); \
1793 if (fWrite) \
1794 memcpy((char *)&pThis->virtioScsiConfig.member + offIntra, pv, cb); \
1795 else \
1796 memcpy(pv, (const char *)&pThis->virtioScsiConfig.member + offIntra, cb); \
1797 LOG_SCSI_CONFIG_ACCESSOR(member); \
1798 } while(0)
1799
1800#define SCSI_CONFIG_ACCESSOR_READONLY(member) \
1801 do \
1802 { \
1803 uint32_t offIntra = offConfig - RT_UOFFSETOF(VIRTIOSCSI_CONFIG_T, member); \
1804 if (fWrite) \
1805 LogFunc(("Guest attempted to write readonly virtio_pci_common_cfg.%s\n", #member)); \
1806 else \
1807 { \
1808 memcpy(pv, (const char *)&pThis->virtioScsiConfig.member + offIntra, cb); \
1809 LOG_SCSI_CONFIG_ACCESSOR(member); \
1810 } \
1811 } while(0)
1812
1813/**
1814 * Worker for virtioScsiR3DevCapWrite and virtioScsiR3DevCapRead.
1815 */
1816static int virtioScsiR3CfgAccessed(PVIRTIOSCSI pThis, uint32_t offConfig, void *pv, uint32_t cb, bool fWrite)
1817{
1818 AssertReturn(pv && cb <= sizeof(uint32_t), fWrite ? VINF_SUCCESS : VINF_IOM_MMIO_UNUSED_00);
1819
1820 if (MATCH_SCSI_CONFIG(uNumQueues))
1821 SCSI_CONFIG_ACCESSOR_READONLY(uNumQueues);
1822 else
1823 if (MATCH_SCSI_CONFIG(uSegMax))
1824 SCSI_CONFIG_ACCESSOR_READONLY(uSegMax);
1825 else
1826 if (MATCH_SCSI_CONFIG(uMaxSectors))
1827 SCSI_CONFIG_ACCESSOR_READONLY(uMaxSectors);
1828 else
1829 if (MATCH_SCSI_CONFIG(uCmdPerLun))
1830 SCSI_CONFIG_ACCESSOR_READONLY(uCmdPerLun);
1831 else
1832 if (MATCH_SCSI_CONFIG(uEventInfoSize))
1833 SCSI_CONFIG_ACCESSOR_READONLY(uEventInfoSize);
1834 else
1835 if (MATCH_SCSI_CONFIG(uSenseSize))
1836 SCSI_CONFIG_ACCESSOR(uSenseSize);
1837 else
1838 if (MATCH_SCSI_CONFIG(uCdbSize))
1839 SCSI_CONFIG_ACCESSOR(uCdbSize);
1840 else
1841 if (MATCH_SCSI_CONFIG(uMaxChannel))
1842 SCSI_CONFIG_ACCESSOR_READONLY(uMaxChannel);
1843 else
1844 if (MATCH_SCSI_CONFIG(uMaxTarget))
1845 SCSI_CONFIG_ACCESSOR_READONLY(uMaxTarget);
1846 else
1847 if (MATCH_SCSI_CONFIG(uMaxLun))
1848 SCSI_CONFIG_ACCESSOR_READONLY(uMaxLun);
1849 else
1850 {
1851 LogFunc(("Bad access by guest to virtio_scsi_config: off=%u (%#x), cb=%u\n", offConfig, offConfig, cb));
1852 return fWrite ? VINF_SUCCESS : VINF_IOM_MMIO_UNUSED_00;
1853 }
1854 return VINF_SUCCESS;
1855}
1856
1857#undef SCSI_CONFIG_ACCESSOR_READONLY
1858#undef SCSI_CONFIG_ACCESSOR
1859#undef LOG_ACCESSOR
1860#undef MATCH_SCSI_CONFIG
1861
1862/**
1863 * @callback_method_impl{VIRTIOCORER3,pfnDevCapRead}
1864 */
1865static DECLCALLBACK(int) virtioScsiR3DevCapRead(PPDMDEVINS pDevIns, uint32_t uOffset, void *pv, uint32_t cb)
1866{
1867 return virtioScsiR3CfgAccessed(PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI), uOffset, pv, cb, false /*fRead*/);
1868}
1869
1870/**
1871 * @callback_method_impl{VIRTIOCORER3,pfnDevCapWrite}
1872 */
1873static DECLCALLBACK(int) virtioScsiR3DevCapWrite(PPDMDEVINS pDevIns, uint32_t uOffset, const void *pv, uint32_t cb)
1874{
1875 return virtioScsiR3CfgAccessed(PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI), uOffset, (void *)pv, cb, true /*fWrite*/);
1876}
1877
1878
1879/*********************************************************************************************************************************
1880* IBase for device and targets *
1881*********************************************************************************************************************************/
1882
1883/**
1884 * @interface_method_impl{PDMIBASE,pfnQueryInterface, Target level.}
1885 */
1886static DECLCALLBACK(void *) virtioScsiR3TargetQueryInterface(PPDMIBASE pInterface, const char *pszIID)
1887{
1888 PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IBase);
1889 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pTarget->IBase);
1890 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIAPORT, &pTarget->IMediaPort);
1891 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIAEXPORT, &pTarget->IMediaExPort);
1892 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDPORTS, &pTarget->ILed);
1893 return NULL;
1894}
1895
1896/**
1897 * @interface_method_impl{PDMIBASE,pfnQueryInterface, Device level.}
1898 */
1899static DECLCALLBACK(void *) virtioScsiR3DeviceQueryInterface(PPDMIBASE pInterface, const char *pszIID)
1900{
1901 PVIRTIOSCSICC pThisCC = RT_FROM_MEMBER(pInterface, VIRTIOSCSICC, IBase);
1902
1903 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThisCC->IBase);
1904 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDPORTS, &pThisCC->ILeds);
1905
1906 return NULL;
1907}
1908
1909
1910/*********************************************************************************************************************************
1911* Misc *
1912*********************************************************************************************************************************/
1913
1914/**
1915 * @callback_method_impl{FNDBGFHANDLERDEV, virtio-scsi debugger info callback.}
1916 */
1917static DECLCALLBACK(void) virtioScsiR3Info(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
1918{
1919 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
1920
1921 /* Parse arguments. */
1922 RT_NOREF(pszArgs); //bool fVerbose = pszArgs && strstr(pszArgs, "verbose") != NULL;
1923
1924 /* Show basic information. */
1925 pHlp->pfnPrintf(pHlp, "%s#%d: virtio-scsci ",
1926 pDevIns->pReg->szName,
1927 pDevIns->iInstance);
1928 pHlp->pfnPrintf(pHlp, "numTargets=%lu", pThis->cTargets);
1929}
1930
1931
1932/*********************************************************************************************************************************
1933* Saved state *
1934*********************************************************************************************************************************/
1935
1936/**
1937 * @callback_method_impl{FNSSMDEVLOADEXEC}
1938 */
1939static DECLCALLBACK(int) virtioScsiR3LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
1940{
1941 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
1942 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
1943 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
1944
1945 LogFunc(("LOAD EXEC!!\n"));
1946
1947 AssertReturn(uPass == SSM_PASS_FINAL, VERR_SSM_UNEXPECTED_PASS);
1948 AssertLogRelMsgReturn(uVersion == VIRTIOSCSI_SAVED_STATE_VERSION,
1949 ("uVersion=%u\n", uVersion), VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);
1950
1951 virtioScsiSetVirtqNames(pThis);
1952 for (int qIdx = 0; qIdx < VIRTIOSCSI_QUEUE_CNT; qIdx++)
1953 pHlp->pfnSSMGetBool(pSSM, &pThis->afQueueAttached[qIdx]);
1954
1955 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uNumQueues);
1956 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uSegMax);
1957 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uMaxSectors);
1958 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uCmdPerLun);
1959 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uEventInfoSize);
1960 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uSenseSize);
1961 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uCdbSize);
1962 pHlp->pfnSSMGetU16(pSSM, &pThis->virtioScsiConfig.uMaxChannel);
1963 pHlp->pfnSSMGetU16(pSSM, &pThis->virtioScsiConfig.uMaxTarget);
1964 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uMaxLun);
1965 pHlp->pfnSSMGetU32(pSSM, &pThis->fAsyncEvtsEnabled);
1966 pHlp->pfnSSMGetBool(pSSM, &pThis->fEventsMissed);
1967 pHlp->pfnSSMGetU32(pSSM, &pThis->fVirtioReady);
1968 pHlp->pfnSSMGetU32(pSSM, &pThis->fHasT10pi);
1969 pHlp->pfnSSMGetU32(pSSM, &pThis->fHasHotplug);
1970 pHlp->pfnSSMGetU32(pSSM, &pThis->fHasInOutBufs);
1971 pHlp->pfnSSMGetU32(pSSM, &pThis->fHasLunChange);
1972 pHlp->pfnSSMGetU32(pSSM, &pThis->fResetting);
1973
1974 uint32_t cTargets;
1975 int rc = pHlp->pfnSSMGetU32(pSSM, &cTargets);
1976 AssertRCReturn(rc, rc);
1977 AssertReturn(cTargets == pThis->cTargets,
1978 pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_LOAD_CONFIG_MISMATCH, RT_SRC_POS,
1979 N_("target count has changed: %u saved, %u configured now"),
1980 cTargets, pThis->cTargets));
1981
1982 for (uint16_t uTarget = 0; uTarget < pThis->cTargets; uTarget++)
1983 {
1984 uint16_t cReqsRedo;
1985 rc = pHlp->pfnSSMGetU16(pSSM, &cReqsRedo);
1986 AssertRCReturn(rc, rc);
1987 AssertReturn(cReqsRedo < VIRTQ_MAX_SIZE,
1988 pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
1989 N_("Bad count of I/O transactions to re-do in saved state (%#x, max %#x - 1)"),
1990 cReqsRedo, VIRTQ_MAX_SIZE));
1991
1992 for (uint16_t qIdx = VIRTQ_REQ_BASE; qIdx < VIRTIOSCSI_QUEUE_CNT; qIdx++)
1993 {
1994 PVIRTIOSCSIWORKERR3 pWorkerR3 = &pThisCC->aWorkers[qIdx];
1995 pWorkerR3->cRedoDescs = 0;
1996 }
1997
1998 for (int i = 0; i < cReqsRedo; i++)
1999 {
2000 uint16_t qIdx;
2001 rc = pHlp->pfnSSMGetU16(pSSM, &qIdx);
2002 AssertRCReturn(rc, rc);
2003 AssertReturn(qIdx < VIRTIOSCSI_QUEUE_CNT,
2004 pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
2005 N_("Bad queue index for re-do in saved state (%#x, max %#x)"),
2006 qIdx, VIRTIOSCSI_QUEUE_CNT - 1));
2007
2008 uint16_t idxHead;
2009 rc = pHlp->pfnSSMGetU16(pSSM, &idxHead);
2010 AssertRCReturn(rc, rc);
2011 AssertReturn(idxHead < VIRTQ_MAX_SIZE,
2012 pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
2013 N_("Bad queue element index for re-do in saved state (%#x, max %#x)"),
2014 idxHead, VIRTQ_MAX_SIZE - 1));
2015
2016 PVIRTIOSCSIWORKERR3 pWorkerR3 = &pThisCC->aWorkers[qIdx];
2017 pWorkerR3->auRedoDescs[pWorkerR3->cRedoDescs++] = idxHead;
2018 pWorkerR3->cRedoDescs %= VIRTQ_MAX_SIZE;
2019 }
2020 }
2021
2022 /*
2023 * Call the virtio core to let it load its state.
2024 */
2025 rc = virtioCoreR3LoadExec(&pThis->Virtio, pDevIns->pHlpR3, pSSM);
2026
2027 /*
2028 * Nudge request queue workers
2029 */
2030 for (int qIdx = VIRTQ_REQ_BASE; qIdx < VIRTIOSCSI_QUEUE_CNT; qIdx++)
2031 {
2032 if (pThis->afQueueAttached[qIdx])
2033 {
2034 LogFunc(("Waking %s worker.\n", VIRTQNAME(qIdx)));
2035 int rc2 = PDMDevHlpSUPSemEventSignal(pDevIns, pThis->aWorkers[qIdx].hEvtProcess);
2036 AssertRCReturn(rc, rc2);
2037 }
2038 }
2039
2040 return rc;
2041}
2042
2043/**
2044 * @callback_method_impl{FNSSMDEVSAVEEXEC}
2045 */
2046static DECLCALLBACK(int) virtioScsiR3SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
2047{
2048 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2049 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2050 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
2051
2052 LogFunc(("SAVE EXEC!!\n"));
2053
2054 for (int qIdx = 0; qIdx < VIRTIOSCSI_QUEUE_CNT; qIdx++)
2055 pHlp->pfnSSMPutBool(pSSM, pThis->afQueueAttached[qIdx]);
2056
2057 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uNumQueues);
2058 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uSegMax);
2059 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uMaxSectors);
2060 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uCmdPerLun);
2061 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uEventInfoSize);
2062 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uSenseSize);
2063 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uCdbSize);
2064 pHlp->pfnSSMPutU16(pSSM, pThis->virtioScsiConfig.uMaxChannel);
2065 pHlp->pfnSSMPutU16(pSSM, pThis->virtioScsiConfig.uMaxTarget);
2066 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uMaxLun);
2067 pHlp->pfnSSMPutU32(pSSM, pThis->fAsyncEvtsEnabled);
2068 pHlp->pfnSSMPutBool(pSSM, pThis->fEventsMissed);
2069 pHlp->pfnSSMPutU32(pSSM, pThis->fVirtioReady);
2070 pHlp->pfnSSMPutU32(pSSM, pThis->fHasT10pi);
2071 pHlp->pfnSSMPutU32(pSSM, pThis->fHasHotplug);
2072 pHlp->pfnSSMPutU32(pSSM, pThis->fHasInOutBufs);
2073 pHlp->pfnSSMPutU32(pSSM, pThis->fHasLunChange);
2074 pHlp->pfnSSMPutU32(pSSM, pThis->fResetting);
2075
2076 AssertMsg(!pThis->cActiveReqs, ("There are still outstanding requests on this device\n"));
2077
2078 pHlp->pfnSSMPutU32(pSSM, pThis->cTargets);
2079
2080 for (uint16_t uTarget = 0; uTarget < pThis->cTargets; uTarget++)
2081 {
2082 PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[uTarget];
2083
2084 /* Query all suspended requests and store them in the request queue. */
2085 if (pTarget->pDrvMediaEx)
2086 {
2087 uint32_t cReqsRedo = pTarget->pDrvMediaEx->pfnIoReqGetSuspendedCount(pTarget->pDrvMediaEx);
2088
2089 pHlp->pfnSSMPutU16(pSSM, cReqsRedo);
2090
2091 if (cReqsRedo)
2092 {
2093 PDMMEDIAEXIOREQ hIoReq;
2094 PVIRTIOSCSIREQ pReq;
2095
2096 int rc = pTarget->pDrvMediaEx->pfnIoReqQuerySuspendedStart(pTarget->pDrvMediaEx, &hIoReq,
2097 (void **)&pReq);
2098 AssertRCBreak(rc);
2099
2100 while(--cReqsRedo)
2101 {
2102 pHlp->pfnSSMPutU16(pSSM, pReq->qIdx);
2103 pHlp->pfnSSMPutU16(pSSM, pReq->pDescChain->uHeadIdx);
2104
2105 rc = pTarget->pDrvMediaEx->pfnIoReqQuerySuspendedNext(pTarget->pDrvMediaEx, hIoReq,
2106 &hIoReq, (void **)&pReq);
2107 AssertRCBreak(rc);
2108 }
2109 }
2110 }
2111 }
2112
2113 /*
2114 * Call the virtio core to let it save its state.
2115 */
2116 return virtioCoreR3SaveExec(&pThis->Virtio, pDevIns->pHlpR3, pSSM);
2117}
2118
2119
2120/*********************************************************************************************************************************
2121* Device interface. *
2122*********************************************************************************************************************************/
2123
2124/**
2125 * @interface_method_impl{PDMDEVREGR3,pfnDetach}
2126 *
2127 * One harddisk at one port has been unplugged.
2128 * The VM is suspended at this point.
2129 */
2130static DECLCALLBACK(void) virtioScsiR3Detach(PPDMDEVINS pDevIns, unsigned uTarget, uint32_t fFlags)
2131{
2132 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2133 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2134 AssertReturnVoid(uTarget < pThis->cTargets);
2135 PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[uTarget];
2136
2137 LogFunc((""));
2138
2139 AssertMsg(fFlags & PDM_TACH_FLAGS_NOT_HOT_PLUG,
2140 ("virtio-scsi: Device does not support hotplugging\n"));
2141 RT_NOREF(fFlags);
2142
2143 /*
2144 * Zero all important members.
2145 */
2146 pTarget->fPresent = false;
2147 pTarget->pDrvBase = NULL;
2148 pTarget->pDrvMedia = NULL;
2149 pTarget->pDrvMediaEx = NULL;
2150}
2151
2152/**
2153 * @interface_method_impl{PDMDEVREGR3,pfnAttach}
2154 *
2155 * This is called when we change block driver.
2156 */
2157static DECLCALLBACK(int) virtioScsiR3Attach(PPDMDEVINS pDevIns, unsigned uTarget, uint32_t fFlags)
2158{
2159 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2160 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2161 AssertReturn(uTarget < pThis->cTargets, VERR_PDM_LUN_NOT_FOUND);
2162 PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[uTarget];
2163
2164 Assert(pTarget->pDevIns == pDevIns);
2165 AssertMsgReturn(fFlags & PDM_TACH_FLAGS_NOT_HOT_PLUG,
2166 ("virtio-scsi: Device does not support hotplugging\n"),
2167 VERR_INVALID_PARAMETER);
2168
2169 AssertRelease(!pTarget->pDrvBase);
2170 Assert(pTarget->uTarget == uTarget);
2171
2172 /*
2173 * Try attach the SCSI driver and get the interfaces, required as well as optional.
2174 */
2175 int rc = PDMDevHlpDriverAttach(pDevIns, pTarget->uTarget, &pDevIns->IBase, &pTarget->pDrvBase, pTarget->pszTargetName);
2176 if (RT_SUCCESS(rc))
2177 {
2178 pTarget->fPresent = true;
2179 pTarget->pDrvMedia = PDMIBASE_QUERY_INTERFACE(pTarget->pDrvBase, PDMIMEDIA);
2180 AssertMsgReturn(VALID_PTR(pTarget->pDrvMedia),
2181 ("virtio-scsi configuration error: LUN#%d missing basic media interface!\n", uTarget),
2182 VERR_PDM_MISSING_INTERFACE);
2183
2184 /* Get the extended media interface. */
2185 pTarget->pDrvMediaEx = PDMIBASE_QUERY_INTERFACE(pTarget->pDrvBase, PDMIMEDIAEX);
2186 AssertMsgReturn(VALID_PTR(pTarget->pDrvMediaEx),
2187 ("virtio-scsi configuration error: LUN#%d missing extended media interface!\n", uTarget),
2188 VERR_PDM_MISSING_INTERFACE);
2189
2190 rc = pTarget->pDrvMediaEx->pfnIoReqAllocSizeSet(pTarget->pDrvMediaEx, sizeof(VIRTIOSCSIREQ));
2191 AssertMsgReturn(VALID_PTR(pTarget->pDrvMediaEx),
2192 ("virtio-scsi configuration error: LUN#%u: Failed to set I/O request size!\n", uTarget),
2193 rc);
2194 }
2195 else
2196 AssertMsgFailed(("Failed to attach %s. rc=%Rrc\n", pTarget->pszTargetName, rc));
2197
2198 if (RT_FAILURE(rc))
2199 {
2200 pTarget->fPresent = false;
2201 pTarget->pDrvBase = NULL;
2202 pTarget->pDrvMedia = NULL;
2203 pTarget->pDrvMediaEx = NULL;
2204 pThisCC->pMediaNotify = NULL;
2205 }
2206 return rc;
2207}
2208
2209/**
2210 * @callback_method_impl{FNPDMDEVASYNCNOTIFY}
2211 */
2212static DECLCALLBACK(bool) virtioScsiR3DeviceQuiesced(PPDMDEVINS pDevIns)
2213{
2214 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2215 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2216
2217 if (ASMAtomicReadU32(&pThis->cActiveReqs))
2218 return false;
2219
2220 LogFunc(("Device I/O activity quiesced: %s\n",
2221 virtioCoreGetStateChangeText(pThisCC->enmQuiescingFor)));
2222
2223 virtioCoreR3VmStateChanged(&pThis->Virtio, pThisCC->enmQuiescingFor);
2224
2225 pThis->fResetting = false;
2226 pThisCC->fQuiescing = false;
2227
2228 return true;
2229}
2230
2231/**
2232 * Worker for virtioScsiR3Reset() and virtioScsiR3SuspendOrPowerOff().
2233 */
2234static void virtioScsiR3QuiesceDevice(PPDMDEVINS pDevIns, VIRTIOVMSTATECHANGED enmQuiscingFor)
2235{
2236 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2237 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2238
2239 /* Prevent worker threads from removing/processing elements from virtq's */
2240 pThisCC->fQuiescing = true;
2241 pThisCC->enmQuiescingFor = enmQuiscingFor;
2242
2243 PDMDevHlpSetAsyncNotification(pDevIns, virtioScsiR3DeviceQuiesced);
2244
2245 /* If already quiesced invoke async callback. */
2246 if (!ASMAtomicReadU32(&pThis->cActiveReqs))
2247 PDMDevHlpAsyncNotificationCompleted(pDevIns);
2248}
2249
2250/**
2251 * @interface_method_impl{PDMDEVREGR3,pfnReset}
2252 */
2253static DECLCALLBACK(void) virtioScsiR3Reset(PPDMDEVINS pDevIns)
2254{
2255 LogFunc(("\n"));
2256 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2257 pThis->fResetting = true;
2258 virtioScsiR3QuiesceDevice(pDevIns, kvirtIoVmStateChangedReset);
2259}
2260
2261/**
2262 * @interface_method_impl{PDMDEVREGR3,pfnPowerOff}
2263 */
2264static DECLCALLBACK(void) virtioScsiR3SuspendOrPowerOff(PPDMDEVINS pDevIns, VIRTIOVMSTATECHANGED enmType)
2265{
2266 LogFunc(("\n"));
2267
2268 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2269 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2270
2271 /* VM is halted, thus no new I/O being dumped into queues by the guest.
2272 * Workers have been flagged to stop pulling stuff already queued-up by the guest.
2273 * Now tell lower-level to to suspend reqs (for example, DrvVD suspends all reqs
2274 * on its wait queue, and we will get a callback as the state changes to
2275 * suspended (and later, resumed) for each).
2276 */
2277 for (uint32_t i = 0; i < pThis->cTargets; i++)
2278 {
2279 PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[i];
2280 if (pTarget->pDrvMediaEx)
2281 pTarget->pDrvMediaEx->pfnNotifySuspend(pTarget->pDrvMediaEx);
2282 }
2283
2284 virtioScsiR3QuiesceDevice(pDevIns, enmType);
2285}
2286
2287/**
2288 * @interface_method_impl{PDMDEVREGR3,pfnSuspend}
2289 */
2290static DECLCALLBACK(void) virtioScsiR3PowerOff(PPDMDEVINS pDevIns)
2291{
2292 LogFunc(("\n"));
2293 virtioScsiR3SuspendOrPowerOff(pDevIns, kvirtIoVmStateChangedPowerOff);
2294}
2295
2296/**
2297 * @interface_method_impl{PDMDEVREGR3,pfnSuspend}
2298 */
2299static DECLCALLBACK(void) virtioScsiR3Suspend(PPDMDEVINS pDevIns)
2300{
2301 LogFunc(("\n"));
2302 virtioScsiR3SuspendOrPowerOff(pDevIns, kvirtIoVmStateChangedSuspend);
2303}
2304
2305/**
2306 * @interface_method_impl{PDMDEVREGR3,pfnResume}
2307 */
2308static DECLCALLBACK(void) virtioScsiR3Resume(PPDMDEVINS pDevIns)
2309{
2310 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2311 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2312 LogFunc(("\n"));
2313
2314 pThisCC->fQuiescing = false;
2315
2316 /* Wake worker threads flagged to skip pulling queue entries during quiesce
2317 * to ensure they re-check their queues. Active request queues may already
2318 * be awake due to new reqs coming in.
2319 */
2320 for (uint16_t qIdx = 0; qIdx < VIRTIOSCSI_REQ_QUEUE_CNT; qIdx++)
2321 {
2322 if (ASMAtomicReadBool(&pThisCC->aWorkers[qIdx].fSleeping))
2323 {
2324 Log6Func(("waking %s worker.\n", VIRTQNAME(qIdx)));
2325 int rc = PDMDevHlpSUPSemEventSignal(pDevIns, pThis->aWorkers[qIdx].hEvtProcess);
2326 AssertRC(rc);
2327 }
2328 }
2329 /* Ensure guest is working the queues too. */
2330 virtioCoreR3VmStateChanged(&pThis->Virtio, kvirtIoVmStateChangedResume);
2331}
2332
2333/**
2334 * @interface_method_impl{PDMIMEDIAEXPORT,pfnMediumEjected}
2335 */
2336static DECLCALLBACK(void) virtioScsiR3MediumEjected(PPDMIMEDIAEXPORT pInterface)
2337{
2338 PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaExPort);
2339 PPDMDEVINS pDevIns = pTarget->pDevIns;
2340 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2341
2342#if 0 /* need more info about how to use this event. The VirtIO 1.0 specification
2343 * lists several SCSI related event types but presumes the reader knows
2344 * how to use them without providing references. */
2345 virtioScsiR3ReportMediaChange(pDevIns, pThis, pTarget->uTarget);
2346#endif
2347
2348 if (pThisCC->pMediaNotify)
2349 {
2350 int rc = VMR3ReqCallNoWait(PDMDevHlpGetVM(pDevIns), VMCPUID_ANY,
2351 (PFNRT)pThisCC->pMediaNotify->pfnEjected, 2,
2352 pThisCC->pMediaNotify, pTarget->uTarget);
2353 AssertRC(rc);
2354 }
2355}
2356
2357/**
2358 * @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqStateChanged}
2359 */
2360static DECLCALLBACK(void) virtioScsiR3IoReqStateChanged(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
2361 void *pvIoReqAlloc, PDMMEDIAEXIOREQSTATE enmState)
2362{
2363 PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaExPort);
2364 PPDMDEVINS pDevIns = pTarget->pDevIns;
2365 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2366 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2367 RT_NOREF(hIoReq, pvIoReqAlloc);
2368
2369 switch (enmState)
2370 {
2371 case PDMMEDIAEXIOREQSTATE_SUSPENDED:
2372 {
2373 /* Stop considering this request active */
2374 if (!ASMAtomicDecU32(&pThis->cActiveReqs) && pThisCC->fQuiescing)
2375 PDMDevHlpAsyncNotificationCompleted(pDevIns);
2376 break;
2377 }
2378 case PDMMEDIAEXIOREQSTATE_ACTIVE:
2379 ASMAtomicIncU32(&pThis->cActiveReqs);
2380 break;
2381 default:
2382 AssertMsgFailed(("Invalid request state given %u\n", enmState));
2383 }
2384}
2385
2386/**
2387 * @interface_method_impl{PDMDEVREGR3,pfnDestruct}
2388 */
2389static DECLCALLBACK(int) virtioScsiR3Destruct(PPDMDEVINS pDevIns)
2390{
2391 PDMDEV_CHECK_VERSIONS_RETURN_QUIET(pDevIns);
2392 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2393 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2394
2395 RTMemFree(pThisCC->paTargetInstances);
2396 pThisCC->paTargetInstances = NULL;
2397 pThisCC->pMediaNotify = NULL;
2398
2399 for (unsigned qIdx = 0; qIdx < VIRTIOSCSI_QUEUE_CNT; qIdx++)
2400 {
2401 PVIRTIOSCSIWORKER pWorker = &pThis->aWorkers[qIdx];
2402 if (pWorker->hEvtProcess != NIL_SUPSEMEVENT)
2403 {
2404 PDMDevHlpSUPSemEventClose(pDevIns, pWorker->hEvtProcess);
2405 pWorker->hEvtProcess = NIL_SUPSEMEVENT;
2406 }
2407
2408 if (pThisCC->aWorkers[qIdx].pThread)
2409 {
2410 /* Destroy the thread. */
2411 int rcThread;
2412 int rc = PDMDevHlpThreadDestroy(pDevIns, pThisCC->aWorkers[qIdx].pThread, &rcThread);
2413 if (RT_FAILURE(rc) || RT_FAILURE(rcThread))
2414 AssertMsgFailed(("%s Failed to destroythread rc=%Rrc rcThread=%Rrc\n",
2415 __FUNCTION__, rc, rcThread));
2416 pThisCC->aWorkers[qIdx].pThread = NULL;
2417 }
2418 }
2419
2420 virtioCoreR3Term(pDevIns, &pThis->Virtio, &pThisCC->Virtio);
2421 return VINF_SUCCESS;
2422}
2423
2424/**
2425 * @interface_method_impl{PDMDEVREGR3,pfnConstruct}
2426 */
2427static DECLCALLBACK(int) virtioScsiR3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
2428{
2429 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
2430 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2431 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2432 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
2433
2434 /*
2435 * Quick initialization of the state data, making sure that the destructor always works.
2436 */
2437 pThisCC->pDevIns = pDevIns;
2438
2439 LogFunc(("PDM device instance: %d\n", iInstance));
2440 RTStrPrintf(pThis->szInstance, sizeof(pThis->szInstance), "VIRTIOSCSI%d", iInstance);
2441
2442 pThisCC->IBase.pfnQueryInterface = virtioScsiR3DeviceQueryInterface;
2443 pThisCC->ILeds.pfnQueryStatusLed = virtioScsiR3DeviceQueryStatusLed;
2444
2445 /*
2446 * Validate and read configuration.
2447 */
2448 PDMDEV_VALIDATE_CONFIG_RETURN(pDevIns, "NumTargets|Bootable", "");
2449
2450 int rc = pHlp->pfnCFGMQueryU32Def(pCfg, "NumTargets", &pThis->cTargets, 1);
2451 if (RT_FAILURE(rc))
2452 return PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio-scsi configuration error: failed to read NumTargets as integer"));
2453 if (pThis->cTargets < 1 || pThis->cTargets > VIRTIOSCSI_MAX_TARGETS)
2454 return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
2455 N_("virtio-scsi configuration error: NumTargets=%u is out of range (1..%u)"),
2456 pThis->cTargets, VIRTIOSCSI_MAX_TARGETS);
2457
2458 rc = pHlp->pfnCFGMQueryBoolDef(pCfg, "Bootable", &pThis->fBootable, true);
2459 if (RT_FAILURE(rc))
2460 return PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio-scsi configuration error: failed to read Bootable as boolean"));
2461
2462 LogRel(("%s: Targets=%u Bootable=%RTbool (unimplemented) R0Enabled=%RTbool RCEnabled=%RTbool\n",
2463 pThis->szInstance, pThis->cTargets, pThis->fBootable, pDevIns->fR0Enabled, pDevIns->fRCEnabled));
2464
2465
2466 /*
2467 * Do core virtio initialization.
2468 */
2469
2470 /* Configure virtio_scsi_config that transacts via VirtIO implementation's Dev. Specific Cap callbacks */
2471 pThis->virtioScsiConfig.uNumQueues = VIRTIOSCSI_REQ_QUEUE_CNT;
2472 pThis->virtioScsiConfig.uSegMax = VIRTIOSCSI_MAX_SEG_COUNT;
2473 pThis->virtioScsiConfig.uMaxSectors = VIRTIOSCSI_MAX_SECTORS_HINT;
2474 pThis->virtioScsiConfig.uCmdPerLun = VIRTIOSCSI_MAX_COMMANDS_PER_LUN;
2475 pThis->virtioScsiConfig.uEventInfoSize = sizeof(VIRTIOSCSI_EVENT_T); /*VirtIO 1.0 Spec says at least this size! */
2476 pThis->virtioScsiConfig.uSenseSize = VIRTIOSCSI_SENSE_SIZE_DEFAULT;
2477 pThis->virtioScsiConfig.uCdbSize = VIRTIOSCSI_CDB_SIZE_DEFAULT;
2478 pThis->virtioScsiConfig.uMaxChannel = VIRTIOSCSI_MAX_CHANNEL_HINT;
2479 pThis->virtioScsiConfig.uMaxTarget = pThis->cTargets;
2480 pThis->virtioScsiConfig.uMaxLun = VIRTIOSCSI_MAX_LUN;
2481
2482 /* Initialize the generic Virtio core: */
2483 pThisCC->Virtio.pfnStatusChanged = virtioScsiR3StatusChanged;
2484 pThisCC->Virtio.pfnQueueNotified = virtioScsiR3Notified;
2485 pThisCC->Virtio.pfnDevCapRead = virtioScsiR3DevCapRead;
2486 pThisCC->Virtio.pfnDevCapWrite = virtioScsiR3DevCapWrite;
2487
2488 VIRTIOPCIPARAMS VirtioPciParams;
2489 VirtioPciParams.uDeviceId = PCI_DEVICE_ID_VIRTIOSCSI_HOST;
2490 VirtioPciParams.uClassBase = PCI_CLASS_BASE_MASS_STORAGE;
2491 VirtioPciParams.uClassSub = PCI_CLASS_SUB_SCSI_STORAGE_CONTROLLER;
2492 VirtioPciParams.uClassProg = PCI_CLASS_PROG_UNSPECIFIED;
2493 VirtioPciParams.uSubsystemId = PCI_DEVICE_ID_VIRTIOSCSI_HOST; /* VirtIO 1.0 spec allows PCI Device ID here */
2494 VirtioPciParams.uInterruptLine = 0x00;
2495 VirtioPciParams.uInterruptPin = 0x01;
2496
2497 rc = virtioCoreR3Init(pDevIns, &pThis->Virtio, &pThisCC->Virtio, &VirtioPciParams, pThis->szInstance,
2498 VIRTIOSCSI_HOST_SCSI_FEATURES_OFFERED,
2499 &pThis->virtioScsiConfig /*pvDevSpecificCap*/, sizeof(pThis->virtioScsiConfig));
2500 if (RT_FAILURE(rc))
2501 return PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio-scsi: failed to initialize VirtIO"));
2502
2503 /*
2504 * Initialize queues.
2505 */
2506
2507 virtioScsiSetVirtqNames(pThis);
2508
2509 /* Attach the queues and create worker threads for them: */
2510 for (uint16_t qIdx = 0; qIdx < VIRTIOSCSI_QUEUE_CNT; qIdx++)
2511 {
2512 rc = virtioCoreR3QueueAttach(&pThis->Virtio, qIdx, VIRTQNAME(qIdx));
2513 if (RT_FAILURE(rc))
2514 continue;
2515 if (qIdx == CONTROLQ_IDX || IS_REQ_QUEUE(qIdx))
2516 {
2517 rc = PDMDevHlpThreadCreate(pDevIns, &pThisCC->aWorkers[qIdx].pThread,
2518 (void *)(uintptr_t)qIdx, virtioScsiR3WorkerThread,
2519 virtioScsiR3WorkerWakeUp, 0, RTTHREADTYPE_IO, VIRTQNAME(qIdx));
2520 if (rc != VINF_SUCCESS)
2521 {
2522 LogRel(("Error creating thread for Virtual Queue %s: %Rrc\n", VIRTQNAME(qIdx), rc));
2523 return rc;
2524 }
2525
2526 rc = PDMDevHlpSUPSemEventCreate(pDevIns, &pThis->aWorkers[qIdx].hEvtProcess);
2527 if (RT_FAILURE(rc))
2528 return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
2529 N_("DevVirtioSCSI: Failed to create SUP event semaphore"));
2530 }
2531 pThis->afQueueAttached[qIdx] = true;
2532 }
2533
2534 /*
2535 * Initialize per device instances (targets).
2536 */
2537 Log2Func(("Probing %d targets ...\n", pThis->cTargets));
2538
2539 pThisCC->paTargetInstances = (PVIRTIOSCSITARGET)RTMemAllocZ(sizeof(VIRTIOSCSITARGET) * pThis->cTargets);
2540 if (!pThisCC->paTargetInstances)
2541 return PDMDEV_SET_ERROR(pDevIns, rc, N_("Failed to allocate memory for target states"));
2542
2543 for (uint32_t uTarget = 0; uTarget < pThis->cTargets; uTarget++)
2544 {
2545 PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[uTarget];
2546
2547 if (RTStrAPrintf(&pTarget->pszTargetName, "VSCSI%u", uTarget) < 0)
2548 AssertLogRelFailedReturn(VERR_NO_MEMORY);
2549
2550 /* Initialize static parts of the device. */
2551 pTarget->pDevIns = pDevIns;
2552 pTarget->uTarget = uTarget;
2553
2554 pTarget->IBase.pfnQueryInterface = virtioScsiR3TargetQueryInterface;
2555
2556 /* IMediaPort and IMediaExPort interfaces provide callbacks for VD media and downstream driver access */
2557 pTarget->IMediaPort.pfnQueryDeviceLocation = virtioScsiR3QueryDeviceLocation;
2558 pTarget->IMediaPort.pfnQueryScsiInqStrings = NULL;
2559 pTarget->IMediaExPort.pfnIoReqCompleteNotify = virtioScsiR3IoReqFinish;
2560 pTarget->IMediaExPort.pfnIoReqCopyFromBuf = virtioScsiR3IoReqCopyFromBuf;
2561 pTarget->IMediaExPort.pfnIoReqCopyToBuf = virtioScsiR3IoReqCopyToBuf;
2562 pTarget->IMediaExPort.pfnIoReqStateChanged = virtioScsiR3IoReqStateChanged;
2563 pTarget->IMediaExPort.pfnMediumEjected = virtioScsiR3MediumEjected;
2564 pTarget->IMediaExPort.pfnIoReqQueryBuf = NULL; /* When used avoids copyFromBuf CopyToBuf*/
2565 pTarget->IMediaExPort.pfnIoReqQueryDiscardRanges = NULL;
2566
2567 pTarget->IBase.pfnQueryInterface = virtioScsiR3TargetQueryInterface;
2568 pTarget->ILed.pfnQueryStatusLed = virtioScsiR3TargetQueryStatusLed;
2569 pTarget->led.u32Magic = PDMLED_MAGIC;
2570
2571 LogFunc(("Attaching LUN: %s\n", pTarget->pszTargetName));
2572
2573 AssertReturn(uTarget < pThis->cTargets, VERR_PDM_NO_SUCH_LUN);
2574 rc = PDMDevHlpDriverAttach(pDevIns, uTarget, &pTarget->IBase, &pTarget->pDrvBase, pTarget->pszTargetName);
2575 if (RT_SUCCESS(rc))
2576 {
2577 pTarget->fPresent = true;
2578
2579 pTarget->pDrvMedia = PDMIBASE_QUERY_INTERFACE(pTarget->pDrvBase, PDMIMEDIA);
2580 AssertMsgReturn(VALID_PTR(pTarget->pDrvMedia),
2581 ("virtio-scsi configuration error: LUN#%d missing basic media interface!\n", uTarget),
2582 VERR_PDM_MISSING_INTERFACE);
2583 /* Get the extended media interface. */
2584 pTarget->pDrvMediaEx = PDMIBASE_QUERY_INTERFACE(pTarget->pDrvBase, PDMIMEDIAEX);
2585 AssertMsgReturn(VALID_PTR(pTarget->pDrvMediaEx),
2586 ("virtio-scsi configuration error: LUN#%d missing extended media interface!\n", uTarget),
2587 VERR_PDM_MISSING_INTERFACE);
2588
2589 rc = pTarget->pDrvMediaEx->pfnIoReqAllocSizeSet(pTarget->pDrvMediaEx, sizeof(VIRTIOSCSIREQ));
2590 AssertMsgReturn(VALID_PTR(pTarget->pDrvMediaEx),
2591 ("virtio-scsi configuration error: LUN#%u: Failed to set I/O request size!\n", uTarget),
2592 rc);
2593 }
2594 else if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
2595 {
2596 pTarget->fPresent = false;
2597 pTarget->pDrvBase = NULL;
2598 Log(("virtio-scsi: no driver attached to device %s\n", pTarget->pszTargetName));
2599 rc = VINF_SUCCESS;
2600 }
2601 else
2602 {
2603 AssertLogRelMsgFailed(("virtio-scsi: Failed to attach %s: %Rrc\n", pTarget->pszTargetName, rc));
2604 return rc;
2605 }
2606 }
2607
2608 /*
2609 * Status driver (optional).
2610 */
2611 PPDMIBASE pUpBase;
2612 AssertCompile(PDM_STATUS_LUN >= VIRTIOSCSI_MAX_TARGETS);
2613 rc = PDMDevHlpDriverAttach(pDevIns, PDM_STATUS_LUN, &pThisCC->IBase, &pUpBase, "Status Port");
2614 if (RT_FAILURE(rc) && rc != VERR_PDM_NO_ATTACHED_DRIVER)
2615 return PDMDEV_SET_ERROR(pDevIns, rc, N_("Failed to attach the status LUN"));
2616 pThisCC->pMediaNotify = PDMIBASE_QUERY_INTERFACE(pUpBase, PDMIMEDIANOTIFY);
2617
2618
2619 /*
2620 * Register saved state.
2621 */
2622 rc = PDMDevHlpSSMRegister(pDevIns, VIRTIOSCSI_SAVED_STATE_VERSION, sizeof(*pThis),
2623 virtioScsiR3SaveExec, virtioScsiR3LoadExec);
2624 AssertRCReturn(rc, rc);
2625
2626 /*
2627 * Register the debugger info callback (ignore errors).
2628 */
2629 char szTmp[128];
2630 RTStrPrintf(szTmp, sizeof(szTmp), "%s%u", pDevIns->pReg->szName, pDevIns->iInstance);
2631 PDMDevHlpDBGFInfoRegister(pDevIns, szTmp, "virtio-scsi info", virtioScsiR3Info);
2632
2633 return rc;
2634}
2635
2636#else /* !IN_RING3 */
2637
2638/**
2639 * @callback_method_impl{PDMDEVREGR0,pfnConstruct}
2640 */
2641static DECLCALLBACK(int) virtioScsiRZConstruct(PPDMDEVINS pDevIns)
2642{
2643 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
2644 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2645 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2646
2647 return virtioCoreRZInit(pDevIns, &pThis->Virtio, &pThisCC->Virtio);
2648}
2649
2650#endif /* !IN_RING3 */
2651
2652
2653/**
2654 * The device registration structure.
2655 */
2656const PDMDEVREG g_DeviceVirtioSCSI =
2657{
2658 /* .u32Version = */ PDM_DEVREG_VERSION,
2659 /* .uReserved0 = */ 0,
2660 /* .szName = */ "virtio-scsi",
2661 /* .fFlags = */ PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_RZ | PDM_DEVREG_FLAGS_NEW_STYLE
2662 | PDM_DEVREG_FLAGS_FIRST_SUSPEND_NOTIFICATION
2663 | PDM_DEVREG_FLAGS_FIRST_POWEROFF_NOTIFICATION,
2664 /* .fClass = */ PDM_DEVREG_CLASS_STORAGE,
2665 /* .cMaxInstances = */ ~0U,
2666 /* .uSharedVersion = */ 42,
2667 /* .cbInstanceShared = */ sizeof(VIRTIOSCSI),
2668 /* .cbInstanceCC = */ sizeof(VIRTIOSCSICC),
2669 /* .cbInstanceRC = */ sizeof(VIRTIOSCSIRC),
2670 /* .cMaxPciDevices = */ 1,
2671 /* .cMaxMsixVectors = */ VBOX_MSIX_MAX_ENTRIES,
2672 /* .pszDescription = */ "Virtio Host SCSI.\n",
2673#if defined(IN_RING3)
2674 /* .pszRCMod = */ "VBoxDDRC.rc",
2675 /* .pszR0Mod = */ "VBoxDDR0.r0",
2676 /* .pfnConstruct = */ virtioScsiR3Construct,
2677 /* .pfnDestruct = */ virtioScsiR3Destruct,
2678 /* .pfnRelocate = */ NULL,
2679 /* .pfnMemSetup = */ NULL,
2680 /* .pfnPowerOn = */ NULL,
2681 /* .pfnReset = */ virtioScsiR3Reset,
2682 /* .pfnSuspend = */ virtioScsiR3Suspend,
2683 /* .pfnResume = */ virtioScsiR3Resume,
2684 /* .pfnAttach = */ virtioScsiR3Attach,
2685 /* .pfnDetach = */ virtioScsiR3Detach,
2686 /* .pfnQueryInterface = */ NULL,
2687 /* .pfnInitComplete = */ NULL,
2688 /* .pfnPowerOff = */ virtioScsiR3PowerOff,
2689 /* .pfnSoftReset = */ NULL,
2690 /* .pfnReserved0 = */ NULL,
2691 /* .pfnReserved1 = */ NULL,
2692 /* .pfnReserved2 = */ NULL,
2693 /* .pfnReserved3 = */ NULL,
2694 /* .pfnReserved4 = */ NULL,
2695 /* .pfnReserved5 = */ NULL,
2696 /* .pfnReserved6 = */ NULL,
2697 /* .pfnReserved7 = */ NULL,
2698#elif defined(IN_RING0)
2699 /* .pfnEarlyConstruct = */ NULL,
2700 /* .pfnConstruct = */ virtioScsiRZConstruct,
2701 /* .pfnDestruct = */ NULL,
2702 /* .pfnFinalDestruct = */ NULL,
2703 /* .pfnRequest = */ NULL,
2704 /* .pfnReserved0 = */ NULL,
2705 /* .pfnReserved1 = */ NULL,
2706 /* .pfnReserved2 = */ NULL,
2707 /* .pfnReserved3 = */ NULL,
2708 /* .pfnReserved4 = */ NULL,
2709 /* .pfnReserved5 = */ NULL,
2710 /* .pfnReserved6 = */ NULL,
2711 /* .pfnReserved7 = */ NULL,
2712#elif defined(IN_RC)
2713 /* .pfnConstruct = */ virtioScsiRZConstruct,
2714 /* .pfnReserved0 = */ NULL,
2715 /* .pfnReserved1 = */ NULL,
2716 /* .pfnReserved2 = */ NULL,
2717 /* .pfnReserved3 = */ NULL,
2718 /* .pfnReserved4 = */ NULL,
2719 /* .pfnReserved5 = */ NULL,
2720 /* .pfnReserved6 = */ NULL,
2721 /* .pfnReserved7 = */ NULL,
2722#else
2723# error "Not in IN_RING3, IN_RING0 or IN_RC!"
2724#endif
2725 /* .u32VersionEnd = */ PDM_DEVREG_VERSION
2726};
2727
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