VirtualBox

source: vbox/trunk/src/VBox/Devices/VirtIO/VirtioCore.cpp@ 104280

Last change on this file since 104280 was 104280, checked in by vboxsync, 2 months ago

VirtioCore: improved chain length checks and MMIO read handling in PciIch0 and PCNet, as well as input context initialization in XHCI. bugref:10635

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 132.6 KB
Line 
1/* $Id: VirtioCore.cpp 104280 2024-04-10 16:48:47Z vboxsync $ */
2
3/** @file
4 * VirtioCore - Virtio Core (PCI, feature & config mgt, queue mgt & proxy, notification mgt)
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
30/*********************************************************************************************************************************
31* Header Files *
32*********************************************************************************************************************************/
33#define LOG_GROUP LOG_GROUP_DEV_VIRTIO
34
35#include <iprt/assert.h>
36#include <iprt/uuid.h>
37#include <iprt/mem.h>
38#include <iprt/sg.h>
39#include <iprt/assert.h>
40#include <iprt/string.h>
41#include <iprt/param.h>
42#include <iprt/types.h>
43#include <VBox/log.h>
44#include <VBox/msi.h>
45#include <iprt/types.h>
46#include <VBox/AssertGuest.h>
47#include <VBox/vmm/pdmdev.h>
48#include "VirtioCore.h"
49
50
51/*********************************************************************************************************************************
52* Defined Constants And Macros *
53*********************************************************************************************************************************/
54
55#define INSTANCE(a_pVirtio) ((a_pVirtio)->szInstance)
56#define VIRTQNAME(a_pVirtio, a_uVirtq) ((a_pVirtio)->aVirtqueues[(a_uVirtq)].szName)
57
58#define IS_VIRTQ_EMPTY(pDevIns, pVirtio, pVirtq) \
59 (virtioCoreVirtqAvailCnt(pDevIns, pVirtio, pVirtq) == 0)
60
61#define IS_DRIVER_OK(a_pVirtio) ((a_pVirtio)->fDeviceStatus & VIRTIO_STATUS_DRIVER_OK)
62#define WAS_DRIVER_OK(a_pVirtio) ((a_pVirtio)->fPrevDeviceStatus & VIRTIO_STATUS_DRIVER_OK)
63
64/**
65 * These defines are used to track guest virtio-net driver writing driver features accepted flags
66 * in two 32-bit operations (in arbitrary order), and one bit dedicated to ensured 'features complete'
67 * is handled once.
68 */
69#define DRIVER_FEATURES_0_WRITTEN 1 /**< fDriverFeatures[0] written by guest virtio-net */
70#define DRIVER_FEATURES_1_WRITTEN 2 /**< fDriverFeatures[1] written by guest virtio-net */
71#define DRIVER_FEATURES_0_AND_1_WRITTEN 3 /**< Both 32-bit parts of fDriverFeatures[] written */
72#define DRIVER_FEATURES_COMPLETE_HANDLED 4 /**< Features negotiation complete handler called */
73
74/**
75 * This macro returns true if the @a a_offAccess and access length (@a
76 * a_cbAccess) are within the range of the mapped capability struct described by
77 * @a a_LocCapData.
78 *
79 * @param[in] a_offAccess Input: The offset into the MMIO bar of the access.
80 * @param[in] a_cbAccess Input: The access size.
81 * @param[out] a_offsetIntoCap Output: uint32_t variable to return the intra-capability offset into.
82 * @param[in] a_LocCapData Input: The capability location info.
83 */
84#define MATCHES_VIRTIO_CAP_STRUCT(a_offAccess, a_cbAccess, a_offsetIntoCap, a_LocCapData) \
85 ( ((a_offsetIntoCap) = (uint32_t)((a_offAccess) - (a_LocCapData).offMmio)) < (uint32_t)(a_LocCapData).cbMmio \
86 && (a_offsetIntoCap) + (uint32_t)(a_cbAccess) <= (uint32_t)(a_LocCapData).cbMmio )
87
88
89/*********************************************************************************************************************************
90* Structures and Typedefs *
91*********************************************************************************************************************************/
92
93/** @name virtq related flags
94 * @{ */
95#define VIRTQ_DESC_F_NEXT 1 /**< Indicates this descriptor chains to next */
96#define VIRTQ_DESC_F_WRITE 2 /**< Marks buffer as write-only (default ro) */
97#define VIRTQ_DESC_F_INDIRECT 4 /**< Buffer is list of buffer descriptors */
98
99#define VIRTQ_USED_F_NO_NOTIFY 1 /**< Dev to Drv: Don't notify when buf added */
100#define VIRTQ_AVAIL_F_NO_INTERRUPT 1 /**< Drv to Dev: Don't notify when buf eaten */
101/** @} */
102
103/**
104 * virtq-related structs
105 * (struct names follow VirtIO 1.0 spec, field names use VBox styled naming, w/respective spec'd name in comments)
106 */
107typedef struct virtq_desc
108{
109 uint64_t GCPhysBuf; /**< addr GC Phys. address of buffer */
110 uint32_t cb; /**< len Buffer length */
111 uint16_t fFlags; /**< flags Buffer specific flags */
112 uint16_t uDescIdxNext; /**< next Idx set if VIRTIO_DESC_F_NEXT */
113} VIRTQ_DESC_T, *PVIRTQ_DESC_T;
114
115typedef struct virtq_avail
116{
117 uint16_t fFlags; /**< flags avail ring guest-to-host flags */
118 uint16_t uIdx; /**< idx Index of next free ring slot */
119 RT_FLEXIBLE_ARRAY_EXTENSION
120 uint16_t auRing[RT_FLEXIBLE_ARRAY]; /**< ring Ring: avail drv to dev bufs */
121 //uint16_t uUsedEventIdx; /**< used_event (if VIRTQ_USED_F_EVENT_IDX) */
122} VIRTQ_AVAIL_T, *PVIRTQ_AVAIL_T;
123
124typedef struct virtq_used_elem
125{
126 uint32_t uDescIdx; /**< idx Start of used desc chain */
127 uint32_t cbElem; /**< len Total len of used desc chain */
128} VIRTQ_USED_ELEM_T;
129
130typedef struct virt_used
131{
132 uint16_t fFlags; /**< flags used ring host-to-guest flags */
133 uint16_t uIdx; /**< idx Index of next ring slot */
134 RT_FLEXIBLE_ARRAY_EXTENSION
135 VIRTQ_USED_ELEM_T aRing[RT_FLEXIBLE_ARRAY]; /**< ring Ring: used dev to drv bufs */
136 //uint16_t uAvailEventIdx; /**< avail_event if (VIRTQ_USED_F_EVENT_IDX) */
137} VIRTQ_USED_T, *PVIRTQ_USED_T;
138
139DECLHIDDEN(const char *) virtioCoreGetStateChangeText(VIRTIOVMSTATECHANGED enmState)
140{
141 switch (enmState)
142 {
143 case kvirtIoVmStateChangedReset: return "VM RESET";
144 case kvirtIoVmStateChangedSuspend: return "VM SUSPEND";
145 case kvirtIoVmStateChangedPowerOff: return "VM POWER OFF";
146 case kvirtIoVmStateChangedResume: return "VM RESUME";
147 default: return "<BAD ENUM>";
148 }
149}
150
151/* Internal Functions */
152
153static void virtioCoreNotifyGuestDriver(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtq);
154static int virtioNudgeGuest(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint8_t uCause, uint16_t uVec);
155
156#ifdef IN_RING3
157# ifdef LOG_ENABLED
158DECLINLINE(uint16_t) virtioCoreR3CountPendingBufs(uint16_t uRingIdx, uint16_t uShadowIdx, uint16_t uQueueSize)
159{
160 if (uShadowIdx == uRingIdx)
161 return 0;
162 else
163 if (uShadowIdx > uRingIdx)
164 return uShadowIdx - uRingIdx;
165 return uQueueSize - (uRingIdx - uShadowIdx);
166}
167# endif
168#endif
169/** @name Internal queue operations
170 * @{ */
171
172/**
173 * Accessor for virtq descriptor
174 */
175#ifdef IN_RING3
176DECLINLINE(void) virtioReadDesc(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTQUEUE pVirtq,
177 uint32_t idxDesc, PVIRTQ_DESC_T pDesc)
178{
179 /*
180 * Shut up assertion for legacy virtio-net driver in FreeBSD up to 12.3 (see virtioCoreR3VirtqUsedBufPut()
181 * for more information).
182 */
183 AssertMsg( IS_DRIVER_OK(pVirtio)
184 || ( pVirtio->fLegacyDriver
185 && pVirtq->GCPhysVirtqDesc),
186 ("Called with guest driver not ready\n"));
187 uint16_t const cVirtqItems = RT_MAX(pVirtq->uQueueSize, 1); /* Make sure to avoid div-by-zero. */
188
189 virtioCoreGCPhysRead(pVirtio, pDevIns,
190 pVirtq->GCPhysVirtqDesc + sizeof(VIRTQ_DESC_T) * (idxDesc % cVirtqItems),
191 pDesc, sizeof(VIRTQ_DESC_T));
192}
193#endif
194
195/**
196 * Accessors for virtq avail ring
197 */
198#ifdef IN_RING3
199DECLINLINE(uint16_t) virtioReadAvailDescIdx(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTQUEUE pVirtq, uint32_t availIdx)
200{
201 uint16_t uDescIdx;
202
203 AssertMsg(pVirtio->fLegacyDriver || IS_DRIVER_OK(pVirtio), ("Called with guest driver not ready\n"));
204 uint16_t const cVirtqItems = RT_MAX(pVirtq->uQueueSize, 1); /* Make sure to avoid div-by-zero. */
205 virtioCoreGCPhysRead(pVirtio, pDevIns,
206 pVirtq->GCPhysVirtqAvail + RT_UOFFSETOF_DYN(VIRTQ_AVAIL_T, auRing[availIdx % cVirtqItems]),
207 &uDescIdx, sizeof(uDescIdx));
208 return uDescIdx;
209}
210
211DECLINLINE(uint16_t) virtioReadAvailUsedEvent(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTQUEUE pVirtq)
212{
213 uint16_t uUsedEventIdx;
214 /* VirtIO 1.0 uUsedEventIdx (used_event) immediately follows ring */
215 AssertMsg(pVirtio->fLegacyDriver || IS_DRIVER_OK(pVirtio), ("Called with guest driver not ready\n"));
216 virtioCoreGCPhysRead(pVirtio, pDevIns,
217 pVirtq->GCPhysVirtqAvail + RT_UOFFSETOF_DYN(VIRTQ_AVAIL_T, auRing[pVirtq->uQueueSize]),
218 &uUsedEventIdx, sizeof(uUsedEventIdx));
219 return uUsedEventIdx;
220}
221#endif
222
223DECLINLINE(uint16_t) virtioReadAvailRingIdx(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTQUEUE pVirtq)
224{
225 uint16_t uIdx = 0;
226 AssertMsg(pVirtio->fLegacyDriver || IS_DRIVER_OK(pVirtio), ("Called with guest driver not ready\n"));
227 virtioCoreGCPhysRead(pVirtio, pDevIns,
228 pVirtq->GCPhysVirtqAvail + RT_UOFFSETOF(VIRTQ_AVAIL_T, uIdx),
229 &uIdx, sizeof(uIdx));
230 return uIdx;
231}
232
233DECLINLINE(uint16_t) virtioReadAvailRingFlags(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTQUEUE pVirtq)
234{
235 uint16_t fFlags = 0;
236 AssertMsg(pVirtio->fLegacyDriver || IS_DRIVER_OK(pVirtio), ("Called with guest driver not ready\n"));
237 virtioCoreGCPhysRead(pVirtio, pDevIns,
238 pVirtq->GCPhysVirtqAvail + RT_UOFFSETOF(VIRTQ_AVAIL_T, fFlags),
239 &fFlags, sizeof(fFlags));
240 return fFlags;
241}
242
243/** @} */
244
245/** @name Accessors for virtq used ring
246 * @{
247 */
248
249#ifdef IN_RING3
250DECLINLINE(void) virtioWriteUsedElem(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTQUEUE pVirtq,
251 uint32_t usedIdx, uint32_t uDescIdx, uint32_t uLen)
252{
253 VIRTQ_USED_ELEM_T elem = { uDescIdx, uLen };
254 AssertMsg(pVirtio->fLegacyDriver || IS_DRIVER_OK(pVirtio), ("Called with guest driver not ready\n"));
255 uint16_t const cVirtqItems = RT_MAX(pVirtq->uQueueSize, 1); /* Make sure to avoid div-by-zero. */
256 virtioCoreGCPhysWrite(pVirtio, pDevIns,
257 pVirtq->GCPhysVirtqUsed
258 + RT_UOFFSETOF_DYN(VIRTQ_USED_T, aRing[usedIdx % cVirtqItems]),
259 &elem, sizeof(elem));
260}
261
262DECLINLINE(void) virtioWriteUsedRingFlags(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTQUEUE pVirtq, uint16_t fFlags)
263{
264 AssertMsg(pVirtio->fLegacyDriver || IS_DRIVER_OK(pVirtio), ("Called with guest driver not ready\n"));
265 RT_UNTRUSTED_VALIDATED_FENCE(); /* VirtIO 1.0, Section 3.2.1.4.1 */
266 virtioCoreGCPhysWrite(pVirtio, pDevIns,
267 pVirtq->GCPhysVirtqUsed + RT_UOFFSETOF(VIRTQ_USED_T, fFlags),
268 &fFlags, sizeof(fFlags));
269}
270#endif
271
272DECLINLINE(void) virtioWriteUsedRingIdx(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTQUEUE pVirtq, uint16_t uIdx)
273{
274 AssertMsg(pVirtio->fLegacyDriver || IS_DRIVER_OK(pVirtio), ("Called with guest driver not ready\n"));
275 RT_UNTRUSTED_VALIDATED_FENCE(); /* VirtIO 1.0, Section 3.2.1.4.1 */
276 virtioCoreGCPhysWrite(pVirtio, pDevIns,
277 pVirtq->GCPhysVirtqUsed + RT_UOFFSETOF(VIRTQ_USED_T, uIdx),
278 &uIdx, sizeof(uIdx));
279}
280
281#ifdef IN_RING3
282DECLINLINE(uint16_t) virtioReadUsedRingIdx(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTQUEUE pVirtq)
283{
284 uint16_t uIdx = 0;
285 AssertMsg(pVirtio->fLegacyDriver || IS_DRIVER_OK(pVirtio), ("Called with guest driver not ready\n"));
286 virtioCoreGCPhysRead(pVirtio, pDevIns,
287 pVirtq->GCPhysVirtqUsed + RT_UOFFSETOF(VIRTQ_USED_T, uIdx),
288 &uIdx, sizeof(uIdx));
289 return uIdx;
290}
291
292DECLINLINE(uint16_t) virtioReadUsedRingFlags(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTQUEUE pVirtq)
293{
294 uint16_t fFlags = 0;
295 AssertMsg(pVirtio->fLegacyDriver || IS_DRIVER_OK(pVirtio), ("Called with guest driver not ready\n"));
296 virtioCoreGCPhysRead(pVirtio, pDevIns,
297 pVirtq->GCPhysVirtqUsed + RT_UOFFSETOF(VIRTQ_USED_T, fFlags),
298 &fFlags, sizeof(fFlags));
299 return fFlags;
300}
301
302DECLINLINE(void) virtioWriteUsedAvailEvent(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTQUEUE pVirtq, uint32_t uAvailEventIdx)
303{
304 /** VirtIO 1.0 uAvailEventIdx (avail_event) immediately follows ring */
305 AssertMsg(pVirtio->fLegacyDriver || IS_DRIVER_OK(pVirtio), ("Called with guest driver not ready\n"));
306 virtioCoreGCPhysWrite(pVirtio, pDevIns,
307 pVirtq->GCPhysVirtqUsed
308 + RT_UOFFSETOF_DYN(VIRTQ_USED_T, aRing[pVirtq->uQueueSize]),
309 &uAvailEventIdx, sizeof(uAvailEventIdx));
310}
311#endif
312/** @} */
313
314
315DECLINLINE(uint16_t) virtioCoreVirtqAvailCnt(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTQUEUE pVirtq)
316{
317 uint16_t uIdxActual = virtioReadAvailRingIdx(pDevIns, pVirtio, pVirtq);
318 uint16_t uIdxShadow = pVirtq->uAvailIdxShadow;
319 uint16_t uIdxDelta;
320
321 if (uIdxActual < uIdxShadow)
322 uIdxDelta = (uIdxActual + pVirtq->uQueueSize) - uIdxShadow;
323 else
324 uIdxDelta = uIdxActual - uIdxShadow;
325
326 return uIdxDelta;
327}
328/**
329 * Get count of new (e.g. pending) elements in available ring.
330 *
331 * @param pDevIns The device instance.
332 * @param pVirtio Pointer to the shared virtio state.
333 * @param uVirtq Virtq number
334 *
335 * @returns how many entries have been added to ring as a delta of the consumer's
336 * avail index and the queue's guest-side current avail index.
337 */
338DECLHIDDEN(uint16_t) virtioCoreVirtqAvailBufCount(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtq)
339{
340 AssertMsgReturn(uVirtq < RT_ELEMENTS(pVirtio->aVirtqueues), ("uVirtq out of range"), 0);
341 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
342
343 if (!IS_DRIVER_OK(pVirtio))
344 {
345 LogRelFunc(("Driver not ready\n"));
346 return 0;
347 }
348 if (!pVirtio->fLegacyDriver && !pVirtq->uEnable)
349 {
350 LogRelFunc(("virtq: %s not enabled\n", VIRTQNAME(pVirtio, uVirtq)));
351 return 0;
352 }
353 return virtioCoreVirtqAvailCnt(pDevIns, pVirtio, pVirtq);
354}
355
356#ifdef IN_RING3
357
358static void virtioCoreR3FeatureDump(VIRTIOCORE *pVirtio, PCDBGFINFOHLP pHlp, const VIRTIO_FEATURES_LIST *s_aFeatures, int cFeatures, int fBanner)
359{
360#define MAXLINE 80
361 /* Display as a single buf to prevent interceding log messages */
362 uint16_t cbBuf = cFeatures * 132;
363 char *pszBuf = (char *)RTMemAllocZ(cbBuf);
364 Assert(pszBuf);
365 char *cp = pszBuf;
366 for (int i = 0; i < cFeatures; ++i)
367 {
368 bool isOffered = RT_BOOL(pVirtio->uDeviceFeatures & s_aFeatures[i].fFeatureBit);
369 bool isNegotiated = RT_BOOL(pVirtio->uDriverFeatures & s_aFeatures[i].fFeatureBit);
370 cp += RTStrPrintf(cp, cbBuf - (cp - pszBuf), " %s %s %s",
371 isOffered ? "+" : "-", isNegotiated ? "x" : " ", s_aFeatures[i].pcszDesc);
372 }
373 if (pHlp) {
374 if (fBanner)
375 pHlp->pfnPrintf(pHlp, "VirtIO Features Configuration\n\n"
376 " Offered Accepted Feature Description\n"
377 " ------- -------- ------- -----------\n");
378 pHlp->pfnPrintf(pHlp, "%s\n", pszBuf);
379 }
380#ifdef LOG_ENABLED
381 else
382 {
383 if (fBanner)
384 Log(("VirtIO Features Configuration\n\n"
385 " Offered Accepted Feature Description\n"
386 " ------- -------- ------- -----------\n"));
387 Log(("%s\n", pszBuf));
388 }
389#endif
390 RTMemFree(pszBuf);
391}
392
393/** API Function: See header file*/
394DECLHIDDEN(void) virtioCorePrintDeviceFeatures(VIRTIOCORE *pVirtio, PCDBGFINFOHLP pHlp,
395 const VIRTIO_FEATURES_LIST *s_aDevSpecificFeatures, int cFeatures) {
396 virtioCoreR3FeatureDump(pVirtio, pHlp, s_aCoreFeatures, RT_ELEMENTS(s_aCoreFeatures), 1 /*fBanner */);
397 virtioCoreR3FeatureDump(pVirtio, pHlp, s_aDevSpecificFeatures, cFeatures, 0 /*fBanner */);
398}
399
400#endif
401
402#ifdef LOG_ENABLED
403
404/** API Function: See header file */
405DECLHIDDEN(void) virtioCoreHexDump(uint8_t *pv, uint32_t cb, uint32_t uBase, const char *pszTitle)
406{
407#define ADJCURSOR(cb) pszOut += cb; cbRemain -= cb;
408 size_t cbPrint = 0, cbRemain = ((cb / 16) + 1) * 80;
409 char *pszBuf = (char *)RTMemAllocZ(cbRemain), *pszOut = pszBuf;
410 AssertMsgReturnVoid(pszBuf, ("Out of Memory"));
411 if (pszTitle)
412 {
413 cbPrint = RTStrPrintf(pszOut, cbRemain, "%s [%d bytes]:\n", pszTitle, cb);
414 ADJCURSOR(cbPrint);
415 }
416 for (uint32_t row = 0; row < RT_MAX(1, (cb / 16) + 1) && row * 16 < cb; row++)
417 {
418 cbPrint = RTStrPrintf(pszOut, cbRemain, "%04x: ", row * 16 + uBase); /* line address */
419 ADJCURSOR(cbPrint);
420 for (uint8_t col = 0; col < 16; col++)
421 {
422 uint32_t idx = row * 16 + col;
423 if (idx >= cb)
424 cbPrint = RTStrPrintf(pszOut, cbRemain, "-- %s", (col + 1) % 8 ? "" : " ");
425 else
426 cbPrint = RTStrPrintf(pszOut, cbRemain, "%02x %s", pv[idx], (col + 1) % 8 ? "" : " ");
427 ADJCURSOR(cbPrint);
428 }
429 for (uint32_t idx = row * 16; idx < row * 16 + 16; idx++)
430 {
431 cbPrint = RTStrPrintf(pszOut, cbRemain, "%c", (idx >= cb) ? ' ' : (pv[idx] >= 0x20 && pv[idx] <= 0x7e ? pv[idx] : '.'));
432 ADJCURSOR(cbPrint);
433 }
434 *pszOut++ = '\n';
435 --cbRemain;
436 }
437 Log(("%s\n", pszBuf));
438 RTMemFree(pszBuf);
439 RT_NOREF2(uBase, pv);
440#undef ADJCURSOR
441}
442
443/* API FUnction: See header file */
444DECLHIDDEN(void) virtioCoreGCPhysHexDump(PPDMDEVINS pDevIns, RTGCPHYS GCPhys, uint16_t cb, uint32_t uBase, const char *pszTitle)
445{
446 PVIRTIOCORE pVirtio = PDMDEVINS_2_DATA(pDevIns, PVIRTIOCORE);
447#define ADJCURSOR(cb) pszOut += cb; cbRemain -= cb;
448 size_t cbPrint = 0, cbRemain = ((cb / 16) + 1) * 80;
449 char *pszBuf = (char *)RTMemAllocZ(cbRemain), *pszOut = pszBuf;
450 AssertMsgReturnVoid(pszBuf, ("Out of Memory"));
451 if (pszTitle)
452 {
453 cbPrint = RTStrPrintf(pszOut, cbRemain, "%s [%d bytes]:\n", pszTitle, cb);
454 ADJCURSOR(cbPrint);
455 }
456 for (uint16_t row = 0; row < (uint16_t)RT_MAX(1, (cb / 16) + 1) && row * 16 < cb; row++)
457 {
458 uint8_t c;
459 cbPrint = RTStrPrintf(pszOut, cbRemain, "%04x: ", row * 16 + uBase); /* line address */
460 ADJCURSOR(cbPrint);
461 for (uint8_t col = 0; col < 16; col++)
462 {
463 uint32_t idx = row * 16 + col;
464 virtioCoreGCPhysRead(pVirtio, pDevIns, GCPhys + idx, &c, 1);
465 if (idx >= cb)
466 cbPrint = RTStrPrintf(pszOut, cbRemain, "-- %s", (col + 1) % 8 ? "" : " ");
467 else
468 cbPrint = RTStrPrintf(pszOut, cbRemain, "%02x %s", c, (col + 1) % 8 ? "" : " ");
469 ADJCURSOR(cbPrint);
470 }
471 for (uint16_t idx = row * 16; idx < row * 16 + 16; idx++)
472 {
473 virtioCoreGCPhysRead(pVirtio, pDevIns, GCPhys + idx, &c, 1);
474 cbPrint = RTStrPrintf(pszOut, cbRemain, "%c", (idx >= cb) ? ' ' : (c >= 0x20 && c <= 0x7e ? c : '.'));
475 ADJCURSOR(cbPrint);
476 }
477 *pszOut++ = '\n';
478 --cbRemain;
479 }
480 Log(("%s\n", pszBuf));
481 RTMemFree(pszBuf);
482 RT_NOREF(uBase);
483#undef ADJCURSOR
484}
485
486
487/** API function: See header file */
488DECLHIDDEN(void) virtioCoreLogMappedIoValue(const char *pszFunc, const char *pszMember, uint32_t uMemberSize,
489 const void *pv, uint32_t cb, uint32_t uOffset, int fWrite,
490 int fHasIndex, uint32_t idx)
491{
492 if (LogIs6Enabled())
493 {
494 char szIdx[16];
495 if (fHasIndex)
496 RTStrPrintf(szIdx, sizeof(szIdx), "[%d]", idx);
497 else
498 szIdx[0] = '\0';
499
500 if (cb == 1 || cb == 2 || cb == 4 || cb == 8)
501 {
502 char szDepiction[64];
503 size_t cchDepiction;
504 if (uOffset != 0 || cb != uMemberSize) /* display bounds if partial member access */
505 cchDepiction = RTStrPrintf(szDepiction, sizeof(szDepiction), "%s%s[%d:%d]",
506 pszMember, szIdx, uOffset, uOffset + cb - 1);
507 else
508 cchDepiction = RTStrPrintf(szDepiction, sizeof(szDepiction), "%s%s", pszMember, szIdx);
509
510 /* padding */
511 if (cchDepiction < 30)
512 szDepiction[cchDepiction++] = ' ';
513 while (cchDepiction < 30)
514 szDepiction[cchDepiction++] = '.';
515 szDepiction[cchDepiction] = '\0';
516
517 RTUINT64U uValue;
518 uValue.u = 0;
519 memcpy(uValue.au8, pv, cb);
520 Log6(("%-23s: Guest %s %s %#0*RX64\n",
521 pszFunc, fWrite ? "wrote" : "read ", szDepiction, 2 + cb * 2, uValue.u));
522 }
523 else /* odd number or oversized access, ... log inline hex-dump style */
524 {
525 Log6(("%-23s: Guest %s %s%s[%d:%d]: %.*Rhxs\n",
526 pszFunc, fWrite ? "wrote" : "read ", pszMember,
527 szIdx, uOffset, uOffset + cb, cb, pv));
528 }
529 }
530 RT_NOREF2(fWrite, pszFunc);
531}
532
533/**
534 * Log MMIO-mapped Virtio fDeviceStatus register bitmask, naming the bits
535 */
536DECLINLINE(void) virtioCoreFormatDeviceStatus(uint8_t bStatus, char *pszBuf, size_t uSize)
537{
538# define ADJCURSOR(len) { cp += len; uSize -= len; sep = (char *)" | "; }
539 memset(pszBuf, 0, uSize);
540 char *cp = pszBuf, *sep = (char *)"";
541 size_t len;
542 if (bStatus == 0)
543 RTStrPrintf(cp, uSize, "RESET");
544 else
545 {
546 if (bStatus & VIRTIO_STATUS_ACKNOWLEDGE)
547 {
548 len = RTStrPrintf(cp, uSize, "ACKNOWLEDGE");
549 ADJCURSOR(len);
550 }
551 if (bStatus & VIRTIO_STATUS_DRIVER)
552 {
553 len = RTStrPrintf(cp, uSize, "%sDRIVER", sep);
554 ADJCURSOR(len);
555 }
556 if (bStatus & VIRTIO_STATUS_FEATURES_OK)
557 {
558 len = RTStrPrintf(cp, uSize, "%sFEATURES_OK", sep);
559 ADJCURSOR(len);
560 }
561 if (bStatus & VIRTIO_STATUS_DRIVER_OK)
562 {
563 len = RTStrPrintf(cp, uSize, "%sDRIVER_OK", sep);
564 ADJCURSOR(len);
565 }
566 if (bStatus & VIRTIO_STATUS_FAILED)
567 {
568 len = RTStrPrintf(cp, uSize, "%sFAILED", sep);
569 ADJCURSOR(len);
570 }
571 if (bStatus & VIRTIO_STATUS_DEVICE_NEEDS_RESET)
572 RTStrPrintf(cp, uSize, "%sNEEDS_RESET", sep);
573 }
574# undef ADJCURSOR
575}
576
577#endif /* LOG_ENABLED */
578
579/** API function: See header file */
580DECLHIDDEN(int) virtioCoreIsLegacyMode(PVIRTIOCORE pVirtio)
581{
582 return pVirtio->fLegacyDriver;
583}
584
585#ifdef IN_RING3
586
587DECLHIDDEN(int) virtioCoreR3VirtqAttach(PVIRTIOCORE pVirtio, uint16_t uVirtq, const char *pcszName)
588{
589 LogFunc(("Attaching %s to VirtIO core\n", pcszName));
590 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
591 pVirtq->uVirtq = uVirtq;
592 pVirtq->fUsedRingEvent = false;
593 pVirtq->fAttached = true;
594 RTStrCopy(pVirtq->szName, sizeof(pVirtq->szName), pcszName);
595 return VINF_SUCCESS;
596}
597
598DECLHIDDEN(int) virtioCoreR3VirtqDetach(PVIRTIOCORE pVirtio, uint16_t uVirtqNbr)
599{
600 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtqNbr];
601 pVirtq->uVirtq = 0;
602 pVirtq->uAvailIdxShadow = 0;
603 pVirtq->uUsedIdxShadow = 0;
604 pVirtq->fUsedRingEvent = false;
605 pVirtq->fAttached = false;
606 memset(pVirtq->szName, 0, sizeof(pVirtq->szName));
607 return VINF_SUCCESS;
608}
609
610DECLHIDDEN(bool) virtioCoreR3VirtqIsAttached(PVIRTIOCORE pVirtio, uint16_t uVirtqNbr)
611{
612 return pVirtio->aVirtqueues[uVirtqNbr].fAttached;
613}
614
615DECLHIDDEN(bool) virtioCoreR3VirtqIsEnabled(PVIRTIOCORE pVirtio, uint16_t uVirtqNbr)
616{
617 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtqNbr];
618 return (bool)pVirtq->uEnable && pVirtq->GCPhysVirtqDesc;
619}
620
621/** API Fuunction: See header file */
622DECLHIDDEN(void) virtioCoreR3VirtqInfo(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs, int uVirtq)
623{
624 RT_NOREF(pszArgs);
625 PVIRTIOCORE pVirtio = PDMDEVINS_2_DATA(pDevIns, PVIRTIOCORE);
626 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
627
628 /** @todo add ability to dump physical contents described by any descriptor (using existing VirtIO core API function) */
629// bool fDump = pszArgs && (*pszArgs == 'd' || *pszArgs == 'D'); /* "dump" (avail phys descriptor)"
630
631 uint16_t uAvailIdx = virtioReadAvailRingIdx(pDevIns, pVirtio, pVirtq);
632 uint16_t uAvailIdxShadow = pVirtq->uAvailIdxShadow;
633
634 uint16_t uUsedIdx = virtioReadUsedRingIdx(pDevIns, pVirtio, pVirtq);
635 uint16_t uUsedIdxShadow = pVirtq->uUsedIdxShadow;
636
637 VIRTQBUF_T VirtqBuf;
638 PVIRTQBUF pVirtqBuf = &VirtqBuf;
639 bool fEmpty = IS_VIRTQ_EMPTY(pDevIns, pVirtio, pVirtq);
640
641 LogFunc(("%s, empty = %s\n", pVirtq->szName, fEmpty ? "true" : "false"));
642
643 int cSendSegs = 0, cReturnSegs = 0;
644 if (!fEmpty)
645 {
646 virtioCoreR3VirtqAvailBufPeek(pDevIns, pVirtio, uVirtq, pVirtqBuf);
647 cSendSegs = pVirtqBuf->pSgPhysSend ? pVirtqBuf->pSgPhysSend->cSegs : 0;
648 cReturnSegs = pVirtqBuf->pSgPhysReturn ? pVirtqBuf->pSgPhysReturn->cSegs : 0;
649 }
650
651 bool fAvailNoInterrupt = virtioReadAvailRingFlags(pDevIns, pVirtio, pVirtq) & VIRTQ_AVAIL_F_NO_INTERRUPT;
652 bool fUsedNoNotify = virtioReadUsedRingFlags(pDevIns, pVirtio, pVirtq) & VIRTQ_USED_F_NO_NOTIFY;
653
654 pHlp->pfnPrintf(pHlp, " queue enabled: ........... %s\n", pVirtq->uEnable ? "true" : "false");
655 pHlp->pfnPrintf(pHlp, " size: .................... %d\n", pVirtq->uQueueSize);
656 pHlp->pfnPrintf(pHlp, " notify offset: ........... %d\n", pVirtq->uNotifyOffset);
657 if (pVirtio->fMsiSupport)
658 pHlp->pfnPrintf(pHlp, " MSIX vector: ....... %4.4x\n", pVirtq->uMsixVector);
659 pHlp->pfnPrintf(pHlp, "\n");
660 pHlp->pfnPrintf(pHlp, " avail ring (%d entries):\n", uAvailIdx - uAvailIdxShadow);
661 pHlp->pfnPrintf(pHlp, " index: ................ %d\n", uAvailIdx);
662 pHlp->pfnPrintf(pHlp, " shadow: ............... %d\n", uAvailIdxShadow);
663 pHlp->pfnPrintf(pHlp, " flags: ................ %s\n", fAvailNoInterrupt ? "NO_INTERRUPT" : "");
664 pHlp->pfnPrintf(pHlp, "\n");
665 pHlp->pfnPrintf(pHlp, " used ring (%d entries):\n", uUsedIdx - uUsedIdxShadow);
666 pHlp->pfnPrintf(pHlp, " index: ................ %d\n", uUsedIdx);
667 pHlp->pfnPrintf(pHlp, " shadow: ............... %d\n", uUsedIdxShadow);
668 pHlp->pfnPrintf(pHlp, " flags: ................ %s\n", fUsedNoNotify ? "NO_NOTIFY" : "");
669 pHlp->pfnPrintf(pHlp, "\n");
670 if (!fEmpty)
671 {
672 pHlp->pfnPrintf(pHlp, " desc chain:\n");
673 pHlp->pfnPrintf(pHlp, " head idx: ............. %d\n", uUsedIdx);
674 pHlp->pfnPrintf(pHlp, " segs: ................. %d\n", cSendSegs + cReturnSegs);
675 pHlp->pfnPrintf(pHlp, " refCnt ................ %d\n", pVirtqBuf->cRefs);
676 pHlp->pfnPrintf(pHlp, "\n");
677 pHlp->pfnPrintf(pHlp, " host-to-guest (%d bytes):\n", pVirtqBuf->cbPhysSend);
678 pHlp->pfnPrintf(pHlp, " segs: .............. %d\n", cSendSegs);
679 if (cSendSegs)
680 {
681 pHlp->pfnPrintf(pHlp, " index: ............. %d\n", pVirtqBuf->pSgPhysSend->idxSeg);
682 pHlp->pfnPrintf(pHlp, " unsent ............. %d\n", pVirtqBuf->pSgPhysSend->cbSegLeft);
683 }
684 pHlp->pfnPrintf(pHlp, "\n");
685 pHlp->pfnPrintf(pHlp, " guest-to-host (%d bytes)\n", pVirtqBuf->cbPhysReturn);
686 pHlp->pfnPrintf(pHlp, " segs: .............. %d\n", cReturnSegs);
687 if (cReturnSegs)
688 {
689 pHlp->pfnPrintf(pHlp, " index: ............. %d\n", pVirtqBuf->pSgPhysReturn->idxSeg);
690 pHlp->pfnPrintf(pHlp, " unsent ............. %d\n", pVirtqBuf->pSgPhysReturn->cbSegLeft);
691 }
692 } else
693 pHlp->pfnPrintf(pHlp, " No desc chains available\n");
694 pHlp->pfnPrintf(pHlp, "\n");
695}
696
697
698/** API Function: See header file */
699DECLHIDDEN(PVIRTQBUF) virtioCoreR3VirtqBufAlloc(void)
700{
701 PVIRTQBUF pVirtqBuf = (PVIRTQBUF)RTMemAllocZ(sizeof(VIRTQBUF_T));
702 AssertReturn(pVirtqBuf, NULL);
703 pVirtqBuf->u32Magic = VIRTQBUF_MAGIC;
704 pVirtqBuf->cRefs = 1;
705 return pVirtqBuf;
706}
707
708
709/** API Function: See header file */
710DECLHIDDEN(uint32_t) virtioCoreR3VirtqBufRetain(PVIRTQBUF pVirtqBuf)
711{
712 AssertReturn(pVirtqBuf, UINT32_MAX);
713 AssertReturn(pVirtqBuf->u32Magic == VIRTQBUF_MAGIC, UINT32_MAX);
714 uint32_t cRefs = ASMAtomicIncU32(&pVirtqBuf->cRefs);
715 Assert(cRefs > 1);
716 Assert(cRefs < 16);
717 return cRefs;
718}
719
720/** API Function: See header file */
721DECLHIDDEN(uint32_t) virtioCoreR3VirtqBufRelease(PVIRTIOCORE pVirtio, PVIRTQBUF pVirtqBuf)
722{
723 if (!pVirtqBuf)
724 return 0;
725 AssertReturn(pVirtqBuf, 0);
726 AssertReturn(pVirtqBuf->u32Magic == VIRTQBUF_MAGIC, 0);
727 uint32_t cRefs = ASMAtomicDecU32(&pVirtqBuf->cRefs);
728 Assert(cRefs < 16);
729 if (cRefs == 0)
730 {
731 pVirtqBuf->u32Magic = ~VIRTQBUF_MAGIC;
732 RTMemFree(pVirtqBuf);
733#ifdef VBOX_WITH_STATISTICS
734 STAM_REL_COUNTER_INC(&pVirtio->StatDescChainsFreed);
735#endif
736 }
737 RT_NOREF(pVirtio);
738 return cRefs;
739}
740
741/** API Function: See header file */
742DECLHIDDEN(void) virtioCoreNotifyConfigChanged(PVIRTIOCORE pVirtio)
743{
744 virtioNudgeGuest(pVirtio->pDevInsR3, pVirtio, VIRTIO_ISR_DEVICE_CONFIG, pVirtio->uMsixConfig);
745}
746
747
748/** API Function: See header file */
749DECLHIDDEN(void) virtioCoreVirtqEnableNotify(PVIRTIOCORE pVirtio, uint16_t uVirtq, bool fEnable)
750{
751 Assert(uVirtq < RT_ELEMENTS(pVirtio->aVirtqueues));
752 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
753
754 if (IS_DRIVER_OK(pVirtio))
755 {
756 uint16_t fFlags = virtioReadUsedRingFlags(pVirtio->pDevInsR3, pVirtio, pVirtq);
757
758 if (fEnable)
759 fFlags &= ~VIRTQ_USED_F_NO_NOTIFY;
760 else
761 fFlags |= VIRTQ_USED_F_NO_NOTIFY;
762
763 virtioWriteUsedRingFlags(pVirtio->pDevInsR3, pVirtio, pVirtq, fFlags);
764 }
765}
766
767/** API function: See Header file */
768DECLHIDDEN(void) virtioCoreResetAll(PVIRTIOCORE pVirtio)
769{
770 LogFunc(("\n"));
771 pVirtio->fDeviceStatus |= VIRTIO_STATUS_DEVICE_NEEDS_RESET;
772 if (IS_DRIVER_OK(pVirtio))
773 {
774 if (!pVirtio->fLegacyDriver)
775 pVirtio->fGenUpdatePending = true;
776 virtioNudgeGuest(pVirtio->pDevInsR3, pVirtio, VIRTIO_ISR_DEVICE_CONFIG, pVirtio->uMsixConfig);
777 }
778}
779
780/** API function: See Header file */
781DECLHIDDEN(int) virtioCoreR3VirtqAvailBufPeek(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtq, PVIRTQBUF pVirtqBuf)
782{
783 return virtioCoreR3VirtqAvailBufGet(pDevIns, pVirtio, uVirtq, pVirtqBuf, false);
784}
785
786
787/** API function: See Header file */
788DECLHIDDEN(int) virtioCoreR3VirtqAvailBufNext(PVIRTIOCORE pVirtio, uint16_t uVirtq)
789{
790 Assert(uVirtq < RT_ELEMENTS(pVirtio->aVirtqueues));
791 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
792
793 if (!pVirtio->fLegacyDriver)
794 AssertMsgReturn((pVirtio->fDeviceStatus & VIRTIO_STATUS_DRIVER_OK) && pVirtq->uEnable,
795 ("Guest driver not in ready state.\n"), VERR_INVALID_STATE);
796
797 if (IS_VIRTQ_EMPTY(pVirtio->pDevInsR3, pVirtio, pVirtq))
798 return VERR_NOT_AVAILABLE;
799
800 Log6Func(("%s avail shadow idx: %u\n", pVirtq->szName, pVirtq->uAvailIdxShadow));
801 pVirtq->uAvailIdxShadow++;
802
803 return VINF_SUCCESS;
804}
805
806/** API Function: See header file */
807DECLHIDDEN(int) virtioCoreR3VirtqAvailBufGet(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtq,
808 uint16_t uHeadIdx, PVIRTQBUF pVirtqBuf)
809{
810 AssertMsgReturn(uVirtq < RT_ELEMENTS(pVirtio->aVirtqueues),
811 ("uVirtq out of range"), VERR_INVALID_PARAMETER);
812
813 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
814
815 if (!pVirtio->fLegacyDriver)
816 AssertMsgReturn((pVirtio->fDeviceStatus & VIRTIO_STATUS_DRIVER_OK) && pVirtq->uEnable,
817 ("Guest driver not in ready state.\n"), VERR_INVALID_STATE);
818
819 uint16_t uDescIdx = uHeadIdx;
820
821 Log6Func(("%s DESC CHAIN: (head idx = %u)\n", pVirtio->aVirtqueues[uVirtq].szName, uHeadIdx));
822
823 /*
824 * Allocate and initialize the descriptor chain structure.
825 */
826 pVirtqBuf->u32Magic = VIRTQBUF_MAGIC;
827 pVirtqBuf->cRefs = 1;
828 pVirtqBuf->uHeadIdx = uHeadIdx;
829 pVirtqBuf->uVirtq = uVirtq;
830
831 /*
832 * Gather segments.
833 */
834 VIRTQ_DESC_T desc;
835
836 uint32_t cbIn = 0;
837 uint32_t cbOut = 0;
838 uint32_t cSegsIn = 0;
839 uint32_t cSegsOut = 0;
840
841 PVIRTIOSGSEG paSegsIn = pVirtqBuf->aSegsIn;
842 PVIRTIOSGSEG paSegsOut = pVirtqBuf->aSegsOut;
843
844 do
845 {
846 PVIRTIOSGSEG pSeg;
847 /*
848 * Malicious guests may go beyond paSegsIn or paSegsOut boundaries by linking
849 * several descriptors into a loop. Since there is no legitimate way to get a sequences of
850 * linked descriptors exceeding the total number of descriptors in the ring (see @bugref{8620}),
851 * the following aborts I/O if breach and employs a simple log throttling algorithm to notify.
852 */
853 if (cSegsIn + cSegsOut >= pVirtq->uQueueSize)
854 {
855 static volatile uint32_t s_cMessages = 0;
856 static volatile uint32_t s_cThreshold = 1;
857 if (ASMAtomicIncU32(&s_cMessages) == ASMAtomicReadU32(&s_cThreshold))
858 {
859 LogRelMax(64, ("Too many linked descriptors; check if the guest arranges descriptors in a loop (cSegsIn=%u cSegsOut=%u uQueueSize=%u).\n",
860 cSegsIn, cSegsOut, pVirtq->uQueueSize));
861 if (ASMAtomicReadU32(&s_cMessages) != 1)
862 LogRelMax(64, ("(the above error has occured %u times so far)\n", ASMAtomicReadU32(&s_cMessages)));
863 ASMAtomicWriteU32(&s_cThreshold, ASMAtomicReadU32(&s_cThreshold) * 10);
864 }
865 break;
866 }
867 /* Check if the limit has been reached for input chain (see section 2.4.4.1 of virtio 1.0 spec). */
868 if (cSegsIn >= RT_ELEMENTS(pVirtqBuf->aSegsIn))
869 {
870 LogRelMax(64, ("Too many input descriptors (cSegsIn=%u).\n", cSegsIn));
871 break;
872 }
873 /* Check if the limit has been reached for output chain (see section 2.4.4.1 of virtio 1.0 spec). */
874 if (cSegsOut >= RT_ELEMENTS(pVirtqBuf->aSegsOut))
875 {
876 LogRelMax(64, ("Too many output descriptors (cSegsOut=%u).\n", cSegsOut));
877 break;
878 }
879 RT_UNTRUSTED_VALIDATED_FENCE();
880
881 virtioReadDesc(pDevIns, pVirtio, pVirtq, uDescIdx, &desc);
882
883 if (desc.fFlags & VIRTQ_DESC_F_WRITE)
884 {
885 Log6Func(("%s IN idx=%-4u seg=%-3u addr=%RGp cb=%u\n", pVirtq->szName, uDescIdx, cSegsIn, desc.GCPhysBuf, desc.cb));
886 cbIn += desc.cb;
887 pSeg = &paSegsIn[cSegsIn++];
888 }
889 else
890 {
891 Log6Func(("%s OUT desc_idx=%-4u seg=%-3u addr=%RGp cb=%u\n", pVirtq->szName, uDescIdx, cSegsOut, desc.GCPhysBuf, desc.cb));
892 cbOut += desc.cb;
893 pSeg = &paSegsOut[cSegsOut++];
894#ifdef DEEP_DEBUG
895 if (LogIs11Enabled())
896 {
897 virtioCoreGCPhysHexDump(pDevIns, desc.GCPhysBuf, desc.cb, 0, NULL);
898 Log(("\n"));
899 }
900#endif
901 }
902 pSeg->GCPhys = desc.GCPhysBuf;
903 pSeg->cbSeg = desc.cb;
904 uDescIdx = desc.uDescIdxNext;
905 } while (desc.fFlags & VIRTQ_DESC_F_NEXT);
906
907 /*
908 * Add segments to the descriptor chain structure.
909 */
910 if (cSegsIn)
911 {
912 virtioCoreGCPhysChainInit(&pVirtqBuf->SgBufIn, paSegsIn, cSegsIn);
913 pVirtqBuf->pSgPhysReturn = &pVirtqBuf->SgBufIn;
914 pVirtqBuf->cbPhysReturn = cbIn;
915#ifdef VBOX_WITH_STATISTICS
916 STAM_REL_COUNTER_ADD(&pVirtio->StatDescChainsSegsIn, cSegsIn);
917#endif
918 }
919
920 if (cSegsOut)
921 {
922 virtioCoreGCPhysChainInit(&pVirtqBuf->SgBufOut, paSegsOut, cSegsOut);
923 pVirtqBuf->pSgPhysSend = &pVirtqBuf->SgBufOut;
924 pVirtqBuf->cbPhysSend = cbOut;
925#ifdef VBOX_WITH_STATISTICS
926 STAM_REL_COUNTER_ADD(&pVirtio->StatDescChainsSegsOut, cSegsOut);
927#endif
928 }
929
930#ifdef VBOX_WITH_STATISTICS
931 STAM_REL_COUNTER_INC(&pVirtio->StatDescChainsAllocated);
932#endif
933 Log6Func(("%s -- segs OUT: %u (%u bytes) IN: %u (%u bytes) --\n",
934 pVirtq->szName, cSegsOut, cbOut, cSegsIn, cbIn));
935
936 return VINF_SUCCESS;
937}
938
939/** API function: See Header file */
940DECLHIDDEN(int) virtioCoreR3VirtqAvailBufGet(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtq,
941 PVIRTQBUF pVirtqBuf, bool fRemove)
942{
943 Assert(uVirtq < RT_ELEMENTS(pVirtio->aVirtqueues));
944 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
945
946 if (IS_VIRTQ_EMPTY(pDevIns, pVirtio, pVirtq))
947 return VERR_NOT_AVAILABLE;
948
949 uint16_t uHeadIdx = virtioReadAvailDescIdx(pDevIns, pVirtio, pVirtq, pVirtq->uAvailIdxShadow);
950
951 if (pVirtio->uDriverFeatures & VIRTIO_F_EVENT_IDX)
952 virtioWriteUsedAvailEvent(pDevIns,pVirtio, pVirtq, pVirtq->uAvailIdxShadow + 1);
953
954 if (fRemove)
955 pVirtq->uAvailIdxShadow++;
956
957 return virtioCoreR3VirtqAvailBufGet(pDevIns, pVirtio, uVirtq, uHeadIdx, pVirtqBuf);
958}
959
960/** API function: See Header file */
961DECLHIDDEN(int) virtioCoreR3VirtqUsedBufPut(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtq, PRTSGBUF pSgVirtReturn,
962 PVIRTQBUF pVirtqBuf, bool fFence)
963{
964 Assert(uVirtq < RT_ELEMENTS(pVirtio->aVirtqueues));
965 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
966
967 PVIRTIOSGBUF pSgPhysReturn = pVirtqBuf->pSgPhysReturn;
968
969 Assert(pVirtqBuf->u32Magic == VIRTQBUF_MAGIC);
970 Assert(pVirtqBuf->cRefs > 0);
971
972 /*
973 * Workaround for a bug in FreeBSD's virtio-net driver up until 12.3 which supports only the legacy style devive.
974 * When the device is re-initialized from the driver it violates the spec and posts commands to the control queue
975 * before setting the DRIVER_OK flag, breaking the following check and rendering the device non-functional.
976 * The queues are properly set up at this stage however so no real harm is done and we can safely continue here,
977 * for the legacy device only of course after making sure the queue is properly set up.
978 */
979 AssertMsgReturn( IS_DRIVER_OK(pVirtio)
980 || ( pVirtio->fLegacyDriver
981 && pVirtq->GCPhysVirtqDesc),
982 ("Guest driver not in ready state.\n"), VERR_INVALID_STATE);
983
984 Log6Func((" Copying device data to %s, [desc:%u -> used ring:%u]\n",
985 VIRTQNAME(pVirtio, uVirtq), pVirtqBuf->uHeadIdx, pVirtq->uUsedIdxShadow));
986
987 /* Copy s/g buf (virtual memory) to guest phys mem (VirtIO "IN" direction). */
988
989 size_t cbCopy = 0, cbTotal = 0, cbRemain = 0;
990
991 if (pSgVirtReturn)
992 {
993 size_t cbTarget = virtioCoreGCPhysChainCalcBufSize(pSgPhysReturn);
994 cbRemain = cbTotal = RTSgBufCalcTotalLength(pSgVirtReturn);
995 AssertMsgReturn(cbTarget >= cbRemain, ("No space to write data to phys memory"), VERR_BUFFER_OVERFLOW);
996 virtioCoreGCPhysChainReset(pSgPhysReturn);
997 while (cbRemain)
998 {
999 cbCopy = RT_MIN(pSgVirtReturn->cbSegLeft, pSgPhysReturn->cbSegLeft);
1000 AssertReturn(cbCopy > 0, VERR_INVALID_PARAMETER);
1001 virtioCoreGCPhysWrite(pVirtio, pDevIns, (RTGCPHYS)pSgPhysReturn->GCPhysCur, pSgVirtReturn->pvSegCur, cbCopy);
1002 RTSgBufAdvance(pSgVirtReturn, cbCopy);
1003 virtioCoreGCPhysChainAdvance(pSgPhysReturn, cbCopy);
1004 cbRemain -= cbCopy;
1005 }
1006
1007 if (fFence)
1008 RT_UNTRUSTED_NONVOLATILE_COPY_FENCE(); /* needed? */
1009
1010 Assert(!(cbCopy >> 32));
1011 }
1012
1013 /* Flag if write-ahead crosses threshold where guest driver indicated it wants event notification */
1014 if (pVirtio->uDriverFeatures & VIRTIO_F_EVENT_IDX)
1015 if (pVirtq->uUsedIdxShadow == virtioReadAvailUsedEvent(pDevIns, pVirtio, pVirtq))
1016 pVirtq->fUsedRingEvent = true;
1017
1018 /*
1019 * Place used buffer's descriptor in used ring but don't update used ring's slot index.
1020 * That will be done with a subsequent client call to virtioCoreVirtqUsedRingSync()
1021 *
1022 * @todo r=aeichner: The increment of the shadow index is not atomic but this code can be called
1023 * concurrently!!
1024 */
1025 virtioWriteUsedElem(pDevIns, pVirtio, pVirtq, pVirtq->uUsedIdxShadow++, pVirtqBuf->uHeadIdx, (uint32_t)cbTotal);
1026
1027#ifdef LOG_ENABLED
1028 if (LogIs6Enabled() && pSgVirtReturn)
1029 {
1030
1031 LogFunc((" ... %d segs, %zu bytes, copied to %u byte buf@offset=%u. Residual: %zu bytes\n",
1032 pSgVirtReturn->cSegs, cbTotal - cbRemain, pVirtqBuf->cbPhysReturn,
1033 ((virtioCoreGCPhysChainCalcBufSize(pVirtqBuf->pSgPhysReturn) -
1034 virtioCoreGCPhysChainCalcLengthLeft(pVirtqBuf->pSgPhysReturn)) - (cbTotal - cbRemain)),
1035 virtioCoreGCPhysChainCalcLengthLeft(pVirtqBuf->pSgPhysReturn) ));
1036
1037 uint16_t uPending = virtioCoreR3CountPendingBufs(
1038 virtioReadUsedRingIdx(pDevIns, pVirtio, pVirtq),
1039 pVirtq->uUsedIdxShadow, pVirtq->uQueueSize);
1040
1041 LogFunc((" %u used buf%s not synced in %s\n", uPending, uPending == 1 ? "" : "s ",
1042 VIRTQNAME(pVirtio, uVirtq)));
1043 }
1044#endif
1045 return VINF_SUCCESS;
1046}
1047
1048/** API function: See Header file */
1049DECLHIDDEN(int) virtioCoreR3VirtqUsedBufPut(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtq,
1050 size_t cb, void const *pv, PVIRTQBUF pVirtqBuf, size_t cbEnqueue, bool fFence)
1051{
1052 Assert(uVirtq < RT_ELEMENTS(pVirtio->aVirtqueues));
1053 Assert(pv);
1054
1055 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
1056 PVIRTIOSGBUF pSgPhysReturn = pVirtqBuf->pSgPhysReturn;
1057
1058 Assert(pVirtqBuf->u32Magic == VIRTQBUF_MAGIC);
1059 Assert(pVirtqBuf->cRefs > 0);
1060
1061 AssertMsgReturn(IS_DRIVER_OK(pVirtio), ("Guest driver not in ready state.\n"), VERR_INVALID_STATE);
1062
1063 Log6Func((" Copying device data to %s, [desc chain head idx:%u]\n",
1064 VIRTQNAME(pVirtio, uVirtq), pVirtqBuf->uHeadIdx));
1065 /*
1066 * Convert virtual memory simple buffer to guest physical memory (VirtIO descriptor chain)
1067 */
1068 uint8_t *pvBuf = (uint8_t *)pv;
1069 size_t cbRemain = cb, cbCopy = 0;
1070 while (cbRemain)
1071 {
1072 cbCopy = RT_MIN(pSgPhysReturn->cbSegLeft, cbRemain);
1073 Assert(cbCopy > 0);
1074 virtioCoreGCPhysWrite(pVirtio, pDevIns, (RTGCPHYS)pSgPhysReturn->GCPhysCur, pvBuf, cbCopy);
1075 virtioCoreGCPhysChainAdvance(pSgPhysReturn, cbCopy);
1076 pvBuf += cbCopy;
1077 cbRemain -= cbCopy;
1078 }
1079 LogFunc((" ...%zu bytes, copied to %u byte buf@offset=%u. Residual: %zu bytes\n",
1080 cb , pVirtqBuf->cbPhysReturn,
1081 ((virtioCoreGCPhysChainCalcBufSize(pVirtqBuf->pSgPhysReturn) -
1082 virtioCoreGCPhysChainCalcLengthLeft(pVirtqBuf->pSgPhysReturn)) - cb),
1083 virtioCoreGCPhysChainCalcLengthLeft(pVirtqBuf->pSgPhysReturn)));
1084
1085 if (cbEnqueue)
1086 {
1087 if (fFence)
1088 {
1089 RT_UNTRUSTED_NONVOLATILE_COPY_FENCE(); /* needed? */
1090 Assert(!(cbCopy >> 32));
1091 }
1092 /* Flag if write-ahead crosses threshold where guest driver indicated it wants event notification */
1093 if (pVirtio->uDriverFeatures & VIRTIO_F_EVENT_IDX)
1094 if (pVirtq->uUsedIdxShadow == virtioReadAvailUsedEvent(pDevIns, pVirtio, pVirtq))
1095 pVirtq->fUsedRingEvent = true;
1096 /*
1097 * Place used buffer's descriptor in used ring but don't update used ring's slot index.
1098 * That will be done with a subsequent client call to virtioCoreVirtqUsedRingSync()
1099 */
1100 Log6Func((" Enqueue desc chain head idx %u to %s used ring @ %u\n", pVirtqBuf->uHeadIdx,
1101 VIRTQNAME(pVirtio, uVirtq), pVirtq->uUsedIdxShadow));
1102
1103 virtioWriteUsedElem(pDevIns, pVirtio, pVirtq, pVirtq->uUsedIdxShadow++, pVirtqBuf->uHeadIdx, (uint32_t)cbEnqueue);
1104
1105#ifdef LOG_ENABLED
1106 if (LogIs6Enabled())
1107 {
1108 uint16_t uPending = virtioCoreR3CountPendingBufs(
1109 virtioReadUsedRingIdx(pDevIns, pVirtio, pVirtq),
1110 pVirtq->uUsedIdxShadow, pVirtq->uQueueSize);
1111
1112 LogFunc((" %u used buf%s not synced in %s\n",
1113 uPending, uPending == 1 ? "" : "s ", VIRTQNAME(pVirtio, uVirtq)));
1114 }
1115#endif
1116 } /* fEnqueue */
1117
1118 return VINF_SUCCESS;
1119}
1120
1121
1122#endif /* IN_RING3 */
1123
1124/** API function: See Header file */
1125DECLHIDDEN(int) virtioCoreVirtqUsedRingSync(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtq)
1126{
1127 Assert(uVirtq < RT_ELEMENTS(pVirtio->aVirtqueues));
1128 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
1129
1130 if (!pVirtio->fLegacyDriver)
1131 AssertMsgReturn((pVirtio->fDeviceStatus & VIRTIO_STATUS_DRIVER_OK) && pVirtq->uEnable,
1132 ("Guest driver not in ready state.\n"), VERR_INVALID_STATE);
1133
1134 Log6Func((" Sync %s used ring (%u -> idx)\n",
1135 pVirtq->szName, pVirtq->uUsedIdxShadow));
1136
1137 virtioWriteUsedRingIdx(pDevIns, pVirtio, pVirtq, pVirtq->uUsedIdxShadow);
1138 virtioCoreNotifyGuestDriver(pDevIns, pVirtio, uVirtq);
1139
1140 return VINF_SUCCESS;
1141}
1142
1143/**
1144 * This is called from the MMIO callback code when the guest does an MMIO access to the
1145 * mapped queue notification capability area corresponding to a particular queue, to notify
1146 * the queue handler of available data in the avail ring of the queue (VirtIO 1.0, 4.1.4.4.1)
1147 *
1148 * @param pDevIns The device instance.
1149 * @param pVirtio Pointer to the shared virtio state.
1150 * @param uVirtq Virtq to check for guest interrupt handling preference
1151 * @param uNotifyIdx Notification index
1152 */
1153static void virtioCoreVirtqNotified(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtq, uint16_t uNotifyIdx)
1154{
1155 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
1156
1157 /* VirtIO 1.0, section 4.1.5.2 implies uVirtq and uNotifyIdx should match. Disregarding any of
1158 * these notifications (if those indicies disagree) may break device/driver synchronization,
1159 * causing eternal throughput starvation, yet there's no specified way to disambiguate
1160 * which queue to wake-up in any awkward situation where the two parameters differ.
1161 */
1162 AssertMsg(uNotifyIdx == uVirtq,
1163 ("Guest kicked virtq %d's notify addr w/non-corresponding virtq idx %d\n",
1164 uVirtq, uNotifyIdx));
1165 RT_NOREF(uNotifyIdx);
1166
1167 AssertReturnVoid(uVirtq < RT_ELEMENTS(pVirtio->aVirtqueues));
1168 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
1169
1170 Log6Func(("%s: (desc chains: %u)\n", *pVirtq->szName ? pVirtq->szName : "?UNAMED QUEUE?",
1171 virtioCoreVirtqAvailCnt(pDevIns, pVirtio, pVirtq)));
1172
1173 /* Inform client */
1174 pVirtioCC->pfnVirtqNotified(pDevIns, pVirtio, uVirtq);
1175 RT_NOREF2(pVirtio, pVirtq);
1176}
1177
1178/**
1179 * Trigger MSI-X or INT# interrupt to notify guest of data added to used ring of
1180 * the specified virtq, depending on the interrupt configuration of the device
1181 * and depending on negotiated and realtime constraints flagged by the guest driver.
1182 *
1183 * See VirtIO 1.0 specification (section 2.4.7).
1184 *
1185 * @param pDevIns The device instance.
1186 * @param pVirtio Pointer to the shared virtio state.
1187 * @param uVirtq Virtq to check for guest interrupt handling preference
1188 */
1189static void virtioCoreNotifyGuestDriver(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t uVirtq)
1190{
1191 Assert(uVirtq < RT_ELEMENTS(pVirtio->aVirtqueues));
1192 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
1193
1194 if (!IS_DRIVER_OK(pVirtio))
1195 {
1196 LogFunc(("Guest driver not in ready state.\n"));
1197 return;
1198 }
1199
1200 if (pVirtio->uDriverFeatures & VIRTIO_F_EVENT_IDX)
1201 {
1202 if (pVirtq->fUsedRingEvent)
1203 {
1204#ifdef IN_RING3
1205 Log6Func(("...kicking guest %s, VIRTIO_F_EVENT_IDX set and threshold (%d) reached\n",
1206 pVirtq->szName, (uint16_t)virtioReadAvailUsedEvent(pDevIns, pVirtio, pVirtq)));
1207#endif
1208 virtioNudgeGuest(pDevIns, pVirtio, VIRTIO_ISR_VIRTQ_INTERRUPT, pVirtq->uMsixVector);
1209 pVirtq->fUsedRingEvent = false;
1210 return;
1211 }
1212#ifdef IN_RING3
1213 Log6Func(("...skip interrupt %s, VIRTIO_F_EVENT_IDX set but threshold (%d) not reached (%d)\n",
1214 pVirtq->szName,(uint16_t)virtioReadAvailUsedEvent(pDevIns, pVirtio, pVirtq), pVirtq->uUsedIdxShadow));
1215#endif
1216 }
1217 else
1218 {
1219 /** If guest driver hasn't suppressed interrupts, interrupt */
1220 if (!(virtioReadAvailRingFlags(pDevIns, pVirtio, pVirtq) & VIRTQ_AVAIL_F_NO_INTERRUPT))
1221 {
1222 virtioNudgeGuest(pDevIns, pVirtio, VIRTIO_ISR_VIRTQ_INTERRUPT, pVirtq->uMsixVector);
1223 return;
1224 }
1225 Log6Func(("...skipping interrupt for %s (guest set VIRTQ_AVAIL_F_NO_INTERRUPT)\n", pVirtq->szName));
1226 }
1227}
1228
1229/**
1230 * Raise interrupt or MSI-X
1231 *
1232 * @param pDevIns The device instance.
1233 * @param pVirtio Pointer to the shared virtio state.
1234 * @param uCause Interrupt cause bit mask to set in PCI ISR port.
1235 * @param uVec MSI-X vector, if enabled
1236 */
1237static int virtioNudgeGuest(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint8_t uCause, uint16_t uMsixVector)
1238{
1239 if (uCause == VIRTIO_ISR_VIRTQ_INTERRUPT)
1240 Log6Func(("Reason for interrupt - buffer added to 'used' ring.\n"));
1241 else
1242 if (uCause == VIRTIO_ISR_DEVICE_CONFIG)
1243 Log6Func(("Reason for interrupt - device config change\n"));
1244
1245 if (pVirtio->uIrqMmio)
1246 {
1247 pVirtio->uISR |= uCause;
1248 PDMDevHlpISASetIrq(pDevIns, pVirtio->uIrqMmio, PDM_IRQ_LEVEL_HIGH);
1249 }
1250 else if (!pVirtio->fMsiSupport)
1251 {
1252 pVirtio->uISR |= uCause;
1253 PDMDevHlpPCISetIrq(pDevIns, 0, PDM_IRQ_LEVEL_HIGH);
1254 }
1255 else if (uMsixVector != VIRTIO_MSI_NO_VECTOR)
1256 PDMDevHlpPCISetIrq(pDevIns, uMsixVector, 1);
1257 return VINF_SUCCESS;
1258}
1259
1260/**
1261 * Lower interrupt (Called when guest reads ISR and when resetting)
1262 *
1263 * @param pDevIns The device instance.
1264 */
1265static void virtioLowerInterrupt(PPDMDEVINS pDevIns, uint16_t uMsixVector)
1266{
1267 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
1268 if (pVirtio->uIrqMmio)
1269 PDMDevHlpISASetIrq(pDevIns, pVirtio->uIrqMmio, PDM_IRQ_LEVEL_LOW);
1270 else if (!pVirtio->fMsiSupport)
1271 PDMDevHlpPCISetIrq(pDevIns, 0, PDM_IRQ_LEVEL_LOW);
1272 else if (uMsixVector != VIRTIO_MSI_NO_VECTOR)
1273 PDMDevHlpPCISetIrq(pDevIns, pVirtio->uMsixConfig, PDM_IRQ_LEVEL_LOW);
1274}
1275
1276#ifdef IN_RING3
1277static void virtioResetVirtq(PVIRTIOCORE pVirtio, uint16_t uVirtq)
1278{
1279 Assert(uVirtq < RT_ELEMENTS(pVirtio->aVirtqueues));
1280 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
1281
1282 pVirtq->uQueueSize = VIRTQ_SIZE;
1283 pVirtq->uEnable = false;
1284 pVirtq->uNotifyOffset = uVirtq;
1285 pVirtq->fUsedRingEvent = false;
1286 pVirtq->uAvailIdxShadow = 0;
1287 pVirtq->uUsedIdxShadow = 0;
1288 pVirtq->uMsixVector = uVirtq + 2;
1289
1290 if (!pVirtio->fMsiSupport) /* VirtIO 1.0, 4.1.4.3 and 4.1.5.1.2 */
1291 pVirtq->uMsixVector = VIRTIO_MSI_NO_VECTOR;
1292
1293 virtioLowerInterrupt(pVirtio->pDevInsR3, pVirtq->uMsixVector);
1294}
1295
1296static void virtioResetDevice(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio)
1297{
1298 LogFunc(("Resetting device VirtIO state\n"));
1299 pVirtio->fLegacyDriver = pVirtio->fOfferLegacy; /* Cleared if VIRTIO_F_VERSION_1 feature ack'd */
1300 pVirtio->uDeviceFeaturesSelect = 0;
1301 pVirtio->uDriverFeaturesSelect = 0;
1302 pVirtio->uConfigGeneration = 0;
1303 pVirtio->fDeviceStatus = 0;
1304 pVirtio->uISR = 0;
1305
1306 if (!pVirtio->fMsiSupport)
1307 virtioLowerInterrupt(pDevIns, 0);
1308 else
1309 {
1310 virtioLowerInterrupt(pDevIns, pVirtio->uMsixConfig);
1311 for (int i = 0; i < VIRTQ_MAX_COUNT; i++)
1312 virtioLowerInterrupt(pDevIns, pVirtio->aVirtqueues[i].uMsixVector);
1313 }
1314
1315 if (!pVirtio->fMsiSupport) /* VirtIO 1.0, 4.1.4.3 and 4.1.5.1.2 */
1316 pVirtio->uMsixConfig = VIRTIO_MSI_NO_VECTOR;
1317
1318 for (uint16_t uVirtq = 0; uVirtq < VIRTQ_MAX_COUNT; uVirtq++)
1319 virtioResetVirtq(pVirtio, uVirtq);
1320}
1321
1322/**
1323 * Invoked by this implementation when guest driver resets the device.
1324 * The driver itself will not until the device has read the status change.
1325 */
1326static void virtioGuestR3WasReset(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC)
1327{
1328 Log(("%-23s: Guest reset the device\n", __FUNCTION__));
1329
1330 /* Let the client know */
1331 pVirtioCC->pfnStatusChanged(pVirtio, pVirtioCC, 0 /* fDriverOk */);
1332 virtioResetDevice(pDevIns, pVirtio);
1333}
1334
1335DECLHIDDEN(void) virtioCoreR3ResetDevice(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC)
1336{
1337 virtioGuestR3WasReset(pDevIns, pVirtio, pVirtioCC);
1338}
1339#endif /* IN_RING3 */
1340
1341/*
1342 * Determines whether guest virtio driver is modern or legacy and does callback
1343 * informing device-specific code that feature negotiation is complete.
1344 * Should be called only once (coordinated via the 'toggle' flag)
1345 */
1346#ifdef IN_RING3
1347DECLINLINE(void) virtioR3DoFeaturesCompleteOnceOnly(PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC)
1348{
1349 if (pVirtio->uDriverFeatures & VIRTIO_F_VERSION_1)
1350 {
1351 LogFunc(("VIRTIO_F_VERSION_1 feature ack'd by guest\n"));
1352 pVirtio->fLegacyDriver = 0;
1353 }
1354 else
1355 {
1356 if (pVirtio->fOfferLegacy)
1357 {
1358 pVirtio->fLegacyDriver = 1;
1359 LogFunc(("VIRTIO_F_VERSION_1 feature was NOT set by guest\n"));
1360 }
1361 else
1362 AssertMsgFailed(("Guest didn't accept VIRTIO_F_VERSION_1, but fLegacyOffered flag not set.\n"));
1363 }
1364 if (pVirtioCC->pfnFeatureNegotiationComplete)
1365 pVirtioCC->pfnFeatureNegotiationComplete(pVirtio, pVirtio->uDriverFeatures, pVirtio->fLegacyDriver);
1366 pVirtio->fDriverFeaturesWritten |= DRIVER_FEATURES_COMPLETE_HANDLED;
1367}
1368#endif
1369
1370
1371/**
1372 * Handles a write to the device status register from the driver.
1373 *
1374 * @returns VBox status code
1375 *
1376 * @param pDevIns The device instance.
1377 * @param pVirtio Pointer to the shared virtio state.
1378 * @param pVirtioCC Pointer to the current context virtio state.
1379 * @param fDeviceStatus The device status to be written.
1380 */
1381DECLINLINE(int) virtioDeviceStatusWrite(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC,
1382 uint8_t fDeviceStatus)
1383{
1384 pVirtio->fDeviceStatus = fDeviceStatus;
1385 bool fDeviceReset = pVirtio->fDeviceStatus == 0;
1386#ifdef LOG_ENABLED
1387 if (LogIs7Enabled())
1388 {
1389 char szOut[80] = { 0 };
1390 virtioCoreFormatDeviceStatus(pVirtio->fDeviceStatus, szOut, sizeof(szOut));
1391 Log(("%-23s: Guest wrote fDeviceStatus ................ (%s)\n", __FUNCTION__, szOut));
1392 }
1393#endif
1394 bool const fStatusChanged = IS_DRIVER_OK(pVirtio) != WAS_DRIVER_OK(pVirtio);
1395
1396 if (fDeviceReset || fStatusChanged)
1397 {
1398#ifdef IN_RING0
1399 /* Since VirtIO status changes are cumbersome by nature, e.g. not a benchmark priority,
1400 * handle the rest in R3 to facilitate logging or whatever dev-specific client needs to do */
1401 Log6(("%-23s: RING0 => RING3 (demote)\n", __FUNCTION__));
1402 return VINF_IOM_R3_MMIO_WRITE;
1403#endif
1404 }
1405
1406#ifdef IN_RING3
1407 /*
1408 * Notify client only if status actually changed from last time and when we're reset.
1409 */
1410 if (fDeviceReset)
1411 virtioGuestR3WasReset(pDevIns, pVirtio, pVirtioCC);
1412
1413 if (fStatusChanged)
1414 pVirtioCC->pfnStatusChanged(pVirtio, pVirtioCC, IS_DRIVER_OK(pVirtio));
1415#else
1416 RT_NOREF(pDevIns, pVirtioCC);
1417#endif
1418 /*
1419 * Save the current status for the next write so we can see what changed.
1420 */
1421 pVirtio->fPrevDeviceStatus = pVirtio->fDeviceStatus;
1422 return VINF_SUCCESS;
1423}
1424
1425
1426/**
1427 * Handles a read from the device status register from the driver.
1428 *
1429 * @returns The device status register value.
1430 *
1431 * @param pVirtio Pointer to the shared virtio state.
1432 */
1433DECLINLINE(uint8_t) virtioDeviceStatusRead(PVIRTIOCORE pVirtio)
1434{
1435#ifdef LOG_ENABLED
1436 if (LogIs7Enabled())
1437 {
1438 char szOut[80] = { 0 };
1439 virtioCoreFormatDeviceStatus(pVirtio->fDeviceStatus, szOut, sizeof(szOut));
1440 LogFunc(("Guest read fDeviceStatus ................ (%s)\n", szOut));
1441 }
1442#endif
1443 return pVirtio->fDeviceStatus;
1444}
1445
1446
1447/**
1448 * Handle accesses to Common Configuration capability
1449 *
1450 * @returns VBox status code
1451 *
1452 * @param pDevIns The device instance.
1453 * @param pVirtio Pointer to the shared virtio state.
1454 * @param pVirtioCC Pointer to the current context virtio state.
1455 * @param fWrite Set if write access, clear if read access.
1456 * @param uOffsetOfAccess The common configuration capability offset.
1457 * @param cb Number of bytes to read or write
1458 * @param pv Pointer to location to write to or read from
1459 */
1460static int virtioCommonCfgAccessed(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC,
1461 int fWrite, uint32_t uOffsetOfAccess, unsigned cb, void *pv)
1462{
1463 uint16_t uVirtq = pVirtio->uVirtqSelect;
1464 int rc = VINF_SUCCESS;
1465 uint64_t val;
1466 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(uDeviceFeatures, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1467 {
1468 if (fWrite) /* Guest WRITE pCommonCfg>uDeviceFeatures */
1469 {
1470 /* VirtIO 1.0, 4.1.4.3 states device_feature is a (guest) driver readonly field,
1471 * yet the linux driver attempts to write/read it back twice */
1472 VIRTIO_DEV_CONFIG_LOG_ACCESS(uDeviceFeatures, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess);
1473 LogFunc(("... WARNING: Guest attempted to write readonly virtio_pci_common_cfg.device_feature (ignoring)\n"));
1474 return VINF_IOM_MMIO_UNUSED_00;
1475 }
1476 else /* Guest READ pCommonCfg->uDeviceFeatures */
1477 {
1478 switch (pVirtio->uDeviceFeaturesSelect)
1479 {
1480 case 0:
1481 val = pVirtio->uDeviceFeatures & UINT32_C(0xffffffff);
1482 memcpy(pv, &val, cb);
1483 VIRTIO_DEV_CONFIG_LOG_ACCESS(uDeviceFeatures, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess);
1484 break;
1485 case 1:
1486 val = pVirtio->uDeviceFeatures >> 32;
1487 memcpy(pv, &val, cb);
1488 VIRTIO_DEV_CONFIG_LOG_ACCESS(uDeviceFeatures, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess + sizeof(uint32_t));
1489 break;
1490 default:
1491 LogFunc(("Guest read uDeviceFeatures with out of range selector (%#x), returning 0\n",
1492 pVirtio->uDeviceFeaturesSelect));
1493 return VINF_IOM_MMIO_UNUSED_00;
1494 }
1495 }
1496 }
1497 else
1498 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(uDriverFeatures, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1499 {
1500 if (fWrite) /* Guest WRITE pCommonCfg->udriverFeatures */
1501 {
1502 switch (pVirtio->uDriverFeaturesSelect)
1503 {
1504 case 0:
1505 memcpy(&pVirtio->uDriverFeatures, pv, cb);
1506 pVirtio->fDriverFeaturesWritten |= DRIVER_FEATURES_0_WRITTEN;
1507 LogFunc(("Set DRIVER_FEATURES_0_WRITTEN. pVirtio->fDriverFeaturesWritten=%d\n", pVirtio->fDriverFeaturesWritten));
1508 if ( (pVirtio->fDriverFeaturesWritten & DRIVER_FEATURES_0_AND_1_WRITTEN) == DRIVER_FEATURES_0_AND_1_WRITTEN
1509 && !(pVirtio->fDriverFeaturesWritten & DRIVER_FEATURES_COMPLETE_HANDLED))
1510#ifdef IN_RING0
1511 return VINF_IOM_R3_MMIO_WRITE;
1512#endif
1513#ifdef IN_RING3
1514 virtioR3DoFeaturesCompleteOnceOnly(pVirtio, pVirtioCC);
1515#endif
1516 VIRTIO_DEV_CONFIG_LOG_ACCESS(uDriverFeatures, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess);
1517 break;
1518 case 1:
1519 memcpy((char *)&pVirtio->uDriverFeatures + sizeof(uint32_t), pv, cb);
1520 pVirtio->fDriverFeaturesWritten |= DRIVER_FEATURES_1_WRITTEN;
1521 LogFunc(("Set DRIVER_FEATURES_1_WRITTEN. pVirtio->fDriverFeaturesWritten=%d\n", pVirtio->fDriverFeaturesWritten));
1522 if ( (pVirtio->fDriverFeaturesWritten & DRIVER_FEATURES_0_AND_1_WRITTEN) == DRIVER_FEATURES_0_AND_1_WRITTEN
1523 && !(pVirtio->fDriverFeaturesWritten & DRIVER_FEATURES_COMPLETE_HANDLED))
1524#ifdef IN_RING0
1525 return VINF_IOM_R3_MMIO_WRITE;
1526#endif
1527#ifdef IN_RING3
1528 virtioR3DoFeaturesCompleteOnceOnly(pVirtio, pVirtioCC);
1529#endif
1530 VIRTIO_DEV_CONFIG_LOG_ACCESS(uDriverFeatures, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess + sizeof(uint32_t));
1531 break;
1532 default:
1533 LogFunc(("Guest wrote uDriverFeatures with out of range selector (%#x), returning 0\n",
1534 pVirtio->uDriverFeaturesSelect));
1535 return VINF_SUCCESS;
1536 }
1537 }
1538 else /* Guest READ pCommonCfg->udriverFeatures */
1539 {
1540 switch (pVirtio->uDriverFeaturesSelect)
1541 {
1542 case 0:
1543 val = pVirtio->uDriverFeatures & 0xffffffff;
1544 memcpy(pv, &val, cb);
1545 VIRTIO_DEV_CONFIG_LOG_ACCESS(uDriverFeatures, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess);
1546 break;
1547 case 1:
1548 val = (pVirtio->uDriverFeatures >> 32) & 0xffffffff;
1549 memcpy(pv, &val, cb);
1550 VIRTIO_DEV_CONFIG_LOG_ACCESS(uDriverFeatures, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess + 4);
1551 break;
1552 default:
1553 LogFunc(("Guest read uDriverFeatures with out of range selector (%#x), returning 0\n",
1554 pVirtio->uDriverFeaturesSelect));
1555 return VINF_IOM_MMIO_UNUSED_00;
1556 }
1557 }
1558 }
1559 else
1560 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(uNumVirtqs, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1561 {
1562 if (fWrite)
1563 {
1564 Log2Func(("Guest attempted to write readonly virtio_pci_common_cfg.num_queues\n"));
1565 return VINF_SUCCESS;
1566 }
1567 *(uint16_t *)pv = VIRTQ_MAX_COUNT;
1568 VIRTIO_DEV_CONFIG_LOG_ACCESS(uNumVirtqs, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess);
1569 }
1570 else
1571 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(fDeviceStatus, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1572 {
1573 if (fWrite) /* Guest WRITE pCommonCfg->fDeviceStatus */
1574 rc = virtioDeviceStatusWrite(pDevIns, pVirtio, pVirtioCC, *(uint8_t *)pv);
1575 else /* Guest READ pCommonCfg->fDeviceStatus */
1576 *(uint8_t *)pv = virtioDeviceStatusRead(pVirtio);
1577 }
1578 else
1579 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMsixConfig, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1580 VIRTIO_DEV_CONFIG_ACCESS( uMsixConfig, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess, pVirtio);
1581 else
1582 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uDeviceFeaturesSelect, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1583 VIRTIO_DEV_CONFIG_ACCESS( uDeviceFeaturesSelect, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess, pVirtio);
1584 else
1585 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uDriverFeaturesSelect, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1586 VIRTIO_DEV_CONFIG_ACCESS( uDriverFeaturesSelect, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess, pVirtio);
1587 else
1588 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uConfigGeneration, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1589 VIRTIO_DEV_CONFIG_ACCESS( uConfigGeneration, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess, pVirtio);
1590 else
1591 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uVirtqSelect, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1592 {
1593 if (fWrite) {
1594 uint16_t uVirtqNew = *(uint16_t *)pv;
1595
1596 if (uVirtqNew < RT_ELEMENTS(pVirtio->aVirtqueues))
1597 VIRTIO_DEV_CONFIG_ACCESS( uVirtqSelect, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess, pVirtio);
1598 else
1599 LogFunc(("... WARNING: Guest attempted to write invalid virtq selector (ignoring)\n"));
1600 }
1601 else
1602 VIRTIO_DEV_CONFIG_ACCESS( uVirtqSelect, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess, pVirtio);
1603 }
1604 else
1605 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( GCPhysVirtqDesc, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1606 VIRTIO_DEV_CONFIG_ACCESS_INDEXED( GCPhysVirtqDesc, uVirtq, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess, pVirtio->aVirtqueues);
1607 else
1608 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( GCPhysVirtqAvail, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1609 VIRTIO_DEV_CONFIG_ACCESS_INDEXED( GCPhysVirtqAvail, uVirtq, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess, pVirtio->aVirtqueues);
1610 else
1611 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( GCPhysVirtqUsed, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1612 VIRTIO_DEV_CONFIG_ACCESS_INDEXED( GCPhysVirtqUsed, uVirtq, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess, pVirtio->aVirtqueues);
1613 else
1614 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uQueueSize, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1615 VIRTIO_DEV_CONFIG_ACCESS_INDEXED( uQueueSize, uVirtq, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess, pVirtio->aVirtqueues);
1616 else
1617 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uEnable, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1618 VIRTIO_DEV_CONFIG_ACCESS_INDEXED( uEnable, uVirtq, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess, pVirtio->aVirtqueues);
1619 else
1620 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uNotifyOffset, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1621 VIRTIO_DEV_CONFIG_ACCESS_INDEXED( uNotifyOffset, uVirtq, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess, pVirtio->aVirtqueues);
1622 else
1623 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMsixVector, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess))
1624 VIRTIO_DEV_CONFIG_ACCESS_INDEXED( uMsixVector, uVirtq, VIRTIO_PCI_COMMON_CFG_T, uOffsetOfAccess, pVirtio->aVirtqueues);
1625 else
1626 {
1627 Log2Func(("Bad guest %s access to virtio_pci_common_cfg: uOffsetOfAccess=%#x (%d), cb=%d\n",
1628 fWrite ? "write" : "read ", uOffsetOfAccess, uOffsetOfAccess, cb));
1629 return fWrite ? VINF_SUCCESS : VINF_IOM_MMIO_UNUSED_00;
1630 }
1631
1632#ifndef IN_RING3
1633 RT_NOREF(pDevIns, pVirtioCC);
1634#endif
1635 return rc;
1636}
1637
1638/**
1639 * @callback_method_impl{FNIOMIOPORTNEWIN)
1640 *
1641 * This I/O handler exists only to handle access from legacy drivers.
1642 */
1643static DECLCALLBACK(VBOXSTRICTRC) virtioLegacyIOPortIn(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT offPort, uint32_t *pu32, unsigned cb)
1644{
1645 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
1646 STAM_PROFILE_ADV_START(&pVirtio->CTX_SUFF(StatRead), a);
1647
1648 RT_NOREF(pvUser);
1649 Log(("%-23s: Port read at offset=%RTiop, cb=%#x%s",
1650 __FUNCTION__, offPort, cb,
1651 VIRTIO_DEV_CONFIG_MATCH_MEMBER(fIsrStatus, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort) ? "" : "\n"));
1652
1653 void *pv = pu32; /* To use existing macros */
1654 int fWrite = 0; /* To use existing macros */
1655
1656 uint16_t uVirtq = pVirtio->uVirtqSelect;
1657
1658 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(uDeviceFeatures, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1659 {
1660 uint32_t val = pVirtio->uDeviceFeatures & UINT32_C(0xffffffff);
1661 memcpy(pu32, &val, cb);
1662 VIRTIO_DEV_CONFIG_LOG_ACCESS(uDeviceFeatures, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort);
1663 }
1664 else
1665 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(uDriverFeatures, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1666 {
1667 uint32_t val = pVirtio->uDriverFeatures & UINT32_C(0xffffffff);
1668 memcpy(pu32, &val, cb);
1669 VIRTIO_DEV_CONFIG_LOG_ACCESS(uDriverFeatures, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort);
1670 }
1671 else
1672 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(fDeviceStatus, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1673 {
1674 *(uint8_t *)pu32 = pVirtio->fDeviceStatus;
1675#ifdef LOG_ENABLED
1676 if (LogIs7Enabled())
1677 {
1678 char szOut[80] = { 0 };
1679 virtioCoreFormatDeviceStatus(pVirtio->fDeviceStatus, szOut, sizeof(szOut));
1680 Log(("%-23s: Guest read fDeviceStatus ................ (%s)\n", __FUNCTION__, szOut));
1681 }
1682#endif
1683 }
1684 else
1685 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(fIsrStatus, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1686 {
1687 ASSERT_GUEST_MSG(cb == 1, ("%d\n", cb));
1688 *(uint8_t *)pu32 = pVirtio->uISR;
1689 pVirtio->uISR = 0;
1690 virtioLowerInterrupt( pDevIns, 0);
1691 Log((" (ISR read and cleared)\n"));
1692 }
1693 else
1694 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uVirtqSelect, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1695 VIRTIO_DEV_CONFIG_ACCESS( uVirtqSelect, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort, pVirtio);
1696 else
1697 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uVirtqPfn, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1698 {
1699 PVIRTQUEUE pVirtQueue = &pVirtio->aVirtqueues[uVirtq];
1700 *pu32 = pVirtQueue->GCPhysVirtqDesc >> GUEST_PAGE_SHIFT;
1701 Log(("%-23s: Guest read uVirtqPfn .................... %#x\n", __FUNCTION__, *pu32));
1702 }
1703 else
1704 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uQueueSize, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1705 VIRTIO_DEV_CONFIG_ACCESS_INDEXED( uQueueSize, uVirtq, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort, pVirtio->aVirtqueues);
1706 else
1707 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uQueueNotify, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1708 VIRTIO_DEV_CONFIG_ACCESS( uQueueNotify, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort, pVirtio);
1709#ifdef LEGACY_MSIX_SUPPORTED
1710 else
1711 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMsixConfig, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1712 VIRTIO_DEV_CONFIG_ACCESS( uMsixConfig, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort, pVirtio);
1713 else
1714 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMsixVector, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1715 VIRTIO_DEV_CONFIG_ACCESS_INDEXED( uMsixVector, uVirtq, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort, pVirtio->aVirtqueues);
1716#endif
1717 else if (offPort >= sizeof(VIRTIO_LEGACY_PCI_COMMON_CFG_T))
1718 {
1719 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatRead), a);
1720#ifdef IN_RING3
1721 /* Access device-specific configuration */
1722 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
1723 int rc = pVirtioCC->pfnDevCapRead(pDevIns, offPort - sizeof(VIRTIO_LEGACY_PCI_COMMON_CFG_T), pv, cb);
1724 return rc;
1725#else
1726 return VINF_IOM_R3_IOPORT_READ;
1727#endif
1728 }
1729 else
1730 {
1731 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatRead), a);
1732 Log2Func(("Bad guest read access to virtio_legacy_pci_common_cfg: offset=%#x, cb=%x\n",
1733 offPort, cb));
1734 int rc = PDMDevHlpDBGFStop(pDevIns, RT_SRC_POS,
1735 "virtioLegacyIOPortIn: no valid port at offset offset=%RTiop cb=%#x\n", offPort, cb);
1736 return rc;
1737 }
1738 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatRead), a);
1739 return VINF_SUCCESS;
1740}
1741
1742/**
1743 * @callback_method_impl{ * @callback_method_impl{FNIOMIOPORTNEWOUT}
1744 *
1745 * This I/O Port interface exists only to handle access from legacy drivers.
1746 */
1747static DECLCALLBACK(VBOXSTRICTRC) virtioLegacyIOPortOut(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT offPort, uint32_t u32, unsigned cb)
1748{
1749 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
1750 STAM_PROFILE_ADV_START(&pVirtio->CTX_SUFF(StatWrite), a);
1751 RT_NOREF(pvUser);
1752
1753 uint16_t uVirtq = pVirtio->uVirtqSelect;
1754 uint32_t u32OnStack = u32; /* allows us to use this impl's MMIO parsing macros */
1755 void *pv = &u32OnStack; /* To use existing macros */
1756 int fWrite = 1; /* To use existing macros */
1757
1758 Log(("%-23s: Port written at offset=%RTiop, cb=%#x, u32=%#x\n", __FUNCTION__, offPort, cb, u32));
1759
1760 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uVirtqSelect, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1761 {
1762 if (u32 < RT_ELEMENTS(pVirtio->aVirtqueues))
1763 VIRTIO_DEV_CONFIG_ACCESS( uVirtqSelect, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort, pVirtio);
1764 else
1765 LogFunc(("... WARNING: Guest attempted to write invalid virtq selector (ignoring)\n"));
1766 }
1767 else
1768#ifdef LEGACY_MSIX_SUPPORTED
1769 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMsixConfig, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1770 VIRTIO_DEV_CONFIG_ACCESS( uMsixConfig, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort, pVirtio);
1771 else
1772 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER( uMsixVector, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1773 VIRTIO_DEV_CONFIG_ACCESS_INDEXED( uMsixVector, uVirtq, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort, pVirtio->aVirtqueues);
1774 else
1775#endif
1776 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(uDeviceFeatures, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1777 {
1778 /* Check to see if guest acknowledged unsupported features */
1779 VIRTIO_DEV_CONFIG_LOG_ACCESS(uDeviceFeatures, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort);
1780 LogFunc(("... WARNING: Guest attempted to write readonly virtio_pci_common_cfg.device_feature (ignoring)\n"));
1781 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatWrite), a);
1782 return VINF_SUCCESS;
1783 }
1784 else
1785 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(uDriverFeatures, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1786 {
1787 memcpy(&pVirtio->uDriverFeatures, pv, cb);
1788 if ((pVirtio->uDriverFeatures & ~VIRTIO_DEV_INDEPENDENT_LEGACY_FEATURES_OFFERED) == 0)
1789 {
1790 Log(("Guest asked for features host does not support! (host=%x guest=%x)\n",
1791 VIRTIO_DEV_INDEPENDENT_LEGACY_FEATURES_OFFERED, pVirtio->uDriverFeatures));
1792 pVirtio->uDriverFeatures &= VIRTIO_DEV_INDEPENDENT_LEGACY_FEATURES_OFFERED;
1793 }
1794 if (!(pVirtio->fDriverFeaturesWritten & DRIVER_FEATURES_COMPLETE_HANDLED))
1795 {
1796#ifdef IN_RING0
1797 Log6(("%-23s: RING0 => RING3 (demote)\n", __FUNCTION__));
1798 return VINF_IOM_R3_IOPORT_WRITE;
1799#endif
1800#ifdef IN_RING3
1801 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
1802 virtioR3DoFeaturesCompleteOnceOnly(pVirtio, pVirtioCC);
1803#endif
1804 }
1805 VIRTIO_DEV_CONFIG_LOG_ACCESS(uDriverFeatures, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort);
1806 }
1807 else
1808 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(uQueueSize, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1809 {
1810 VIRTIO_DEV_CONFIG_LOG_ACCESS(uQueueSize, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort);
1811 LogFunc(("... WARNING: Guest attempted to write readonly device_feature (queue size) (ignoring)\n"));
1812 return VINF_SUCCESS;
1813 }
1814 else
1815 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(fDeviceStatus, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1816 {
1817 bool const fDriverInitiatedReset = (pVirtio->fDeviceStatus = (uint8_t)u32) == 0;
1818 bool const fDriverStateImproved = IS_DRIVER_OK(pVirtio) && !WAS_DRIVER_OK(pVirtio);
1819#ifdef LOG_ENABLED
1820 if (LogIs7Enabled())
1821 {
1822 char szOut[80] = { 0 };
1823 virtioCoreFormatDeviceStatus(pVirtio->fDeviceStatus, szOut, sizeof(szOut));
1824 Log(("%-23s: Guest wrote fDeviceStatus ................ (%s)\n", __FUNCTION__, szOut));
1825 }
1826#endif
1827 if (fDriverStateImproved || fDriverInitiatedReset)
1828 {
1829#ifdef IN_RING0
1830 Log6(("%-23s: RING0 => RING3 (demote)\n", __FUNCTION__));
1831 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatWrite), a);
1832 return VINF_IOM_R3_IOPORT_WRITE;
1833#endif
1834 }
1835
1836#ifdef IN_RING3
1837 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
1838 if (fDriverInitiatedReset)
1839 virtioGuestR3WasReset(pDevIns, pVirtio, pVirtioCC);
1840
1841 else if (fDriverStateImproved)
1842 pVirtioCC->pfnStatusChanged(pVirtio, pVirtioCC, 1 /* fDriverOk */);
1843
1844#endif
1845 pVirtio->fPrevDeviceStatus = pVirtio->fDeviceStatus;
1846 }
1847 else
1848 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(uVirtqPfn, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1849 {
1850 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
1851 uint64_t uVirtqPfn = (uint64_t)u32;
1852
1853 if (uVirtqPfn)
1854 {
1855 /* Transitional devices calculate ring physical addresses using rigid spec-defined formulae,
1856 * instead of guest conveying respective address of each ring, as "modern" VirtIO drivers do,
1857 * thus there is no virtq PFN or single base queue address stored in instance data for
1858 * this transitional device, but rather it is derived, when read back, from GCPhysVirtqDesc */
1859
1860 pVirtq->GCPhysVirtqDesc = uVirtqPfn * VIRTIO_PAGE_SIZE;
1861 pVirtq->GCPhysVirtqAvail = pVirtq->GCPhysVirtqDesc + sizeof(VIRTQ_DESC_T) * pVirtq->uQueueSize;
1862 pVirtq->GCPhysVirtqUsed =
1863 RT_ALIGN(pVirtq->GCPhysVirtqAvail + RT_UOFFSETOF_DYN(VIRTQ_AVAIL_T, auRing[pVirtq->uQueueSize]), VIRTIO_PAGE_SIZE);
1864 }
1865 else
1866 {
1867 /* Don't set ring addresses for queue (to meaningless values), when guest resets the virtq's PFN */
1868 pVirtq->GCPhysVirtqDesc = 0;
1869 pVirtq->GCPhysVirtqAvail = 0;
1870 pVirtq->GCPhysVirtqUsed = 0;
1871 }
1872 Log(("%-23s: Guest wrote uVirtqPfn .................... %#x:\n"
1873 "%68s... %p -> GCPhysVirtqDesc\n%68s... %p -> GCPhysVirtqAvail\n%68s... %p -> GCPhysVirtqUsed\n",
1874 __FUNCTION__, u32, " ", pVirtq->GCPhysVirtqDesc, " ", pVirtq->GCPhysVirtqAvail, " ", pVirtq->GCPhysVirtqUsed));
1875 }
1876 else
1877 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(uQueueNotify, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1878 {
1879#ifdef IN_RING3
1880 ASSERT_GUEST_MSG(cb == 2, ("cb=%u\n", cb));
1881 pVirtio->uQueueNotify = u32 & 0xFFFF;
1882 if (uVirtq < VIRTQ_MAX_COUNT)
1883 {
1884 RT_UNTRUSTED_VALIDATED_FENCE();
1885
1886 /* Need to check that queue is configured. Legacy spec didn't have a queue enabled flag */
1887 if (pVirtio->aVirtqueues[pVirtio->uQueueNotify].GCPhysVirtqDesc)
1888 virtioCoreVirtqNotified(pDevIns, pVirtio, pVirtio->uQueueNotify, pVirtio->uQueueNotify /* uNotifyIdx */);
1889 else
1890 Log(("The queue (#%d) being notified has not been initialized.\n", pVirtio->uQueueNotify));
1891 }
1892 else
1893 Log(("Invalid queue number (%d)\n", pVirtio->uQueueNotify));
1894#else
1895 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatWrite), a);
1896 return VINF_IOM_R3_IOPORT_WRITE;
1897#endif
1898 }
1899 else
1900 if (VIRTIO_DEV_CONFIG_MATCH_MEMBER(fIsrStatus, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort))
1901 {
1902 VIRTIO_DEV_CONFIG_LOG_ACCESS( fIsrStatus, VIRTIO_LEGACY_PCI_COMMON_CFG_T, offPort);
1903 LogFunc(("... WARNING: Guest attempted to write readonly device_feature (ISR status) (ignoring)\n"));
1904 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatWrite), a);
1905 return VINF_SUCCESS;
1906 }
1907 else if (offPort >= sizeof(VIRTIO_LEGACY_PCI_COMMON_CFG_T))
1908 {
1909#ifdef IN_RING3
1910
1911 /* Access device-specific configuration */
1912 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
1913 return pVirtioCC->pfnDevCapWrite(pDevIns, offPort - sizeof(VIRTIO_LEGACY_PCI_COMMON_CFG_T), pv, cb);
1914#else
1915 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatWrite), a);
1916 return VINF_IOM_R3_IOPORT_WRITE;
1917#endif
1918 }
1919 else
1920 {
1921 Log2Func(("Bad guest write access to virtio_legacy_pci_common_cfg: offset=%#x, cb=0x%x\n",
1922 offPort, cb));
1923 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatWrite), a);
1924 int rc = PDMDevHlpDBGFStop(pDevIns, RT_SRC_POS,
1925 "virtioLegacyIOPortOut: no valid port at offset offset=%RTiop cb=0x%#x\n", offPort, cb);
1926 return rc;
1927 }
1928
1929 RT_NOREF(uVirtq);
1930 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatWrite), a);
1931 return VINF_SUCCESS;
1932}
1933
1934
1935/**
1936 * Read from the device specific configuration at the given offset.
1937 *
1938 * @returns VBox status code.
1939 * @param pDevIns
1940 */
1941DECLINLINE(VBOXSTRICTRC) virtioDeviceCfgRead(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC,
1942 uint32_t offDevCfg, void *pv, unsigned cb)
1943{
1944#ifdef IN_RING3
1945 /*
1946 * Callback to client to manage device-specific configuration.
1947 */
1948 VBOXSTRICTRC rcStrict = pVirtioCC->pfnDevCapRead(pDevIns, offDevCfg, pv, cb);
1949
1950 /*
1951 * Anytime any part of the dev-specific dev config (which this virtio core implementation sees
1952 * as a blob, and virtio dev-specific code separates into fields) is READ, it must be compared
1953 * for deltas from previous read to maintain a config gen. seq. counter (VirtIO 1.0, section 4.1.4.3.1)
1954 */
1955 bool fDevSpecificFieldChanged = RT_BOOL(memcmp(pVirtioCC->pbDevSpecificCfg + offDevCfg,
1956 pVirtioCC->pbPrevDevSpecificCfg + offDevCfg,
1957 RT_MIN(cb, pVirtioCC->cbDevSpecificCfg - offDevCfg)));
1958
1959 memcpy(pVirtioCC->pbPrevDevSpecificCfg, pVirtioCC->pbDevSpecificCfg, pVirtioCC->cbDevSpecificCfg);
1960
1961 if (pVirtio->fGenUpdatePending || fDevSpecificFieldChanged)
1962 {
1963 ++pVirtio->uConfigGeneration;
1964 Log6Func(("Bumped cfg. generation to %d because %s%s\n", pVirtio->uConfigGeneration,
1965 fDevSpecificFieldChanged ? "<dev cfg changed> " : "",
1966 pVirtio->fGenUpdatePending ? "<update was pending>" : ""));
1967 pVirtio->fGenUpdatePending = false;
1968 }
1969
1970 virtioLowerInterrupt(pDevIns, 0);
1971 return rcStrict;
1972#else
1973 RT_NOREF(pDevIns, pVirtio, pVirtioCC, offDevCfg, pv, cb);
1974 return VINF_IOM_R3_MMIO_READ;
1975#endif
1976}
1977
1978
1979/**
1980 * @callback_method_impl{FNIOMMMIONEWREAD,
1981 * Memory mapped I/O Handler for PCI Capabilities read operations.}
1982 *
1983 * This MMIO handler specifically supports the VIRTIO_PCI_CAP_PCI_CFG capability defined
1984 * in the VirtIO 1.0 specification, section 4.1.4.7, and as such is restricted to reads
1985 * of 1, 2 or 4 bytes, only.
1986 *
1987 */
1988static DECLCALLBACK(VBOXSTRICTRC) virtioMmioRead(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS off, void *pv, unsigned cb)
1989{
1990 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
1991 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
1992 AssertReturn(cb == 1 || cb == 2 || cb == 4, VINF_IOM_MMIO_UNUSED_FF);
1993 Assert(pVirtio == (PVIRTIOCORE)pvUser); RT_NOREF(pvUser);
1994
1995 STAM_PROFILE_ADV_START(&pVirtio->CTX_SUFF(StatRead), a);
1996
1997 VBOXSTRICTRC rcStrict;
1998 uint32_t uOffset;
1999 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, uOffset, pVirtio->LocDeviceCap))
2000 rcStrict = virtioDeviceCfgRead(pDevIns, pVirtio, pVirtioCC, uOffset, pv, cb);
2001 else if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, uOffset, pVirtio->LocCommonCfgCap))
2002 rcStrict = virtioCommonCfgAccessed(pDevIns, pVirtio, pVirtioCC, false /* fWrite */, uOffset, cb, pv);
2003 else if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, uOffset, pVirtio->LocIsrCap))
2004 {
2005 *(uint8_t *)pv = pVirtio->uISR;
2006 Log6Func(("Read and clear ISR\n"));
2007 pVirtio->uISR = 0; /* VirtIO spec requires reads of ISR to clear it */
2008 virtioLowerInterrupt(pDevIns, 0);
2009 rcStrict = VINF_SUCCESS;
2010 }
2011 else
2012 {
2013 ASSERT_GUEST_MSG_FAILED(("Bad read access to mapped capabilities region: off=%RGp cb=%u\n", off, cb));
2014 memset(pv, 0xFF, cb);
2015 rcStrict = PDMDevHlpDBGFStop(pDevIns, RT_SRC_POS,
2016 "virtioMmioRead: Bad MMIO access to capabilities, offset=%RTiop cb=%08x\n", off, cb);
2017 }
2018
2019 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatRead), a);
2020 return rcStrict;
2021}
2022
2023/**
2024 * @callback_method_impl{FNIOMMMIONEWREAD,
2025 * Memory mapped I/O Handler for PCI Capabilities write operations.}
2026 *
2027 * This MMIO handler specifically supports the VIRTIO_PCI_CAP_PCI_CFG capability defined
2028 * in the VirtIO 1.0 specification, section 4.1.4.7, and as such is restricted to writes
2029 * of 1, 2 or 4 bytes, only.
2030 */
2031static DECLCALLBACK(VBOXSTRICTRC) virtioMmioWrite(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS off, void const *pv, unsigned cb)
2032{
2033 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
2034 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
2035 AssertReturn(cb == 1 || cb == 2 || cb == 4, VERR_INVALID_PARAMETER);
2036 Assert(pVirtio == (PVIRTIOCORE)pvUser); RT_NOREF(pvUser);
2037 STAM_PROFILE_ADV_START(&pVirtio->CTX_SUFF(StatWrite), a);
2038
2039 VBOXSTRICTRC rcStrict;
2040 uint32_t uOffset;
2041 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, uOffset, pVirtio->LocDeviceCap))
2042 {
2043#ifdef IN_RING3
2044 /*
2045 * Foreward this MMIO write access for client to deal with.
2046 */
2047 rcStrict = pVirtioCC->pfnDevCapWrite(pDevIns, uOffset, pv, cb);
2048#else
2049 Log6(("%-23s: RING0 => RING3 (demote)\n", __FUNCTION__));
2050 rcStrict = VINF_IOM_R3_MMIO_WRITE;
2051#endif
2052 }
2053 else if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, uOffset, pVirtio->LocCommonCfgCap))
2054 rcStrict = virtioCommonCfgAccessed(pDevIns, pVirtio, pVirtioCC, true /* fWrite */, uOffset, cb, (void *)pv);
2055 else if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, uOffset, pVirtio->LocIsrCap) && cb == sizeof(uint8_t))
2056 {
2057 pVirtio->uISR = *(uint8_t *)pv;
2058 Log6Func(("Setting uISR = 0x%02x (virtq interrupt: %d, dev confg interrupt: %d)\n",
2059 pVirtio->uISR & 0xff,
2060 pVirtio->uISR & VIRTIO_ISR_VIRTQ_INTERRUPT,
2061 RT_BOOL(pVirtio->uISR & VIRTIO_ISR_DEVICE_CONFIG)));
2062 rcStrict = VINF_SUCCESS;
2063 }
2064 else if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, uOffset, pVirtio->LocNotifyCap) && cb == sizeof(uint16_t))
2065 {
2066 /* This *should* be guest driver dropping index of a new descriptor in avail ring */
2067 virtioCoreVirtqNotified(pDevIns, pVirtio, uOffset / VIRTIO_NOTIFY_OFFSET_MULTIPLIER, *(uint16_t *)pv);
2068 rcStrict = VINF_SUCCESS;
2069 }
2070 else
2071 {
2072 ASSERT_GUEST_MSG_FAILED(("Bad write access to mapped capabilities region: off=%RGp pv=%#p{%.*Rhxs} cb=%u\n", off, pv, cb, pv, cb));
2073 rcStrict = PDMDevHlpDBGFStop(pDevIns, RT_SRC_POS,
2074 "virtioMmioRead: Bad MMIO access to capabilities, offset=%RTiop cb=%08x\n", off, cb);
2075 }
2076
2077 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatWrite), a);
2078 return rcStrict;
2079}
2080
2081
2082/**
2083 * @callback_method_impl{FNIOMMMIONEWREAD,
2084 * Memory mapped I/O Handler for Virtio over MMIO read operations.}
2085 *
2086 */
2087static DECLCALLBACK(VBOXSTRICTRC) virtioMmioTransportRead(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS off, void *pv, unsigned cb)
2088{
2089 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
2090 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
2091 RT_NOREF(pvUser);
2092 STAM_PROFILE_ADV_START(&pVirtio->CTX_SUFF(StatRead), a);
2093
2094 if (off >= VIRTIO_MMIO_SIZE)
2095 {
2096 VBOXSTRICTRC rcStrict = virtioDeviceCfgRead(pDevIns, pVirtio, pVirtioCC, (uint32_t)off - VIRTIO_MMIO_SIZE, pv, cb);
2097 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatRead), a);
2098 return rcStrict;
2099 }
2100
2101 /* All accesses below need to be aligned on a 32-bit boundary and must be 32-bit in size. */
2102 ASSERT_GUEST_MSG_RETURN(!(off & 0x3) && cb == sizeof(uint32_t),
2103 ("Bad read access: off=%RGp pv=%#p{%.*Rhxs} cb=%u\n", off, pv, cb, pv, cb),
2104 VINF_IOM_MMIO_UNUSED_FF);
2105
2106 int rc = VINF_SUCCESS;
2107 uint32_t *pu32 = (uint32_t *)pv;
2108 switch (off)
2109 {
2110 case VIRTIO_MMIO_REG_MAGIC_OFF:
2111 *pu32 = RT_H2LE_U32(VIRTIO_MMIO_REG_MAGIC_VALUE);
2112 break;
2113 case VIRTIO_MMIO_REG_VERSION_OFF:
2114 *pu32 = RT_H2LE_U32(VIRTIO_MMIO_REG_VERSION_VALUE);
2115 break;
2116 case VIRTIO_MMIO_REG_DEVICEID_OFF:
2117 *pu32 = pVirtio->uDeviceType;
2118 break;
2119 case VIRTIO_MMIO_REG_VENDORID_OFF:
2120 *pu32 = RT_H2LE_U32(DEVICE_PCI_VENDOR_ID_VIRTIO);
2121 break;
2122 case VIRTIO_MMIO_REG_DEVICEFEAT_OFF:
2123 {
2124 switch (pVirtio->uDeviceFeaturesSelect)
2125 {
2126 case 0:
2127 *pu32 = pVirtio->uDeviceFeatures & UINT32_C(0xffffffff);
2128 break;
2129 case 1:
2130 *pu32 = pVirtio->uDeviceFeatures >> 32;
2131 break;
2132 default:
2133 LogFunc(("Guest read uDeviceFeatures with out of range selector (%#x), returning 0\n",
2134 pVirtio->uDeviceFeaturesSelect));
2135 rc = VINF_IOM_MMIO_UNUSED_00;
2136 }
2137 break;
2138 }
2139 case VIRTIO_MMIO_REG_QUEUENUMMAX_OFF:
2140 *pu32 = VIRTQ_SIZE; /** @todo */
2141 break;
2142 case VIRTIO_MMIO_REG_QUEUERDY_OFF:
2143 {
2144 Assert(pVirtio->uVirtqSelect < RT_ELEMENTS(pVirtio->aVirtqueues));
2145 PVIRTQUEUE pVirtQueue = &pVirtio->aVirtqueues[pVirtio->uVirtqSelect];
2146 *pu32 = pVirtQueue->uEnable;
2147 break;
2148 }
2149 case VIRTIO_MMIO_REG_INTRSTATUS_OFF:
2150 *pu32 = pVirtio->uISR;
2151 break;
2152 case VIRTIO_MMIO_REG_DEVSTATUS_OFF:
2153 *pu32 = virtioDeviceStatusRead(pVirtio);
2154 break;
2155 case VIRTIO_MMIO_REG_CFGGEN_OFF:
2156 *pu32 = pVirtio->uConfigGeneration;
2157 break;
2158 default:
2159 ASSERT_GUEST_MSG_FAILED(("Bad read access to mapped capabilities region: off=%RGp cb=%u\n", off, cb));
2160 rc = PDMDevHlpDBGFStop(pDevIns, RT_SRC_POS,
2161 "virtioMmioTransportRead: Bad MMIO access to capabilities, offset=%RTiop cb=%08x\n", off, cb);
2162 }
2163
2164 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatRead), a);
2165 return rc;
2166}
2167
2168/**
2169 * @callback_method_impl{FNIOMMMIONEWREAD,
2170 * Memory mapped I/O Handler for Virtio over MMIO write operations.}
2171 */
2172static DECLCALLBACK(VBOXSTRICTRC) virtioMmioTransportWrite(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS off, void const *pv, unsigned cb)
2173{
2174 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
2175 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
2176 RT_NOREF(pvUser);
2177 STAM_PROFILE_ADV_START(&pVirtio->CTX_SUFF(StatWrite), a);
2178
2179 if (off >= VIRTIO_MMIO_SIZE)
2180 {
2181#ifdef IN_RING3
2182 /*
2183 * Forward this MMIO write access for client to deal with.
2184 */
2185 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatWrite), a);
2186 return pVirtioCC->pfnDevCapWrite(pDevIns, (uint32_t)off - VIRTIO_MMIO_SIZE, pv, cb);
2187#else
2188 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatWrite), a);
2189 Log6(("%-23s: RING0 => RING3 (demote)\n", __FUNCTION__));
2190 return VINF_IOM_R3_MMIO_WRITE;
2191#endif
2192 }
2193
2194 /* All accesses below need to be aligned on a 32-bit boundary and must be 32-bit in size. */
2195 ASSERT_GUEST_MSG_RETURN(!(off & 0x3) && cb == sizeof(uint32_t),
2196 ("Bad write access: off=%RGp pv=%#p{%.*Rhxs} cb=%u\n", off, pv, cb, pv, cb),
2197 VINF_SUCCESS);
2198
2199 int rc = VINF_SUCCESS;
2200 uint32_t const u32Val = *(const uint32_t *)pv;
2201 switch (off)
2202 {
2203 case VIRTIO_MMIO_REG_DEVICEFEATSEL_OFF:
2204 {
2205 pVirtio->uDeviceFeaturesSelect = u32Val;
2206 break;
2207 }
2208 case VIRTIO_MMIO_REG_DRIVERFEAT_OFF:
2209 {
2210 switch (pVirtio->uDriverFeaturesSelect)
2211 {
2212 case 0:
2213 pVirtio->uDriverFeatures = (pVirtio->uDriverFeatures & UINT64_C(0xffffffff00000000)) | u32Val;
2214 pVirtio->fDriverFeaturesWritten |= DRIVER_FEATURES_0_WRITTEN;
2215 LogFunc(("Set DRIVER_FEATURES_0_WRITTEN. pVirtio->fDriverFeaturesWritten=%d\n", pVirtio->fDriverFeaturesWritten));
2216 if ( (pVirtio->fDriverFeaturesWritten & DRIVER_FEATURES_0_AND_1_WRITTEN) == DRIVER_FEATURES_0_AND_1_WRITTEN
2217 && !(pVirtio->fDriverFeaturesWritten & DRIVER_FEATURES_COMPLETE_HANDLED))
2218#ifdef IN_RING0
2219 return VINF_IOM_R3_MMIO_WRITE;
2220#endif
2221#ifdef IN_RING3
2222 virtioR3DoFeaturesCompleteOnceOnly(pVirtio, pVirtioCC);
2223#endif
2224 break;
2225 case 1:
2226 pVirtio->uDriverFeatures = (pVirtio->uDriverFeatures & UINT64_C(0x00000000ffffffff)) | ((uint64_t)u32Val << 32);
2227 pVirtio->fDriverFeaturesWritten |= DRIVER_FEATURES_1_WRITTEN;
2228 LogFunc(("Set DRIVER_FEATURES_1_WRITTEN. pVirtio->fDriverFeaturesWritten=%d\n", pVirtio->fDriverFeaturesWritten));
2229 if ( (pVirtio->fDriverFeaturesWritten & DRIVER_FEATURES_0_AND_1_WRITTEN) == DRIVER_FEATURES_0_AND_1_WRITTEN
2230 && !(pVirtio->fDriverFeaturesWritten & DRIVER_FEATURES_COMPLETE_HANDLED))
2231#ifdef IN_RING0
2232 return VINF_IOM_R3_MMIO_WRITE;
2233#endif
2234#ifdef IN_RING3
2235 virtioR3DoFeaturesCompleteOnceOnly(pVirtio, pVirtioCC);
2236#endif
2237 break;
2238 default:
2239 LogFunc(("Guest wrote uDriverFeatures with out of range selector (%#x), returning 0\n",
2240 pVirtio->uDriverFeaturesSelect));
2241 return VINF_SUCCESS;
2242 }
2243 break;
2244 }
2245 case VIRTIO_MMIO_REG_DRIVERFEATSEL_OFF:
2246 {
2247 pVirtio->uDriverFeaturesSelect = u32Val;
2248 break;
2249 }
2250 case VIRTIO_MMIO_REG_QUEUESEL_OFF:
2251 {
2252 if (u32Val < RT_ELEMENTS(pVirtio->aVirtqueues))
2253 pVirtio->uVirtqSelect = (uint16_t)u32Val;
2254 else
2255 LogFunc(("... WARNING: Guest attempted to write invalid virtq selector (ignoring)\n"));
2256 break;
2257 }
2258 case VIRTIO_MMIO_REG_QUEUENUM_OFF:
2259 {
2260 Assert(pVirtio->uVirtqSelect < RT_ELEMENTS(pVirtio->aVirtqueues));
2261 PVIRTQUEUE pVirtQueue = &pVirtio->aVirtqueues[pVirtio->uVirtqSelect];
2262 pVirtQueue->uQueueSize = (uint16_t)u32Val;
2263 break;
2264 }
2265 case VIRTIO_MMIO_REG_QUEUERDY_OFF:
2266 {
2267 Assert(pVirtio->uVirtqSelect < RT_ELEMENTS(pVirtio->aVirtqueues));
2268 PVIRTQUEUE pVirtQueue = &pVirtio->aVirtqueues[pVirtio->uVirtqSelect];
2269 pVirtQueue->uEnable = (uint16_t)u32Val;
2270 break;
2271 }
2272 case VIRTIO_MMIO_REG_QUEUENOTIFY_OFF:
2273 {
2274 virtioCoreVirtqNotified(pDevIns, pVirtio, u32Val, (uint16_t)u32Val);
2275 break;
2276 }
2277 case VIRTIO_MMIO_REG_INTRACK_OFF:
2278 {
2279 pVirtio->uISR &= ~u32Val;
2280 if (!pVirtio->uISR)
2281 virtioLowerInterrupt(pDevIns, 0);
2282 break;
2283 }
2284 case VIRTIO_MMIO_REG_DEVSTATUS_OFF:
2285 {
2286 rc = virtioDeviceStatusWrite(pDevIns, pVirtio, pVirtioCC, (uint8_t)u32Val);
2287 break;
2288 }
2289 case VIRTIO_MMIO_REG_QUEUEALIGN_LEGACY_OFF:
2290 {
2291 /* Written by edk2 even though we don't offer legacy mode, ignore. */
2292 break;
2293 }
2294 case VIRTIO_MMIO_REG_QUEUEDESCLOW_OFF:
2295 {
2296 Assert(pVirtio->uVirtqSelect < RT_ELEMENTS(pVirtio->aVirtqueues));
2297 PVIRTQUEUE pVirtQueue = &pVirtio->aVirtqueues[pVirtio->uVirtqSelect];
2298 pVirtQueue->GCPhysVirtqDesc = (pVirtQueue->GCPhysVirtqDesc & UINT64_C(0xffffffff00000000)) | u32Val;
2299 break;
2300 }
2301 case VIRTIO_MMIO_REG_QUEUEDESCHIGH_OFF:
2302 {
2303 Assert(pVirtio->uVirtqSelect < RT_ELEMENTS(pVirtio->aVirtqueues));
2304 PVIRTQUEUE pVirtQueue = &pVirtio->aVirtqueues[pVirtio->uVirtqSelect];
2305 pVirtQueue->GCPhysVirtqDesc = (pVirtQueue->GCPhysVirtqDesc & UINT64_C(0x00000000ffffffff)) | ((uint64_t)u32Val << 32);
2306 break;
2307 }
2308 case VIRTIO_MMIO_REG_QUEUEDRVLOW_OFF:
2309 {
2310 Assert(pVirtio->uVirtqSelect < RT_ELEMENTS(pVirtio->aVirtqueues));
2311 PVIRTQUEUE pVirtQueue = &pVirtio->aVirtqueues[pVirtio->uVirtqSelect];
2312 pVirtQueue->GCPhysVirtqAvail = (pVirtQueue->GCPhysVirtqAvail & UINT64_C(0xffffffff00000000)) | u32Val;
2313 break;
2314 }
2315 case VIRTIO_MMIO_REG_QUEUEDRVHIGH_OFF:
2316 {
2317 Assert(pVirtio->uVirtqSelect < RT_ELEMENTS(pVirtio->aVirtqueues));
2318 PVIRTQUEUE pVirtQueue = &pVirtio->aVirtqueues[pVirtio->uVirtqSelect];
2319 pVirtQueue->GCPhysVirtqAvail = (pVirtQueue->GCPhysVirtqAvail & UINT64_C(0x00000000ffffffff)) | ((uint64_t)u32Val << 32);
2320 break;
2321 }
2322 case VIRTIO_MMIO_REG_QUEUEDEVLOW_OFF:
2323 {
2324 Assert(pVirtio->uVirtqSelect < RT_ELEMENTS(pVirtio->aVirtqueues));
2325 PVIRTQUEUE pVirtQueue = &pVirtio->aVirtqueues[pVirtio->uVirtqSelect];
2326 pVirtQueue->GCPhysVirtqUsed = (pVirtQueue->GCPhysVirtqUsed & UINT64_C(0xffffffff00000000)) | u32Val;
2327 break;
2328 }
2329 case VIRTIO_MMIO_REG_QUEUEDEVHIGH_OFF:
2330 {
2331 Assert(pVirtio->uVirtqSelect < RT_ELEMENTS(pVirtio->aVirtqueues));
2332 PVIRTQUEUE pVirtQueue = &pVirtio->aVirtqueues[pVirtio->uVirtqSelect];
2333 pVirtQueue->GCPhysVirtqUsed = (pVirtQueue->GCPhysVirtqUsed & UINT64_C(0x00000000ffffffff)) | ((uint64_t)u32Val << 32);
2334 break;
2335 }
2336 default:
2337 ASSERT_GUEST_MSG_FAILED(("Bad write access to mapped capabilities region: off=%RGp pv=%#p{%.*Rhxs} cb=%u\n", off, pv, cb, pv, cb));
2338 rc = PDMDevHlpDBGFStop(pDevIns, RT_SRC_POS,
2339 "virtioMmioTransportWrite: Bad MMIO access to capabilities, offset=%RTiop cb=%08x\n", off, cb);
2340 }
2341
2342 STAM_PROFILE_ADV_STOP(&pVirtio->CTX_SUFF(StatWrite), a);
2343 return rc;
2344}
2345
2346
2347#ifdef IN_RING3
2348
2349/**
2350 * @callback_method_impl{FNPCICONFIGREAD}
2351 */
2352static DECLCALLBACK(VBOXSTRICTRC) virtioR3PciConfigRead(PPDMDEVINS pDevIns, PPDMPCIDEV pPciDev,
2353 uint32_t uAddress, unsigned cb, uint32_t *pu32Value)
2354{
2355 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
2356 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
2357 RT_NOREF(pPciDev);
2358
2359 if (uAddress == pVirtio->uPciCfgDataOff)
2360 {
2361 /* See comments in PCI Cfg capability initialization (in capabilities setup section of this code) */
2362 struct virtio_pci_cap *pPciCap = &pVirtioCC->pPciCfgCap->pciCap;
2363 uint32_t uLength = pPciCap->uLength;
2364
2365 Log7Func((" pDevIns=%p pPciDev=%p uAddress=%#x%s cb=%u uLength=%d, bar=%d\n",
2366 pDevIns, pPciDev, uAddress, uAddress < 0x10 ? " " : "", cb, uLength, pPciCap->uBar));
2367
2368 if ( (uLength != 1 && uLength != 2 && uLength != 4)
2369 || pPciCap->uBar != VIRTIO_REGION_PCI_CAP)
2370 {
2371 ASSERT_GUEST_MSG_FAILED(("Guest read virtio_pci_cfg_cap.pci_cfg_data using mismatching config. "
2372 "Ignoring\n"));
2373 *pu32Value = UINT32_MAX;
2374 return VINF_SUCCESS;
2375 }
2376
2377 VBOXSTRICTRC rcStrict = virtioMmioRead(pDevIns, pVirtio, pPciCap->uOffset, pu32Value, cb);
2378 Log7Func((" Guest read virtio_pci_cfg_cap.pci_cfg_data, bar=%d, offset=%d, length=%d, result=0x%x -> %Rrc\n",
2379 pPciCap->uBar, pPciCap->uOffset, uLength, *pu32Value, VBOXSTRICTRC_VAL(rcStrict)));
2380 return rcStrict;
2381 }
2382 Log7Func((" pDevIns=%p pPciDev=%p uAddress=%#x%s cb=%u pu32Value=%p\n",
2383 pDevIns, pPciDev, uAddress, uAddress < 0x10 ? " " : "", cb, pu32Value));
2384 return VINF_PDM_PCI_DO_DEFAULT;
2385}
2386
2387/**
2388 * @callback_method_impl{FNPCICONFIGWRITE}
2389 */
2390static DECLCALLBACK(VBOXSTRICTRC) virtioR3PciConfigWrite(PPDMDEVINS pDevIns, PPDMPCIDEV pPciDev,
2391 uint32_t uAddress, unsigned cb, uint32_t u32Value)
2392{
2393 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
2394 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
2395 RT_NOREF(pPciDev);
2396
2397 Log7Func(("pDevIns=%p pPciDev=%p uAddress=%#x %scb=%u u32Value=%#x\n", pDevIns, pPciDev, uAddress, uAddress < 0xf ? " " : "", cb, u32Value));
2398 if (uAddress == pVirtio->uPciCfgDataOff)
2399 {
2400 /* See comments in PCI Cfg capability initialization (in capabilities setup section of this code) */
2401 struct virtio_pci_cap *pPciCap = &pVirtioCC->pPciCfgCap->pciCap;
2402 uint32_t uLength = pPciCap->uLength;
2403
2404 if ( (uLength != 1 && uLength != 2 && uLength != 4)
2405 || cb != uLength
2406 || pPciCap->uBar != VIRTIO_REGION_PCI_CAP)
2407 {
2408 ASSERT_GUEST_MSG_FAILED(("Guest write virtio_pci_cfg_cap.pci_cfg_data using mismatching config. Ignoring\n"));
2409 return VINF_SUCCESS;
2410 }
2411
2412 VBOXSTRICTRC rcStrict = virtioMmioWrite(pDevIns, pVirtio, pPciCap->uOffset, &u32Value, cb);
2413 Log2Func(("Guest wrote virtio_pci_cfg_cap.pci_cfg_data, bar=%d, offset=%x, length=%x, value=%d -> %Rrc\n",
2414 pPciCap->uBar, pPciCap->uOffset, uLength, u32Value, VBOXSTRICTRC_VAL(rcStrict)));
2415 return rcStrict;
2416 }
2417 return VINF_PDM_PCI_DO_DEFAULT;
2418}
2419
2420
2421/*********************************************************************************************************************************
2422* Saved state (SSM) *
2423*********************************************************************************************************************************/
2424
2425
2426/**
2427 * Loads a saved device state (called from device-specific code on SSM final pass)
2428 *
2429 * @param pVirtio Pointer to the shared virtio state.
2430 * @param pHlp The ring-3 device helpers.
2431 * @param pSSM The saved state handle.
2432 * @returns VBox status code.
2433 */
2434DECLHIDDEN(int) virtioCoreR3LegacyDeviceLoadExec(PVIRTIOCORE pVirtio, PCPDMDEVHLPR3 pHlp, PSSMHANDLE pSSM,
2435 uint32_t uVersion, uint32_t uVirtioLegacy_3_1_Beta)
2436{
2437 int rc;
2438 uint32_t uDriverFeaturesLegacy32bit;
2439
2440 rc = pHlp->pfnSSMGetU32( pSSM, &uDriverFeaturesLegacy32bit);
2441 AssertRCReturn(rc, rc);
2442 pVirtio->uDriverFeatures = (uint64_t)uDriverFeaturesLegacy32bit;
2443
2444 rc = pHlp->pfnSSMGetU16( pSSM, &pVirtio->uVirtqSelect);
2445 AssertRCReturn(rc, rc);
2446
2447 rc = pHlp->pfnSSMGetU8( pSSM, &pVirtio->fDeviceStatus);
2448 AssertRCReturn(rc, rc);
2449
2450#ifdef LOG_ENABLED
2451 char szOut[80] = { 0 };
2452 virtioCoreFormatDeviceStatus(pVirtio->fDeviceStatus, szOut, sizeof(szOut));
2453 Log(("Loaded legacy device status = (%s)\n", szOut));
2454#endif
2455
2456 rc = pHlp->pfnSSMGetU8( pSSM, &pVirtio->uISR);
2457 AssertRCReturn(rc, rc);
2458
2459 uint32_t cQueues = 3; /* This constant default value copied from earliest v0.9 code */
2460 if (uVersion > uVirtioLegacy_3_1_Beta)
2461 {
2462 rc = pHlp->pfnSSMGetU32(pSSM, &cQueues);
2463 AssertRCReturn(rc, rc);
2464 }
2465
2466 AssertLogRelMsgReturn(cQueues <= VIRTQ_MAX_COUNT, ("%#x\n", cQueues), VERR_SSM_LOAD_CONFIG_MISMATCH);
2467 AssertLogRelMsgReturn(pVirtio->uVirtqSelect < cQueues || (cQueues == 0 && pVirtio->uVirtqSelect),
2468 ("uVirtqSelect=%u cQueues=%u\n", pVirtio->uVirtqSelect, cQueues),
2469 VERR_SSM_LOAD_CONFIG_MISMATCH);
2470
2471 Log(("\nRestoring %d legacy-only virtio-net device queues from saved state:\n", cQueues));
2472 for (unsigned uVirtq = 0; uVirtq < cQueues; uVirtq++)
2473 {
2474 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[uVirtq];
2475
2476 if (uVirtq == cQueues - 1)
2477 RTStrPrintf(pVirtq->szName, sizeof(pVirtq->szName), "legacy-ctrlq");
2478 else if (uVirtq % 2)
2479 RTStrPrintf(pVirtq->szName, sizeof(pVirtq->szName), "legacy-xmitq<%d>", uVirtq / 2);
2480 else
2481 RTStrPrintf(pVirtq->szName, sizeof(pVirtq->szName), "legacy-recvq<%d>", uVirtq / 2);
2482
2483 rc = pHlp->pfnSSMGetU16(pSSM, &pVirtq->uQueueSize);
2484 AssertRCReturn(rc, rc);
2485
2486 uint32_t uVirtqPfn;
2487 rc = pHlp->pfnSSMGetU32(pSSM, &uVirtqPfn);
2488 AssertRCReturn(rc, rc);
2489
2490 rc = pHlp->pfnSSMGetU16(pSSM, &pVirtq->uAvailIdxShadow);
2491 AssertRCReturn(rc, rc);
2492
2493 rc = pHlp->pfnSSMGetU16(pSSM, &pVirtq->uUsedIdxShadow);
2494 AssertRCReturn(rc, rc);
2495
2496 if (uVirtqPfn)
2497 {
2498 pVirtq->GCPhysVirtqDesc = (uint64_t)uVirtqPfn * VIRTIO_PAGE_SIZE;
2499 pVirtq->GCPhysVirtqAvail = pVirtq->GCPhysVirtqDesc + sizeof(VIRTQ_DESC_T) * pVirtq->uQueueSize;
2500 pVirtq->GCPhysVirtqUsed =
2501 RT_ALIGN(pVirtq->GCPhysVirtqAvail + RT_UOFFSETOF_DYN(VIRTQ_AVAIL_T, auRing[pVirtq->uQueueSize]), VIRTIO_PAGE_SIZE);
2502 pVirtq->uEnable = 1;
2503 }
2504 else
2505 {
2506 LogFunc(("WARNING: QUEUE \"%s\" PAGE NUMBER ZERO IN SAVED STATE\n", pVirtq->szName));
2507 pVirtq->uEnable = 0;
2508 }
2509 pVirtq->uNotifyOffset = 0; /* unused in legacy mode */
2510 pVirtq->uMsixVector = 0; /* unused in legacy mode */
2511 }
2512 pVirtio->fGenUpdatePending = 0; /* unused in legacy mode */
2513 pVirtio->uConfigGeneration = 0; /* unused in legacy mode */
2514 pVirtio->uPciCfgDataOff = 0; /* unused in legacy mode (port I/O used instead) */
2515
2516 return VINF_SUCCESS;
2517}
2518
2519/**
2520 * Loads a saved device state (called from device-specific code on SSM final pass)
2521 *
2522 * Note: This loads state saved by a Modern (VirtIO 1.0+) device, of which this transitional device is one,
2523 * and thus supports both legacy and modern guest virtio drivers.
2524 *
2525 * @param pVirtio Pointer to the shared virtio state.
2526 * @param pHlp The ring-3 device helpers.
2527 * @param pSSM The saved state handle.
2528 * @returns VBox status code.
2529 */
2530DECLHIDDEN(int) virtioCoreR3ModernDeviceLoadExec(PVIRTIOCORE pVirtio, PCPDMDEVHLPR3 pHlp, PSSMHANDLE pSSM,
2531 uint32_t uVersion, uint32_t uTestVersion, uint32_t cQueues)
2532{
2533 RT_NOREF2(cQueues, uVersion);
2534 LogFunc(("\n"));
2535 /*
2536 * Check the marker and (embedded) version number.
2537 */
2538 uint64_t uMarker = 0;
2539 int rc;
2540
2541 rc = pHlp->pfnSSMGetU64(pSSM, &uMarker);
2542 AssertRCReturn(rc, rc);
2543 if (uMarker != VIRTIO_SAVEDSTATE_MARKER)
2544 return pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
2545 N_("Expected marker value %#RX64 found %#RX64 instead"),
2546 VIRTIO_SAVEDSTATE_MARKER, uMarker);
2547 uint32_t uVersionSaved = 0;
2548 rc = pHlp->pfnSSMGetU32(pSSM, &uVersionSaved);
2549 AssertRCReturn(rc, rc);
2550 if (uVersionSaved != uTestVersion)
2551 return pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
2552 N_("Unsupported virtio version: %u"), uVersionSaved);
2553 /*
2554 * Load the state.
2555 */
2556 rc = pHlp->pfnSSMGetU32( pSSM, &pVirtio->fLegacyDriver);
2557 AssertRCReturn(rc, rc);
2558 rc = pHlp->pfnSSMGetBool( pSSM, &pVirtio->fGenUpdatePending);
2559 AssertRCReturn(rc, rc);
2560 rc = pHlp->pfnSSMGetU8( pSSM, &pVirtio->fDeviceStatus);
2561 AssertRCReturn(rc, rc);
2562 rc = pHlp->pfnSSMGetU8( pSSM, &pVirtio->uConfigGeneration);
2563 AssertRCReturn(rc, rc);
2564 rc = pHlp->pfnSSMGetU8( pSSM, &pVirtio->uPciCfgDataOff);
2565 AssertRCReturn(rc, rc);
2566 rc = pHlp->pfnSSMGetU8( pSSM, &pVirtio->uISR);
2567 AssertRCReturn(rc, rc);
2568 rc = pHlp->pfnSSMGetU16( pSSM, &pVirtio->uVirtqSelect);
2569 AssertRCReturn(rc, rc);
2570 rc = pHlp->pfnSSMGetU32( pSSM, &pVirtio->uDeviceFeaturesSelect);
2571 AssertRCReturn(rc, rc);
2572 rc = pHlp->pfnSSMGetU32( pSSM, &pVirtio->uDriverFeaturesSelect);
2573 AssertRCReturn(rc, rc);
2574 rc = pHlp->pfnSSMGetU64( pSSM, &pVirtio->uDriverFeatures);
2575 AssertRCReturn(rc, rc);
2576
2577 /** @todo Adapt this loop use cQueues argument instead of static queue count (safely with SSM versioning) */
2578 for (uint32_t i = 0; i < VIRTQ_MAX_COUNT; i++)
2579 {
2580 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[i];
2581 rc = pHlp->pfnSSMGetGCPhys64( pSSM, &pVirtq->GCPhysVirtqDesc);
2582 AssertRCReturn(rc, rc);
2583 rc = pHlp->pfnSSMGetGCPhys64( pSSM, &pVirtq->GCPhysVirtqAvail);
2584 AssertRCReturn(rc, rc);
2585 rc = pHlp->pfnSSMGetGCPhys64( pSSM, &pVirtq->GCPhysVirtqUsed);
2586 AssertRCReturn(rc, rc);
2587 rc = pHlp->pfnSSMGetU16( pSSM, &pVirtq->uNotifyOffset);
2588 AssertRCReturn(rc, rc);
2589 rc = pHlp->pfnSSMGetU16( pSSM, &pVirtq->uMsixVector);
2590 AssertRCReturn(rc, rc);
2591 rc = pHlp->pfnSSMGetU16( pSSM, &pVirtq->uEnable);
2592 AssertRCReturn(rc, rc);
2593 rc = pHlp->pfnSSMGetU16( pSSM, &pVirtq->uQueueSize);
2594 AssertRCReturn(rc, rc);
2595 rc = pHlp->pfnSSMGetU16( pSSM, &pVirtq->uAvailIdxShadow);
2596 AssertRCReturn(rc, rc);
2597 rc = pHlp->pfnSSMGetU16( pSSM, &pVirtq->uUsedIdxShadow);
2598 AssertRCReturn(rc, rc);
2599 rc = pHlp->pfnSSMGetMem( pSSM, pVirtq->szName, sizeof(pVirtq->szName));
2600 AssertRCReturn(rc, rc);
2601 }
2602 return VINF_SUCCESS;
2603}
2604
2605/**
2606 * Called from the FNSSMDEVSAVEEXEC function of the device.
2607 *
2608 * @param pVirtio Pointer to the shared virtio state.
2609 * @param pHlp The ring-3 device helpers.
2610 * @param pSSM The saved state handle.
2611 * @returns VBox status code.
2612 */
2613DECLHIDDEN(int) virtioCoreR3SaveExec(PVIRTIOCORE pVirtio, PCPDMDEVHLPR3 pHlp, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t cQueues)
2614{
2615 RT_NOREF(cQueues);
2616 /** @todo figure out a way to save cQueues (with SSM versioning) */
2617
2618 LogFunc(("\n"));
2619 pHlp->pfnSSMPutU64(pSSM, VIRTIO_SAVEDSTATE_MARKER);
2620 pHlp->pfnSSMPutU32(pSSM, uVersion);
2621
2622 pHlp->pfnSSMPutU32( pSSM, pVirtio->fLegacyDriver);
2623 pHlp->pfnSSMPutBool(pSSM, pVirtio->fGenUpdatePending);
2624 pHlp->pfnSSMPutU8( pSSM, pVirtio->fDeviceStatus);
2625 pHlp->pfnSSMPutU8( pSSM, pVirtio->uConfigGeneration);
2626 pHlp->pfnSSMPutU8( pSSM, pVirtio->uPciCfgDataOff);
2627 pHlp->pfnSSMPutU8( pSSM, pVirtio->uISR);
2628 pHlp->pfnSSMPutU16( pSSM, pVirtio->uVirtqSelect);
2629 pHlp->pfnSSMPutU32( pSSM, pVirtio->uDeviceFeaturesSelect);
2630 pHlp->pfnSSMPutU32( pSSM, pVirtio->uDriverFeaturesSelect);
2631 pHlp->pfnSSMPutU64( pSSM, pVirtio->uDriverFeatures);
2632
2633 for (uint32_t i = 0; i < VIRTQ_MAX_COUNT; i++)
2634 {
2635 PVIRTQUEUE pVirtq = &pVirtio->aVirtqueues[i];
2636
2637 pHlp->pfnSSMPutGCPhys64( pSSM, pVirtq->GCPhysVirtqDesc);
2638 pHlp->pfnSSMPutGCPhys64( pSSM, pVirtq->GCPhysVirtqAvail);
2639 pHlp->pfnSSMPutGCPhys64( pSSM, pVirtq->GCPhysVirtqUsed);
2640 pHlp->pfnSSMPutU16( pSSM, pVirtq->uNotifyOffset);
2641 pHlp->pfnSSMPutU16( pSSM, pVirtq->uMsixVector);
2642 pHlp->pfnSSMPutU16( pSSM, pVirtq->uEnable);
2643 pHlp->pfnSSMPutU16( pSSM, pVirtq->uQueueSize);
2644 pHlp->pfnSSMPutU16( pSSM, pVirtq->uAvailIdxShadow);
2645 pHlp->pfnSSMPutU16( pSSM, pVirtq->uUsedIdxShadow);
2646 int rc = pHlp->pfnSSMPutMem(pSSM, pVirtq->szName, 32);
2647 AssertRCReturn(rc, rc);
2648 }
2649 return VINF_SUCCESS;
2650}
2651
2652
2653/*********************************************************************************************************************************
2654* Device Level *
2655*********************************************************************************************************************************/
2656
2657/**
2658 * This must be called by the client to handle VM state changes after the client takes care of its device-specific
2659 * tasks for the state change (i.e. reset, suspend, power-off, resume)
2660 *
2661 * @param pDevIns The device instance.
2662 * @param pVirtio Pointer to the shared virtio state.
2663 */
2664DECLHIDDEN(void) virtioCoreR3VmStateChanged(PVIRTIOCORE pVirtio, VIRTIOVMSTATECHANGED enmState)
2665{
2666 LogFunc(("State changing to %s\n",
2667 virtioCoreGetStateChangeText(enmState)));
2668
2669 switch(enmState)
2670 {
2671 case kvirtIoVmStateChangedReset:
2672 virtioCoreResetAll(pVirtio);
2673 break;
2674 case kvirtIoVmStateChangedSuspend:
2675 break;
2676 case kvirtIoVmStateChangedPowerOff:
2677 break;
2678 case kvirtIoVmStateChangedResume:
2679 for (int uVirtq = 0; uVirtq < VIRTQ_MAX_COUNT; uVirtq++)
2680 {
2681 if ((!pVirtio->fLegacyDriver && pVirtio->aVirtqueues[uVirtq].uEnable)
2682 | pVirtio->aVirtqueues[uVirtq].GCPhysVirtqDesc)
2683 virtioCoreNotifyGuestDriver(pVirtio->pDevInsR3, pVirtio, uVirtq);
2684 }
2685 break;
2686 default:
2687 LogRelFunc(("Bad enum value"));
2688 return;
2689 }
2690}
2691
2692/**
2693 * This should be called from PDMDEVREGR3::pfnDestruct.
2694 *
2695 * @param pDevIns The device instance.
2696 * @param pVirtio Pointer to the shared virtio state.
2697 * @param pVirtioCC Pointer to the ring-3 virtio state.
2698 */
2699DECLHIDDEN(void) virtioCoreR3Term(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC)
2700{
2701 if (pVirtioCC->pbPrevDevSpecificCfg)
2702 {
2703 RTMemFree(pVirtioCC->pbPrevDevSpecificCfg);
2704 pVirtioCC->pbPrevDevSpecificCfg = NULL;
2705 }
2706
2707 RT_NOREF(pDevIns, pVirtio);
2708}
2709
2710
2711/**
2712 * Setup the Virtio device as a PCI device.
2713 *
2714 * @returns VBox status code.
2715 * @param pDevIns Device instance.
2716 * @param pVirtio Pointer to the shared virtio state. This
2717 * must be the first member in the shared
2718 * device instance data!
2719 * @param pVirtioCC Pointer to the ring-3 virtio state. This
2720 * must be the first member in the ring-3
2721 * device instance data!
2722 * @param pPciParams Values to populate industry standard PCI Configuration Space data structure
2723 * @param pcszInstance Device instance name (format-specifier)
2724 * @param cbDevSpecificCfg Size of virtio_pci_device_cap device-specific struct
2725 */
2726static int virtioR3PciTransportInit(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC, PVIRTIOPCIPARAMS pPciParams,
2727 const char *pcszInstance, uint16_t cbDevSpecificCfg)
2728{
2729 /* Set PCI config registers (assume 32-bit mode) */
2730 PPDMPCIDEV pPciDev = pDevIns->apPciDevs[0];
2731 PDMPCIDEV_ASSERT_VALID(pDevIns, pPciDev);
2732
2733 PDMPciDevSetVendorId(pPciDev, DEVICE_PCI_VENDOR_ID_VIRTIO);
2734 PDMPciDevSetDeviceId(pPciDev, pPciParams->uDeviceId);
2735
2736 if (pPciParams->uDeviceId < DEVICE_PCI_DEVICE_ID_VIRTIO_BASE)
2737 /* Transitional devices MUST have a PCI Revision ID of 0. */
2738 PDMPciDevSetRevisionId(pPciDev, DEVICE_PCI_REVISION_ID_VIRTIO_TRANS);
2739 else
2740 /* Non-transitional devices SHOULD have a PCI Revision ID of 1 or higher. */
2741 PDMPciDevSetRevisionId(pPciDev, DEVICE_PCI_REVISION_ID_VIRTIO_V1);
2742
2743 PDMPciDevSetSubSystemId(pPciDev, pPciParams->uSubsystemId);
2744 PDMPciDevSetSubSystemVendorId(pPciDev, DEVICE_PCI_VENDOR_ID_VIRTIO);
2745 PDMPciDevSetClassBase(pPciDev, pPciParams->uClassBase);
2746 PDMPciDevSetClassSub(pPciDev, pPciParams->uClassSub);
2747 PDMPciDevSetClassProg(pPciDev, pPciParams->uClassProg);
2748 PDMPciDevSetInterruptLine(pPciDev, pPciParams->uInterruptLine);
2749 PDMPciDevSetInterruptPin(pPciDev, pPciParams->uInterruptPin);
2750
2751 /* Register PCI device */
2752 int rc = PDMDevHlpPCIRegister(pDevIns, pPciDev);
2753 if (RT_FAILURE(rc))
2754 return PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio: cannot register PCI Device")); /* can we put params in this error? */
2755
2756 rc = PDMDevHlpPCIInterceptConfigAccesses(pDevIns, pPciDev, virtioR3PciConfigRead, virtioR3PciConfigWrite);
2757 AssertRCReturn(rc, rc);
2758
2759 /* Construct & map PCI vendor-specific capabilities for virtio host negotiation with guest driver */
2760
2761#define CFG_ADDR_2_IDX(addr) ((uint8_t)(((uintptr_t)(addr) - (uintptr_t)&pPciDev->abConfig[0])))
2762#define SET_PCI_CAP_LOC(a_pPciDev, a_pCfg, a_LocCap, a_uMmioLengthAlign) \
2763 do { \
2764 (a_LocCap).offMmio = (a_pCfg)->uOffset; \
2765 (a_LocCap).cbMmio = RT_ALIGN_T((a_pCfg)->uLength, a_uMmioLengthAlign, uint16_t); \
2766 (a_LocCap).offPci = (uint16_t)(uintptr_t)((uint8_t *)(a_pCfg) - &(a_pPciDev)->abConfig[0]); \
2767 (a_LocCap).cbPci = (a_pCfg)->uCapLen; \
2768 } while (0)
2769
2770 PVIRTIO_PCI_CAP_T pCfg;
2771 uint32_t cbRegion = 0;
2772
2773 /*
2774 * Common capability (VirtIO 1.0, section 4.1.4.3)
2775 */
2776 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[0x40];
2777 pCfg->uCfgType = VIRTIO_PCI_CAP_COMMON_CFG;
2778 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
2779 pCfg->uCapLen = sizeof(VIRTIO_PCI_CAP_T);
2780 pCfg->uCapNext = CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen;
2781 pCfg->uBar = VIRTIO_REGION_PCI_CAP;
2782 pCfg->uOffset = RT_ALIGN_32(0, 4); /* Currently 0, but reminder to 32-bit align if changing this */
2783 pCfg->uLength = sizeof(VIRTIO_PCI_COMMON_CFG_T);
2784 cbRegion += pCfg->uLength;
2785 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocCommonCfgCap, 2);
2786 pVirtioCC->pCommonCfgCap = pCfg;
2787
2788 /*
2789 * Notify capability (VirtIO 1.0, section 4.1.4.4).
2790 *
2791 * The size of the spec-defined subregion described by this VirtIO capability is
2792 * based-on the choice of this implementation to make the notification area of each
2793 * queue equal to queue's ordinal position (e.g. queue selector value). The VirtIO
2794 * specification leaves it up to implementation to define queue notification area layout.
2795 */
2796 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[pCfg->uCapNext];
2797 pCfg->uCfgType = VIRTIO_PCI_CAP_NOTIFY_CFG;
2798 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
2799 pCfg->uCapLen = sizeof(VIRTIO_PCI_NOTIFY_CAP_T);
2800 pCfg->uCapNext = CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen;
2801 pCfg->uBar = VIRTIO_REGION_PCI_CAP;
2802 pCfg->uOffset = pVirtioCC->pCommonCfgCap->uOffset + pVirtioCC->pCommonCfgCap->uLength;
2803 pCfg->uOffset = RT_ALIGN_32(pCfg->uOffset, 4);
2804 pCfg->uLength = VIRTQ_MAX_COUNT * VIRTIO_NOTIFY_OFFSET_MULTIPLIER + 2; /* will change in VirtIO 1.1 */
2805 cbRegion += pCfg->uLength;
2806 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocNotifyCap, 1);
2807 pVirtioCC->pNotifyCap = (PVIRTIO_PCI_NOTIFY_CAP_T)pCfg;
2808 pVirtioCC->pNotifyCap->uNotifyOffMultiplier = VIRTIO_NOTIFY_OFFSET_MULTIPLIER;
2809
2810 /* ISR capability (VirtIO 1.0, section 4.1.4.5)
2811 *
2812 * VirtIO 1.0 spec says 8-bit, unaligned in MMIO space. The specification example/diagram
2813 * illustrates this capability as 32-bit field with upper bits 'reserved'. Those depictions
2814 * differ. The spec's wording, not the diagram, is seen to work in practice.
2815 */
2816 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[pCfg->uCapNext];
2817 pCfg->uCfgType = VIRTIO_PCI_CAP_ISR_CFG;
2818 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
2819 pCfg->uCapLen = sizeof(VIRTIO_PCI_CAP_T);
2820 pCfg->uCapNext = CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen;
2821 pCfg->uBar = VIRTIO_REGION_PCI_CAP;
2822 pCfg->uOffset = pVirtioCC->pNotifyCap->pciCap.uOffset + pVirtioCC->pNotifyCap->pciCap.uLength;
2823 pCfg->uOffset = RT_ALIGN_32(pCfg->uOffset, 4);
2824 pCfg->uLength = sizeof(uint8_t);
2825 cbRegion += pCfg->uLength;
2826 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocIsrCap, 4);
2827 pVirtioCC->pIsrCap = pCfg;
2828
2829 /* PCI Cfg capability (VirtIO 1.0, section 4.1.4.7)
2830 *
2831 * This capability facilitates early-boot access to this device (BIOS).
2832 * This region isn't page-MMIO mapped. PCI configuration accesses are intercepted,
2833 * wherein uBar, uOffset and uLength are modulated by consumers to locate and read/write
2834 * values in any part of any region. (NOTE: Linux driver doesn't utilize this feature.
2835 * This capability only appears in lspci output on Linux if uLength is non-zero, 4-byte aligned,
2836 * during initialization of linux virtio driver).
2837 */
2838 pVirtio->uPciCfgDataOff = pCfg->uCapNext + RT_OFFSETOF(VIRTIO_PCI_CFG_CAP_T, uPciCfgData);
2839 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[pCfg->uCapNext];
2840 pCfg->uCfgType = VIRTIO_PCI_CAP_PCI_CFG;
2841 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
2842 pCfg->uCapLen = sizeof(VIRTIO_PCI_CFG_CAP_T);
2843 pCfg->uCapNext = (pVirtio->fMsiSupport || pVirtioCC->pbDevSpecificCfg) ? CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen : 0;
2844 pCfg->uBar = VIRTIO_REGION_PCI_CAP;
2845 pCfg->uOffset = 0;
2846 pCfg->uLength = 4;
2847 cbRegion += pCfg->uLength;
2848 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocPciCfgCap, 1);
2849 pVirtioCC->pPciCfgCap = (PVIRTIO_PCI_CFG_CAP_T)pCfg;
2850
2851 if (pVirtioCC->pbDevSpecificCfg)
2852 {
2853 /* Device-specific config capability (VirtIO 1.0, section 4.1.4.6).
2854 *
2855 * Client defines the device-specific config struct and passes size to virtioCoreR3Init()
2856 * to inform this.
2857 */
2858 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[pCfg->uCapNext];
2859 pCfg->uCfgType = VIRTIO_PCI_CAP_DEVICE_CFG;
2860 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
2861 pCfg->uCapLen = sizeof(VIRTIO_PCI_CAP_T);
2862 pCfg->uCapNext = pVirtio->fMsiSupport ? CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen : 0;
2863 pCfg->uBar = VIRTIO_REGION_PCI_CAP;
2864 pCfg->uOffset = pVirtioCC->pIsrCap->uOffset + pVirtioCC->pIsrCap->uLength;
2865 pCfg->uOffset = RT_ALIGN_32(pCfg->uOffset, 4);
2866 pCfg->uLength = cbDevSpecificCfg;
2867 cbRegion += pCfg->uLength;
2868 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocDeviceCap, 4);
2869 pVirtioCC->pDeviceCap = pCfg;
2870 }
2871 else
2872 Assert(pVirtio->LocDeviceCap.cbMmio == 0 && pVirtio->LocDeviceCap.cbPci == 0);
2873
2874 if (pVirtio->fMsiSupport)
2875 {
2876 PDMMSIREG aMsiReg;
2877 RT_ZERO(aMsiReg);
2878 aMsiReg.iMsixCapOffset = pCfg->uCapNext;
2879 aMsiReg.iMsixNextOffset = 0;
2880 aMsiReg.iMsixBar = VIRTIO_REGION_MSIX_CAP;
2881 aMsiReg.cMsixVectors = VBOX_MSIX_MAX_ENTRIES;
2882 rc = PDMDevHlpPCIRegisterMsi(pDevIns, &aMsiReg); /* see MsixR3init() */
2883 if (RT_FAILURE(rc))
2884 {
2885 /* See PDMDevHlp.cpp:pdmR3DevHlp_PCIRegisterMsi */
2886 LogFunc(("Failed to configure MSI-X (%Rrc). Reverting to INTx\n", rc));
2887 pVirtio->fMsiSupport = false;
2888 }
2889 else
2890 Log2Func(("Using MSI-X for guest driver notification\n"));
2891 }
2892 else
2893 LogFunc(("MSI-X not available for VBox, using INTx notification\n"));
2894
2895 /* Set offset to first capability and enable PCI dev capabilities */
2896 PDMPciDevSetCapabilityList(pPciDev, 0x40);
2897 PDMPciDevSetStatus(pPciDev, VBOX_PCI_STATUS_CAP_LIST);
2898
2899 size_t cbSize = RTStrPrintf(pVirtioCC->szMmioName, sizeof(pVirtioCC->szMmioName), "%s (modern)", pcszInstance);
2900 if (cbSize <= 0)
2901 return PDMDEV_SET_ERROR(pDevIns, VERR_BUFFER_OVERFLOW, N_("virtio: out of memory allocating string")); /* can we put params in this error? */
2902
2903 cbSize = RTStrPrintf(pVirtioCC->szPortIoName, sizeof(pVirtioCC->szPortIoName), "%s (legacy)", pcszInstance);
2904 if (cbSize <= 0)
2905 return PDMDEV_SET_ERROR(pDevIns, VERR_BUFFER_OVERFLOW, N_("virtio: out of memory allocating string")); /* can we put params in this error? */
2906
2907 if (pVirtio->fOfferLegacy)
2908 {
2909 /* As a transitional device that supports legacy VirtIO drivers, this VirtIO device generic implementation presents
2910 * legacy driver interface in I/O space at BAR0. The following maps the common (e.g. device independent)
2911 * dev config area as well as device-specific dev config area (whose size is passed to init function of this VirtIO
2912 * generic device code) for access via Port I/O, since legacy drivers (e.g. pre VirtIO 1.0) don't use MMIO callbacks.
2913 * (See VirtIO 1.1, Section 4.1.4.8).
2914 */
2915 rc = PDMDevHlpPCIIORegionCreateIo(pDevIns, VIRTIO_REGION_LEGACY_IO, sizeof(VIRTIO_LEGACY_PCI_COMMON_CFG_T) + cbDevSpecificCfg,
2916 virtioLegacyIOPortOut, virtioLegacyIOPortIn, NULL /*pvUser*/, pVirtioCC->szPortIoName,
2917 NULL /*paExtDescs*/, &pVirtio->hLegacyIoPorts);
2918 AssertLogRelRCReturn(rc, PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio: cannot register legacy config in I/O space at BAR0 */")));
2919 }
2920
2921 /* Note: The Linux driver at drivers/virtio/virtio_pci_modern.c tries to map at least a page for the
2922 * 'unknown' device-specific capability without querying the capability to determine size, so pad w/extra page.
2923 */
2924 rc = PDMDevHlpPCIIORegionCreateMmio(pDevIns, VIRTIO_REGION_PCI_CAP, RT_ALIGN_32(cbRegion + VIRTIO_PAGE_SIZE, VIRTIO_PAGE_SIZE),
2925 PCI_ADDRESS_SPACE_MEM, virtioMmioWrite, virtioMmioRead, pVirtio,
2926 IOMMMIO_FLAGS_READ_PASSTHRU | IOMMMIO_FLAGS_WRITE_PASSTHRU,
2927 pVirtioCC->szMmioName,
2928 &pVirtio->hMmioPciCap);
2929 AssertLogRelRCReturn(rc, PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio: cannot register PCI Capabilities address space")));
2930 return VINF_SUCCESS;
2931}
2932
2933
2934/**
2935 * Initializes the VirtIO device using the VirtIO over MMIO transport mode.
2936 *
2937 * @returns VBox status code.
2938 * @param pDevIns Device instance.
2939 * @param pVirtio Pointer to the shared virtio state. This
2940 * must be the first member in the shared
2941 * device instance data!
2942 * @param pVirtioCC Pointer to the ring-3 virtio state. This
2943 * must be the first member in the ring-3
2944 * device instance data!
2945 * @param pcszInstance Device instance name (format-specifier)
2946 * @param cbDevSpecificCfg Size of virtio_pci_device_cap device-specific struct
2947 * @param GCPhysMmioBase The physical guest address of the start of the MMIO area.
2948 * @param u16Irq The interrupt number to use for the virtio device.
2949 */
2950static int virtioR3MmioTransportInit(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC, const char *pcszInstance,
2951 uint16_t cbDevSpecificCfg, RTGCPHYS GCPhysMmioBase, uint16_t u16Irq)
2952{
2953 pVirtio->uIrqMmio = u16Irq;
2954
2955 size_t cbSize = RTStrPrintf(pVirtioCC->szMmioName, sizeof(pVirtioCC->szMmioName), "%s (modern)", pcszInstance);
2956 if (cbSize <= 0)
2957 return PDMDEV_SET_ERROR(pDevIns, VERR_BUFFER_OVERFLOW, N_("virtio: out of memory allocating string")); /* can we put params in this error? */
2958
2959 /*
2960 * Register and map the MMIO region.
2961 */
2962 int rc = PDMDevHlpMmioCreateAndMap(pDevIns, GCPhysMmioBase, RT_ALIGN_32(cbDevSpecificCfg + VIRTIO_MMIO_SIZE, 512),
2963 virtioMmioTransportWrite, virtioMmioTransportRead,
2964 IOMMMIO_FLAGS_READ_PASSTHRU | IOMMMIO_FLAGS_WRITE_PASSTHRU,
2965 pVirtioCC->szMmioName, &pVirtio->hMmioPciCap);
2966 AssertLogRelRCReturn(rc, PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio: cannot register PCI Capabilities address space")));
2967 return VINF_SUCCESS;
2968}
2969
2970
2971/** API Function: See header file */
2972DECLHIDDEN(int) virtioCoreR3Init(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC, PVIRTIOPCIPARAMS pPciParams,
2973 const char *pcszInstance, uint64_t fDevSpecificFeatures, uint32_t fOfferLegacy,
2974 void *pvDevSpecificCfg, uint16_t cbDevSpecificCfg)
2975{
2976 /*
2977 * Virtio state must be the first member of shared device instance data,
2978 * otherwise can't get our bearings in PCI config callbacks.
2979 */
2980 AssertLogRelReturn(pVirtio == PDMINS_2_DATA(pDevIns, PVIRTIOCORE), VERR_STATE_CHANGED);
2981 AssertLogRelReturn(pVirtioCC == PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC), VERR_STATE_CHANGED);
2982
2983 pVirtio->pDevInsR3 = pDevIns;
2984
2985 /*
2986 * Caller must initialize these.
2987 */
2988 AssertReturn(pVirtioCC->pfnStatusChanged, VERR_INVALID_POINTER);
2989 AssertReturn(pVirtioCC->pfnVirtqNotified, VERR_INVALID_POINTER);
2990 AssertReturn(VIRTQ_SIZE > 0 && VIRTQ_SIZE <= 32768, VERR_OUT_OF_RANGE); /* VirtIO specification-defined limit */
2991
2992 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
2993
2994 uint16_t u16Irq = 0;
2995 int rc = pHlp->pfnCFGMQueryU16Def(pDevIns->pCfg, "Irq", &u16Irq, 0);
2996 if (RT_FAILURE(rc))
2997 return PDMDEV_SET_ERROR(pDevIns, rc, N_("Configuration error: Failed to get the \"Irq\" value"));
2998
2999 RTGCPHYS GCPhysMmioBase = 0;
3000 rc = pHlp->pfnCFGMQueryU64Def(pDevIns->pCfg, "MmioBase", &GCPhysMmioBase, NIL_RTGCPHYS);
3001 if (RT_FAILURE(rc))
3002 return PDMDEV_SET_ERROR(pDevIns, rc,
3003 N_("Configuration error: Failed to get the \"MmioBase\" value"));
3004
3005#if 0 /* Until pdmR3DvHlp_PCISetIrq() impl is fixed and Assert that limits vec to 0 is removed
3006 * VBox legacy MSI support has not been implemented yet
3007 */
3008# ifdef VBOX_WITH_MSI_DEVICES
3009 pVirtio->fMsiSupport = true;
3010# endif
3011#endif
3012
3013 /*
3014 * Host features (presented as a buffet for guest to select from)
3015 * include both dev-specific features & reserved dev-independent features (bitmask).
3016 */
3017 pVirtio->uDeviceType = pPciParams->uDeviceType;
3018 pVirtio->uDeviceFeatures = VIRTIO_F_VERSION_1
3019 | VIRTIO_DEV_INDEPENDENT_FEATURES_OFFERED
3020 | fDevSpecificFeatures;
3021
3022 pVirtio->fLegacyDriver = pVirtio->fOfferLegacy = fOfferLegacy;
3023
3024 RTStrCopy(pVirtio->szInstance, sizeof(pVirtio->szInstance), pcszInstance);
3025 pVirtioCC->cbDevSpecificCfg = cbDevSpecificCfg;
3026 pVirtioCC->pbDevSpecificCfg = (uint8_t *)pvDevSpecificCfg;
3027 pVirtioCC->pbPrevDevSpecificCfg = (uint8_t *)RTMemDup(pvDevSpecificCfg, cbDevSpecificCfg);
3028 AssertLogRelReturn(pVirtioCC->pbPrevDevSpecificCfg, VERR_NO_MEMORY);
3029
3030 if (GCPhysMmioBase != NIL_RTGCPHYS)
3031 rc = virtioR3MmioTransportInit(pDevIns, pVirtio, pVirtioCC, pcszInstance, cbDevSpecificCfg,
3032 GCPhysMmioBase, u16Irq);
3033 else
3034 rc = virtioR3PciTransportInit(pDevIns, pVirtio, pVirtioCC, pPciParams, pcszInstance, cbDevSpecificCfg);
3035 AssertLogRelRCReturn(rc, rc);
3036
3037 /*
3038 * Statistics.
3039 */
3040# ifdef VBOX_WITH_STATISTICS
3041 PDMDevHlpSTAMRegisterF(pDevIns, &pVirtio->StatDescChainsAllocated, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_COUNT,
3042 "Total number of allocated descriptor chains", "DescChainsAllocated");
3043 PDMDevHlpSTAMRegisterF(pDevIns, &pVirtio->StatDescChainsFreed, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_COUNT,
3044 "Total number of freed descriptor chains", "DescChainsFreed");
3045 PDMDevHlpSTAMRegisterF(pDevIns, &pVirtio->StatDescChainsSegsIn, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_COUNT,
3046 "Total number of inbound segments", "DescChainsSegsIn");
3047 PDMDevHlpSTAMRegisterF(pDevIns, &pVirtio->StatDescChainsSegsOut, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_COUNT,
3048 "Total number of outbound segments", "DescChainsSegsOut");
3049 PDMDevHlpSTAMRegister(pDevIns, &pVirtio->StatReadR3, STAMTYPE_PROFILE, "IO/ReadR3", STAMUNIT_TICKS_PER_CALL, "Profiling IO reads in R3");
3050 PDMDevHlpSTAMRegister(pDevIns, &pVirtio->StatReadR0, STAMTYPE_PROFILE, "IO/ReadR0", STAMUNIT_TICKS_PER_CALL, "Profiling IO reads in R0");
3051 PDMDevHlpSTAMRegister(pDevIns, &pVirtio->StatReadRC, STAMTYPE_PROFILE, "IO/ReadRC", STAMUNIT_TICKS_PER_CALL, "Profiling IO reads in RC");
3052 PDMDevHlpSTAMRegister(pDevIns, &pVirtio->StatWriteR3, STAMTYPE_PROFILE, "IO/WriteR3", STAMUNIT_TICKS_PER_CALL, "Profiling IO writes in R3");
3053 PDMDevHlpSTAMRegister(pDevIns, &pVirtio->StatWriteR0, STAMTYPE_PROFILE, "IO/WriteR0", STAMUNIT_TICKS_PER_CALL, "Profiling IO writes in R0");
3054 PDMDevHlpSTAMRegister(pDevIns, &pVirtio->StatWriteRC, STAMTYPE_PROFILE, "IO/WriteRC", STAMUNIT_TICKS_PER_CALL, "Profiling IO writes in RC");
3055# endif /* VBOX_WITH_STATISTICS */
3056
3057 return VINF_SUCCESS;
3058}
3059
3060#else /* !IN_RING3 */
3061
3062/**
3063 * Sets up the core ring-0/raw-mode virtio bits.
3064 *
3065 * @returns VBox status code.
3066 * @param pDevIns The device instance.
3067 * @param pVirtio Pointer to the shared virtio state. This must be the first
3068 * member in the shared device instance data!
3069 */
3070DECLHIDDEN(int) virtioCoreRZInit(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio)
3071{
3072 AssertLogRelReturn(pVirtio == PDMINS_2_DATA(pDevIns, PVIRTIOCORE), VERR_STATE_CHANGED);
3073 int rc;
3074#ifdef FUTURE_OPTIMIZATION
3075 rc = PDMDevHlpSetDeviceCritSect(pDevIns, PDMDevHlpCritSectGetNop(pDevIns));
3076 AssertRCReturn(rc, rc);
3077#endif
3078
3079 if (pVirtio->uIrqMmio != 0)
3080 {
3081 rc = PDMDevHlpMmioSetUpContext(pDevIns, pVirtio->hMmioPciCap, virtioMmioTransportWrite, virtioMmioTransportRead, pVirtio);
3082 AssertRCReturn(rc, rc);
3083 }
3084 else
3085 {
3086 rc = PDMDevHlpMmioSetUpContext(pDevIns, pVirtio->hMmioPciCap, virtioMmioWrite, virtioMmioRead, pVirtio);
3087 AssertRCReturn(rc, rc);
3088
3089 if (pVirtio->fOfferLegacy)
3090 {
3091 rc = PDMDevHlpIoPortSetUpContext(pDevIns, pVirtio->hLegacyIoPorts, virtioLegacyIOPortOut, virtioLegacyIOPortIn, NULL /*pvUser*/);
3092 AssertRCReturn(rc, rc);
3093 }
3094 }
3095 return rc;
3096}
3097
3098#endif /* !IN_RING3 */
3099
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use