VirtualBox

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

Last change on this file since 85101 was 85045, checked in by vboxsync, 4 years ago

Network/DevVirtioNet_1_0.cpp: Return virtioCoreVirtqAttach() to virtioCoreR3VirtqAttach() because it otherwise drags a RTStrCopy() reference into VBoxDD0 and breaks things.

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