VirtualBox

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

Last change on this file since 97441 was 97402, checked in by vboxsync, 2 years ago

Devices/DevVirtioSCSI: Fix reference counting issue where a reference would've been released twice in the I/O request finish handler when the underlying driver reported a CHECK CONDITION error for the request causing the VM to hang when powering off, ticketref:21144 [build fix]

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