VirtualBox

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

Last change on this file since 99739 was 99739, checked in by vboxsync, 19 months ago

*: doxygen corrections (mostly about removing @returns from functions returning void).

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