VirtualBox

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

Last change on this file since 95433 was 94970, checked in by vboxsync, 3 years ago

Devices/Virtio|ai: Fixes and performance improvements for the 1.0 virtio-net implementation, bugref:8651 [scm fix]

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