VirtualBox

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

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

fix formatting burn from copying code from online changeset diff into text editor

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 118.5 KB
Line 
1/* $Id: DevVirtioSCSI.cpp 93614 2022-02-06 04:33:08Z 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-2022 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 1 /**< 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_SIZE];/**< 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_HOTPLUG was negotiated */
460 uint32_t fHasHotplug;
461
462 /** True if VIRTIO_SCSI_F_INOUT was negotiated */
463 uint32_t fHasInOutBufs;
464
465 /** True if VIRTIO_SCSI_F_CHANGE 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 datain 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 reqhdr + cdb (precede dataout) */
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 virtioCoreVirtqUsedRingSync(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: Response 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 virtioCoreVirtqUsedRingSync(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 virtioCoreVirtqUsedRingSync(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 && 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 0
1273 if (RT_LIKELY(!cbDataIn || !cbDataOut || pThis->fHasInOutBufs)) /* VirtIO 1.0, 5.6.6.1.1 */
1274 { /* likely */ }
1275 else
1276 {
1277 Log2Func(("Error submitting request, got datain & dataout bufs w/o INOUT feature negotated\n"));
1278 uint8_t abSense[] = { RT_BIT(7) | SCSI_SENSE_RESPONSE_CODE_CURR_FIXED,
1279 0, SCSI_SENSE_ILLEGAL_REQUEST, 0, 0, 0, 0, 10, 0, 0, 0 };
1280 return virtioScsiR3ReqErr4(pDevIns, pThis, pThisCC, uVirtqNbr, pVirtqBuf, cbDataIn + cbDataOut, SCSI_STATUS_CHECK_CONDITION,
1281 VIRTIOSCSI_S_FAILURE, abSense, sizeof(abSense), cbSenseCfg);
1282 }
1283#endif
1284 /*
1285 * Have underlying driver allocate a req of size set during initialization of this device.
1286 */
1287 PDMMEDIAEXIOREQ hIoReq = NULL;
1288 PVIRTIOSCSIREQ pReq = NULL;
1289 PPDMIMEDIAEX pIMediaEx = pTarget->pDrvMediaEx;
1290
1291 int rc = pIMediaEx->pfnIoReqAlloc(pIMediaEx, &hIoReq, (void **)&pReq, 0 /* uIoReqId */,
1292 PDMIMEDIAEX_F_SUSPEND_ON_RECOVERABLE_ERR);
1293
1294 AssertMsgRCReturn(rc, ("Failed to allocate I/O request, rc=%Rrc\n", rc), rc);
1295
1296 pReq->hIoReq = hIoReq;
1297 pReq->pTarget = pTarget;
1298 pReq->uVirtqNbr = uVirtqNbr;
1299 pReq->cbDataIn = cbDataIn;
1300 pReq->cbDataOut = cbDataOut;
1301 pReq->pVirtqBuf = pVirtqBuf;
1302 virtioCoreR3VirtqBufRetain(pVirtqBuf); /* (For pReq->pVirtqBuf. Released by virtioScsiR3FreeReq.) */
1303 pReq->uDataInOff = offDataIn;
1304 pReq->uDataOutOff = offDataOut;
1305
1306 pReq->cbSenseAlloc = cbSenseCfg;
1307 pReq->pbSense = (uint8_t *)RTMemAllocZ(pReq->cbSenseAlloc);
1308 AssertMsgReturnStmt(pReq->pbSense, ("Out of memory allocating sense buffer"),
1309 virtioScsiR3FreeReq(pTarget, pReq);, VERR_NO_MEMORY);
1310
1311 /* Note: DrvSCSI allocates one virtual memory buffer for input and output phases of the request */
1312 rc = pIMediaEx->pfnIoReqSendScsiCmd(pIMediaEx, pReq->hIoReq, uScsiLun,
1313 &VirtqReq.abCdb[0], cbCdb,
1314 PDMMEDIAEXIOREQSCSITXDIR_UNKNOWN, &pReq->enmTxDir,
1315 RT_MAX(cbDataIn, cbDataOut),
1316 pReq->pbSense, pReq->cbSenseAlloc, &pReq->cbSenseLen,
1317 &pReq->uStatus, RT_MS_30SEC);
1318
1319 if (rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
1320 {
1321 /*
1322 * Getting here means the request failed in early in the submission to the lower level driver,
1323 * and there will be no callback to the finished/completion function for this request
1324 */
1325 Assert(RT_FAILURE_NP(rc));
1326 Log2Func(("Request-submission error from lower-level driver\n"));
1327 uint8_t uASC, uASCQ = 0;
1328 switch (rc)
1329 {
1330 case VERR_NO_MEMORY:
1331 uASC = SCSI_ASC_SYSTEM_RESOURCE_FAILURE;
1332 break;
1333 default:
1334 uASC = SCSI_ASC_INTERNAL_TARGET_FAILURE;
1335 break;
1336 }
1337 uint8_t abSense[] = { RT_BIT(7) | SCSI_SENSE_RESPONSE_CODE_CURR_FIXED,
1338 0, SCSI_SENSE_VENDOR_SPECIFIC,
1339 0, 0, 0, 0, 10, uASC, uASCQ, 0 };
1340 REQ_RESP_HDR_T respHdr = { 0 };
1341 respHdr.cbSenseLen = sizeof(abSense);
1342 respHdr.uStatus = SCSI_STATUS_CHECK_CONDITION;
1343 respHdr.uResponse = VIRTIOSCSI_S_FAILURE;
1344 respHdr.uResidual = (cbDataIn + cbDataOut) & UINT32_MAX;
1345 virtioScsiR3ReqErr(pDevIns, pThis, pThisCC, uVirtqNbr, pVirtqBuf, &respHdr, abSense, cbSenseCfg);
1346 virtioScsiR3FreeReq(pTarget, pReq);
1347 }
1348 return VINF_SUCCESS;
1349}
1350
1351/**
1352 * Handles control transfers for/on a worker thread.
1353 *
1354 * @returns VBox status code (ignored by the caller).
1355 * @param pDevIns The device instance.
1356 * @param pThis VirtIO SCSI shared instance data.
1357 * @param pThisCC VirtIO SCSI ring-3 instance data.
1358 * @param uVirtqNbr CONTROLQ_IDX
1359 * @param pVirtqBuf Descriptor chain to process.
1360 */
1361static int virtioScsiR3Ctrl(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, PVIRTIOSCSICC pThisCC,
1362 uint16_t uVirtqNbr, PVIRTQBUF pVirtqBuf)
1363{
1364 AssertReturn(pVirtqBuf->cbPhysSend >= RT_MIN(sizeof(VIRTIOSCSI_CTRL_AN_T),
1365 sizeof(VIRTIOSCSI_CTRL_TMF_T)), 0);
1366
1367 /*
1368 * Allocate buffer and read in the control command
1369 */
1370 VIRTIO_SCSI_CTRL_UNION_T ScsiCtrlUnion;
1371 RT_ZERO(ScsiCtrlUnion);
1372
1373 size_t const cb = RT_MIN(pVirtqBuf->cbPhysSend, sizeof(VIRTIO_SCSI_CTRL_UNION_T));
1374 for (size_t uOffset = 0; uOffset < cb; )
1375 {
1376 size_t cbSeg = cb - uOffset;
1377 RTGCPHYS GCPhys = virtioCoreGCPhysChainGetNextSeg(pVirtqBuf->pSgPhysSend, &cbSeg);
1378 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhys, &ScsiCtrlUnion.ab[uOffset], cbSeg);
1379 uOffset += cbSeg;
1380 }
1381
1382 AssertReturn( (ScsiCtrlUnion.Type.uType == VIRTIOSCSI_T_TMF
1383 && pVirtqBuf->cbPhysSend >= sizeof(VIRTIOSCSI_CTRL_TMF_T))
1384 || ( ( ScsiCtrlUnion.Type.uType == VIRTIOSCSI_T_AN_QUERY
1385 || ScsiCtrlUnion.Type.uType == VIRTIOSCSI_T_AN_SUBSCRIBE)
1386 && pVirtqBuf->cbPhysSend >= sizeof(VIRTIOSCSI_CTRL_AN_T)),
1387 0 /** @todo r=bird: what kind of status is '0' here? */);
1388
1389 union
1390 {
1391 uint32_t fSupportedEvents;
1392 } uData;
1393 uint8_t bResponse = VIRTIOSCSI_S_OK;
1394 uint8_t cSegs;
1395 RTSGSEG aReqSegs[2];
1396 switch (ScsiCtrlUnion.Type.uType)
1397 {
1398 case VIRTIOSCSI_T_TMF: /* Task Management Functions */
1399 {
1400 uint8_t uTarget = ScsiCtrlUnion.Tmf.abScsiLun[1];
1401 uint32_t uScsiLun = RT_MAKE_U16(ScsiCtrlUnion.Tmf.abScsiLun[3], ScsiCtrlUnion.Tmf.abScsiLun[2]) & 0x3fff;
1402 Log2Func(("[%s] (Target: %d LUN: %d) Task Mgt Function: %s\n",
1403 VIRTQNAME(uVirtqNbr), uTarget, uScsiLun, virtioGetTMFTypeText(ScsiCtrlUnion.Tmf.uSubtype)));
1404
1405 if (uTarget >= pThis->cTargets || !pThisCC->paTargetInstances[uTarget].fPresent)
1406 bResponse = VIRTIOSCSI_S_BAD_TARGET;
1407 else
1408 if (uScsiLun != 0)
1409 bResponse = VIRTIOSCSI_S_INCORRECT_LUN;
1410 else
1411 switch (ScsiCtrlUnion.Tmf.uSubtype)
1412 {
1413 case VIRTIOSCSI_T_TMF_ABORT_TASK:
1414 bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
1415 break;
1416 case VIRTIOSCSI_T_TMF_ABORT_TASK_SET:
1417 bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
1418 break;
1419 case VIRTIOSCSI_T_TMF_CLEAR_ACA:
1420 bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
1421 break;
1422 case VIRTIOSCSI_T_TMF_CLEAR_TASK_SET:
1423 bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
1424 break;
1425 case VIRTIOSCSI_T_TMF_I_T_NEXUS_RESET:
1426 bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
1427 break;
1428 case VIRTIOSCSI_T_TMF_LOGICAL_UNIT_RESET:
1429 bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED;
1430 break;
1431 case VIRTIOSCSI_T_TMF_QUERY_TASK:
1432 bResponse = VIRTIOSCSI_S_FUNCTION_REJECTED;
1433 break;
1434 case VIRTIOSCSI_T_TMF_QUERY_TASK_SET:
1435 bResponse = VIRTIOSCSI_S_FUNCTION_REJECTED;
1436 break;
1437 default:
1438 LogFunc(("Unknown TMF type\n"));
1439 bResponse = VIRTIOSCSI_S_FAILURE;
1440 }
1441 cSegs = 0; /* only bResponse */
1442 break;
1443 }
1444 case VIRTIOSCSI_T_AN_QUERY: /* Guest SCSI driver is querying supported async event notifications */
1445 {
1446 uint8_t uTarget = ScsiCtrlUnion.AsyncNotify.abScsiLun[1];
1447 uint32_t uScsiLun = RT_MAKE_U16(ScsiCtrlUnion.AsyncNotify.abScsiLun[3],
1448 ScsiCtrlUnion.AsyncNotify.abScsiLun[2]) & 0x3fff;
1449
1450 if (uTarget >= pThis->cTargets || !pThisCC->paTargetInstances[uTarget].fPresent)
1451 bResponse = VIRTIOSCSI_S_BAD_TARGET;
1452 else
1453 if (uScsiLun != 0)
1454 bResponse = VIRTIOSCSI_S_INCORRECT_LUN;
1455 else
1456 bResponse = VIRTIOSCSI_S_FUNCTION_COMPLETE;
1457
1458#ifdef LOG_ENABLED
1459 if (LogIs2Enabled())
1460 {
1461 char szTypeText[128];
1462 virtioGetControlAsyncMaskText(szTypeText, sizeof(szTypeText), ScsiCtrlUnion.AsyncNotify.fEventsRequested);
1463 Log2Func(("[%s] (Target: %d LUN: %d) Async. Notification Query: %s\n",
1464 VIRTQNAME(uVirtqNbr), uTarget, uScsiLun, szTypeText));
1465 }
1466#endif
1467 uData.fSupportedEvents = SUPPORTED_EVENTS;
1468 aReqSegs[0].pvSeg = &uData.fSupportedEvents;
1469 aReqSegs[0].cbSeg = sizeof(uData.fSupportedEvents);
1470 cSegs = 1;
1471 break;
1472 }
1473 case VIRTIOSCSI_T_AN_SUBSCRIBE: /* Guest SCSI driver is subscribing to async event notification(s) */
1474 {
1475 if (ScsiCtrlUnion.AsyncNotify.fEventsRequested & ~SUBSCRIBABLE_EVENTS)
1476 LogFunc(("Unsupported bits in event subscription event mask: %#x\n",
1477 ScsiCtrlUnion.AsyncNotify.fEventsRequested));
1478
1479 uint8_t uTarget = ScsiCtrlUnion.AsyncNotify.abScsiLun[1];
1480 uint32_t uScsiLun = RT_MAKE_U16(ScsiCtrlUnion.AsyncNotify.abScsiLun[3],
1481 ScsiCtrlUnion.AsyncNotify.abScsiLun[2]) & 0x3fff;
1482
1483#ifdef LOG_ENABLED
1484 if (LogIs2Enabled())
1485 {
1486 char szTypeText[128];
1487 virtioGetControlAsyncMaskText(szTypeText, sizeof(szTypeText), ScsiCtrlUnion.AsyncNotify.fEventsRequested);
1488 Log2Func(("[%s] (Target: %d LUN: %d) Async. Notification Subscribe: %s\n",
1489 VIRTQNAME(uVirtqNbr), uTarget, uScsiLun, szTypeText));
1490 }
1491#endif
1492 if (uTarget >= pThis->cTargets || !pThisCC->paTargetInstances[uTarget].fPresent)
1493 bResponse = VIRTIOSCSI_S_BAD_TARGET;
1494 else
1495 if (uScsiLun != 0)
1496 bResponse = VIRTIOSCSI_S_INCORRECT_LUN;
1497 else
1498 {
1499 bResponse = VIRTIOSCSI_S_FUNCTION_SUCCEEDED; /* or VIRTIOSCSI_S_FUNCTION_COMPLETE? */
1500 pThis->fAsyncEvtsEnabled = SUPPORTED_EVENTS & ScsiCtrlUnion.AsyncNotify.fEventsRequested;
1501 }
1502
1503 aReqSegs[0].pvSeg = &pThis->fAsyncEvtsEnabled;
1504 aReqSegs[0].cbSeg = sizeof(pThis->fAsyncEvtsEnabled);
1505 cSegs = 1;
1506 break;
1507 }
1508 default:
1509 {
1510 LogFunc(("Unknown control type extracted from %s: %u\n", VIRTQNAME(uVirtqNbr), ScsiCtrlUnion.Type.uType));
1511
1512 bResponse = VIRTIOSCSI_S_FAILURE;
1513 cSegs = 0; /* only bResponse */
1514 break;
1515 }
1516 }
1517
1518 /* Add the response code: */
1519 aReqSegs[cSegs].pvSeg = &bResponse;
1520 aReqSegs[cSegs].cbSeg = sizeof(bResponse);
1521 cSegs++;
1522 Assert(cSegs <= RT_ELEMENTS(aReqSegs));
1523
1524 LogFunc(("Response code: %s\n", virtioGetReqRespText(bResponse)));
1525
1526 RTSGBUF ReqSgBuf;
1527 RTSgBufInit(&ReqSgBuf, aReqSegs, cSegs);
1528
1529 virtioCoreR3VirtqUsedBufPut(pDevIns, &pThis->Virtio, uVirtqNbr, &ReqSgBuf, pVirtqBuf, true /*fFence*/);
1530 virtioCoreVirtqUsedRingSync(pDevIns, &pThis->Virtio, uVirtqNbr);
1531
1532 return VINF_SUCCESS;
1533}
1534
1535/**
1536 * @callback_method_impl{FNPDMTHREADWAKEUPDEV}
1537 */
1538static DECLCALLBACK(int) virtioScsiR3WorkerWakeUp(PPDMDEVINS pDevIns, PPDMTHREAD pThread)
1539{
1540 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
1541 return PDMDevHlpSUPSemEventSignal(pDevIns, pThis->aWorkers[(uintptr_t)pThread->pvUser].hEvtProcess);
1542}
1543
1544/**
1545 * @callback_method_impl{FNPDMTHREADDEV}
1546 */
1547static DECLCALLBACK(int) virtioScsiR3WorkerThread(PPDMDEVINS pDevIns, PPDMTHREAD pThread)
1548{
1549 uint16_t const uVirtqNbr = (uint16_t)(uintptr_t)pThread->pvUser;
1550 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
1551 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
1552 PVIRTIOSCSIWORKER pWorker = &pThis->aWorkers[uVirtqNbr];
1553 PVIRTIOSCSIWORKERR3 pWorkerR3 = &pThisCC->aWorkers[uVirtqNbr];
1554
1555 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
1556 return VINF_SUCCESS;
1557
1558 Log6Func(("[Re]starting %s worker\n", VIRTQNAME(uVirtqNbr)));
1559 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
1560 {
1561 if ( !pWorkerR3->cRedoDescs
1562 && IS_VIRTQ_EMPTY(pDevIns, &pThis->Virtio, uVirtqNbr))
1563 {
1564 /* Atomic interlocks avoid missing alarm while going to sleep & notifier waking the awoken */
1565 ASMAtomicWriteBool(&pWorker->fSleeping, true);
1566 bool fNotificationSent = ASMAtomicXchgBool(&pWorker->fNotified, false);
1567 if (!fNotificationSent)
1568 {
1569 Log6Func(("%s worker sleeping...\n", VIRTQNAME(uVirtqNbr)));
1570 Assert(ASMAtomicReadBool(&pWorker->fSleeping));
1571 int rc = PDMDevHlpSUPSemEventWaitNoResume(pDevIns, pWorker->hEvtProcess, RT_INDEFINITE_WAIT);
1572 AssertLogRelMsgReturn(RT_SUCCESS(rc) || rc == VERR_INTERRUPTED, ("%Rrc\n", rc), rc);
1573 if (RT_UNLIKELY(pThread->enmState != PDMTHREADSTATE_RUNNING))
1574 {
1575 Log6Func(("%s worker thread not running, exiting\n", VIRTQNAME(uVirtqNbr)));
1576 return VINF_SUCCESS;
1577 }
1578 if (rc == VERR_INTERRUPTED)
1579 {
1580 Log6Func(("%s worker interrupted ... continuing\n", VIRTQNAME(uVirtqNbr)));
1581 continue;
1582 }
1583 Log6Func(("%s worker woken\n", VIRTQNAME(uVirtqNbr)));
1584 ASMAtomicWriteBool(&pWorker->fNotified, false);
1585 }
1586 ASMAtomicWriteBool(&pWorker->fSleeping, false);
1587 }
1588 if (!virtioCoreIsVirtqEnabled(&pThis->Virtio, uVirtqNbr))
1589 {
1590 LogFunc(("%s queue not enabled, worker aborting...\n", VIRTQNAME(uVirtqNbr)));
1591 break;
1592 }
1593
1594 if (!pThis->afVirtqAttached[uVirtqNbr])
1595 {
1596 LogFunc(("%s queue not attached, worker aborting...\n", VIRTQNAME(uVirtqNbr)));
1597 break;
1598 }
1599 if (!pThisCC->fQuiescing)
1600 {
1601 /* Process any reqs that were suspended saved to the redo queue in save exec. */
1602 for (int i = 0; i < pWorkerR3->cRedoDescs; i++)
1603 {
1604 PVIRTQBUF pVirtqBuf;
1605 int rc = virtioCoreR3VirtqAvailBufGet(pDevIns, &pThis->Virtio, uVirtqNbr,
1606 pWorkerR3->auRedoDescs[i], &pVirtqBuf);
1607 if (RT_FAILURE(rc))
1608 LogRel(("Error fetching desc chain to redo, %Rrc", rc));
1609
1610 rc = virtioScsiR3ReqSubmit(pDevIns, pThis, pThisCC, uVirtqNbr, pVirtqBuf);
1611 if (RT_FAILURE(rc))
1612 LogRel(("Error submitting req packet, resetting %Rrc", rc));
1613
1614 virtioCoreR3VirtqBufRelease(&pThis->Virtio, pVirtqBuf);
1615 }
1616 pWorkerR3->cRedoDescs = 0;
1617
1618 Log6Func(("fetching next descriptor chain from %s\n", VIRTQNAME(uVirtqNbr)));
1619 PVIRTQBUF pVirtqBuf = NULL;
1620 int rc = virtioCoreR3VirtqAvailBufGet(pDevIns, &pThis->Virtio, uVirtqNbr, &pVirtqBuf, true);
1621 if (rc == VERR_NOT_AVAILABLE)
1622 {
1623 Log6Func(("Nothing found in %s\n", VIRTQNAME(uVirtqNbr)));
1624 continue;
1625 }
1626
1627 AssertRC(rc);
1628 if (uVirtqNbr == CONTROLQ_IDX)
1629 virtioScsiR3Ctrl(pDevIns, pThis, pThisCC, uVirtqNbr, pVirtqBuf);
1630 else /* request queue index */
1631 {
1632 rc = virtioScsiR3ReqSubmit(pDevIns, pThis, pThisCC, uVirtqNbr, pVirtqBuf);
1633 if (RT_FAILURE(rc))
1634 LogRel(("Error submitting req packet, resetting %Rrc", rc));
1635 }
1636
1637 virtioCoreR3VirtqBufRelease(&pThis->Virtio, pVirtqBuf);
1638 }
1639 }
1640 return VINF_SUCCESS;
1641}
1642
1643
1644/*********************************************************************************************************************************
1645* Sending evnets
1646*********************************************************************************************************************************/
1647
1648/*
1649 * @todo Figure out how to implement this with R0 changes. Not used by current linux driver
1650 */
1651
1652#if 0
1653DECLINLINE(void) virtioScsiR3ReportEventsMissed(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget)
1654{
1655 virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_NO_EVENT | VIRTIOSCSI_T_EVENTS_MISSED, 0);
1656}
1657#endif
1658
1659#if 0
1660/* SUBSCRIBABLE EVENT - not sure when to call this or how to detect when media is added or removed
1661 * via the VBox GUI */
1662DECLINLINE(void) virtioScsiR3ReportMediaChange(PPDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget)
1663{
1664 if (pThis->fAsyncEvtsEnabled & VIRTIOSCSI_EVT_ASYNC_MEDIA_CHANGE)
1665 virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_ASYNC_NOTIFY, VIRTIOSCSI_EVT_ASYNC_MEDIA_CHANGE);
1666}
1667
1668/* ESSENTIAL (NON-SUBSCRIBABLE) EVENT TYPES (most guest virtio-scsi drivers ignore?) */
1669
1670DECLINLINE(void) virtioScsiR3ReportTransportReset(PDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget)
1671{
1672 virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_TRANSPORT_RESET, VIRTIOSCSI_EVT_RESET_HARD);
1673}
1674
1675DECLINLINE(void) virtioScsiR3ReportParamChange(PDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget,
1676 uint32_t uSenseCode, uint32_t uSenseQualifier)
1677{
1678 uint32_t uReason = uSenseQualifier << 8 | uSenseCode;
1679 virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_PARAM_CHANGE, uReason);
1680
1681}
1682
1683DECLINLINE(void) virtioScsiR3ReportTargetRemoved(PDMDEVINS pDevIns, PVIRTIOSCSI pThis, uint16_t uTarget)
1684{
1685 if (pThis->fHasHotplug)
1686 virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_TRANSPORT_RESET, VIRTIOSCSI_EVT_RESET_REMOVED);
1687}
1688
1689DECLINLINE(void) virtioScsiR3ReportTargetAdded(PDMDEVINS pDevInsPVIRTIOSCSI pThis, uint16_t uTarget)
1690{
1691 if (pThis->fHasHotplug)
1692 virtioScsiR3SendEvent(pDevIns, pThis, uTarget, VIRTIOSCSI_T_TRANSPORT_RESET, VIRTIOSCSI_EVT_RESET_RESCAN);
1693}
1694
1695#endif
1696
1697/**
1698 * @callback_method_impl{VIRTIOCORER3,pfnStatusChanged}
1699 */
1700static DECLCALLBACK(void) virtioScsiR3StatusChanged(PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC, uint32_t fVirtioReady)
1701{
1702 PVIRTIOSCSI pThis = RT_FROM_MEMBER(pVirtio, VIRTIOSCSI, Virtio);
1703 PVIRTIOSCSICC pThisCC = RT_FROM_MEMBER(pVirtioCC, VIRTIOSCSICC, Virtio);
1704
1705 pThis->fVirtioReady = fVirtioReady;
1706
1707 if (fVirtioReady)
1708 {
1709 LogFunc(("VirtIO ready\n-----------------------------------------------------------------------------------------\n"));
1710 uint64_t fFeatures = virtioCoreGetNegotiatedFeatures(&pThis->Virtio);
1711 pThis->fHasT10pi = fFeatures & VIRTIO_SCSI_F_T10_PI;
1712 pThis->fHasHotplug = fFeatures & VIRTIO_SCSI_F_HOTPLUG;
1713 pThis->fHasInOutBufs = fFeatures & VIRTIO_SCSI_F_INOUT;
1714 pThis->fHasLunChange = fFeatures & VIRTIO_SCSI_F_CHANGE;
1715 pThis->fResetting = false;
1716 pThisCC->fQuiescing = false;
1717
1718 for (unsigned i = 0; i < VIRTIOSCSI_VIRTQ_CNT; i++)
1719 pThis->afVirtqAttached[i] = true;
1720 }
1721 else
1722 {
1723 LogFunc(("VirtIO is resetting\n"));
1724 for (unsigned i = 0; i < VIRTIOSCSI_VIRTQ_CNT; i++)
1725 pThis->afVirtqAttached[i] = false;
1726
1727 /*
1728 * BIOS may change these values. When the OS comes up, and KVM driver accessed
1729 * through Windows, it assumes they are the default size. So as per the VirtIO 1.0 spec,
1730 * 5.6.4, these device configuration values must be set to default upon device reset.
1731 */
1732 pThis->virtioScsiConfig.uSenseSize = VIRTIOSCSI_SENSE_SIZE_DEFAULT;
1733 pThis->virtioScsiConfig.uCdbSize = VIRTIOSCSI_CDB_SIZE_DEFAULT;
1734 }
1735
1736
1737}
1738
1739
1740/*********************************************************************************************************************************
1741* LEDs *
1742*********************************************************************************************************************************/
1743
1744/**
1745 * @interface_method_impl{PDMILEDPORTS,pfnQueryStatusLed, Target level.}
1746 */
1747static DECLCALLBACK(int) virtioScsiR3TargetQueryStatusLed(PPDMILEDPORTS pInterface, unsigned iLUN, PPDMLED *ppLed)
1748{
1749 PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, ILed);
1750 if (iLUN == 0)
1751 {
1752 *ppLed = &pTarget->led;
1753 Assert((*ppLed)->u32Magic == PDMLED_MAGIC);
1754 return VINF_SUCCESS;
1755 }
1756 return VERR_PDM_LUN_NOT_FOUND;
1757}
1758/**
1759 * @interface_method_impl{PDMILEDPORTS,pfnQueryStatusLed, Device level.}
1760 */
1761static DECLCALLBACK(int) virtioScsiR3DeviceQueryStatusLed(PPDMILEDPORTS pInterface, unsigned iLUN, PPDMLED *ppLed)
1762{
1763 PVIRTIOSCSICC pThisCC = RT_FROM_MEMBER(pInterface, VIRTIOSCSICC, ILeds);
1764 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pThisCC->pDevIns, PVIRTIOSCSI);
1765 if (iLUN < pThis->cTargets)
1766 {
1767 *ppLed = &pThisCC->paTargetInstances[iLUN].led;
1768 Assert((*ppLed)->u32Magic == PDMLED_MAGIC);
1769 return VINF_SUCCESS;
1770 }
1771 return VERR_PDM_LUN_NOT_FOUND;
1772}
1773
1774
1775/*********************************************************************************************************************************
1776* PDMIMEDIAPORT (target) *
1777*********************************************************************************************************************************/
1778
1779/**
1780 * @interface_method_impl{PDMIMEDIAPORT,pfnQueryDeviceLocation, Target level.}
1781 */
1782static DECLCALLBACK(int) virtioScsiR3QueryDeviceLocation(PPDMIMEDIAPORT pInterface, const char **ppcszController,
1783 uint32_t *piInstance, uint32_t *piLUN)
1784{
1785 PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaPort);
1786 PPDMDEVINS pDevIns = pTarget->pDevIns;
1787
1788 AssertPtrReturn(ppcszController, VERR_INVALID_POINTER);
1789 AssertPtrReturn(piInstance, VERR_INVALID_POINTER);
1790 AssertPtrReturn(piLUN, VERR_INVALID_POINTER);
1791
1792 *ppcszController = pDevIns->pReg->szName;
1793 *piInstance = pDevIns->iInstance;
1794 *piLUN = pTarget->uTarget;
1795
1796 return VINF_SUCCESS;
1797}
1798
1799
1800/*********************************************************************************************************************************
1801* Virtio config. *
1802*********************************************************************************************************************************/
1803
1804/**
1805 * Worker for virtioScsiR3DevCapWrite and virtioScsiR3DevCapRead.
1806 */
1807static int virtioScsiR3CfgAccessed(PVIRTIOSCSI pThis, uint32_t uOffsetOfAccess, void *pv, uint32_t cb, bool fWrite)
1808{
1809 AssertReturn(pv && cb <= sizeof(uint32_t), fWrite ? VINF_SUCCESS : VINF_IOM_MMIO_UNUSED_00);
1810
1811 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uNumVirtqs, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
1812 VIRTIO_DEV_CONFIG_ACCESS_READONLY( uNumVirtqs, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
1813 else
1814 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uSegMax, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
1815 VIRTIO_DEV_CONFIG_ACCESS_READONLY( uSegMax, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
1816 else
1817 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMaxSectors, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
1818 VIRTIO_DEV_CONFIG_ACCESS_READONLY( uMaxSectors, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
1819 else
1820 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uCmdPerLun, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
1821 VIRTIO_DEV_CONFIG_ACCESS_READONLY( uCmdPerLun, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
1822 else
1823 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uEventInfoSize, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
1824 VIRTIO_DEV_CONFIG_ACCESS_READONLY( uEventInfoSize, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
1825 else
1826 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uSenseSize, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
1827 VIRTIO_DEV_CONFIG_ACCESS( uSenseSize, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
1828 else
1829 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uCdbSize, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
1830 VIRTIO_DEV_CONFIG_ACCESS( uCdbSize, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
1831 else
1832 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMaxChannel, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
1833 VIRTIO_DEV_CONFIG_ACCESS_READONLY( uMaxChannel, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
1834 else
1835 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMaxTarget, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
1836 VIRTIO_DEV_CONFIG_ACCESS_READONLY( uMaxTarget, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
1837 else
1838 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMaxLun, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess))
1839 VIRTIO_DEV_CONFIG_ACCESS_READONLY( uMaxLun, VIRTIOSCSI_CONFIG_T, uOffsetOfAccess, &pThis->virtioScsiConfig);
1840 else
1841 {
1842 LogFunc(("Bad access by guest to virtio_scsi_config: off=%u (%#x), cb=%u\n", uOffsetOfAccess, uOffsetOfAccess, cb));
1843 return fWrite ? VINF_SUCCESS : VINF_IOM_MMIO_UNUSED_00;
1844 }
1845 return VINF_SUCCESS;
1846}
1847
1848/**
1849 * @callback_method_impl{VIRTIOCORER3,pfnDevCapRead}
1850 */
1851static DECLCALLBACK(int) virtioScsiR3DevCapRead(PPDMDEVINS pDevIns, uint32_t uOffset, void *pv, uint32_t cb)
1852{
1853 return virtioScsiR3CfgAccessed(PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI), uOffset, pv, cb, false /*fRead*/);
1854}
1855
1856/**
1857 * @callback_method_impl{VIRTIOCORER3,pfnDevCapWrite}
1858 */
1859static DECLCALLBACK(int) virtioScsiR3DevCapWrite(PPDMDEVINS pDevIns, uint32_t uOffset, const void *pv, uint32_t cb)
1860{
1861 return virtioScsiR3CfgAccessed(PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI), uOffset, (void *)pv, cb, true /*fWrite*/);
1862}
1863
1864
1865/*********************************************************************************************************************************
1866* IBase for device and targets *
1867*********************************************************************************************************************************/
1868
1869/**
1870 * @interface_method_impl{PDMIBASE,pfnQueryInterface, Target level.}
1871 */
1872static DECLCALLBACK(void *) virtioScsiR3TargetQueryInterface(PPDMIBASE pInterface, const char *pszIID)
1873{
1874 PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IBase);
1875 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pTarget->IBase);
1876 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIAPORT, &pTarget->IMediaPort);
1877 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIAEXPORT, &pTarget->IMediaExPort);
1878 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDPORTS, &pTarget->ILed);
1879 return NULL;
1880}
1881
1882/**
1883 * @interface_method_impl{PDMIBASE,pfnQueryInterface, Device level.}
1884 */
1885static DECLCALLBACK(void *) virtioScsiR3DeviceQueryInterface(PPDMIBASE pInterface, const char *pszIID)
1886{
1887 PVIRTIOSCSICC pThisCC = RT_FROM_MEMBER(pInterface, VIRTIOSCSICC, IBase);
1888
1889 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThisCC->IBase);
1890 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDPORTS, &pThisCC->ILeds);
1891
1892 return NULL;
1893}
1894
1895
1896/*********************************************************************************************************************************
1897* Misc *
1898*********************************************************************************************************************************/
1899
1900/**
1901 * @callback_method_impl{FNDBGFHANDLERDEV, virtio-scsi debugger info callback.}
1902 */
1903static DECLCALLBACK(void) virtioScsiR3Info(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
1904{
1905 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
1906
1907 /* Parse arguments. */
1908 RT_NOREF(pszArgs); //bool fVerbose = pszArgs && strstr(pszArgs, "verbose") != NULL;
1909
1910 /* Show basic information. */
1911 pHlp->pfnPrintf(pHlp, "%s#%d: virtio-scsci ",
1912 pDevIns->pReg->szName,
1913 pDevIns->iInstance);
1914 pHlp->pfnPrintf(pHlp, "numTargets=%lu", pThis->cTargets);
1915}
1916
1917
1918/*********************************************************************************************************************************
1919* Saved state *
1920*********************************************************************************************************************************/
1921
1922/**
1923 * @callback_method_impl{FNSSMDEVLOADEXEC}
1924 */
1925static DECLCALLBACK(int) virtioScsiR3LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
1926{
1927 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
1928 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
1929 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
1930
1931 LogFunc(("LOAD EXEC!!\n"));
1932
1933 AssertReturn(uPass == SSM_PASS_FINAL, VERR_SSM_UNEXPECTED_PASS);
1934 AssertLogRelMsgReturn(uVersion == VIRTIOSCSI_SAVED_STATE_VERSION,
1935 ("uVersion=%u\n", uVersion), VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);
1936
1937 virtioScsiSetVirtqNames(pThis);
1938 for (int uVirtqNbr = 0; uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT; uVirtqNbr++)
1939 pHlp->pfnSSMGetBool(pSSM, &pThis->afVirtqAttached[uVirtqNbr]);
1940
1941 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uNumVirtqs);
1942 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uSegMax);
1943 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uMaxSectors);
1944 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uCmdPerLun);
1945 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uEventInfoSize);
1946 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uSenseSize);
1947 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uCdbSize);
1948 pHlp->pfnSSMGetU16(pSSM, &pThis->virtioScsiConfig.uMaxChannel);
1949 pHlp->pfnSSMGetU16(pSSM, &pThis->virtioScsiConfig.uMaxTarget);
1950 pHlp->pfnSSMGetU32(pSSM, &pThis->virtioScsiConfig.uMaxLun);
1951 pHlp->pfnSSMGetU32(pSSM, &pThis->fAsyncEvtsEnabled);
1952 pHlp->pfnSSMGetBool(pSSM, &pThis->fEventsMissed);
1953 pHlp->pfnSSMGetU32(pSSM, &pThis->fVirtioReady);
1954 pHlp->pfnSSMGetU32(pSSM, &pThis->fHasT10pi);
1955 pHlp->pfnSSMGetU32(pSSM, &pThis->fHasHotplug);
1956 pHlp->pfnSSMGetU32(pSSM, &pThis->fHasInOutBufs);
1957 pHlp->pfnSSMGetU32(pSSM, &pThis->fHasLunChange);
1958 pHlp->pfnSSMGetU32(pSSM, &pThis->fResetting);
1959
1960 uint32_t cTargets;
1961 int rc = pHlp->pfnSSMGetU32(pSSM, &cTargets);
1962 AssertRCReturn(rc, rc);
1963 AssertReturn(cTargets == pThis->cTargets,
1964 pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_LOAD_CONFIG_MISMATCH, RT_SRC_POS,
1965 N_("target count has changed: %u saved, %u configured now"),
1966 cTargets, pThis->cTargets));
1967
1968 for (uint16_t uTarget = 0; uTarget < pThis->cTargets; uTarget++)
1969 {
1970 uint16_t cReqsRedo;
1971 rc = pHlp->pfnSSMGetU16(pSSM, &cReqsRedo);
1972 AssertRCReturn(rc, rc);
1973 AssertReturn(cReqsRedo < VIRTQ_SIZE,
1974 pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
1975 N_("Bad count of I/O transactions to re-do in saved state (%#x, max %#x - 1)"),
1976 cReqsRedo, VIRTQ_SIZE));
1977
1978 for (uint16_t uVirtqNbr = VIRTQ_REQ_BASE; uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT; uVirtqNbr++)
1979 {
1980 PVIRTIOSCSIWORKERR3 pWorkerR3 = &pThisCC->aWorkers[uVirtqNbr];
1981 pWorkerR3->cRedoDescs = 0;
1982 }
1983
1984 for (int i = 0; i < cReqsRedo; i++)
1985 {
1986 uint16_t uVirtqNbr;
1987 rc = pHlp->pfnSSMGetU16(pSSM, &uVirtqNbr);
1988 AssertRCReturn(rc, rc);
1989 AssertReturn(uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT,
1990 pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
1991 N_("Bad queue index for re-do in saved state (%#x, max %#x)"),
1992 uVirtqNbr, VIRTIOSCSI_VIRTQ_CNT - 1));
1993
1994 uint16_t idxHead;
1995 rc = pHlp->pfnSSMGetU16(pSSM, &idxHead);
1996 AssertRCReturn(rc, rc);
1997 AssertReturn(idxHead < VIRTQ_SIZE,
1998 pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
1999 N_("Bad queue element index for re-do in saved state (%#x, max %#x)"),
2000 idxHead, VIRTQ_SIZE - 1));
2001
2002 PVIRTIOSCSIWORKERR3 pWorkerR3 = &pThisCC->aWorkers[uVirtqNbr];
2003 pWorkerR3->auRedoDescs[pWorkerR3->cRedoDescs++] = idxHead;
2004 pWorkerR3->cRedoDescs %= VIRTQ_SIZE;
2005 }
2006 }
2007
2008 /*
2009 * Call the virtio core to let it load its state.
2010 */
2011 rc = virtioCoreR3ModernDeviceLoadExec(&pThis->Virtio, pDevIns->pHlpR3, pSSM,
2012 uVersion, VIRTIOSCSI_SAVED_STATE_VERSION, pThis->virtioScsiConfig.uNumVirtqs);
2013
2014 /*
2015 * Nudge request queue workers
2016 */
2017 for (int uVirtqNbr = VIRTQ_REQ_BASE; uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT; uVirtqNbr++)
2018 {
2019 if (pThis->afVirtqAttached[uVirtqNbr])
2020 {
2021 LogFunc(("Waking %s worker.\n", VIRTQNAME(uVirtqNbr)));
2022 int rc2 = PDMDevHlpSUPSemEventSignal(pDevIns, pThis->aWorkers[uVirtqNbr].hEvtProcess);
2023 AssertRCReturn(rc, rc2);
2024 }
2025 }
2026
2027 return rc;
2028}
2029
2030/**
2031 * @callback_method_impl{FNSSMDEVSAVEEXEC}
2032 */
2033static DECLCALLBACK(int) virtioScsiR3SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
2034{
2035 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2036 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2037 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
2038
2039 LogFunc(("SAVE EXEC!!\n"));
2040
2041 for (int uVirtqNbr = 0; uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT; uVirtqNbr++)
2042 pHlp->pfnSSMPutBool(pSSM, pThis->afVirtqAttached[uVirtqNbr]);
2043
2044 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uNumVirtqs);
2045 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uSegMax);
2046 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uMaxSectors);
2047 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uCmdPerLun);
2048 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uEventInfoSize);
2049 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uSenseSize);
2050 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uCdbSize);
2051 pHlp->pfnSSMPutU16(pSSM, pThis->virtioScsiConfig.uMaxChannel);
2052 pHlp->pfnSSMPutU16(pSSM, pThis->virtioScsiConfig.uMaxTarget);
2053 pHlp->pfnSSMPutU32(pSSM, pThis->virtioScsiConfig.uMaxLun);
2054 pHlp->pfnSSMPutU32(pSSM, pThis->fAsyncEvtsEnabled);
2055 pHlp->pfnSSMPutBool(pSSM, pThis->fEventsMissed);
2056 pHlp->pfnSSMPutU32(pSSM, pThis->fVirtioReady);
2057 pHlp->pfnSSMPutU32(pSSM, pThis->fHasT10pi);
2058 pHlp->pfnSSMPutU32(pSSM, pThis->fHasHotplug);
2059 pHlp->pfnSSMPutU32(pSSM, pThis->fHasInOutBufs);
2060 pHlp->pfnSSMPutU32(pSSM, pThis->fHasLunChange);
2061 pHlp->pfnSSMPutU32(pSSM, pThis->fResetting);
2062
2063 AssertMsg(!pThis->cActiveReqs, ("There are still outstanding requests on this device\n"));
2064
2065 pHlp->pfnSSMPutU32(pSSM, pThis->cTargets);
2066
2067 for (uint16_t uTarget = 0; uTarget < pThis->cTargets; uTarget++)
2068 {
2069 PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[uTarget];
2070
2071 /* Query all suspended requests and store them in the request queue. */
2072 if (pTarget->pDrvMediaEx)
2073 {
2074 uint32_t cReqsRedo = pTarget->pDrvMediaEx->pfnIoReqGetSuspendedCount(pTarget->pDrvMediaEx);
2075
2076 pHlp->pfnSSMPutU16(pSSM, cReqsRedo);
2077
2078 if (cReqsRedo)
2079 {
2080 PDMMEDIAEXIOREQ hIoReq;
2081 PVIRTIOSCSIREQ pReq;
2082
2083 int rc = pTarget->pDrvMediaEx->pfnIoReqQuerySuspendedStart(pTarget->pDrvMediaEx, &hIoReq,
2084 (void **)&pReq);
2085 AssertRCBreak(rc);
2086
2087 while(--cReqsRedo)
2088 {
2089 pHlp->pfnSSMPutU16(pSSM, pReq->uVirtqNbr);
2090 pHlp->pfnSSMPutU16(pSSM, pReq->pVirtqBuf->uHeadIdx);
2091
2092 rc = pTarget->pDrvMediaEx->pfnIoReqQuerySuspendedNext(pTarget->pDrvMediaEx, hIoReq,
2093 &hIoReq, (void **)&pReq);
2094 AssertRCBreak(rc);
2095 }
2096 }
2097 }
2098 }
2099
2100 /*
2101 * Call the virtio core to let it save its state.
2102 */
2103 return virtioCoreR3SaveExec(&pThis->Virtio, pDevIns->pHlpR3, pSSM, VIRTIOSCSI_SAVED_STATE_VERSION, VIRTIOSCSI_VIRTQ_CNT);
2104}
2105
2106
2107/*********************************************************************************************************************************
2108* Device interface. *
2109*********************************************************************************************************************************/
2110
2111/**
2112 * @interface_method_impl{PDMDEVREGR3,pfnDetach}
2113 *
2114 * One harddisk at one port has been unplugged.
2115 * The VM is suspended at this point.
2116 */
2117static DECLCALLBACK(void) virtioScsiR3Detach(PPDMDEVINS pDevIns, unsigned uTarget, uint32_t fFlags)
2118{
2119 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2120 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2121 AssertReturnVoid(uTarget < pThis->cTargets);
2122 PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[uTarget];
2123
2124 LogFunc((""));
2125
2126 AssertMsg(fFlags & PDM_TACH_FLAGS_NOT_HOT_PLUG,
2127 ("virtio-scsi: Device does not support hotplugging\n"));
2128 RT_NOREF(fFlags);
2129
2130 /*
2131 * Zero all important members.
2132 */
2133 pTarget->fPresent = false;
2134 pTarget->pDrvBase = NULL;
2135 pTarget->pDrvMedia = NULL;
2136 pTarget->pDrvMediaEx = NULL;
2137}
2138
2139/**
2140 * @interface_method_impl{PDMDEVREGR3,pfnAttach}
2141 *
2142 * This is called when we change block driver.
2143 */
2144static DECLCALLBACK(int) virtioScsiR3Attach(PPDMDEVINS pDevIns, unsigned uTarget, uint32_t fFlags)
2145{
2146 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2147 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2148 AssertReturn(uTarget < pThis->cTargets, VERR_PDM_LUN_NOT_FOUND);
2149 PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[uTarget];
2150
2151 Assert(pTarget->pDevIns == pDevIns);
2152 AssertMsgReturn(fFlags & PDM_TACH_FLAGS_NOT_HOT_PLUG,
2153 ("virtio-scsi: Device does not support hotplugging\n"),
2154 VERR_INVALID_PARAMETER);
2155
2156 AssertRelease(!pTarget->pDrvBase);
2157 Assert(pTarget->uTarget == uTarget);
2158
2159 /*
2160 * Try attach the SCSI driver and get the interfaces, required as well as optional.
2161 */
2162 int rc = PDMDevHlpDriverAttach(pDevIns, pTarget->uTarget, &pDevIns->IBase, &pTarget->pDrvBase, pTarget->pszTargetName);
2163 if (RT_SUCCESS(rc))
2164 {
2165 pTarget->fPresent = true;
2166 pTarget->pDrvMedia = PDMIBASE_QUERY_INTERFACE(pTarget->pDrvBase, PDMIMEDIA);
2167 AssertMsgReturn(RT_VALID_PTR(pTarget->pDrvMedia),
2168 ("virtio-scsi configuration error: LUN#%d missing basic media interface!\n", uTarget),
2169 VERR_PDM_MISSING_INTERFACE);
2170
2171 /* Get the extended media interface. */
2172 pTarget->pDrvMediaEx = PDMIBASE_QUERY_INTERFACE(pTarget->pDrvBase, PDMIMEDIAEX);
2173 AssertMsgReturn(RT_VALID_PTR(pTarget->pDrvMediaEx),
2174 ("virtio-scsi configuration error: LUN#%d missing extended media interface!\n", uTarget),
2175 VERR_PDM_MISSING_INTERFACE);
2176
2177 rc = pTarget->pDrvMediaEx->pfnIoReqAllocSizeSet(pTarget->pDrvMediaEx, sizeof(VIRTIOSCSIREQ));
2178 AssertMsgReturn(RT_VALID_PTR(pTarget->pDrvMediaEx),
2179 ("virtio-scsi configuration error: LUN#%u: Failed to set I/O request size!\n", uTarget),
2180 rc);
2181 }
2182 else
2183 AssertMsgFailed(("Failed to attach %s. rc=%Rrc\n", pTarget->pszTargetName, rc));
2184
2185 if (RT_FAILURE(rc))
2186 {
2187 pTarget->fPresent = false;
2188 pTarget->pDrvBase = NULL;
2189 pTarget->pDrvMedia = NULL;
2190 pTarget->pDrvMediaEx = NULL;
2191 pThisCC->pMediaNotify = NULL;
2192 }
2193 return rc;
2194}
2195
2196/**
2197 * @callback_method_impl{FNPDMDEVASYNCNOTIFY}
2198 */
2199static DECLCALLBACK(bool) virtioScsiR3DeviceQuiesced(PPDMDEVINS pDevIns)
2200{
2201 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2202 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2203
2204 if (ASMAtomicReadU32(&pThis->cActiveReqs))
2205 return false;
2206
2207 LogFunc(("Device I/O activity quiesced: %s\n",
2208 virtioCoreGetStateChangeText(pThisCC->enmQuiescingFor)));
2209
2210 virtioCoreR3VmStateChanged(&pThis->Virtio, pThisCC->enmQuiescingFor);
2211
2212 pThis->fResetting = false;
2213 pThisCC->fQuiescing = false;
2214
2215 return true;
2216}
2217
2218/**
2219 * Worker for virtioScsiR3Reset() and virtioScsiR3SuspendOrPowerOff().
2220 */
2221static void virtioScsiR3QuiesceDevice(PPDMDEVINS pDevIns, VIRTIOVMSTATECHANGED enmQuiscingFor)
2222{
2223 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2224 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2225
2226 /* Prevent worker threads from removing/processing elements from virtq's */
2227 pThisCC->fQuiescing = true;
2228 pThisCC->enmQuiescingFor = enmQuiscingFor;
2229
2230 PDMDevHlpSetAsyncNotification(pDevIns, virtioScsiR3DeviceQuiesced);
2231
2232 /* If already quiesced invoke async callback. */
2233 if (!ASMAtomicReadU32(&pThis->cActiveReqs))
2234 PDMDevHlpAsyncNotificationCompleted(pDevIns);
2235}
2236
2237/**
2238 * @interface_method_impl{PDMDEVREGR3,pfnReset}
2239 */
2240static DECLCALLBACK(void) virtioScsiR3Reset(PPDMDEVINS pDevIns)
2241{
2242 LogFunc(("\n"));
2243 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2244 pThis->fResetting = true;
2245 virtioScsiR3QuiesceDevice(pDevIns, kvirtIoVmStateChangedReset);
2246}
2247
2248/**
2249 * @interface_method_impl{PDMDEVREGR3,pfnPowerOff}
2250 */
2251static DECLCALLBACK(void) virtioScsiR3SuspendOrPowerOff(PPDMDEVINS pDevIns, VIRTIOVMSTATECHANGED enmType)
2252{
2253 LogFunc(("\n"));
2254
2255 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2256 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2257
2258 /* VM is halted, thus no new I/O being dumped into queues by the guest.
2259 * Workers have been flagged to stop pulling stuff already queued-up by the guest.
2260 * Now tell lower-level to to suspend reqs (for example, DrvVD suspends all reqs
2261 * on its wait queue, and we will get a callback as the state changes to
2262 * suspended (and later, resumed) for each).
2263 */
2264 for (uint32_t i = 0; i < pThis->cTargets; i++)
2265 {
2266 PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[i];
2267 if (pTarget->pDrvMediaEx)
2268 pTarget->pDrvMediaEx->pfnNotifySuspend(pTarget->pDrvMediaEx);
2269 }
2270
2271 virtioScsiR3QuiesceDevice(pDevIns, enmType);
2272}
2273
2274/**
2275 * @interface_method_impl{PDMDEVREGR3,pfnSuspend}
2276 */
2277static DECLCALLBACK(void) virtioScsiR3PowerOff(PPDMDEVINS pDevIns)
2278{
2279 LogFunc(("\n"));
2280 virtioScsiR3SuspendOrPowerOff(pDevIns, kvirtIoVmStateChangedPowerOff);
2281}
2282
2283/**
2284 * @interface_method_impl{PDMDEVREGR3,pfnSuspend}
2285 */
2286static DECLCALLBACK(void) virtioScsiR3Suspend(PPDMDEVINS pDevIns)
2287{
2288 LogFunc(("\n"));
2289 virtioScsiR3SuspendOrPowerOff(pDevIns, kvirtIoVmStateChangedSuspend);
2290}
2291
2292/**
2293 * @interface_method_impl{PDMDEVREGR3,pfnResume}
2294 */
2295static DECLCALLBACK(void) virtioScsiR3Resume(PPDMDEVINS pDevIns)
2296{
2297 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2298 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2299 LogFunc(("\n"));
2300
2301 pThisCC->fQuiescing = false;
2302
2303 /* Wake worker threads flagged to skip pulling queue entries during quiesce
2304 * to ensure they re-check their queues. Active request queues may already
2305 * be awake due to new reqs coming in.
2306 */
2307 for (uint16_t uVirtqNbr = 0; uVirtqNbr < VIRTIOSCSI_REQ_VIRTQ_CNT; uVirtqNbr++)
2308 {
2309 if ( virtioCoreIsVirtqEnabled(&pThis->Virtio, uVirtqNbr)
2310 && ASMAtomicReadBool(&pThis->aWorkers[uVirtqNbr].fSleeping))
2311 {
2312 Log6Func(("waking %s worker.\n", VIRTQNAME(uVirtqNbr)));
2313 int rc = PDMDevHlpSUPSemEventSignal(pDevIns, pThis->aWorkers[uVirtqNbr].hEvtProcess);
2314 AssertRC(rc);
2315 }
2316 }
2317 /* Ensure guest is working the queues too. */
2318 virtioCoreR3VmStateChanged(&pThis->Virtio, kvirtIoVmStateChangedResume);
2319}
2320
2321/**
2322 * @interface_method_impl{PDMIMEDIAEXPORT,pfnMediumEjected}
2323 */
2324static DECLCALLBACK(void) virtioScsiR3MediumEjected(PPDMIMEDIAEXPORT pInterface)
2325{
2326 PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaExPort);
2327 PPDMDEVINS pDevIns = pTarget->pDevIns;
2328 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2329
2330#if 0 /* need more info about how to use this event. The VirtIO 1.0 specification
2331 * lists several SCSI related event types but presumes the reader knows
2332 * how to use them without providing references. */
2333 virtioScsiR3ReportMediaChange(pDevIns, pThis, pTarget->uTarget);
2334#endif
2335
2336 if (pThisCC->pMediaNotify)
2337 {
2338 int rc = PDMDevHlpVMReqCallNoWait(pDevIns, VMCPUID_ANY,
2339 (PFNRT)pThisCC->pMediaNotify->pfnEjected, 2,
2340 pThisCC->pMediaNotify, pTarget->uTarget);
2341 AssertRC(rc);
2342 }
2343}
2344
2345/**
2346 * @interface_method_impl{PDMIMEDIAEXPORT,pfnIoReqStateChanged}
2347 */
2348static DECLCALLBACK(void) virtioScsiR3IoReqStateChanged(PPDMIMEDIAEXPORT pInterface, PDMMEDIAEXIOREQ hIoReq,
2349 void *pvIoReqAlloc, PDMMEDIAEXIOREQSTATE enmState)
2350{
2351 PVIRTIOSCSITARGET pTarget = RT_FROM_MEMBER(pInterface, VIRTIOSCSITARGET, IMediaExPort);
2352 PPDMDEVINS pDevIns = pTarget->pDevIns;
2353 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2354 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2355 RT_NOREF(hIoReq, pvIoReqAlloc);
2356
2357 switch (enmState)
2358 {
2359 case PDMMEDIAEXIOREQSTATE_SUSPENDED:
2360 {
2361 /* Stop considering this request active */
2362 if (!ASMAtomicDecU32(&pThis->cActiveReqs) && pThisCC->fQuiescing)
2363 PDMDevHlpAsyncNotificationCompleted(pDevIns);
2364 break;
2365 }
2366 case PDMMEDIAEXIOREQSTATE_ACTIVE:
2367 ASMAtomicIncU32(&pThis->cActiveReqs);
2368 break;
2369 default:
2370 AssertMsgFailed(("Invalid request state given %u\n", enmState));
2371 }
2372}
2373
2374/**
2375 * @interface_method_impl{PDMDEVREGR3,pfnDestruct}
2376 */
2377static DECLCALLBACK(int) virtioScsiR3Destruct(PPDMDEVINS pDevIns)
2378{
2379 PDMDEV_CHECK_VERSIONS_RETURN_QUIET(pDevIns);
2380 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2381 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2382
2383 RTMemFree(pThisCC->paTargetInstances);
2384 pThisCC->paTargetInstances = NULL;
2385 pThisCC->pMediaNotify = NULL;
2386
2387 for (unsigned uVirtqNbr = 0; uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT; uVirtqNbr++)
2388 {
2389 PVIRTIOSCSIWORKER pWorker = &pThis->aWorkers[uVirtqNbr];
2390 if (pWorker->hEvtProcess != NIL_SUPSEMEVENT)
2391 {
2392 PDMDevHlpSUPSemEventClose(pDevIns, pWorker->hEvtProcess);
2393 pWorker->hEvtProcess = NIL_SUPSEMEVENT;
2394 }
2395
2396 if (pThisCC->aWorkers[uVirtqNbr].pThread)
2397 {
2398 /* Destroy the thread. */
2399 int rcThread;
2400 int rc = PDMDevHlpThreadDestroy(pDevIns, pThisCC->aWorkers[uVirtqNbr].pThread, &rcThread);
2401 if (RT_FAILURE(rc) || RT_FAILURE(rcThread))
2402 AssertMsgFailed(("%s Failed to destroythread rc=%Rrc rcThread=%Rrc\n",
2403 __FUNCTION__, rc, rcThread));
2404 pThisCC->aWorkers[uVirtqNbr].pThread = NULL;
2405 }
2406 }
2407
2408 virtioCoreR3Term(pDevIns, &pThis->Virtio, &pThisCC->Virtio);
2409 return VINF_SUCCESS;
2410}
2411
2412/**
2413 * @interface_method_impl{PDMDEVREGR3,pfnConstruct}
2414 */
2415static DECLCALLBACK(int) virtioScsiR3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
2416{
2417 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
2418 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2419 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2420 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
2421
2422 /*
2423 * Quick initialization of the state data, making sure that the destructor always works.
2424 */
2425 pThisCC->pDevIns = pDevIns;
2426
2427 LogFunc(("PDM device instance: %d\n", iInstance));
2428 RTStrPrintf(pThis->szInstance, sizeof(pThis->szInstance), "VIRTIOSCSI%d", iInstance);
2429
2430 pThisCC->IBase.pfnQueryInterface = virtioScsiR3DeviceQueryInterface;
2431 pThisCC->ILeds.pfnQueryStatusLed = virtioScsiR3DeviceQueryStatusLed;
2432
2433 /*
2434 * Validate and read configuration.
2435 */
2436 PDMDEV_VALIDATE_CONFIG_RETURN(pDevIns, "NumTargets|Bootable", "");
2437
2438 int rc = pHlp->pfnCFGMQueryU32Def(pCfg, "NumTargets", &pThis->cTargets, 1);
2439 if (RT_FAILURE(rc))
2440 return PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio-scsi configuration error: failed to read NumTargets as integer"));
2441 if (pThis->cTargets < 1 || pThis->cTargets > VIRTIOSCSI_MAX_TARGETS)
2442 return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
2443 N_("virtio-scsi configuration error: NumTargets=%u is out of range (1..%u)"),
2444 pThis->cTargets, VIRTIOSCSI_MAX_TARGETS);
2445
2446 rc = pHlp->pfnCFGMQueryBoolDef(pCfg, "Bootable", &pThis->fBootable, true);
2447 if (RT_FAILURE(rc))
2448 return PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio-scsi configuration error: failed to read Bootable as boolean"));
2449
2450 LogRel(("%s: Targets=%u Bootable=%RTbool (unimplemented) R0Enabled=%RTbool RCEnabled=%RTbool\n",
2451 pThis->szInstance, pThis->cTargets, pThis->fBootable, pDevIns->fR0Enabled, pDevIns->fRCEnabled));
2452
2453
2454 /*
2455 * Do core virtio initialization.
2456 */
2457
2458 /* Configure virtio_scsi_config that transacts via VirtIO implementation's Dev. Specific Cap callbacks */
2459 pThis->virtioScsiConfig.uNumVirtqs = VIRTIOSCSI_REQ_VIRTQ_CNT;
2460 pThis->virtioScsiConfig.uSegMax = VIRTIOSCSI_MAX_SEG_COUNT;
2461 pThis->virtioScsiConfig.uMaxSectors = VIRTIOSCSI_MAX_SECTORS_HINT;
2462 pThis->virtioScsiConfig.uCmdPerLun = VIRTIOSCSI_MAX_COMMANDS_PER_LUN;
2463 pThis->virtioScsiConfig.uEventInfoSize = sizeof(VIRTIOSCSI_EVENT_T); /*VirtIO 1.0 Spec says at least this size! */
2464 pThis->virtioScsiConfig.uSenseSize = VIRTIOSCSI_SENSE_SIZE_DEFAULT;
2465 pThis->virtioScsiConfig.uCdbSize = VIRTIOSCSI_CDB_SIZE_DEFAULT;
2466 pThis->virtioScsiConfig.uMaxChannel = VIRTIOSCSI_MAX_CHANNEL_HINT;
2467 pThis->virtioScsiConfig.uMaxTarget = pThis->cTargets;
2468 pThis->virtioScsiConfig.uMaxLun = VIRTIOSCSI_MAX_LUN;
2469
2470 /* Initialize the generic Virtio core: */
2471 pThisCC->Virtio.pfnVirtqNotified = virtioScsiNotified;
2472 pThisCC->Virtio.pfnStatusChanged = virtioScsiR3StatusChanged;
2473 pThisCC->Virtio.pfnDevCapRead = virtioScsiR3DevCapRead;
2474 pThisCC->Virtio.pfnDevCapWrite = virtioScsiR3DevCapWrite;
2475
2476 VIRTIOPCIPARAMS VirtioPciParams;
2477 VirtioPciParams.uDeviceId = PCI_DEVICE_ID_VIRTIOSCSI_HOST;
2478 VirtioPciParams.uClassBase = PCI_CLASS_BASE_MASS_STORAGE;
2479 VirtioPciParams.uClassSub = PCI_CLASS_SUB_SCSI_STORAGE_CONTROLLER;
2480 VirtioPciParams.uClassProg = PCI_CLASS_PROG_UNSPECIFIED;
2481 VirtioPciParams.uSubsystemId = PCI_DEVICE_ID_VIRTIOSCSI_HOST; /* VirtIO 1.0 spec allows PCI Device ID here */
2482 VirtioPciParams.uInterruptLine = 0x00;
2483 VirtioPciParams.uInterruptPin = 0x01;
2484
2485 rc = virtioCoreR3Init(pDevIns, &pThis->Virtio, &pThisCC->Virtio, &VirtioPciParams, pThis->szInstance,
2486 VIRTIOSCSI_HOST_SCSI_FEATURES_OFFERED, 0 /*fOfferLegacy*/,
2487 &pThis->virtioScsiConfig /*pvDevSpecificCap*/, sizeof(pThis->virtioScsiConfig));
2488 if (RT_FAILURE(rc))
2489 return PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio-scsi: failed to initialize VirtIO"));
2490
2491 /*
2492 * Initialize queues.
2493 */
2494
2495 virtioScsiSetVirtqNames(pThis);
2496
2497 /* Attach the queues and create worker threads for them: */
2498 for (uint16_t uVirtqNbr = 0; uVirtqNbr < VIRTIOSCSI_VIRTQ_CNT; uVirtqNbr++)
2499 {
2500 rc = virtioCoreR3VirtqAttach(&pThis->Virtio, uVirtqNbr, VIRTQNAME(uVirtqNbr));
2501 if (RT_FAILURE(rc))
2502 continue;
2503 if (uVirtqNbr == CONTROLQ_IDX || IS_REQ_VIRTQ(uVirtqNbr))
2504 {
2505 rc = PDMDevHlpThreadCreate(pDevIns, &pThisCC->aWorkers[uVirtqNbr].pThread,
2506 (void *)(uintptr_t)uVirtqNbr, virtioScsiR3WorkerThread,
2507 virtioScsiR3WorkerWakeUp, 0, RTTHREADTYPE_IO, VIRTQNAME(uVirtqNbr));
2508 if (rc != VINF_SUCCESS)
2509 {
2510 LogRel(("Error creating thread for Virtual Virtq %s: %Rrc\n", VIRTQNAME(uVirtqNbr), rc));
2511 return rc;
2512 }
2513
2514 rc = PDMDevHlpSUPSemEventCreate(pDevIns, &pThis->aWorkers[uVirtqNbr].hEvtProcess);
2515 if (RT_FAILURE(rc))
2516 return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
2517 N_("DevVirtioSCSI: Failed to create SUP event semaphore"));
2518 }
2519 pThis->afVirtqAttached[uVirtqNbr] = true;
2520 }
2521
2522 /*
2523 * Initialize per device instances (targets).
2524 */
2525 Log2Func(("Probing %d targets ...\n", pThis->cTargets));
2526
2527 pThisCC->paTargetInstances = (PVIRTIOSCSITARGET)RTMemAllocZ(sizeof(VIRTIOSCSITARGET) * pThis->cTargets);
2528 if (!pThisCC->paTargetInstances)
2529 return PDMDEV_SET_ERROR(pDevIns, rc, N_("Failed to allocate memory for target states"));
2530
2531 for (uint32_t uTarget = 0; uTarget < pThis->cTargets; uTarget++)
2532 {
2533 PVIRTIOSCSITARGET pTarget = &pThisCC->paTargetInstances[uTarget];
2534
2535 if (RTStrAPrintf(&pTarget->pszTargetName, "VSCSI%u", uTarget) < 0)
2536 AssertLogRelFailedReturn(VERR_NO_MEMORY);
2537
2538 /* Initialize static parts of the device. */
2539 pTarget->pDevIns = pDevIns;
2540 pTarget->uTarget = uTarget;
2541
2542 pTarget->IBase.pfnQueryInterface = virtioScsiR3TargetQueryInterface;
2543
2544 /* IMediaPort and IMediaExPort interfaces provide callbacks for VD media and downstream driver access */
2545 pTarget->IMediaPort.pfnQueryDeviceLocation = virtioScsiR3QueryDeviceLocation;
2546 pTarget->IMediaPort.pfnQueryScsiInqStrings = NULL;
2547 pTarget->IMediaExPort.pfnIoReqCompleteNotify = virtioScsiR3IoReqFinish;
2548 pTarget->IMediaExPort.pfnIoReqCopyFromBuf = virtioScsiR3IoReqCopyFromBuf;
2549 pTarget->IMediaExPort.pfnIoReqCopyToBuf = virtioScsiR3IoReqCopyToBuf;
2550 pTarget->IMediaExPort.pfnIoReqStateChanged = virtioScsiR3IoReqStateChanged;
2551 pTarget->IMediaExPort.pfnMediumEjected = virtioScsiR3MediumEjected;
2552 pTarget->IMediaExPort.pfnIoReqQueryBuf = NULL; /* When used avoids copyFromBuf CopyToBuf*/
2553 pTarget->IMediaExPort.pfnIoReqQueryDiscardRanges = NULL;
2554
2555 pTarget->IBase.pfnQueryInterface = virtioScsiR3TargetQueryInterface;
2556 pTarget->ILed.pfnQueryStatusLed = virtioScsiR3TargetQueryStatusLed;
2557 pTarget->led.u32Magic = PDMLED_MAGIC;
2558
2559 LogFunc(("Attaching LUN: %s\n", pTarget->pszTargetName));
2560
2561 AssertReturn(uTarget < pThis->cTargets, VERR_PDM_NO_SUCH_LUN);
2562 rc = PDMDevHlpDriverAttach(pDevIns, uTarget, &pTarget->IBase, &pTarget->pDrvBase, pTarget->pszTargetName);
2563 if (RT_SUCCESS(rc))
2564 {
2565 pTarget->fPresent = true;
2566
2567 pTarget->pDrvMedia = PDMIBASE_QUERY_INTERFACE(pTarget->pDrvBase, PDMIMEDIA);
2568 AssertMsgReturn(RT_VALID_PTR(pTarget->pDrvMedia),
2569 ("virtio-scsi configuration error: LUN#%d missing basic media interface!\n", uTarget),
2570 VERR_PDM_MISSING_INTERFACE);
2571 /* Get the extended media interface. */
2572 pTarget->pDrvMediaEx = PDMIBASE_QUERY_INTERFACE(pTarget->pDrvBase, PDMIMEDIAEX);
2573 AssertMsgReturn(RT_VALID_PTR(pTarget->pDrvMediaEx),
2574 ("virtio-scsi configuration error: LUN#%d missing extended media interface!\n", uTarget),
2575 VERR_PDM_MISSING_INTERFACE);
2576
2577 rc = pTarget->pDrvMediaEx->pfnIoReqAllocSizeSet(pTarget->pDrvMediaEx, sizeof(VIRTIOSCSIREQ));
2578 AssertMsgReturn(RT_VALID_PTR(pTarget->pDrvMediaEx),
2579 ("virtio-scsi configuration error: LUN#%u: Failed to set I/O request size!\n", uTarget),
2580 rc);
2581 }
2582 else if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
2583 {
2584 pTarget->fPresent = false;
2585 pTarget->pDrvBase = NULL;
2586 Log(("virtio-scsi: no driver attached to device %s\n", pTarget->pszTargetName));
2587 rc = VINF_SUCCESS;
2588 }
2589 else
2590 {
2591 AssertLogRelMsgFailed(("virtio-scsi: Failed to attach %s: %Rrc\n", pTarget->pszTargetName, rc));
2592 return rc;
2593 }
2594 }
2595
2596 /*
2597 * Status driver (optional).
2598 */
2599 PPDMIBASE pUpBase = NULL;
2600 AssertCompile(PDM_STATUS_LUN >= VIRTIOSCSI_MAX_TARGETS);
2601 rc = PDMDevHlpDriverAttach(pDevIns, PDM_STATUS_LUN, &pThisCC->IBase, &pUpBase, "Status Port");
2602 if (RT_FAILURE(rc) && rc != VERR_PDM_NO_ATTACHED_DRIVER)
2603 return PDMDEV_SET_ERROR(pDevIns, rc, N_("Failed to attach the status LUN"));
2604 if (RT_SUCCESS(rc) && pUpBase)
2605 pThisCC->pMediaNotify = PDMIBASE_QUERY_INTERFACE(pUpBase, PDMIMEDIANOTIFY);
2606
2607
2608 /*
2609 * Register saved state.
2610 */
2611 rc = PDMDevHlpSSMRegister(pDevIns, VIRTIOSCSI_SAVED_STATE_VERSION, sizeof(*pThis),
2612 virtioScsiR3SaveExec, virtioScsiR3LoadExec);
2613 AssertRCReturn(rc, rc);
2614
2615 /*
2616 * Register the debugger info callback (ignore errors).
2617 */
2618 char szTmp[128];
2619 RTStrPrintf(szTmp, sizeof(szTmp), "%s%u", pDevIns->pReg->szName, pDevIns->iInstance);
2620 PDMDevHlpDBGFInfoRegister(pDevIns, szTmp, "virtio-scsi info", virtioScsiR3Info);
2621
2622 return rc;
2623}
2624
2625#else /* !IN_RING3 */
2626
2627/**
2628 * @callback_method_impl{PDMDEVREGR0,pfnConstruct}
2629 */
2630static DECLCALLBACK(int) virtioScsiRZConstruct(PPDMDEVINS pDevIns)
2631{
2632 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
2633
2634 PVIRTIOSCSI pThis = PDMDEVINS_2_DATA(pDevIns, PVIRTIOSCSI);
2635 PVIRTIOSCSICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVIRTIOSCSICC);
2636
2637
2638 pThisCC->Virtio.pfnVirtqNotified = virtioScsiNotified;
2639 return virtioCoreRZInit(pDevIns, &pThis->Virtio);
2640}
2641
2642#endif /* !IN_RING3 */
2643
2644
2645/**
2646 * The device registration structure.
2647 */
2648const PDMDEVREG g_DeviceVirtioSCSI =
2649{
2650 /* .u32Version = */ PDM_DEVREG_VERSION,
2651 /* .uReserved0 = */ 0,
2652 /* .szName = */ "virtio-scsi",
2653 /* .fFlags = */ PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_RZ | PDM_DEVREG_FLAGS_NEW_STYLE
2654 | PDM_DEVREG_FLAGS_FIRST_SUSPEND_NOTIFICATION
2655 | PDM_DEVREG_FLAGS_FIRST_POWEROFF_NOTIFICATION,
2656 /* .fClass = */ PDM_DEVREG_CLASS_STORAGE,
2657 /* .cMaxInstances = */ ~0U,
2658 /* .uSharedVersion = */ 42,
2659 /* .cbInstanceShared = */ sizeof(VIRTIOSCSI),
2660 /* .cbInstanceCC = */ sizeof(VIRTIOSCSICC),
2661 /* .cbInstanceRC = */ sizeof(VIRTIOSCSIRC),
2662 /* .cMaxPciDevices = */ 1,
2663 /* .cMaxMsixVectors = */ VBOX_MSIX_MAX_ENTRIES,
2664 /* .pszDescription = */ "Virtio Host SCSI.\n",
2665#if defined(IN_RING3)
2666 /* .pszRCMod = */ "VBoxDDRC.rc",
2667 /* .pszR0Mod = */ "VBoxDDR0.r0",
2668 /* .pfnConstruct = */ virtioScsiR3Construct,
2669 /* .pfnDestruct = */ virtioScsiR3Destruct,
2670 /* .pfnRelocate = */ NULL,
2671 /* .pfnMemSetup = */ NULL,
2672 /* .pfnPowerOn = */ NULL,
2673 /* .pfnReset = */ virtioScsiR3Reset,
2674 /* .pfnSuspend = */ virtioScsiR3Suspend,
2675 /* .pfnResume = */ virtioScsiR3Resume,
2676 /* .pfnAttach = */ virtioScsiR3Attach,
2677 /* .pfnDetach = */ virtioScsiR3Detach,
2678 /* .pfnQueryInterface = */ NULL,
2679 /* .pfnInitComplete = */ NULL,
2680 /* .pfnPowerOff = */ virtioScsiR3PowerOff,
2681 /* .pfnSoftReset = */ NULL,
2682 /* .pfnReserved0 = */ NULL,
2683 /* .pfnReserved1 = */ NULL,
2684 /* .pfnReserved2 = */ NULL,
2685 /* .pfnReserved3 = */ NULL,
2686 /* .pfnReserved4 = */ NULL,
2687 /* .pfnReserved5 = */ NULL,
2688 /* .pfnReserved6 = */ NULL,
2689 /* .pfnReserved7 = */ NULL,
2690#elif defined(IN_RING0)
2691 /* .pfnEarlyConstruct = */ NULL,
2692 /* .pfnConstruct = */ virtioScsiRZConstruct,
2693 /* .pfnDestruct = */ NULL,
2694 /* .pfnFinalDestruct = */ NULL,
2695 /* .pfnRequest = */ NULL,
2696 /* .pfnReserved0 = */ NULL,
2697 /* .pfnReserved1 = */ NULL,
2698 /* .pfnReserved2 = */ NULL,
2699 /* .pfnReserved3 = */ NULL,
2700 /* .pfnReserved4 = */ NULL,
2701 /* .pfnReserved5 = */ NULL,
2702 /* .pfnReserved6 = */ NULL,
2703 /* .pfnReserved7 = */ NULL,
2704#elif defined(IN_RC)
2705 /* .pfnConstruct = */ virtioScsiRZConstruct,
2706 /* .pfnReserved0 = */ NULL,
2707 /* .pfnReserved1 = */ NULL,
2708 /* .pfnReserved2 = */ NULL,
2709 /* .pfnReserved3 = */ NULL,
2710 /* .pfnReserved4 = */ NULL,
2711 /* .pfnReserved5 = */ NULL,
2712 /* .pfnReserved6 = */ NULL,
2713 /* .pfnReserved7 = */ NULL,
2714#else
2715# error "Not in IN_RING3, IN_RING0 or IN_RC!"
2716#endif
2717 /* .u32VersionEnd = */ PDM_DEVREG_VERSION
2718};
2719
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