VirtualBox

source: vbox/trunk/src/VBox/Devices/VirtIO/VirtioCore.h@ 109188

Last change on this file since 109188 was 109188, checked in by vboxsync, 3 days ago

VirtioNet: Temporary code from 7.0 branch for debugging descriptor loop issue ​bugref:10572

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 73.0 KB
Line 
1/* $Id: VirtioCore.h 109188 2025-05-07 07:42:49Z vboxsync $ */
2
3/** @file
4 * VirtioCore.h - Virtio Declarations
5 */
6
7/*
8 * Copyright (C) 2009-2024 Oracle and/or its affiliates.
9 *
10 * This file is part of VirtualBox base platform packages, as
11 * available from https://www.virtualbox.org.
12 *
13 * This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License
15 * as published by the Free Software Foundation, in version 3 of the
16 * License.
17 *
18 * This program is distributed in the hope that it will be useful, but
19 * WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, see <https://www.gnu.org/licenses>.
25 *
26 * SPDX-License-Identifier: GPL-3.0-only
27 */
28
29#ifndef VBOX_INCLUDED_SRC_VirtIO_VirtioCore_h
30#define VBOX_INCLUDED_SRC_VirtIO_VirtioCore_h
31#ifndef RT_WITHOUT_PRAGMA_ONCE
32# pragma once
33#endif
34
35#include <iprt/ctype.h>
36#include <iprt/sg.h>
37#include <iprt/types.h>
38
39/*
40 * WARNING! NEVER ENABLE IN PRODUCTION BUILDS!
41 * Enables temporary printouts to release log in descriptor chain handling code.
42 */
43//#define VIRTIO_REL_INFO_DUMP 1
44
45#ifdef LOG_ENABLED
46# define VIRTIO_HEX_DUMP(logLevel, pv, cb, base, title) \
47 do { \
48 if (LogIsItEnabled(logLevel, LOG_GROUP)) \
49 virtioCoreHexDump((pv), (cb), (base), (title)); \
50 } while (0)
51#else
52# define VIRTIO_HEX_DUMP(logLevel, pv, cb, base, title) do { } while (0)
53#endif
54
55/** Marks the start of the virtio saved state (just for sanity). */
56#define VIRTIO_SAVEDSTATE_MARKER UINT64_C(0x1133557799bbddff)
57
58/** Pointer to the shared VirtIO state. */
59typedef struct VIRTIOCORE *PVIRTIOCORE;
60/** Pointer to the ring-3 VirtIO state. */
61typedef struct VIRTIOCORER3 *PVIRTIOCORER3;
62/** Pointer to the ring-0 VirtIO state. */
63typedef struct VIRTIOCORER0 *PVIRTIOCORER0;
64/** Pointer to the raw-mode VirtIO state. */
65typedef struct VIRTIOCORERC *PVIRTIOCORERC;
66/** Pointer to the instance data for the current context. */
67typedef CTX_SUFF(PVIRTIOCORE) PVIRTIOCORECC;
68
69#define VIRTIO_MAX_VIRTQ_NAME_SIZE 32 /**< Maximum length of a queue name */
70#define VIRTQ_SIZE 1024 /**< Max size (# entries) of a virtq */
71#define VIRTQ_MAX_COUNT 24 /**< Max queues we allow guest to create */
72#define VIRTIO_NOTIFY_OFFSET_MULTIPLIER 2 /**< VirtIO Notify Cap. MMIO config param */
73#define VIRTIO_REGION_LEGACY_IO 0 /**< BAR for VirtIO legacy drivers MBZ */
74#define VIRTIO_REGION_PCI_CAP 2 /**< BAR for VirtIO Cap. MMIO (impl specific) */
75#define VIRTIO_REGION_MSIX_CAP 0 /**< Bar for MSI-X handling */
76#define VIRTIO_PAGE_SIZE 4096 /**< Page size used by VirtIO specification */
77
78/** Virtio-over-MMIO transport region size, excluding the device specific configuration area. */
79#define VIRTIO_MMIO_SIZE 256
80/** Register containing a magic value identifying a VirtIO over MMIO device - readonly. */
81#define VIRTIO_MMIO_REG_MAGIC_OFF 0
82/** Magic value read from the register. */
83# define VIRTIO_MMIO_REG_MAGIC_VALUE UINT32_C(0x74726976)
84/** Register containing th version of the MMIO transport - readonly. */
85#define VIRTIO_MMIO_REG_VERSION_OFF 4
86/** Version value read from the register. */
87# define VIRTIO_MMIO_REG_VERSION_VALUE UINT32_C(0x2)
88/** Register containing the device ID of the device - readonly. */
89#define VIRTIO_MMIO_REG_DEVICEID_OFF 8
90/** Register containing the vendor ID of the device - readonly. */
91#define VIRTIO_MMIO_REG_VENDORID_OFF 12
92/** Register containing the features the device supports - readonly. */
93#define VIRTIO_MMIO_REG_DEVICEFEAT_OFF 16
94/** Device features selection - writeonly. */
95#define VIRTIO_MMIO_REG_DEVICEFEATSEL_OFF 20
96/** Features of the device selected by the driver - writeonly. */
97#define VIRTIO_MMIO_REG_DRIVERFEAT_OFF 32
98/** - writeonly. */
99#define VIRTIO_MMIO_REG_DRIVERFEATSEL_OFF 36
100/** Virtual queue selection - writeonly. */
101#define VIRTIO_MMIO_REG_QUEUESEL_OFF 48
102/** - readonly */
103#define VIRTIO_MMIO_REG_QUEUENUMMAX_OFF 52
104/** - writeonly */
105#define VIRTIO_MMIO_REG_QUEUENUM_OFF 56
106/** - read/write. */
107#define VIRTIO_MMIO_REG_QUEUEALIGN_LEGACY_OFF 60
108/** - read/write. */
109#define VIRTIO_MMIO_REG_QUEUERDY_OFF 68
110/** - writeonly */
111#define VIRTIO_MMIO_REG_QUEUENOTIFY_OFF 80
112/** - readonly */
113#define VIRTIO_MMIO_REG_INTRSTATUS_OFF 96
114/** - writeonly */
115#define VIRTIO_MMIO_REG_INTRACK_OFF 100
116/** - read/write */
117#define VIRTIO_MMIO_REG_DEVSTATUS_OFF 112
118/** - writeonly */
119#define VIRTIO_MMIO_REG_QUEUEDESCLOW_OFF 128
120/** - writeonly */
121#define VIRTIO_MMIO_REG_QUEUEDESCHIGH_OFF 132
122/** - writeonly */
123#define VIRTIO_MMIO_REG_QUEUEDRVLOW_OFF 144
124/** - writeonly */
125#define VIRTIO_MMIO_REG_QUEUEDRVHIGH_OFF 148
126/** - writeonly */
127#define VIRTIO_MMIO_REG_QUEUEDEVLOW_OFF 160
128/** - writeonly */
129#define VIRTIO_MMIO_REG_QUEUEDEVHIGH_OFF 164
130/** - readonly */
131#define VIRTIO_MMIO_REG_CFGGEN_OFF 252
132
133
134/**
135 * @todo Move the following virtioCoreGCPhysChain*() functions mimic the functionality of the related
136 * into some VirtualBox source tree common location and out of this code.
137 *
138 * They behave identically to the S/G utilities in the RT library, except they work with that
139 * GCPhys data type specifically instead of void *, to avoid potentially disastrous mismatch
140 * between sizeof(void *) and sizeof(GCPhys).
141 *
142 */
143typedef struct VIRTIOSGSEG /**< An S/G entry */
144{
145 RTGCPHYS GCPhys; /**< Pointer to the segment buffer */
146 size_t cbSeg; /**< Size of the segment buffer */
147} VIRTIOSGSEG;
148
149typedef VIRTIOSGSEG *PVIRTIOSGSEG, **PPVIRTIOSGSEG;
150typedef const VIRTIOSGSEG *PCVIRTIOSGSEG;
151
152typedef struct VIRTIOSGBUF
153{
154 PVIRTIOSGSEG paSegs; /**< Pointer to the scatter/gather array */
155 unsigned cSegs; /**< Number of segs in scatter/gather array */
156 unsigned idxSeg; /**< Current segment we are in */
157 RTGCPHYS GCPhysCur; /**< Ptr to byte within the current seg */
158 size_t cbSegLeft; /**< # of bytes left in the current segment */
159} VIRTIOSGBUF;
160
161typedef VIRTIOSGBUF *PVIRTIOSGBUF, **PPVIRTIOSGBUF;
162typedef const VIRTIOSGBUF *PCVIRTIOSGBUF;
163
164/**
165 * VirtIO buffers are descriptor chains (e.g. scatter-gather vectors). A VirtIO buffer is referred to by the index
166 * of its head descriptor. Each descriptor optionally chains to another descriptor, and so on.
167 *
168 * For any given descriptor, each length and GCPhys pair in the chain represents either an OUT segment (e.g. guest-to-host)
169 * or an IN segment (host-to-guest).
170 *
171 * A VIRTQBUF is created and retured from a call to to either virtioCoreR3VirtqAvailBufPeek() or virtioCoreR3VirtqAvailBufGet().
172 *
173 * Those functions consolidate the VirtIO descriptor chain into a single representation where:
174 *
175 * pSgPhysSend GCPhys s/g buffer containing all of the (VirtIO) OUT descriptors
176 * pSgPhysReturn GCPhys s/g buffer containing all of the (VirtIO) IN descriptors
177 *
178 * The OUT descriptors are data sent from guest to host (dev-specific commands and/or data)
179 * The IN are to be filled with data (converted to physical) on host, to be returned to guest
180 *
181 */
182typedef struct VIRTQBUF
183{
184 uint32_t u32Magic; /**< Magic value, VIRTQBUF_MAGIC. */
185 uint16_t uVirtq; /**< VirtIO index of associated virtq */
186 uint16_t pad;
187 uint32_t volatile cRefs; /**< Reference counter. */
188 uint32_t uHeadIdx; /**< Head idx of associated desc chain */
189 size_t cbPhysSend; /**< Total size of src buffer */
190 PVIRTIOSGBUF pSgPhysSend; /**< Phys S/G buf for data from guest */
191 size_t cbPhysReturn; /**< Total size of dst buffer */
192 PVIRTIOSGBUF pSgPhysReturn; /**< Phys S/G buf to store result for guest */
193
194 /** @name Internal (bird combined 5 allocations into a single), fingers off.
195 * @{ */
196 VIRTIOSGBUF SgBufIn;
197 VIRTIOSGBUF SgBufOut;
198 VIRTIOSGSEG aSegsIn[VIRTQ_SIZE];
199 VIRTIOSGSEG aSegsOut[VIRTQ_SIZE];
200 /** @} */
201} VIRTQBUF_T;
202
203/** Pointers to a Virtio descriptor chain. */
204typedef VIRTQBUF_T *PVIRTQBUF, **PPVIRTQBUF;
205
206/** Magic value for VIRTQBUF_T::u32Magic. */
207#define VIRTQBUF_MAGIC UINT32_C(0x19600219)
208
209typedef struct VIRTIOPCIPARAMS
210{
211 uint16_t uDeviceId; /**< PCI Cfg Device ID */
212 uint16_t uClassBase; /**< PCI Cfg Base Class */
213 uint16_t uClassSub; /**< PCI Cfg Subclass */
214 uint16_t uClassProg; /**< PCI Cfg Programming Interface Class */
215 uint16_t uSubsystemId; /**< PCI Cfg Card Manufacturer Vendor ID */
216 uint16_t uInterruptLine; /**< PCI Cfg Interrupt line */
217 uint16_t uInterruptPin; /**< PCI Cfg Interrupt pin */
218 uint8_t uDeviceType; /**< Device type (used for Virtio-over-MMIO) */
219} VIRTIOPCIPARAMS, *PVIRTIOPCIPARAMS;
220
221
222/* Virtio Platform Independent Reserved Feature Bits (see 1.1 specification section 6) */
223
224#define VIRTIO_F_NOTIFY_ON_EMPTY RT_BIT_64(24) /**< Legacy feature: Force intr if no AVAIL */
225#define VIRTIO_F_ANY_LAYOUT RT_BIT_64(27) /**< Doc bug: Goes under two names in spec */
226#define VIRTIO_F_RING_INDIRECT_DESC RT_BIT_64(28) /**< Doc bug: Goes under two names in spec */
227#define VIRTIO_F_INDIRECT_DESC RT_BIT_64(28) /**< Allow descs to point to list of descs */
228#define VIRTIO_F_RING_EVENT_IDX RT_BIT_64(29) /**< Doc bug: Goes under two names in spec */
229#define VIRTIO_F_EVENT_IDX RT_BIT_64(29) /**< Allow notification disable for n elems */
230#define VIRTIO_F_BAD_FEATURE RT_BIT_64(30) /**< QEMU kludge. UNUSED as of >= VirtIO 1.0 */
231#define VIRTIO_F_VERSION_1 RT_BIT_64(32) /**< Required feature bit for 1.0 devices */
232#define VIRTIO_F_ACCESS_PLATFORM RT_BIT_64(33) /**< Funky guest mem access (VirtIO 1.1 NYI) */
233#define VIRTIO_F_RING_PACKED RT_BIT_64(34) /**< Packed Queue Layout (VirtIO 1.1 NYI) */
234#define VIRTIO_F_IN_ORDER RT_BIT_64(35) /**< Honor guest buf order (VirtIO 1.1 NYI) */
235#define VIRTIO_F_ORDER_PLATFORM RT_BIT_64(36) /**< Host mem access honored (VirtIO 1.1 NYI) */
236#define VIRTIO_F_SR_IOV RT_BIT_64(37) /**< Dev Single Root I/O virt (VirtIO 1.1 NYI) */
237#define VIRTIO_F_NOTIFICAITON_DATA RT_BIT_64(38) /**< Driver passes extra data (VirtIO 1.1 NYI) */
238
239typedef struct VIRTIO_FEATURES_LIST
240{
241 uint64_t fFeatureBit;
242 const char *pcszDesc;
243} VIRTIO_FEATURES_LIST, *PVIRTIO_FEATURES_LIST;
244
245static const VIRTIO_FEATURES_LIST s_aCoreFeatures[] =
246{
247 { VIRTIO_F_VERSION_1, " VERSION_1 Guest driver supports VirtIO specification V1.0+ (e.g. \"modern\")\n" },
248 { VIRTIO_F_RING_EVENT_IDX, " RING_EVENT_IDX Enables use_event and avail_event fields described in 2.4.7, 2.4.8\n" },
249 { VIRTIO_F_RING_INDIRECT_DESC, " RING_INDIRECT_DESC Driver can use descriptors with VIRTQ_DESC_F_INDIRECT flag set\n" },
250};
251
252#define VIRTIO_DEV_INDEPENDENT_FEATURES_OFFERED ( 0 ) /**< TBD: Add VIRTIO_F_INDIRECT_DESC */
253#define VIRTIO_DEV_INDEPENDENT_LEGACY_FEATURES_OFFERED ( 0 ) /**< Only offered to legacy drivers */
254
255#define VIRTIO_ISR_VIRTQ_INTERRUPT RT_BIT_32(0) /**< Virtq interrupt bit of ISR register */
256#define VIRTIO_ISR_DEVICE_CONFIG RT_BIT_32(1) /**< Device configuration changed bit of ISR */
257#define DEVICE_PCI_NETWORK_SUBSYSTEM 1 /**< Network Card, per VirtIO legacy spec. */
258#define DEVICE_PCI_REVISION_ID_VIRTIO_TRANS 0 /**< VirtIO Transitional device revision (MBZ) */
259#define DEVICE_PCI_REVISION_ID_VIRTIO_V1 1 /**< VirtIO device revision (SHOULD be >= 1) */
260
261#define DEVICE_PCI_VENDOR_ID_VIRTIO 0x1AF4 /**< Guest driver locates dev via (mandatory) */
262
263/**
264 * Start of the PCI device id range for non-transitional devices.
265 *
266 * "Devices ... have the PCI Device ID calculated by adding 0x1040 to
267 * the Virtio Device ID, as indicated in section [Device Types]. ...
268 * Non-transitional devices SHOULD have a PCI Device ID in the range
269 * 0x1040 to 0x107f.
270 */
271#define DEVICE_PCI_DEVICE_ID_VIRTIO_BASE 0x1040
272
273/**
274 * @name Virtio Device types as outlined in chapter 5.
275 * @{ */
276#define VIRTIO_DEVICE_TYPE_INVALID 0
277#define VIRTIO_DEVICE_TYPE_NETWORK 1
278#define VIRTIO_DEVICE_TYPE_BLOCK 2
279#define VIRTIO_DEVICE_TYPE_CONSOLE 3
280#define VIRTIO_DEVICE_TYPE_ENTROPY_SOURCE 4
281#define VIRTIO_DEVICE_TYPE_MEMORY_BALLOONING_TRAD 5
282#define VIRTIO_DEVICE_TYPE_IOMEM 6
283#define VIRTIO_DEVICE_TYPE_RPMSG 7
284#define VIRTIO_DEVICE_TYPE_SCSI_HOST 8
285#define VIRTIO_DEVICE_TYPE_9P_TRANSPORT 9
286#define VIRTIO_DEVICE_TYPE_MAC80211_WLAN 10
287#define VIRTIO_DEVICE_TYPE_RPROC_SERIAL 11
288#define VIRTIO_DEVICE_TYPE_CAIF 12
289#define VIRTIO_DEVICE_TYPE_MEMORY_BALLOONING 13
290#define VIRTIO_DEVICE_TYPE_GPU 16
291#define VIRTIO_DEVICE_TYPE_TIMER 17
292#define VIRTIO_DEVICE_TYPE_INPUT 18
293#define VIRTIO_DEVICE_TYPE_SOCKET 19
294#define VIRTIO_DEVICE_TYPE_CRYPTO 20
295#define VIRTIO_DEVICE_TYPE_SIGNAL_DIST_MOD 21
296#define VIRTIO_DEVICE_TYPE_PSTORE 22
297#define VIRTIO_DEVICE_TYPE_IOMMU 23
298#define VIRTIO_DEVICE_TYPE_MEMORY 24
299/** @} */
300
301/** Reserved (*negotiated*) Feature Bits (e.g. device independent features, VirtIO 1.0 spec,section 6) */
302
303#define VIRTIO_MSI_NO_VECTOR 0xffff /**< Vector value to disable MSI for queue */
304
305/** Device Status field constants (from Virtio 1.0 spec) */
306#define VIRTIO_STATUS_ACKNOWLEDGE 0x01 /**< Guest driver: Located this VirtIO device */
307#define VIRTIO_STATUS_DRIVER 0x02 /**< Guest driver: Can drive this VirtIO dev. */
308#define VIRTIO_STATUS_DRIVER_OK 0x04 /**< Guest driver: Driver set-up and ready */
309#define VIRTIO_STATUS_FEATURES_OK 0x08 /**< Guest driver: Feature negotiation done */
310#define VIRTIO_STATUS_FAILED 0x80 /**< Guest driver: Fatal error, gave up */
311#define VIRTIO_STATUS_DEVICE_NEEDS_RESET 0x40 /**< Device experienced unrecoverable error */
312
313typedef enum VIRTIOVMSTATECHANGED
314{
315 kvirtIoVmStateChangedInvalid = 0,
316 kvirtIoVmStateChangedReset,
317 kvirtIoVmStateChangedSuspend,
318 kvirtIoVmStateChangedPowerOff,
319 kvirtIoVmStateChangedResume,
320 kvirtIoVmStateChangedFor32BitHack = 0x7fffffff
321} VIRTIOVMSTATECHANGED;
322
323/** @def Virtio Device PCI Capabilities type codes */
324#define VIRTIO_PCI_CAP_COMMON_CFG 1 /**< Common configuration PCI capability ID */
325#define VIRTIO_PCI_CAP_NOTIFY_CFG 2 /**< Notification area PCI capability ID */
326#define VIRTIO_PCI_CAP_ISR_CFG 3 /**< ISR PCI capability id */
327#define VIRTIO_PCI_CAP_DEVICE_CFG 4 /**< Device-specific PCI cfg capability ID */
328#define VIRTIO_PCI_CAP_PCI_CFG 5 /**< PCI CFG capability ID */
329
330#define VIRTIO_PCI_CAP_ID_VENDOR 0x09 /**< Vendor-specific PCI CFG Device Cap. ID */
331
332/**
333 * The following is the PCI capability struct common to all VirtIO capability types
334 */
335typedef struct virtio_pci_cap
336{
337 /* All little-endian */
338 uint8_t uCapVndr; /**< Generic PCI field: PCI_CAP_ID_VNDR */
339 uint8_t uCapNext; /**< Generic PCI field: next ptr. */
340 uint8_t uCapLen; /**< Generic PCI field: capability length */
341 uint8_t uCfgType; /**< Identifies the structure. */
342 uint8_t uBar; /**< Where to find it. */
343 uint8_t uPadding[3]; /**< Pad to full dword. */
344 uint32_t uOffset; /**< Offset within bar. (L.E.) */
345 uint32_t uLength; /**< Length of struct, in bytes. (L.E.) */
346} VIRTIO_PCI_CAP_T, *PVIRTIO_PCI_CAP_T;
347
348/**
349 * VirtIO Legacy Capabilities' related MMIO-mapped structs (see virtio-0.9.5 spec)
350 *
351 * Note: virtio_pci_device_cap is dev-specific, implemented by client. Definition unknown here.
352 */
353typedef struct virtio_legacy_pci_common_cfg
354{
355 /* Device-specific fields */
356 uint32_t uDeviceFeatures; /**< RO (device reports features to driver) */
357 uint32_t uDriverFeatures; /**< RW (driver-accepted device features) */
358 uint32_t uVirtqPfn; /**< RW (driver writes queue page number) */
359 uint16_t uQueueSize; /**< RW (queue size, 0 - 2^n) */
360 uint16_t uVirtqSelect; /**< RW (selects queue focus for these fields) */
361 uint16_t uQueueNotify; /**< RO (offset into virtqueue; see spec) */
362 uint8_t fDeviceStatus; /**< RW (driver writes device status, 0=reset) */
363 uint8_t fIsrStatus; /**< RW (driver writes ISR status, 0=reset) */
364#ifdef LEGACY_MSIX_SUPPORTED
365 uint16_t uMsixConfig; /**< RW (driver sets MSI-X config vector) */
366 uint16_t uMsixVector; /**< RW (driver sets MSI-X config vector) */
367#endif
368} VIRTIO_LEGACY_PCI_COMMON_CFG_T, *PVIRTIO_LEGACY_PCI_COMMON_CFG_T;
369
370/**
371 * VirtIO 1.0 Capabilities' related MMIO-mapped structs:
372 *
373 * Note: virtio_pci_device_cap is dev-specific, implemented by client. Definition unknown here.
374 */
375typedef struct virtio_pci_common_cfg
376{
377 /* Device-specific fields */
378 uint32_t uDeviceFeaturesSelect; /**< RW (driver selects device features) */
379 uint32_t uDeviceFeatures; /**< RO (device reports features to driver) */
380 uint32_t uDriverFeaturesSelect; /**< RW (driver selects driver features) */
381 uint32_t uDriverFeatures; /**< RW (driver-accepted device features) */
382 uint16_t uMsixConfig; /**< RW (driver sets MSI-X config vector) */
383 uint16_t uNumVirtqs; /**< RO (device specifies max queues) */
384 uint8_t fDeviceStatus; /**< RW (driver writes device status, 0=reset) */
385 uint8_t uConfigGeneration; /**< RO (device changes when changing configs) */
386
387 /* Virtq-specific fields (values reflect (via MMIO) info related to queue indicated by uVirtqSelect. */
388 uint16_t uVirtqSelect; /**< RW (selects queue focus for these fields) */
389 uint16_t uQueueSize; /**< RW (queue size, 0 - 2^n) */
390 uint16_t uMsixVector; /**< RW (driver selects MSI-X queue vector) */
391 uint16_t uEnable; /**< RW (driver controls usability of queue) */
392 uint16_t uNotifyOffset; /**< RO (offset into virtqueue; see spec) */
393 uint64_t GCPhysVirtqDesc; /**< RW (driver writes desc table phys addr) */
394 uint64_t GCPhysVirtqAvail; /**< RW (driver writes avail ring phys addr) */
395 uint64_t GCPhysVirtqUsed; /**< RW (driver writes used ring phys addr) */
396} VIRTIO_PCI_COMMON_CFG_T, *PVIRTIO_PCI_COMMON_CFG_T;
397
398typedef struct virtio_pci_notify_cap
399{
400 struct virtio_pci_cap pciCap; /**< Notification MMIO mapping capability */
401 uint32_t uNotifyOffMultiplier; /**< notify_off_multiplier */
402} VIRTIO_PCI_NOTIFY_CAP_T, *PVIRTIO_PCI_NOTIFY_CAP_T;
403
404typedef struct virtio_pci_cfg_cap
405{
406 struct virtio_pci_cap pciCap; /**< Cap. defines the BAR/off/len to access */
407 uint8_t uPciCfgData[4]; /**< I/O buf for above cap. */
408} VIRTIO_PCI_CFG_CAP_T, *PVIRTIO_PCI_CFG_CAP_T;
409
410/**
411 * PCI capability data locations (PCI CFG and MMIO).
412 */
413typedef struct VIRTIO_PCI_CAP_LOCATIONS_T
414{
415 uint16_t offMmio;
416 uint16_t cbMmio;
417 uint16_t offPci;
418 uint16_t cbPci;
419} VIRTIO_PCI_CAP_LOCATIONS_T;
420
421typedef struct VIRTQUEUE
422{
423 RTGCPHYS GCPhysVirtqDesc; /**< (MMIO) Addr of virtq's desc ring GUEST */
424 RTGCPHYS GCPhysVirtqAvail; /**< (MMIO) Addr of virtq's avail ring GUEST */
425 RTGCPHYS GCPhysVirtqUsed; /**< (MMIO) Addr of virtq's used ring GUEST */
426 uint16_t uMsixVector; /**< (MMIO) MSI-X vector GUEST */
427 uint16_t uEnable; /**< (MMIO) Queue enable flag GUEST */
428 uint16_t uNotifyOffset; /**< (MMIO) Notification offset for queue HOST */
429 uint16_t uQueueSize; /**< (MMIO) Size of queue HOST/GUEST */
430 uint16_t uAvailIdxShadow; /**< Consumer's position in avail ring */
431 uint16_t uUsedIdxShadow; /**< Consumer's position in used ring */
432 uint16_t uVirtq; /**< Index of this queue */
433 char szName[32]; /**< Dev-specific name of queue */
434 bool fUsedRingEvent; /**< Flags if used idx to notify guest reached */
435 bool fAttached; /**< Flags if dev-specific client attached */
436} VIRTQUEUE, *PVIRTQUEUE;
437
438/**
439 * The core/common state of the VirtIO PCI devices, shared edition.
440 */
441typedef struct VIRTIOCORE
442{
443 char szInstance[16]; /**< Instance name, e.g. "VIRTIOSCSI0" */
444 PPDMDEVINS pDevInsR0; /**< Client device instance */
445 PPDMDEVINS pDevInsR3; /**< Client device instance */
446 VIRTQUEUE aVirtqueues[VIRTQ_MAX_COUNT]; /**< (MMIO) VirtIO contexts for queues */
447 uint64_t uDeviceFeatures; /**< (MMIO) Host features offered HOST */
448 uint64_t uDriverFeatures; /**< (MMIO) Host features accepted GUEST */
449 uint32_t fDriverFeaturesWritten; /**< (MMIO) Host features complete tracking */
450 uint32_t uDeviceFeaturesSelect; /**< (MMIO) hi/lo select uDeviceFeatures GUEST */
451 uint32_t uDriverFeaturesSelect; /**< (MMIO) hi/lo select uDriverFeatures GUEST */
452 uint32_t uMsixConfig; /**< (MMIO) MSI-X vector GUEST */
453 uint8_t fDeviceStatus; /**< (MMIO) Device Status GUEST */
454 uint8_t fPrevDeviceStatus; /**< (MMIO) Prev Device Status GUEST */
455 uint8_t uConfigGeneration; /**< (MMIO) Device config sequencer HOST */
456 uint16_t uQueueNotify; /**< Caches queue idx in legacy mode GUEST */
457 bool fGenUpdatePending; /**< If set, update cfg gen after driver reads */
458 uint8_t uPciCfgDataOff; /**< Offset to PCI configuration data area */
459 uint8_t uISR; /**< Interrupt Status Register. */
460 uint8_t fMsiSupport; /**< Flag set if using MSI instead of ISR */
461 uint16_t uVirtqSelect; /**< (MMIO) queue selector GUEST */
462 uint32_t fLegacyDriver; /**< Set if guest drv < VirtIO 1.0 and allowed */
463 uint32_t fOfferLegacy; /**< Set at init call from dev-specific code */
464 uint16_t uIrqMmio; /**< The interrupt number when Virtio-over-MMIO is used */
465 uint8_t uDeviceType; /**< The implemented device type for Virtio-over-MMIO */
466#ifdef VIRTIO_REL_INFO_DUMP
467 bool fRecovering;
468 bool fTestRecovery;
469#define VIRTIO_CORE_TRACE_BUF_SIZE (256 /* header */ + 256 * 256 /* buffer*/)
470 RTTRACEBUF hTraceBuf;
471 uint8_t aTraceBuf[VIRTIO_CORE_TRACE_BUF_SIZE];
472#endif /* VIRTIO_REL_INFO_DUMP */
473
474 /** @name The locations of the capability structures in PCI config space and the BAR.
475 * @{ */
476 VIRTIO_PCI_CAP_LOCATIONS_T LocPciCfgCap; /**< VIRTIO_PCI_CFG_CAP_T */
477 VIRTIO_PCI_CAP_LOCATIONS_T LocNotifyCap; /**< VIRTIO_PCI_NOTIFY_CAP_T */
478 VIRTIO_PCI_CAP_LOCATIONS_T LocCommonCfgCap; /**< VIRTIO_PCI_CAP_T */
479 VIRTIO_PCI_CAP_LOCATIONS_T LocIsrCap; /**< VIRTIO_PCI_CAP_T */
480 VIRTIO_PCI_CAP_LOCATIONS_T LocDeviceCap; /**< VIRTIO_PCI_CAP_T + custom data. */
481 /** @} */
482
483 IOMMMIOHANDLE hMmioPciCap; /**< MMIO handle of PCI cap. region (\#2) */
484 IOMIOPORTHANDLE hLegacyIoPorts; /**< Handle of legacy I/O port range. */
485
486#ifdef VBOX_WITH_STATISTICS
487 /** @name Statistics
488 * @{ */
489 STAMCOUNTER StatDescChainsAllocated;
490 STAMCOUNTER StatDescChainsFreed;
491 STAMCOUNTER StatDescChainsSegsIn;
492 STAMCOUNTER StatDescChainsSegsOut;
493 STAMPROFILEADV StatReadR3; /** I/O port and MMIO R3 Read profiling */
494 STAMPROFILEADV StatReadR0; /** I/O port and MMIO R0 Read profiling */
495 STAMPROFILEADV StatReadRC; /** I/O port and MMIO R3 Read profiling */
496 STAMPROFILEADV StatWriteR3; /** I/O port and MMIO R3 Write profiling */
497 STAMPROFILEADV StatWriteR0; /** I/O port and MMIO R3 Write profiling */
498 STAMPROFILEADV StatWriteRC; /** I/O port and MMIO R3 Write profiling */
499#endif
500 /** @} */
501
502} VIRTIOCORE;
503
504#define MAX_NAME 64
505
506/**
507 * The core/common state of the VirtIO PCI devices, ring-3 edition.
508 */
509typedef struct VIRTIOCORER3
510{
511 /** @name Callbacks filled by the device before calling virtioCoreR3Init.
512 * @{ */
513 /**
514 * Implementation-specific client callback to report VirtIO when feature negotiation is
515 * complete. It should be invoked by the VirtIO core only once.
516 *
517 * @param pVirtio Pointer to the shared virtio state.
518 * @param fDriverFeatures Bitmask of features the guest driver has accepted/declined.
519 * @param fLegacy true if legacy mode offered and until guest driver identifies itself
520 * as modern(e.g. VirtIO 1.0 featured)
521 */
522 DECLCALLBACKMEMBER(void, pfnFeatureNegotiationComplete, (PVIRTIOCORE pVirtio, uint64_t fDriverFeatures, uint32_t fLegacy));
523
524 /**
525 * Implementation-specific client callback to notify client of significant device status
526 * changes.
527 *
528 * @param pVirtio Pointer to the shared virtio state.
529 * @param pVirtioCC Pointer to the ring-3 virtio state.
530 * @param fDriverOk True if guest driver is okay (thus queues, etc... are
531 * valid)
532 */
533 DECLCALLBACKMEMBER(void, pfnStatusChanged,(PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC, uint32_t fDriverOk));
534
535 /**
536 * Implementation-specific client callback to access VirtIO Device-specific capabilities
537 * (other VirtIO capabilities and features are handled in VirtIO implementation)
538 *
539 * @param pDevIns The device instance.
540 * @param offCap Offset within device specific capabilities struct.
541 * @param pvBuf Buffer in which to save read data.
542 * @param cbToRead Number of bytes to read.
543 */
544 DECLCALLBACKMEMBER(int, pfnDevCapRead,(PPDMDEVINS pDevIns, uint32_t offCap, void *pvBuf, uint32_t cbToRead));
545
546 /**
547 * Implementation-specific client callback to access VirtIO Device-specific capabilities
548 * (other VirtIO capabilities and features are handled in VirtIO implementation)
549 *
550 * @param pDevIns The device instance.
551 * @param offCap Offset within device specific capabilities struct.
552 * @param pvBuf Buffer with the bytes to write.
553 * @param cbToWrite Number of bytes to write.
554 */
555 DECLCALLBACKMEMBER(int, pfnDevCapWrite,(PPDMDEVINS pDevIns, uint32_t offCap, const void *pvBuf, uint32_t cbWrite));
556
557 /**
558 * When guest-to-host queue notifications are enabled, the guest driver notifies the host
559 * that the avail queue has buffers, and this callback informs the client.
560 *
561 * @param pVirtio Pointer to the shared virtio state.
562 * @param pVirtioCC Pointer to the ring-3 virtio state.
563 * @param uVirtqNbr Index of the notified queue
564 */
565 DECLCALLBACKMEMBER(void, pfnVirtqNotified,(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtqNbr));
566
567 /** @} */
568
569 R3PTRTYPE(PVIRTIO_PCI_CFG_CAP_T) pPciCfgCap; /**< Pointer to struct in PCI config area. */
570 R3PTRTYPE(PVIRTIO_PCI_NOTIFY_CAP_T) pNotifyCap; /**< Pointer to struct in PCI config area. */
571 R3PTRTYPE(PVIRTIO_PCI_CAP_T) pCommonCfgCap; /**< Pointer to struct in PCI config area. */
572 R3PTRTYPE(PVIRTIO_PCI_CAP_T) pIsrCap; /**< Pointer to struct in PCI config area. */
573 R3PTRTYPE(PVIRTIO_PCI_CAP_T) pDeviceCap; /**< Pointer to struct in PCI config area. */
574
575 uint32_t cbDevSpecificCfg; /**< Size of client's dev-specific config data */
576 R3PTRTYPE(uint8_t *) pbDevSpecificCfg; /**< Pointer to client's struct */
577 R3PTRTYPE(uint8_t *) pbPrevDevSpecificCfg; /**< Previous read dev-specific cfg of client */
578 bool fGenUpdatePending; /**< If set, update cfg gen after driver reads */
579 char szMmioName[MAX_NAME]; /**< MMIO mapping name */
580 char szPortIoName[MAX_NAME]; /**< PORT mapping name */
581} VIRTIOCORER3;
582
583/**
584 * The core/common state of the VirtIO PCI devices, ring-0 edition.
585 */
586typedef struct VIRTIOCORER0
587{
588 /**
589 * This callback notifies the device-specific portion of this device implementation (if guest-to-host
590 * queue notifications are enabled), that the guest driver has notified the host (this device)
591 * that the VirtIO "avail" ring of a queue has some new s/g buffers added by the guest VirtIO driver.
592 *
593 * @param pVirtio Pointer to the shared virtio state.
594 * @param pVirtioCC Pointer to the ring-3 virtio state.
595 * @param uVirtqNbr Index of the notified queue
596 */
597 DECLCALLBACKMEMBER(void, pfnVirtqNotified,(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtqNbr));
598
599} VIRTIOCORER0;
600
601/**
602 * The core/common state of the VirtIO PCI devices, raw-mode edition.
603 */
604typedef struct VIRTIOCORERC
605{
606 uint64_t uUnusedAtTheMoment;
607} VIRTIOCORERC;
608
609/** @typedef VIRTIOCORECC
610 * The instance data for the current context. */
611typedef CTX_SUFF(VIRTIOCORE) VIRTIOCORECC;
612
613/** @name API for VirtIO parent device
614 * @{ */
615
616/**
617 * Setup PCI device controller and Virtio state
618 *
619 * This should be called from PDMDEVREGR3::pfnConstruct.
620 *
621 * @param pDevIns Device instance.
622 * @param pVirtio Pointer to the shared virtio state. This
623 * must be the first member in the shared
624 * device instance data!
625 * @param pVirtioCC Pointer to the ring-3 virtio state. This
626 * must be the first member in the ring-3
627 * device instance data!
628 * @param pPciParams Values to populate industry standard PCI Configuration Space data structure
629 * @param pcszInstance Device instance name (format-specifier)
630 * @param fDevSpecificFeatures VirtIO device-specific features offered by
631 * client
632 * @param cbDevSpecificCfg Size of virtio_pci_device_cap device-specific struct
633 * @param pvDevSpecificCfg Address of client's dev-specific
634 * configuration struct.
635 */
636DECLHIDDEN(int) virtioCoreR3Init(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC,
637 PVIRTIOPCIPARAMS pPciParams, const char *pcszInstance,
638 uint64_t fDevSpecificFeatures, uint32_t fOfferLegacy, void *pvDevSpecificCfg, uint16_t cbDevSpecificCfg);
639/**
640 * Initiate orderly reset procedure. This is an exposed API for clients that might need it.
641 * Invoked by client to reset the device and driver (see VirtIO 1.0 section 2.1.1/2.1.2)
642 *
643 * @param pVirtio Pointer to the virtio state.
644 */
645DECLHIDDEN(void) virtioCoreResetAll(PVIRTIOCORE pVirtio);
646
647/**
648 * Resets the device state upon a VM reset for instance.
649 *
650 * @param pVirtio Pointer to the virtio state.
651 *
652 * @note Calls back into the upper device when the status changes.
653 */
654DECLHIDDEN(void) virtioCoreR3ResetDevice(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC);
655
656/**
657 * 'Attaches' host device-specific implementation's queue state to host VirtIO core
658 * virtqueue management infrastructure, informing the virtio core of the name of the
659 * queue to associate with the queue number.
660
661 * Note: uVirtqNbr (ordinal index) is used as the 'handle' for virtqs in this VirtioCore
662 * implementation's API (as an opaque selector into the VirtIO core's array of queues' states).
663 *
664 * Virtqueue numbers are actually VirtIO-specification defined device-specifically
665 * (i.e. they are unique within each VirtIO device type), but are in some cases scalable
666 * so only the pattern of queue numbers is defined by the spec and implementations may contain
667 * a self-determined plurality of queues.
668 *
669 * @param pVirtio Pointer to the shared virtio state.
670 * @param uVirtqNbr Virtq number
671 * @param pcszName Name to give queue
672 *
673 * @returns VBox status code.
674 */
675DECLHIDDEN(int) virtioCoreR3VirtqAttach(PVIRTIOCORE pVirtio, uint16_t uVirtqNbr, const char *pcszName);
676
677/**
678 * Detaches host device-specific implementation's queue state from the host VirtIO core
679 * virtqueue management infrastructure, informing the VirtIO core that the queue is
680 * not utilized by the device-specific code.
681 *
682 * @param pVirtio Pointer to the shared virtio state.
683 * @param uVirtqNbr Virtq number
684 * @param pcszName Name to give queue
685 *
686 * @returns VBox status code.
687 */
688DECLHIDDEN(int) virtioCoreR3VirtqDetach(PVIRTIOCORE pVirtio, uint16_t uVirtqNbr);
689
690/**
691 * Checks to see whether queue is attached to core.
692 *
693 * @param pVirtio Pointer to the shared virtio state.
694 * @param uVirtqNbr Virtq number
695 *
696 * Returns boolean true or false indicating whether dev-specific reflection
697 * of queue is attached to core.
698 */
699DECLHIDDEN(bool) virtioCoreR3VirtqIsAttached(PVIRTIOCORE pVirtio, uint16_t uVirtqNbr);
700
701/**
702 * Checks to see whether queue is enabled.
703 *
704 * @param pVirtio Pointer to the shared virtio state.
705 * @param uVirtqNbr Virtq number
706 *
707 * Returns boolean true or false indicating core queue enable state.
708 * There is no API function to enable the queue, because the actual enabling is handled
709 * by the guest via MMIO.
710 *
711 * NOTE: Guest VirtIO driver's claim over this state is overridden (which violates VirtIO 1.0 spec
712 * in a carefully controlled manner) in the case where the queue MUST be disabled, due to observed
713 * control queue corruption (e.g. null GCPhys virtq base addr) while restoring legacy-only device's
714 * (DevVirtioNet.cpp) as a way to flag that the queue is unusable-as-saved and must to be removed.
715 * That is all handled in the load/save exec logic. Device reset could potentially, depending on
716 * parameters passed from host VirtIO device to guest VirtIO driver, result in guest re-establishing
717 * queue, except, in that situation, the queue operational state would be valid.
718 */
719DECLHIDDEN(bool) virtioCoreR3VirtqIsEnabled(PVIRTIOCORE pVirtio, uint16_t uVirtqNbr);
720
721/**
722 * Enable or disable notification for the specified queue.
723 *
724 * When queue notifications are enabled, the guest VirtIO driver notifies host VirtIO device
725 * (via MMIO, see VirtIO 1.0, 4.1.4.4 "Notification Structure Layout") whenever guest driver adds
726 * a new s/g buffer to the "avail" ring of the queue.
727 *
728 * Note: VirtIO queue layout includes flags the device controls in "used" ring to inform guest
729 * driver if it should notify host of guest's buffer additions to the "avail" ring, and
730 * conversely, the guest driver sets flags in the "avail" ring to communicate to host device
731 * whether or not to interrupt guest when it adds buffers to used ring.
732 *
733 * @param pVirtio Pointer to the shared virtio state.
734 * @param uVirtqNbr Virtq number
735 * @param fEnable Selects notification mode (enabled or disabled)
736 */
737DECLHIDDEN(void) virtioCoreVirtqEnableNotify(PVIRTIOCORE pVirtio, uint16_t uVirtqNbr, bool fEnable);
738
739/**
740 * Notifies guest (via ISR or MSI-X) of device configuration change
741 *
742 * @param pVirtio Pointer to the shared virtio state.
743 */
744DECLHIDDEN(void) virtioCoreNotifyConfigChanged(PVIRTIOCORE pVirtio);
745
746/**
747 * Displays a well-formatted human-readable translation of otherwise inscrutable bitmasks
748 * that embody features VirtIO specification definitions, indicating: Totality of features
749 * that can be implemented by host and guest, which features were offered by the host, and
750 * which were actually accepted by the guest. It displays it as a summary view of the device's
751 * finalized operational state (host-guest negotiated architecture) in such a way that shows
752 * which options are available for implementing or enabling.
753 *
754 * The non-device-specific VirtIO features list are managed by core API (e.g. implied).
755 * Only dev-specific features must be passed as parameter.
756
757 * @param pVirtio Pointer to the shared virtio state.
758 * @param pHlp Pointer to the debug info hlp struct
759 * @param s_aDevSpecificFeatures Dev-specific features (virtio-net, virtio-scsi...)
760 * @param cFeatures Number of features in aDevSpecificFeatures
761 */
762DECLHIDDEN(void) virtioCorePrintDeviceFeatures(VIRTIOCORE *pVirtio, PCDBGFINFOHLP pHlp,
763 const VIRTIO_FEATURES_LIST *aDevSpecificFeatures, int cFeatures);
764
765/*
766 * Debug-assist utility function to display state of the VirtIO core code, including
767 * an overview of the state of all of the queues.
768 *
769 * This can be invoked when running the VirtualBox debugger, or from the command line
770 * using the command: "VboxManage debugvm <VM name or id> info <device name> [args]"
771 *
772 * Example: VBoxManage debugvm myVnetVm info "virtio-net" help
773 *
774 * This is implemented currently to be invoked by the inheriting device-specific code
775 * (see the the VirtualBox virtio-net (VirtIO network controller device implementation)
776 * for an example of code that receive debugvm callback directly).
777 *
778 * DevVirtioNet lists available sub-options if no arguments are provided. In that
779 * example this virtq info related function is invoked hierarchically when virtio-net
780 * displays its device-specific queue info.
781 *
782 * @param pDevIns The device instance.
783 * @param pHlp Pointer to the debug info hlp struct
784 * @param pVirtio Pointer to the virtio core embedded into the calling device
785 * @param pszArgs Arguments to function
786 */
787DECLHIDDEN(void) virtioCoreR3VirtqInfo(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, PVIRTIOCORE pVirtio, const char *pszArgs, int uVirtqNbr);
788
789/**
790 * Returns the number of avail bufs in the virtq.
791 *
792 * @param pDevIns The device instance.
793 * @param pVirtio Pointer to the shared virtio state.
794 * @param uVirtqNbr Virtqueue to return the count of buffers available for.
795 */
796DECLHIDDEN(uint16_t) virtioCoreVirtqAvailBufCount(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtqNbr);
797
798#ifdef VIRTIO_REL_INFO_DUMP
799/**
800 * Copies all available chains to used ring. Only indices of chains are copied, not the chains
801 * themselves. This can only be done for virtionet TX ring to work around the issue in NetKVM
802 * driver, which does not complete NBLs on device reset, if these NBLs are already in 'avail' ring.
803 *
804 * @param pDevIns The device instance.
805 * @param pVirtio Pointer to the shared virtio state.
806 * @param uVirtqNbr Virtqueue to modify.
807 */
808void virtioCorePutAllAvailBufsToUsedRing(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtqNbr);
809#endif /* VIRTIO_REL_INFO_DUMP */
810
811/**
812 * This function is identical to virtioCoreR3VirtqAvailBufGet(), *except* it doesn't consume
813 * peeked buffer from avail ring of the virtq. The function *becomes* identical to the
814 * virtioCoreR3VirtqAvailBufGet() only if virtioCoreR3VirtqAvailRingNext() is invoked to
815 * consume buf from the queue's avail ring, followed by invocation of virtioCoreR3VirtqUsedBufPut(),
816 * to hand host-processed buffer back to guest, which completes guest-initiated virtq buffer circuit.
817 *
818 * @param pDevIns The device instance.
819 * @param pVirtio Pointer to the shared virtio state.
820 * @param uVirtqNbr Virtq number
821 * @param pVirtqBuf Pointer to descriptor chain that contains the
822 * pre-processed transaction information pulled from the virtq.
823 *
824 * @returns VBox status code:
825 * @retval VINF_SUCCESS Success
826 * @retval VERR_INVALID_STATE VirtIO not in ready state (asserted).
827 * @retval VERR_NOT_AVAILABLE If the queue is empty.
828 */
829DECLHIDDEN(int) virtioCoreR3VirtqAvailBufPeek(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtqNbr,
830 PVIRTQBUF pVirtqBuf);
831
832/**
833 * This function fetches the next buffer (descriptor chain) from the VirtIO "avail" ring of
834 * indicated queue, separating the buf's s/g vectors into OUT (e.g. guest-to-host)
835 * components and and IN (host-to-guest) components.
836 *
837 * Caller is responsible for GCPhys to host virtual memory conversions. If the
838 * virtq buffer being peeked at is "consumed", virtioCoreR3VirtqAvailRingNext() must
839 * be called, and after that virtioCoreR3VirtqUsedBufPut() must be called to
840 * complete the buffer transfer cycle with the guest.
841 *
842 * @param pDevIns The device instance.
843 * @param pVirtio Pointer to the shared virtio state.
844 * @param uVirtqNbr Virtq number
845 * @param pVirtqBuf Pointer to descriptor chain that contains the
846 * pre-processed transaction information pulled from the virtq.
847 * @param fRemove flags whether to remove desc chain from queue (false = peek)
848 *
849 * @returns VBox status code:
850 * @retval VINF_SUCCESS Success
851 * @retval VERR_INVALID_STATE VirtIO not in ready state (asserted).
852 * @retval VERR_NOT_AVAILABLE If the queue is empty.
853 */
854DECLHIDDEN(int) virtioCoreR3VirtqAvailBufGet(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtqNbr,
855 PVIRTQBUF pVirtqBuf, bool fRemove);
856
857/**
858 * Fetches a specific descriptor chain using avail ring of indicated queue and converts the
859 * descriptor chain into its OUT (to device) and IN (to guest) components.
860 *
861 * The caller is responsible for GCPhys to host virtual memory conversions and *must*
862 * return the virtq buffer using virtioCoreR3VirtqUsedBufPut() to complete the roundtrip
863 * virtq transaction.
864 * *
865 * @param pDevIns The device instance.
866 * @param pVirtio Pointer to the shared virtio state.
867 * @param uVirtqNbr Virtq number
868 * @param pVirtqBuf Pointer to descriptor chain that contains the
869 * pre-processed transaction information pulled from the virtq.
870 * @param fRemove flags whether to remove desc chain from queue (false = peek)
871 *
872 * @returns VBox status code:
873 * @retval VINF_SUCCESS Success
874 * @retval VERR_INVALID_STATE VirtIO not in ready state (asserted).
875 * @retval VERR_NOT_AVAILABLE If the queue is empty.
876 */
877DECLHIDDEN(int) virtioCoreR3VirtqAvailBufGet(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtqNbr,
878 uint16_t uHeadIdx, PVIRTQBUF pVirtqBuf);
879
880/**
881 * Returns data to the guest to complete a transaction initiated by virtioCoreR3VirtqAvailBufGet(),
882 * (or virtioCoreR3VirtqAvailBufPeek()/virtioCoreR3VirtqBufSync() call pair), to complete each
883 * buffer transfer transaction (guest-host buffer cycle), ultimately moving each descriptor chain
884 * from the avail ring of a queue onto the used ring of the queue. Note that VirtIO buffer
885 * transactions are *always* initiated by the guest and completed by the host. In other words,
886 * for the host to send any I/O related data to the guest (and in some cases configuration data),
887 * the guest must provide buffers via the virtq's avail ring, for the host to fill.
888 *
889 * At some some point virtioCoreR3VirtqUsedRingSync() must be called to return data to the guest,
890 * completing all pending virtioCoreR3VirtqAvailBufPut() operations that have accumulated since
891 * the last call to virtioCoreR3VirtqUsedRingSync().
892
893 * @note This function effectively performs write-ahead to the used ring of the virtq.
894 * Data written won't be seen by the guest until the next call to virtioCoreVirtqUsedRingSync()
895 *
896 * @param pDevIns The device instance (for reading).
897 * @param pVirtio Pointer to the shared virtio state.
898 * @param uVirtqNbr Virtq number
899 *
900 * @param pSgVirtReturn Points to scatter-gather buffer of virtual memory
901 * segments the caller is returning to the guest.
902 *
903 * @param pVirtqBuf This contains the context of the scatter-gather
904 * buffer originally pulled from the queue.
905 *
906 * @param fFence If true (default), put up copy-fence (memory barrier) after
907 * copying to guest phys. mem.
908 *
909 * @returns VBox status code.
910 * @retval VINF_SUCCESS Success
911 * @retval VERR_INVALID_STATE VirtIO not in ready state
912 * @retval VERR_NOT_AVAILABLE Virtq is empty
913 *
914 * @note This function will not release any reference to pVirtqBuf. The
915 * caller must take care of that.
916 */
917DECLHIDDEN(int) virtioCoreR3VirtqUsedBufPut(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtqNbr, PRTSGBUF pSgVirtReturn,
918 PVIRTQBUF pVirtqBuf, bool fFence = true);
919
920
921/**
922 * Quicker variant of same-named function (directly above) that it overloads,
923 * Instead, this variant accepts as input a pointer to a buffer and count,
924 * instead of S/G buffer thus doesn't have to copy between two S/G buffers and avoids some overhead.
925 *
926 * @param pDevIns The device instance (for reading).
927 * @param pVirtio Pointer to the shared virtio state.
928 * @param uVirtqNbr Virtq number
929 * @param cb Number of bytes to add to copy to phys. buf.
930 * @param pv Virtual mem buf to copy to phys buf.
931 * @param cbEnqueue How many bytes in packet to enqueue (0 = don't enqueue)
932 * @param fFence If true (default), put up copy-fence (memory barrier) after
933 * copying to guest phys. mem.
934 *
935 * @returns VBox status code.
936 * @retval VINF_SUCCESS Success
937 * @retval VERR_INVALID_STATE VirtIO not in ready state
938 * @retval VERR_NOT_AVAILABLE Virtq is empty
939 *
940 * @note This function will not release any reference to pVirtqBuf. The
941 * caller must take care of that.
942 */
943DECLHIDDEN(int) virtioCoreR3VirtqUsedBufPut(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtq, size_t cb, const void *pv,
944 PVIRTQBUF pVirtqBuf, size_t cbEnqueue, bool fFence = true);
945
946
947/**
948 * Advance index of avail ring to next entry in specified virtq (see virtioCoreR3VirtqAvailBufPeek())
949 *
950 * @param pVirtio Pointer to the virtio state.
951 * @param uVirtqNbr Index of queue
952 */
953DECLHIDDEN(int) virtioCoreR3VirtqAvailBufNext(PVIRTIOCORE pVirtio, uint16_t uVirtqNbr);
954
955/**
956 * Checks to see if guest has accepted host device's VIRTIO_F_VERSION_1 (i.e. "modern")
957 * behavioral modeling, indicating guest agreed to comply with the modern VirtIO 1.0+ specification.
958 * Otherwise unavoidable presumption is that the host device is dealing with legacy VirtIO
959 * guest driver, thus must be prepared to cope with less mature architecture and behaviors
960 * from prototype era of VirtIO. (see comments in PDM-invoked device constructor for more
961 * information).
962 *
963 * @param pVirtio Pointer to the virtio state.
964 */
965DECLHIDDEN(int) virtioCoreIsLegacyMode(PVIRTIOCORE pVirtio);
966
967/**
968 * This VirtIO transitional device supports "modern" (rev 1.0+) as well as "legacy" (e.g. < 1.0) VirtIO drivers.
969 * Some legacy guest drivers are known to mishandle PCI bus mastering wherein the PCI flavor of GC phys
970 * access functions can't be used. The following wrappers select the memory access method based on whether the
971 * device is operating in legacy mode or not.
972 */
973DECLINLINE(int) virtioCoreGCPhysWrite(PVIRTIOCORE pVirtio, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, void *pvBuf, size_t cbWrite)
974{
975 int rc;
976 if ( virtioCoreIsLegacyMode(pVirtio)
977 || pVirtio->uIrqMmio)
978 rc = PDMDevHlpPhysWrite(pDevIns, GCPhys, pvBuf, cbWrite);
979 else
980 rc = PDMDevHlpPCIPhysWrite(pDevIns, GCPhys, pvBuf, cbWrite);
981 return rc;
982}
983
984DECLINLINE(int) virtioCoreGCPhysRead(PVIRTIOCORE pVirtio, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, void *pvBuf, size_t cbRead)
985{
986 int rc;
987 if ( virtioCoreIsLegacyMode(pVirtio)
988 || pVirtio->uIrqMmio)
989 rc = PDMDevHlpPhysRead(pDevIns, GCPhys, pvBuf, cbRead);
990 else
991 rc = PDMDevHlpPCIPhysRead(pDevIns, GCPhys, pvBuf, cbRead);
992 return rc;
993}
994
995/*
996 * (See comments for corresponding function in sg.h)
997 */
998DECLINLINE(void) virtioCoreGCPhysChainInit(PVIRTIOSGBUF pGcSgBuf, PVIRTIOSGSEG paSegs, size_t cSegs)
999{
1000 AssertPtr(pGcSgBuf);
1001 Assert((cSegs > 0 && RT_VALID_PTR(paSegs)) || (!cSegs && !paSegs));
1002 Assert(cSegs < (~(unsigned)0 >> 1));
1003
1004 pGcSgBuf->paSegs = paSegs;
1005 pGcSgBuf->cSegs = (unsigned)cSegs;
1006 pGcSgBuf->idxSeg = 0;
1007 if (cSegs && paSegs)
1008 {
1009 pGcSgBuf->GCPhysCur = paSegs[0].GCPhys;
1010 pGcSgBuf->cbSegLeft = paSegs[0].cbSeg;
1011 }
1012 else
1013 {
1014 pGcSgBuf->GCPhysCur = 0;
1015 pGcSgBuf->cbSegLeft = 0;
1016 }
1017}
1018
1019/*
1020 * (See comments for corresponding function in sg.h)
1021 */
1022DECLINLINE(RTGCPHYS) virtioCoreGCPhysChainGet(PVIRTIOSGBUF pGcSgBuf, size_t *pcbData)
1023{
1024 size_t cbData;
1025 RTGCPHYS pGcBuf;
1026
1027 /* Check that the S/G buffer has memory left. */
1028 if (RT_LIKELY(pGcSgBuf->idxSeg < pGcSgBuf->cSegs || pGcSgBuf->cbSegLeft))
1029 { /* likely */ }
1030 else
1031 {
1032 *pcbData = 0;
1033 return 0;
1034 }
1035
1036 AssertMsg( pGcSgBuf->cbSegLeft <= 128 * _1M
1037 && (RTGCPHYS)pGcSgBuf->GCPhysCur >= (RTGCPHYS)pGcSgBuf->paSegs[pGcSgBuf->idxSeg].GCPhys
1038 && (RTGCPHYS)pGcSgBuf->GCPhysCur + pGcSgBuf->cbSegLeft <=
1039 (RTGCPHYS)pGcSgBuf->paSegs[pGcSgBuf->idxSeg].GCPhys + pGcSgBuf->paSegs[pGcSgBuf->idxSeg].cbSeg,
1040 ("pGcSgBuf->idxSeg=%d pGcSgBuf->cSegs=%d pGcSgBuf->GCPhysCur=%p pGcSgBuf->cbSegLeft=%zd "
1041 "pGcSgBuf->paSegs[%d].GCPhys=%p pGcSgBuf->paSegs[%d].cbSeg=%zd\n",
1042 pGcSgBuf->idxSeg, pGcSgBuf->cSegs, pGcSgBuf->GCPhysCur, pGcSgBuf->cbSegLeft,
1043 pGcSgBuf->idxSeg, pGcSgBuf->paSegs[pGcSgBuf->idxSeg].GCPhys, pGcSgBuf->idxSeg,
1044 pGcSgBuf->paSegs[pGcSgBuf->idxSeg].cbSeg));
1045
1046 cbData = RT_MIN(*pcbData, pGcSgBuf->cbSegLeft);
1047 pGcBuf = pGcSgBuf->GCPhysCur;
1048 pGcSgBuf->cbSegLeft -= cbData;
1049 if (!pGcSgBuf->cbSegLeft)
1050 {
1051 pGcSgBuf->idxSeg++;
1052
1053 if (pGcSgBuf->idxSeg < pGcSgBuf->cSegs)
1054 {
1055 pGcSgBuf->GCPhysCur = pGcSgBuf->paSegs[pGcSgBuf->idxSeg].GCPhys;
1056 pGcSgBuf->cbSegLeft = pGcSgBuf->paSegs[pGcSgBuf->idxSeg].cbSeg;
1057 }
1058 *pcbData = cbData;
1059 }
1060 else
1061 pGcSgBuf->GCPhysCur = pGcSgBuf->GCPhysCur + cbData;
1062
1063 return pGcBuf;
1064}
1065
1066/*
1067 * (See comments for corresponding function in sg.h)
1068 */
1069DECLINLINE(void) virtioCoreGCPhysChainReset(PVIRTIOSGBUF pGcSgBuf)
1070{
1071 AssertPtrReturnVoid(pGcSgBuf);
1072
1073 pGcSgBuf->idxSeg = 0;
1074 if (pGcSgBuf->cSegs)
1075 {
1076 pGcSgBuf->GCPhysCur = pGcSgBuf->paSegs[0].GCPhys;
1077 pGcSgBuf->cbSegLeft = pGcSgBuf->paSegs[0].cbSeg;
1078 }
1079 else
1080 {
1081 pGcSgBuf->GCPhysCur = 0;
1082 pGcSgBuf->cbSegLeft = 0;
1083 }
1084}
1085
1086/*
1087 * (See comments for corresponding function in sg.h)
1088 */
1089DECLINLINE(RTGCPHYS) virtioCoreGCPhysChainAdvance(PVIRTIOSGBUF pGcSgBuf, size_t cbAdvance)
1090{
1091 AssertReturn(pGcSgBuf, 0);
1092
1093 size_t cbLeft = cbAdvance;
1094 while (cbLeft)
1095 {
1096 size_t cbThisAdvance = cbLeft;
1097 virtioCoreGCPhysChainGet(pGcSgBuf, &cbThisAdvance);
1098 if (!cbThisAdvance)
1099 break;
1100
1101 cbLeft -= cbThisAdvance;
1102 }
1103 return cbAdvance - cbLeft;
1104}
1105
1106/*
1107 * (See comments for corresponding function in sg.h)
1108 */
1109DECLINLINE(RTGCPHYS) virtioCoreGCPhysChainGetNextSeg(PVIRTIOSGBUF pGcSgBuf, size_t *pcbSeg)
1110{
1111 AssertReturn(pGcSgBuf, 0);
1112 AssertPtrReturn(pcbSeg, 0);
1113
1114 if (!*pcbSeg)
1115 *pcbSeg = pGcSgBuf->cbSegLeft;
1116
1117 return virtioCoreGCPhysChainGet(pGcSgBuf, pcbSeg);
1118}
1119
1120/**
1121 * Calculate the length of a GCPhys s/g buffer by tallying the size of each segment.
1122 *
1123 * @param pGcSgBuf Guest Context (GCPhys) S/G buffer to calculate length of
1124 */
1125DECLINLINE(size_t) virtioCoreGCPhysChainCalcBufSize(PCVIRTIOSGBUF pGcSgBuf)
1126{
1127 size_t cb = 0;
1128 unsigned i = pGcSgBuf->cSegs;
1129 while (i-- > 0)
1130 cb += pGcSgBuf->paSegs[i].cbSeg;
1131 return cb;
1132}
1133
1134/*
1135 * (See comments for corresponding function in sg.h)
1136 */
1137DECLINLINE(size_t) virtioCoreGCPhysChainCalcLengthLeft(PVIRTIOSGBUF pGcSgBuf)
1138{
1139 size_t cb = pGcSgBuf->cbSegLeft;
1140 unsigned i = pGcSgBuf->cSegs;
1141 while (i-- > pGcSgBuf->idxSeg + 1)
1142 cb += pGcSgBuf->paSegs[i].cbSeg;
1143 return cb;
1144}
1145#define VIRTQNAME(a_pVirtio, a_uVirtq) ((a_pVirtio)->aVirtqueues[(a_uVirtq)].szName)
1146
1147/**
1148 * Convert and append bytes from a virtual-memory simple buffer to VirtIO guest's
1149 * physical memory described by a buffer pulled form the avail ring of a virtq.
1150 *
1151 * @param pVirtio Pointer to the shared virtio state.
1152 * @param pVirtqBuf VirtIO buffer to fill
1153 * @param pv input: virtual memory buffer to receive bytes
1154 * @param cb number of bytes to add to the s/g buffer.
1155 */
1156DECLINLINE(void) virtioCoreR3VirqBufFill(PVIRTIOCORE pVirtio, PVIRTQBUF pVirtqBuf, void *pv, size_t cb)
1157{
1158 uint8_t *pvBuf = (uint8_t *)pv;
1159 size_t cbRemain = cb, cbTotal = 0;
1160 PVIRTIOSGBUF pSgPhysReturn = pVirtqBuf->pSgPhysReturn;
1161 while (cbRemain)
1162 {
1163 size_t cbBounded = RT_MIN(pSgPhysReturn->cbSegLeft, cbRemain);
1164 Assert(cbBounded > 0);
1165 virtioCoreGCPhysWrite(pVirtio, CTX_SUFF(pVirtio->pDevIns), (RTGCPHYS)pSgPhysReturn->GCPhysCur, pvBuf, cbBounded);
1166 virtioCoreGCPhysChainAdvance(pSgPhysReturn, cbBounded);
1167 pvBuf += cbBounded;
1168 cbRemain -= cbBounded;
1169 cbTotal += cbBounded;
1170 }
1171 LogFunc(("Appended %d bytes to guest phys buf [head: %u]. %d bytes unused in buf.)\n",
1172 cbTotal, pVirtqBuf->uHeadIdx, virtioCoreGCPhysChainCalcLengthLeft(pSgPhysReturn)));
1173}
1174
1175/**
1176 * Extract some bytes from of a virtq s/g buffer, converting them from GCPhys space to
1177 * to ordinary virtual memory (i.e. making data directly accessible to host device code)
1178 *
1179 * As a performance optimization, it is left to the caller to validate buffer size.
1180 *
1181 * @param pVirtio Pointer to the shared virtio state.
1182 * @param pVirtqBuf input: virtq buffer
1183 * @param pv output: virtual memory buffer to receive bytes
1184 * @param cb number of bytes to Drain from buffer
1185 */
1186DECLINLINE(void) virtioCoreR3VirtqBufDrain(PVIRTIOCORE pVirtio, PVIRTQBUF pVirtqBuf, void *pv, size_t cb)
1187{
1188 uint8_t *pb = (uint8_t *)pv;
1189 size_t cbLim = RT_MIN(pVirtqBuf->cbPhysSend, cb);
1190 while (cbLim)
1191 {
1192 size_t cbSeg = cbLim;
1193 RTGCPHYS GCPhys = virtioCoreGCPhysChainGetNextSeg(pVirtqBuf->pSgPhysSend, &cbSeg);
1194 if (pVirtio->uIrqMmio)
1195 PDMDevHlpPhysRead(pVirtio->pDevInsR3, GCPhys, pb, cbSeg);
1196 else
1197 PDMDevHlpPCIPhysRead(pVirtio->pDevInsR3, GCPhys, pb, cbSeg);
1198 pb += cbSeg;
1199 cbLim -= cbSeg;
1200 pVirtqBuf->cbPhysSend -= cbSeg;
1201 }
1202 LogFunc(("Drained %d/%d bytes from %s buffer, head idx: %u (%d bytes left)\n",
1203 cb - cbLim, cb, VIRTQNAME(pVirtio, pVirtqBuf->uVirtq),
1204 pVirtqBuf->uHeadIdx, virtioCoreGCPhysChainCalcLengthLeft(pVirtqBuf->pSgPhysReturn)));
1205}
1206
1207#undef VIRTQNAME
1208
1209/**
1210 * Updates indicated virtq's "used ring" descriptor index to match "shadow" index that tracks
1211 * pending buffers added to the used ring, thus exposing all the data added by virtioCoreR3VirtqUsedBufPut()
1212 * to the "used ring" since the last virtioCoreVirtqUsedRingSync().
1213 *
1214 * This *must* be invoked after one or more virtioCoreR3VirtqUsedBufPut() calls to inform guest driver
1215 * there is data in the queue. If enabled by guest, IRQ or MSI-X signalling will notify guest
1216 * proactively, otherwise guest detects updates by polling. (see VirtIO 1.0, Section 2.4 "Virtqueues").
1217 *
1218 * @param pDevIns The device instance.
1219 * @param pVirtio Pointer to the shared virtio state.
1220 * @param uVirtqNbr Virtq number
1221 *
1222 * @returns VBox status code.
1223 * @retval VINF_SUCCESS Success
1224 * @retval VERR_INVALID_STATE VirtIO not in ready state
1225 */
1226DECLHIDDEN(int) virtioCoreVirtqUsedRingSync(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtqNbr);
1227
1228/**
1229 * Allocates a descriptor chain object with the reference count of one. Copying the reference
1230 * to this object requires a call to virtioCoreR3VirtqBufRetain. All references must be later
1231 * released with virtioCoreR3VirtqBufRelease. Just to be clear, one alloc plus one retain will
1232 * require two releases.
1233 *
1234 * @returns A descriptor chain object.
1235 *
1236 * @retval NULL if out of memory.
1237 *
1238 * NOTE: VIRTQBUF_T objects allocated on the stack will have garbage in the u32Magic field,
1239 * triggering an assertion if virtioCoreR3VirtqBufRelease is called on them.
1240 */
1241DECLHIDDEN(PVIRTQBUF) virtioCoreR3VirtqBufAlloc(void);
1242
1243/**
1244 * Retains a reference to the given descriptor chain.
1245 *
1246 * @param pVirtqBuf The descriptor chain to reference.
1247 *
1248 * @returns New reference count.
1249 * @retval UINT32_MAX on invalid parameter.
1250 */
1251DECLHIDDEN(uint32_t) virtioCoreR3VirtqBufRetain(PVIRTQBUF pVirtqBuf);
1252
1253/**
1254 * Releases a reference to the given descriptor chain.
1255 *
1256 * @param pVirtio Pointer to the shared virtio state.
1257 * @param pVirtqBuf The descriptor chain to reference. NULL is quietly
1258 * ignored (returns 0).
1259 * @returns New reference count.
1260 * @retval 0 if freed or invalid parameter.
1261 */
1262DECLHIDDEN(uint32_t) virtioCoreR3VirtqBufRelease(PVIRTIOCORE pVirtio, PVIRTQBUF pVirtqBuf);
1263
1264/**
1265 * Return queue enable state
1266 *
1267 * @param pVirtio Pointer to the virtio state.
1268 * @param uVirtqNbr Virtq number.
1269 *
1270 * @returns true or false indicating queue is enabled or not.
1271 */
1272DECLINLINE(bool) virtioCoreIsVirtqEnabled(PVIRTIOCORE pVirtio, uint16_t uVirtqNbr)
1273{
1274 Assert(uVirtqNbr < RT_ELEMENTS(pVirtio->aVirtqueues));
1275 if (pVirtio->fLegacyDriver)
1276 return pVirtio->aVirtqueues[uVirtqNbr].GCPhysVirtqDesc != 0;
1277 return pVirtio->aVirtqueues[uVirtqNbr].uEnable != 0;
1278}
1279
1280/**
1281 * Get name of queue, via uVirtqNbr, assigned during virtioCoreR3VirtqAttach()
1282 *
1283 * @param pVirtio Pointer to the virtio state.
1284 * @param uVirtqNbr Virtq number.
1285 *
1286 * @returns Pointer to read-only queue name.
1287 */
1288DECLINLINE(const char *) virtioCoreVirtqGetName(PVIRTIOCORE pVirtio, uint16_t uVirtqNbr)
1289{
1290 Assert((size_t)uVirtqNbr < RT_ELEMENTS(pVirtio->aVirtqueues));
1291 return pVirtio->aVirtqueues[uVirtqNbr].szName;
1292}
1293
1294/**
1295 * Get the bitmask of features VirtIO is running with. This is called by the device-specific
1296 * VirtIO implementation to identify this device's operational configuration after features
1297 * have been negotiated with guest VirtIO driver. Feature negotiation entails host indicating
1298 * to guest which features it supports, then guest accepting from among the offered, which features
1299 * it will enable. That becomes the agreement between the host and guest. The bitmask containing
1300 * virtio core features plus device-specific features is provided as a parameter to virtioCoreR3Init()
1301 * by the host side device-specific virtio implementation.
1302 *
1303 * @param pVirtio Pointer to the virtio state.
1304 *
1305 * @returns Features the guest driver has accepted, finalizing the operational features
1306 */
1307DECLINLINE(uint64_t) virtioCoreGetNegotiatedFeatures(PVIRTIOCORE pVirtio)
1308{
1309 return pVirtio->uDriverFeatures;
1310}
1311
1312/**
1313 * Get name of the VM state change associated with the enumeration variable
1314 *
1315 * @param enmState VM state (enumeration value)
1316 *
1317 * @returns associated text.
1318 */
1319DECLHIDDEN(const char *) virtioCoreGetStateChangeText(VIRTIOVMSTATECHANGED enmState);
1320
1321/**
1322 * Debug assist code for any consumer that inherits VIRTIOCORE.
1323 * Log memory-mapped I/O input or output value.
1324 *
1325 * This is to be invoked by macros that assume they are invoked in functions with
1326 * the relevant arguments. (See Virtio_1_0.cpp).
1327 *
1328 * It is exposed via the API so inheriting device-specific clients can provide similar
1329 * logging capabilities for a consistent look-and-feel.
1330 *
1331 * @param pszFunc To avoid displaying this function's name via __FUNCTION__ or LogFunc()
1332 * @param pszMember Name of struct member
1333 * @param pv pointer to value
1334 * @param cb size of value
1335 * @param uOffset offset into member where value starts
1336 * @param fWrite True if write I/O
1337 * @param fHasIndex True if the member is indexed
1338 * @param idx The index if fHasIndex
1339 */
1340DECLHIDDEN(void) virtioCoreLogMappedIoValue(const char *pszFunc, const char *pszMember, uint32_t uMemberSize,
1341 const void *pv, uint32_t cb, uint32_t uOffset,
1342 int fWrite, int fHasIndex, uint32_t idx);
1343
1344/**
1345 * Debug assist for any consumer
1346 *
1347 * Does a formatted hex dump using Log(()), recommend using VIRTIO_HEX_DUMP() macro to
1348 * control enabling of logging efficiently.
1349 *
1350 * @param pv pointer to buffer to dump contents of
1351 * @param cb count of characters to dump from buffer
1352 * @param uBase base address of per-row address prefixing of hex output
1353 * @param pszTitle Optional title. If present displays title that lists
1354 * provided text with value of cb to indicate VIRTQ_SIZE next to it.
1355 */
1356DECLHIDDEN(void) virtioCoreHexDump(uint8_t *pv, uint32_t cb, uint32_t uBase, const char *pszTitle);
1357
1358/**
1359 * Debug assist for any consumer device code
1360 * Do a hex dump of memory in guest physical context
1361 *
1362 * @param GCPhys pointer to buffer to dump contents of
1363 * @param cb count of characters to dump from buffer
1364 * @param uBase base address of per-row address prefixing of hex output
1365 * @param pszTitle Optional title. If present displays title that lists
1366 * provided text with value of cb to indicate size next to it.
1367 */
1368DECLHIDDEN(void) virtioCoreGCPhysHexDump(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, uint16_t cb, uint32_t uBase, const char *pszTitle);
1369
1370/**
1371 * The following API is functions identically to the similarly-named calls pertaining to the RTSGBUF
1372 */
1373
1374/** Misc VM and PDM boilerplate */
1375DECLHIDDEN(int) virtioCoreR3SaveExec(PVIRTIOCORE pVirtio, PCPDMDEVHLPR3 pHlp, PSSMHANDLE pSSM,
1376 uint32_t uVersion, uint32_t cQueues);
1377DECLHIDDEN(int) virtioCoreR3ModernDeviceLoadExec(PVIRTIOCORE pVirtio, PCPDMDEVHLPR3 pHlp, PSSMHANDLE pSSM,
1378 uint32_t uVersion, uint32_t uTestVersion, uint32_t cQueues);
1379DECLHIDDEN(int) virtioCoreR3LegacyDeviceLoadExec(PVIRTIOCORE pVirtio, PCPDMDEVHLPR3 pHlp, PSSMHANDLE pSSM,
1380 uint32_t uVersion, uint32_t uVirtioLegacy_3_1_Beta);
1381DECLHIDDEN(void) virtioCoreR3VmStateChanged(PVIRTIOCORE pVirtio, VIRTIOVMSTATECHANGED enmState);
1382DECLHIDDEN(void) virtioCoreR3Term(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC);
1383DECLHIDDEN(int) virtioCoreRZInit(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio);
1384DECLHIDDEN(const char *) virtioCoreGetStateChangeText(VIRTIOVMSTATECHANGED enmState);
1385
1386/*
1387 * The following macros assist with handling/logging MMIO accesses to VirtIO dev-specific config area,
1388 * in a way that enhances code readability and debug logging consistency.
1389 *
1390 * cb, pv and fWrite are implicit parameters and must be defined by the invoker.
1391 */
1392#ifdef LOG_ENABLED
1393
1394# define VIRTIO_DEV_CONFIG_LOG_ACCESS(member, tCfgStruct, uOffsetOfAccess) \
1395 if (LogIs7Enabled()) { \
1396 uint32_t uMbrOffset = uOffsetOfAccess - RT_UOFFSETOF(tCfgStruct, member); \
1397 uint32_t uMbrSize = RT_SIZEOFMEMB(tCfgStruct, member); \
1398 virtioCoreLogMappedIoValue(__FUNCTION__, #member, uMbrSize, pv, cb, uMbrOffset, fWrite, false, 0); \
1399 }
1400
1401# define VIRTIO_DEV_CONFIG_LOG_INDEXED_ACCESS(member, tCfgStruct, uOffsetOfAccess, uIdx) \
1402 if (LogIs7Enabled()) { \
1403 uint32_t uMbrOffset = uOffsetOfAccess - RT_UOFFSETOF(tCfgStruct, member); \
1404 uint32_t uMbrSize = RT_SIZEOFMEMB(tCfgStruct, member); \
1405 virtioCoreLogMappedIoValue(__FUNCTION__, #member, uMbrSize, pv, cb, uMbrOffset, fWrite, true, uIdx); \
1406 }
1407#else
1408# define VIRTIO_DEV_CONFIG_LOG_ACCESS(member, tCfgStruct, uMbrOffset) do { } while (0)
1409# define VIRTIO_DEV_CONFIG_LOG_INDEXED_ACCESS(member, tCfgStruct, uMbrOffset, uIdx) do { } while (0)
1410#endif
1411
1412DECLINLINE(bool) virtioCoreMatchMember(uint32_t uOffset, uint32_t cb, uint32_t uMemberOff,
1413 size_t uMemberSize, bool fSubFieldMatch)
1414{
1415 /* Test for 8-byte field (always accessed as two 32-bit components) */
1416 if (uMemberSize == 8)
1417 return (cb == sizeof(uint32_t)) && (uOffset == uMemberOff || uOffset == (uMemberOff + sizeof(uint32_t)));
1418
1419 if (fSubFieldMatch)
1420 return (uOffset >= uMemberOff) && (cb <= uMemberSize - (uOffset - uMemberOff));
1421
1422 /* Test for exact match */
1423 return (uOffset == uMemberOff) && (cb == uMemberSize);
1424}
1425
1426/**
1427 * Yields boolean true if uOffsetOfAccess falls within bytes of specified member of config struct
1428 */
1429#define VIRTIO_DEV_CONFIG_SUBMATCH_MEMBER(member, tCfgStruct, uOffsetOfAccess) \
1430 virtioCoreMatchMember(uOffsetOfAccess, cb, \
1431 RT_UOFFSETOF(tCfgStruct, member), \
1432 RT_SIZEOFMEMB(tCfgStruct, member), true /* fSubfieldMatch */)
1433
1434#define VIRTIO_DEV_CONFIG_MATCH_MEMBER(member, tCfgStruct, uOffsetOfAccess) \
1435 virtioCoreMatchMember(uOffsetOfAccess, cb, \
1436 RT_UOFFSETOF(tCfgStruct, member), \
1437 RT_SIZEOFMEMB(tCfgStruct, member), false /* fSubfieldMatch */)
1438
1439
1440
1441/**
1442 * Copy reads or copy writes specified member field of config struct (based on fWrite),
1443 * the memory described by cb and pv.
1444 *
1445 * cb, pv and fWrite are implicit parameters and must be defined by invoker.
1446 */
1447#define VIRTIO_DEV_CONFIG_ACCESS(member, tCfgStruct, uOffsetOfAccess, pCfgStruct) \
1448 do \
1449 { \
1450 uint32_t uOffsetInMember = uOffsetOfAccess - RT_UOFFSETOF(tCfgStruct, member); \
1451 if (fWrite) \
1452 memcpy(((char *)&(pCfgStruct)->member) + uOffsetInMember, pv, cb); \
1453 else \
1454 memcpy(pv, ((const char *)&(pCfgStruct)->member) + uOffsetInMember, cb); \
1455 VIRTIO_DEV_CONFIG_LOG_ACCESS(member, tCfgStruct, uOffsetOfAccess); \
1456 } while(0)
1457
1458/**
1459 * Copies bytes into memory described by cb, pv from the specified member field of the config struct.
1460 * The operation is a NOP, logging an error if an implied parameter, fWrite, is boolean true.
1461 *
1462 * cb, pv and fWrite are implicit parameters and must be defined by the invoker.
1463 */
1464#define VIRTIO_DEV_CONFIG_ACCESS_READONLY(member, tCfgStruct, uOffsetOfAccess, pCfgStruct) \
1465 do \
1466 { \
1467 uint32_t uOffsetInMember = uOffsetOfAccess - RT_UOFFSETOF(tCfgStruct, member); \
1468 if (fWrite) \
1469 LogFunc(("Guest attempted to write readonly virtio config struct (member %s)\n", #member)); \
1470 else \
1471 { \
1472 memcpy(pv, ((const char *)&(pCfgStruct)->member) + uOffsetInMember, cb); \
1473 VIRTIO_DEV_CONFIG_LOG_ACCESS(member, tCfgStruct, uOffsetOfAccess); \
1474 } \
1475 } while(0)
1476
1477/**
1478 * Copies into or out of specified member field of config struct (based on fWrite),
1479 * the memory described by cb and pv.
1480 *
1481 * cb, pv and fWrite are implicit parameters and must be defined by invoker.
1482 */
1483#define VIRTIO_DEV_CONFIG_ACCESS_INDEXED(member, uIdx, tCfgStruct, uOffsetOfAccess, pCfgStruct) \
1484 do \
1485 { \
1486 uint32_t uOffsetInMember = uOffsetOfAccess - RT_UOFFSETOF(tCfgStruct, member); \
1487 if (fWrite) \
1488 memcpy(((char *)&(pCfgStruct[uIdx].member)) + uOffsetInMember, pv, cb); \
1489 else \
1490 memcpy(pv, ((const char *)&(pCfgStruct[uIdx].member)) + uOffsetInMember, cb); \
1491 VIRTIO_DEV_CONFIG_LOG_INDEXED_ACCESS(member, tCfgStruct, uOffsetOfAccess, uIdx); \
1492 } while(0)
1493
1494/**
1495 * Copies bytes into memory described by cb, pv from the specified member field of the config struct.
1496 * The operation is a nop and logs error if implied parameter fWrite is true.
1497 *
1498 * cb, pv and fWrite are implicit parameters and must be defined by invoker.
1499 */
1500#define VIRTIO_DEV_CONFIG_ACCESS_INDEXED_READONLY(member, uidx, tCfgStruct, uOffsetOfAccess, pCfgStruct) \
1501 do \
1502 { \
1503 uint32_t uOffsetInMember = uOffsetOfAccess - RT_UOFFSETOF(tCfgStruct, member); \
1504 if (fWrite) \
1505 LogFunc(("Guest attempted to write readonly virtio config struct (member %s)\n", #member)); \
1506 else \
1507 { \
1508 memcpy(pv, ((const char *)&(pCfgStruct[uIdx].member)) + uOffsetInMember, cb); \
1509 VIRTIO_DEV_CONFIG_LOG_INDEXED_ACCESS(member, tCfgStruct, uOffsetOfAccess, uIdx); \
1510 } \
1511 } while(0)
1512
1513/** @} */
1514
1515/** @name API for VirtIO parent device
1516 * @{ */
1517
1518#endif /* !VBOX_INCLUDED_SRC_VirtIO_VirtioCore_h */
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette