VirtualBox

source: vbox/trunk/src/VBox/Devices/VirtIO/Virtio_1_0.cpp@ 82829

Last change on this file since 82829 was 82681, checked in by vboxsync, 5 years ago

Network/DevVirtioNet_1_0.cpp: Ported skeletal framwork from VirtIO 0.9 to VirtIO 1.0 semantics. Builds but not working. See BugRef(8561) Comment #49 for details

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 80.1 KB
Line 
1/* $Id: Virtio_1_0.cpp 82681 2020-01-09 04:31:04Z vboxsync $ */
2/** @file
3 * Virtio_1_0 - Virtio Common (PCI, feature & config mgt, queue mgt & proxy, notification mgt)
4 */
5
6/*
7 * Copyright (C) 2009-2019 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DEV_VIRTIO
23
24#include <VBox/log.h>
25#include <VBox/msi.h>
26#include <VBox/AssertGuest.h>
27#include <iprt/param.h>
28#include <iprt/assert.h>
29#include <iprt/uuid.h>
30#include <iprt/mem.h>
31#include <iprt/assert.h>
32#include <iprt/sg.h>
33#include <iprt/string.h>
34#include <VBox/vmm/pdmdev.h>
35#include "Virtio_1_0.h"
36
37
38/*********************************************************************************************************************************
39* Defined Constants And Macros *
40*********************************************************************************************************************************/
41#define INSTANCE(a_pVirtio) ((a_pVirtio)->szInstance)
42#define QUEUE_NAME(a_pVirtio, a_idxQueue) ((a_pVirtio)->virtqState[(a_idxQueue)].szVirtqName)
43#define IS_DRIVER_OK(a_pVirtio) ((a_pVirtio)->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK)
44
45/**
46 * This macro returns true if the @a a_offAccess and access length (@a
47 * a_cbAccess) are within the range of the mapped capability struct described by
48 * @a a_LocCapData.
49 *
50 * @param[in] a_offAccess The offset into the MMIO bar of the access.
51 * @param[in] a_cbAccess The access size.
52 * @param[out] a_offIntraVar The variable to return the intra-capability
53 * offset into. ASSUMES this is uint32_t.
54 * @param[in] a_LocCapData The capability location info.
55 */
56#define MATCHES_VIRTIO_CAP_STRUCT(a_offAccess, a_cbAccess, a_offIntraVar, a_LocCapData) \
57 ( ((a_offIntraVar) = (uint32_t)((a_offAccess) - (a_LocCapData).offMmio)) < (uint32_t)(a_LocCapData).cbMmio \
58 && (a_offIntraVar) + (uint32_t)(a_cbAccess) <= (uint32_t)(a_LocCapData).cbMmio )
59
60
61/** Marks the start of the virtio saved state (just for sanity). */
62#define VIRTIO_SAVEDSTATE_MARKER UINT64_C(0x1133557799bbddff)
63/** The current saved state version for the virtio core. */
64#define VIRTIO_SAVEDSTATE_VERSION UINT32_C(1)
65
66
67/*********************************************************************************************************************************
68* Structures and Typedefs *
69*********************************************************************************************************************************/
70/**
71 * virtq related structs
72 * (struct names follow VirtIO 1.0 spec, typedef use VBox style)
73 */
74typedef struct virtq_desc
75{
76 uint64_t GCPhysBuf; /**< addr GC Phys. address of buffer */
77 uint32_t cb; /**< len Buffer length */
78 uint16_t fFlags; /**< flags Buffer specific flags */
79 uint16_t uDescIdxNext; /**< next Idx set if VIRTIO_DESC_F_NEXT */
80} VIRTQ_DESC_T, *PVIRTQ_DESC_T;
81
82typedef struct virtq_avail
83{
84 uint16_t fFlags; /**< flags avail ring drv to dev flags */
85 uint16_t uIdx; /**< idx Index of next free ring slot */
86 uint16_t auRing[RT_FLEXIBLE_ARRAY]; /**< ring Ring: avail drv to dev bufs */
87 /* uint16_t uUsedEventIdx; - used_event (if VIRTQ_USED_F_EVENT_IDX) */
88} VIRTQ_AVAIL_T, *PVIRTQ_AVAIL_T;
89
90typedef struct virtq_used_elem
91{
92 uint32_t uDescIdx; /**< idx Start of used desc chain */
93 uint32_t cbElem; /**< len Total len of used desc chain */
94} VIRTQ_USED_ELEM_T;
95
96typedef struct virt_used
97{
98 uint16_t fFlags; /**< flags used ring host-to-guest flags */
99 uint16_t uIdx; /**< idx Index of next ring slot */
100 VIRTQ_USED_ELEM_T aRing[RT_FLEXIBLE_ARRAY]; /**< ring Ring: used dev to drv bufs */
101 /* uint16_t uAvailEventIdx; - avail_event if (VIRTQ_USED_F_EVENT_IDX) */
102} VIRTQ_USED_T, *PVIRTQ_USED_T;
103
104
105const char *virtioCoreGetStateChangeText(VIRTIOVMSTATECHANGED enmState)
106{
107 switch (enmState)
108 {
109 case kvirtIoVmStateChangedReset: return "VM RESET";
110 case kvirtIoVmStateChangedSuspend: return "VM SUSPEND";
111 case kvirtIoVmStateChangedPowerOff: return "VM POWER OFF";
112 case kvirtIoVmStateChangedResume: return "VM RESUME";
113 default: return "<BAD ENUM>";
114 }
115}
116
117/* Internal Functions */
118
119static void virtioNotifyGuestDriver(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue, bool fForce);
120static int virtioKick(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint8_t uCause, uint16_t uVec, bool fForce);
121
122/** @name Internal queue operations
123 * @{ */
124
125#if 0 /* unused */
126DECLINLINE(int) virtqIsEventNeeded(uint16_t uEventIdx, uint16_t uDescIdxNew, uint16_t uDescIdxOld)
127{
128 return (uint16_t)(uDescIdxNew - uEventIdx - 1) < (uint16_t)(uDescIdxNew - uDescIdxOld);
129}
130#endif
131
132/**
133 * Accessor for virtq descriptor
134 */
135#ifdef IN_RING3
136DECLINLINE(void) virtioReadDesc(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue,
137 uint32_t idxDesc, PVIRTQ_DESC_T pDesc)
138{
139 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
140 uint16_t const cQueueItems = RT_MAX(pVirtio->uQueueSize[idxQueue], 1); /* Make sure to avoid div-by-zero. */
141 PDMDevHlpPCIPhysRead(pDevIns,
142 pVirtio->aGCPhysQueueDesc[idxQueue] + sizeof(VIRTQ_DESC_T) * (idxDesc % cQueueItems),
143 pDesc, sizeof(VIRTQ_DESC_T));
144}
145#endif
146
147/**
148 * Accessors for virtq avail ring
149 */
150#ifdef IN_RING3
151DECLINLINE(uint16_t) virtioReadAvailDescIdx(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue, uint32_t availIdx)
152{
153 uint16_t uDescIdx;
154 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
155 uint16_t const cQueueItems = RT_MAX(pVirtio->uQueueSize[idxQueue], 1); /* Make sure to avoid div-by-zero. */
156 PDMDevHlpPCIPhysRead(pDevIns,
157 pVirtio->aGCPhysQueueAvail[idxQueue]
158 + RT_UOFFSETOF_DYN(VIRTQ_AVAIL_T, auRing[availIdx % cQueueItems]),
159 &uDescIdx, sizeof(uDescIdx));
160 return uDescIdx;
161}
162#endif
163
164DECLINLINE(uint16_t) virtioReadAvailRingIdx(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
165{
166 uint16_t uIdx = 0;
167 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
168 PDMDevHlpPCIPhysRead(pDevIns,
169 pVirtio->aGCPhysQueueAvail[idxQueue] + RT_UOFFSETOF(VIRTQ_AVAIL_T, uIdx),
170 &uIdx, sizeof(uIdx));
171 return uIdx;
172}
173
174DECLINLINE(bool) virtqIsEmpty(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
175{
176 uint16_t uAvailGst = virtioReadAvailRingIdx(pDevIns, pVirtio, idxQueue);
177 bool fEmpty = uAvailGst == pVirtio->virtqState[idxQueue].uAvailIdx;
178
179 Log6Func(("Q<%u>: uAvailGst=%u uAvailIdx=%u -> fEmpty=%RTbool\n",
180 idxQueue, uAvailGst, pVirtio->virtqState[idxQueue].uAvailIdx, fEmpty));
181 return fEmpty;
182}
183
184#if 0 /* unused - Will be used when VIRTIO_F_EVENT_IDX optional feature is implemented, VirtIO 1.0, 2.4.7 */
185DECLINLINE(uint16_t) virtioReadAvailFlags(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
186{
187 uint16_t fFlags;
188 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
189 PDMDevHlpPCIPhysRead(pDevIns,
190 pVirtio->aGCPhysQueueAvail[idxQueue] + RT_UOFFSETOF(VIRTQ_AVAIL_T, fFlags),
191 &fFlags, sizeof(fFlags));
192 return fFlags;
193}
194#endif
195
196#ifdef IN_RING3
197DECLINLINE(uint16_t) virtioReadAvailUsedEvent(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
198{
199 uint16_t uUsedEventIdx;
200 /* VirtIO 1.0 uUsedEventIdx (used_event) immediately follows ring */
201 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
202 PDMDevHlpPCIPhysRead(pDevIns,
203 pVirtio->aGCPhysQueueAvail[idxQueue] + RT_UOFFSETOF_DYN(VIRTQ_AVAIL_T, auRing[pVirtio->uQueueSize[idxQueue]]),
204 &uUsedEventIdx, sizeof(uUsedEventIdx));
205 return uUsedEventIdx;
206}
207#endif
208
209/** @} */
210
211/** @name Accessors for virtq used ring
212 * @{
213 */
214
215#ifdef IN_RING3
216DECLINLINE(void) virtioWriteUsedElem(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue,
217 uint32_t usedIdx, uint32_t uDescIdx, uint32_t uLen)
218{
219 VIRTQ_USED_ELEM_T elem = { uDescIdx, uLen };
220 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
221 uint16_t const cQueueItems = RT_MAX(pVirtio->uQueueSize[idxQueue], 1); /* Make sure to avoid div-by-zero. */
222 PDMDevHlpPCIPhysWrite(pDevIns,
223 pVirtio->aGCPhysQueueUsed[idxQueue] + RT_UOFFSETOF_DYN(VIRTQ_USED_T, aRing[usedIdx % cQueueItems]),
224 &elem, sizeof(elem));
225}
226#endif
227
228DECLINLINE(void) virtioWriteUsedRingIdx(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue, uint16_t uIdx)
229{
230 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
231 PDMDevHlpPCIPhysWrite(pDevIns,
232 pVirtio->aGCPhysQueueUsed[idxQueue] + RT_UOFFSETOF(VIRTQ_USED_T, uIdx),
233 &uIdx, sizeof(uIdx));
234}
235
236#ifdef LOG_ENABLED
237DECLINLINE(uint16_t) virtioReadUsedRingIdx(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
238{
239 uint16_t uIdx = 0;
240 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
241 PDMDevHlpPCIPhysRead(pDevIns,
242 pVirtio->aGCPhysQueueUsed[idxQueue] + RT_UOFFSETOF(VIRTQ_USED_T, uIdx),
243 &uIdx, sizeof(uIdx));
244 return uIdx;
245}
246#endif
247
248DECLINLINE(uint16_t) virtioReadUsedFlags(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
249{
250 uint16_t fFlags = 0;
251 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
252 PDMDevHlpPCIPhysRead(pDevIns,
253 pVirtio->aGCPhysQueueUsed[idxQueue] + RT_UOFFSETOF(VIRTQ_USED_T, fFlags),
254 &fFlags, sizeof(fFlags));
255 return fFlags;
256}
257
258#if 0 /* unused - This may eventually be used to set no-notify for the ring as an optimization */
259DECLINLINE(void) virtioWriteUsedFlags(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue, uint32_t fFlags)
260{
261 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
262 RT_UNTRUSTED_VALIDATED_FENCE(); /* VirtIO 1.0, Section 3.2.1.4.1 */
263 PDMDevHlpPCIPhysWrite(pDevIns,
264 pVirtio->aGCPhysQueueUsed[idxQueue] + RT_UOFFSETOF(VIRTQ_USED_T, fFlags),
265 &fFlags, sizeof(fFlags));
266}
267#endif
268
269#if 0 /* unused - *May* be used when VIRTIO_F_EVENT_IDX optional feature is implemented VirtIO 1.0, 2.4.9.2*/
270DECLINLINE(void) virtioWriteUsedAvailEvent(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue, uint32_t uAvailEventIdx)
271{
272 /** VirtIO 1.0 uAvailEventIdx (avail_event) immediately follows ring */
273 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
274 PDMDevHlpPCIPhysWrite(pDevIns,
275 pVirtio->aGCPhysQueueUsed[idxQueue] + RT_UOFFSETOF_DYN(VIRTQ_USED_T, aRing[pVirtio->uQueueSize[idxQueue]]),
276 &uAvailEventIdx, sizeof(uAvailEventIdx));
277}
278#endif
279
280/** @} */
281
282void virtioCoreSgBufInit(PVIRTIOSGBUF pGcSgBuf, PVIRTIOSGSEG paSegs, size_t cSegs)
283{
284 AssertPtr(pGcSgBuf);
285 Assert( (cSegs > 0 && VALID_PTR(paSegs)) || (!cSegs && !paSegs));
286 Assert(cSegs < (~(unsigned)0 >> 1));
287
288 pGcSgBuf->paSegs = paSegs;
289 pGcSgBuf->cSegs = (unsigned)cSegs;
290 pGcSgBuf->idxSeg = 0;
291 if (cSegs && paSegs)
292 {
293 pGcSgBuf->pGcSegCur = paSegs[0].pGcSeg;
294 pGcSgBuf->cbSegLeft = paSegs[0].cbSeg;
295 }
296 else
297 {
298 pGcSgBuf->pGcSegCur = 0;
299 pGcSgBuf->cbSegLeft = 0;
300 }
301}
302
303static RTGCPHYS virtioCoreSgBufGet(PVIRTIOSGBUF pGcSgBuf, size_t *pcbData)
304{
305 size_t cbData;
306 RTGCPHYS pGcBuf;
307
308 /* Check that the S/G buffer has memory left. */
309 if (RT_LIKELY(pGcSgBuf->idxSeg < pGcSgBuf->cSegs && pGcSgBuf->cbSegLeft))
310 { /* likely */ }
311 else
312 {
313 *pcbData = 0;
314 return 0;
315 }
316
317 AssertMsg( pGcSgBuf->cbSegLeft <= 128 * _1M
318 && (RTGCPHYS)pGcSgBuf->pGcSegCur >= (RTGCPHYS)pGcSgBuf->paSegs[pGcSgBuf->idxSeg].pGcSeg
319 && (RTGCPHYS)pGcSgBuf->pGcSegCur + pGcSgBuf->cbSegLeft <=
320 (RTGCPHYS)pGcSgBuf->paSegs[pGcSgBuf->idxSeg].pGcSeg + pGcSgBuf->paSegs[pGcSgBuf->idxSeg].cbSeg,
321 ("pGcSgBuf->idxSeg=%d pGcSgBuf->cSegs=%d pGcSgBuf->pGcSegCur=%p pGcSgBuf->cbSegLeft=%zd "
322 "pGcSgBuf->paSegs[%d].pGcSeg=%p pGcSgBuf->paSegs[%d].cbSeg=%zd\n",
323 pGcSgBuf->idxSeg, pGcSgBuf->cSegs, pGcSgBuf->pGcSegCur, pGcSgBuf->cbSegLeft,
324 pGcSgBuf->idxSeg, pGcSgBuf->paSegs[pGcSgBuf->idxSeg].pGcSeg, pGcSgBuf->idxSeg,
325 pGcSgBuf->paSegs[pGcSgBuf->idxSeg].cbSeg));
326
327 cbData = RT_MIN(*pcbData, pGcSgBuf->cbSegLeft);
328 pGcBuf = pGcSgBuf->pGcSegCur;
329 pGcSgBuf->cbSegLeft -= cbData;
330 if (!pGcSgBuf->cbSegLeft)
331 {
332 pGcSgBuf->idxSeg++;
333
334 if (pGcSgBuf->idxSeg < pGcSgBuf->cSegs)
335 {
336 pGcSgBuf->pGcSegCur = pGcSgBuf->paSegs[pGcSgBuf->idxSeg].pGcSeg;
337 pGcSgBuf->cbSegLeft = pGcSgBuf->paSegs[pGcSgBuf->idxSeg].cbSeg;
338 }
339 *pcbData = cbData;
340 }
341 else
342 pGcSgBuf->pGcSegCur = pGcSgBuf->pGcSegCur + cbData;
343
344 return pGcBuf;
345}
346
347void virtioCoreSgBufReset(PVIRTIOSGBUF pGcSgBuf)
348{
349 AssertPtrReturnVoid(pGcSgBuf);
350
351 pGcSgBuf->idxSeg = 0;
352 if (pGcSgBuf->cSegs)
353 {
354 pGcSgBuf->pGcSegCur = pGcSgBuf->paSegs[0].pGcSeg;
355 pGcSgBuf->cbSegLeft = pGcSgBuf->paSegs[0].cbSeg;
356 }
357 else
358 {
359 pGcSgBuf->pGcSegCur = 0;
360 pGcSgBuf->cbSegLeft = 0;
361 }
362}
363
364RTGCPHYS virtioCoreSgBufAdvance(PVIRTIOSGBUF pGcSgBuf, size_t cbAdvance)
365{
366 AssertReturn(pGcSgBuf, 0);
367
368 size_t cbLeft = cbAdvance;
369 while (cbLeft)
370 {
371 size_t cbThisAdvance = cbLeft;
372 virtioCoreSgBufGet(pGcSgBuf, &cbThisAdvance);
373 if (!cbThisAdvance)
374 break;
375
376 cbLeft -= cbThisAdvance;
377 }
378 return cbAdvance - cbLeft;
379}
380
381RTGCPHYS virtioCoreSgBufGetNextSegment(PVIRTIOSGBUF pGcSgBuf, size_t *pcbSeg)
382{
383 AssertReturn(pGcSgBuf, 0);
384 AssertPtrReturn(pcbSeg, 0);
385
386 if (!*pcbSeg)
387 *pcbSeg = pGcSgBuf->cbSegLeft;
388
389 return virtioCoreSgBufGet(pGcSgBuf, pcbSeg);
390}
391
392#ifdef LOG_ENABLED
393
394/**
395 * Does a formatted hex dump using Log(()), recommend using VIRTIO_HEX_DUMP() macro to
396 * control enabling of logging efficiently.
397 *
398 * @param pv pointer to buffer to dump contents of
399 * @param cb count of characters to dump from buffer
400 * @param uBase base address of per-row address prefixing of hex output
401 * @param pszTitle Optional title. If present displays title that lists
402 * provided text with value of cb to indicate size next to it.
403 */
404void virtioCoreHexDump(uint8_t *pv, uint32_t cb, uint32_t uBase, const char *pszTitle)
405{
406 if (pszTitle)
407 Log(("%s [%d bytes]:\n", pszTitle, cb));
408 for (uint32_t row = 0; row < RT_MAX(1, (cb / 16) + 1) && row * 16 < cb; row++)
409 {
410 Log(("%04x: ", row * 16 + uBase)); /* line address */
411 for (uint8_t col = 0; col < 16; col++)
412 {
413 uint32_t idx = row * 16 + col;
414 if (idx >= cb)
415 Log(("-- %s", (col + 1) % 8 ? "" : " "));
416 else
417 Log(("%02x %s", pv[idx], (col + 1) % 8 ? "" : " "));
418 }
419 for (uint32_t idx = row * 16; idx < row * 16 + 16; idx++)
420 Log(("%c", (idx >= cb) ? ' ' : (pv[idx] >= 0x20 && pv[idx] <= 0x7e ? pv[idx] : '.')));
421 Log(("\n"));
422 }
423 Log(("\n"));
424 RT_NOREF2(uBase, pv);
425}
426
427#endif /* LOG_ENABLED */
428
429/**
430 * Log memory-mapped I/O input or output value.
431 *
432 * This is designed to be invoked by macros that can make contextual assumptions
433 * (e.g. implicitly derive MACRO parameters from the invoking function). It is exposed
434 * for the VirtIO client doing the device-specific implementation in order to log in a
435 * similar fashion accesses to the device-specific MMIO configuration structure. Macros
436 * that leverage this function are found in virtioCommonCfgAccessed() and can be
437 * used as an example of how to use this effectively for the device-specific
438 * code.
439 *
440 * @param pszFunc To avoid displaying this function's name via __FUNCTION__ or LogFunc()
441 * @param pszMember Name of struct member
442 * @param pv pointer to value
443 * @param cb size of value
444 * @param uOffset offset into member where value starts
445 * @param fWrite True if write I/O
446 * @param fHasIndex True if the member is indexed
447 * @param idx The index if fHasIndex
448 */
449void virtioCoreLogMappedIoValue(const char *pszFunc, const char *pszMember, uint32_t uMemberSize,
450 const void *pv, uint32_t cb, uint32_t uOffset, int fWrite,
451 int fHasIndex, uint32_t idx)
452{
453 if (!LogIs6Enabled())
454 return;
455
456 char szIdx[16];
457 if (fHasIndex)
458 RTStrPrintf(szIdx, sizeof(szIdx), "[%d]", idx);
459 else
460 szIdx[0] = '\0';
461
462 if (cb == 1 || cb == 2 || cb == 4 || cb == 8)
463 {
464 char szDepiction[64];
465 size_t cchDepiction;
466 if (uOffset != 0 || cb != uMemberSize) /* display bounds if partial member access */
467 cchDepiction = RTStrPrintf(szDepiction, sizeof(szDepiction), "%s%s[%d:%d]",
468 pszMember, szIdx, uOffset, uOffset + cb - 1);
469 else
470 cchDepiction = RTStrPrintf(szDepiction, sizeof(szDepiction), "%s%s", pszMember, szIdx);
471
472 /* padding */
473 if (cchDepiction < 30)
474 szDepiction[cchDepiction++] = ' ';
475 while (cchDepiction < 30)
476 szDepiction[cchDepiction++] = '.';
477 szDepiction[cchDepiction] = '\0';
478
479 RTUINT64U uValue;
480 uValue.u = 0;
481 memcpy(uValue.au8, pv, cb);
482 Log6(("%s: Guest %s %s %#0*RX64\n",
483 pszFunc, fWrite ? "wrote" : "read ", szDepiction, 2 + cb * 2, uValue.u));
484 }
485 else /* odd number or oversized access, ... log inline hex-dump style */
486 {
487 Log6(("%s: Guest %s %s%s[%d:%d]: %.*Rhxs\n",
488 pszFunc, fWrite ? "wrote" : "read ", pszMember,
489 szIdx, uOffset, uOffset + cb, cb, pv));
490 }
491 RT_NOREF2(fWrite, pszFunc);
492}
493
494
495/**
496 * Makes the MMIO-mapped Virtio uDeviceStatus registers non-cryptic
497 */
498DECLINLINE(void) virtioLogDeviceStatus(uint8_t bStatus)
499{
500 if (bStatus == 0)
501 Log6(("RESET"));
502 else
503 {
504 int primed = 0;
505 if (bStatus & VIRTIO_STATUS_ACKNOWLEDGE)
506 Log6(("%sACKNOWLEDGE", primed++ ? "" : ""));
507 if (bStatus & VIRTIO_STATUS_DRIVER)
508 Log6(("%sDRIVER", primed++ ? " | " : ""));
509 if (bStatus & VIRTIO_STATUS_FEATURES_OK)
510 Log6(("%sFEATURES_OK", primed++ ? " | " : ""));
511 if (bStatus & VIRTIO_STATUS_DRIVER_OK)
512 Log6(("%sDRIVER_OK", primed++ ? " | " : ""));
513 if (bStatus & VIRTIO_STATUS_FAILED)
514 Log6(("%sFAILED", primed++ ? " | " : ""));
515 if (bStatus & VIRTIO_STATUS_DEVICE_NEEDS_RESET)
516 Log6(("%sNEEDS_RESET", primed++ ? " | " : ""));
517 (void)primed;
518 }
519}
520
521#ifdef IN_RING3
522/**
523 * Allocate client context for client to work with VirtIO-provided with queue
524 *
525 * @param pVirtio Pointer to the shared virtio state.
526 * @param idxQueue Queue number
527 * @param pcszName Name to give queue
528 *
529 * @returns VBox status code.
530 */
531int virtioCoreR3QueueAttach(PVIRTIOCORE pVirtio, uint16_t idxQueue, const char *pcszName)
532{
533 LogFunc(("%s\n", pcszName));
534 PVIRTQSTATE pVirtq = &pVirtio->virtqState[idxQueue];
535 pVirtq->uAvailIdx = 0;
536 pVirtq->uUsedIdx = 0;
537 pVirtq->fEventThresholdReached = false;
538 RTStrCopy(pVirtq->szVirtqName, sizeof(pVirtq->szVirtqName), pcszName);
539 return VINF_SUCCESS;
540}
541#endif /* IN_RING3 */
542
543/**
544 * See API comments in header file for description
545 */
546int virtioQueueSkip(PVIRTIOCORE pVirtio, uint16_t idxQueue)
547{
548 Assert(idxQueue < RT_ELEMENTS(pVirtio->virtqState));
549 PVIRTQSTATE pVirtq = &pVirtio->virtqState[idxQueue];
550
551 AssertMsgReturn(IS_DRIVER_OK(pVirtio) && pVirtio->uQueueEnable[idxQueue],
552 ("Guest driver not in ready state.\n"), VERR_INVALID_STATE);
553
554 if (virtioCoreQueueIsEmpty(pVirtio->pDevIns, pVirtio, idxQueue))
555 return VERR_NOT_AVAILABLE;
556
557 Log2Func(("%s avail_idx=%u\n", pVirtq->szVirtqName, pVirtq->uAvailIdx));
558 pVirtq->uAvailIdx++;
559
560 return VINF_SUCCESS;
561}
562
563/**
564 * Check if the associated queue is empty
565 *
566 * @param pDevIns The device instance (for reading).
567 * @param pVirtio Pointer to the shared virtio state.
568 * @param idxQueue Queue number
569 *
570 * @retval true Queue is empty or unavailable.
571 * @retval false Queue is available and has entries
572 */
573bool virtioCoreQueueIsEmpty(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
574{
575 if (pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK)
576 return virtqIsEmpty(pDevIns, pVirtio, idxQueue);
577 return true;
578}
579
580#ifdef IN_RING3
581
582
583int virtioCoreR3DescChainGet(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue,
584 uint16_t uHeadIdx, PPVIRTIO_DESC_CHAIN_T ppDescChain)
585{
586 AssertReturn(ppDescChain, VERR_INVALID_PARAMETER);
587
588 Assert(idxQueue < RT_ELEMENTS(pVirtio->virtqState));
589
590 PVIRTQSTATE pVirtq = &pVirtio->virtqState[idxQueue];
591
592 PVIRTIOSGSEG paSegsIn = (PVIRTIOSGSEG)RTMemAlloc(VIRTQ_MAX_SIZE * sizeof(VIRTIOSGSEG));
593 AssertReturn(paSegsIn, VERR_NO_MEMORY);
594
595 PVIRTIOSGSEG paSegsOut = (PVIRTIOSGSEG)RTMemAlloc(VIRTQ_MAX_SIZE * sizeof(VIRTIOSGSEG));
596 AssertReturn(paSegsOut, VERR_NO_MEMORY);
597
598 AssertMsgReturn(IS_DRIVER_OK(pVirtio) && pVirtio->uQueueEnable[idxQueue],
599 ("Guest driver not in ready state.\n"), VERR_INVALID_STATE);
600
601 uint16_t uDescIdx = uHeadIdx;
602
603 Log3Func(("%s DESC CHAIN: (head) desc_idx=%u\n", pVirtq->szVirtqName, uHeadIdx));
604 RT_NOREF(pVirtq);
605
606 VIRTQ_DESC_T desc;
607
608 uint32_t cbIn = 0, cbOut = 0, cSegsIn = 0, cSegsOut = 0;
609
610 do
611 {
612 PVIRTIOSGSEG pSeg;
613
614 /*
615 * Malicious guests may go beyond paSegsIn or paSegsOut boundaries by linking
616 * several descriptors into a loop. Since there is no legitimate way to get a sequences of
617 * linked descriptors exceeding the total number of descriptors in the ring (see @bugref{8620}),
618 * the following aborts I/O if breach and employs a simple log throttling algorithm to notify.
619 */
620 if (cSegsIn + cSegsOut >= VIRTQ_MAX_SIZE)
621 {
622 static volatile uint32_t s_cMessages = 0;
623 static volatile uint32_t s_cThreshold = 1;
624 if (ASMAtomicIncU32(&s_cMessages) == ASMAtomicReadU32(&s_cThreshold))
625 {
626 LogRelMax(64, ("Too many linked descriptors; check if the guest arranges descriptors in a loop.\n"));
627 if (ASMAtomicReadU32(&s_cMessages) != 1)
628 LogRelMax(64, ("(the above error has occured %u times so far)\n", ASMAtomicReadU32(&s_cMessages)));
629 ASMAtomicWriteU32(&s_cThreshold, ASMAtomicReadU32(&s_cThreshold) * 10);
630 }
631 break;
632 }
633 RT_UNTRUSTED_VALIDATED_FENCE();
634
635 virtioReadDesc(pDevIns, pVirtio, idxQueue, uDescIdx, &desc);
636
637 if (desc.fFlags & VIRTQ_DESC_F_WRITE)
638 {
639 Log3Func(("%s IN desc_idx=%u seg=%u addr=%RGp cb=%u\n", QUEUE_NAME(pVirtio, idxQueue), uDescIdx, cSegsIn, desc.GCPhysBuf, desc.cb));
640 cbIn += desc.cb;
641 pSeg = &(paSegsIn[cSegsIn++]);
642 }
643 else
644 {
645 Log3Func(("%s OUT desc_idx=%u seg=%u addr=%RGp cb=%u\n", QUEUE_NAME(pVirtio, idxQueue), uDescIdx, cSegsOut, desc.GCPhysBuf, desc.cb));
646 cbOut += desc.cb;
647 pSeg = &(paSegsOut[cSegsOut++]);
648 }
649
650 pSeg->pGcSeg = desc.GCPhysBuf;
651 pSeg->cbSeg = desc.cb;
652
653 uDescIdx = desc.uDescIdxNext;
654 } while (desc.fFlags & VIRTQ_DESC_F_NEXT);
655
656 PVIRTIOSGBUF pSgPhysIn = (PVIRTIOSGBUF)RTMemAllocZ(sizeof(VIRTIOSGBUF));
657 AssertReturn(pSgPhysIn, VERR_NO_MEMORY);
658
659 virtioCoreSgBufInit(pSgPhysIn, paSegsIn, cSegsIn);
660
661 PVIRTIOSGBUF pSgPhysOut = (PVIRTIOSGBUF)RTMemAllocZ(sizeof(VIRTIOSGBUF));
662 AssertReturn(pSgPhysOut, VERR_NO_MEMORY);
663
664 virtioCoreSgBufInit(pSgPhysOut, paSegsOut, cSegsOut);
665
666 PVIRTIO_DESC_CHAIN_T pDescChain = (PVIRTIO_DESC_CHAIN_T)RTMemAllocZ(sizeof(VIRTIO_DESC_CHAIN_T));
667 AssertReturn(pDescChain, VERR_NO_MEMORY);
668
669 pDescChain->uHeadIdx = uHeadIdx;
670 pDescChain->cbPhysSend = cbOut;
671 pDescChain->pSgPhysSend = pSgPhysOut;
672 pDescChain->cbPhysReturn = cbIn;
673 pDescChain->pSgPhysReturn = pSgPhysIn;
674 *ppDescChain = pDescChain;
675
676 Log3Func(("%s -- segs OUT: %u (%u bytes) IN: %u (%u bytes) --\n", pVirtq->szVirtqName, cSegsOut, cbOut, cSegsIn, cbIn));
677
678 return VINF_SUCCESS;
679}
680
681/**
682 * Fetches descriptor chain using avail ring of indicated queue and converts the descriptor
683 * chain into its OUT (to device) and IN to guest components.
684 *
685 * Additionally it converts the OUT desc chain data to a contiguous virtual
686 * memory buffer for easy consumption by the caller. The caller must return the
687 * descriptor chain pointer via virtioCoreR3QueuePut() and then call virtioCoreQueueSync()
688 * at some point to return the data to the guest and complete the transaction.
689 *
690 * @param pDevIns The device instance.
691 * @param pVirtio Pointer to the shared virtio state.
692 * @param idxQueue Queue number
693 * @param fRemove flags whether to remove desc chain from queue (false = peek)
694 * @param ppDescChain Address to store pointer to descriptor chain that contains the
695 * pre-processed transaction information pulled from the virtq.
696 *
697 * @returns VBox status code:
698 * @retval VINF_SUCCESS Success
699 * @retval VERR_INVALID_STATE VirtIO not in ready state (asserted).
700 * @retval VERR_NOT_AVAILABLE If the queue is empty.
701 */
702int virtioCoreR3QueueGet(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue,
703 PPVIRTIO_DESC_CHAIN_T ppDescChain, bool fRemove)
704{
705 PVIRTQSTATE pVirtq = &pVirtio->virtqState[idxQueue];
706
707 if (virtqIsEmpty(pDevIns, pVirtio, idxQueue))
708 return VERR_NOT_AVAILABLE;
709
710 uint16_t uHeadIdx = virtioReadAvailDescIdx(pDevIns, pVirtio, idxQueue, pVirtq->uAvailIdx);
711
712 if (fRemove)
713 pVirtq->uAvailIdx++;
714
715 int rc = virtioCoreR3DescChainGet(pDevIns, pVirtio, idxQueue, uHeadIdx, ppDescChain);
716 return rc;
717}
718
719/**
720 * Returns data to the guest to complete a transaction initiated by virtQueueGet().
721 *
722 * The caller passes in a pointer to a scatter-gather buffer of virtual memory segments
723 * and a pointer to the descriptor chain context originally derived from the pulled
724 * queue entry, and this function will write the virtual memory s/g buffer into the
725 * guest's physical memory free the descriptor chain. The caller handles the freeing
726 * (as needed) of the virtual memory buffer.
727 *
728 * @note This does a write-ahead to the used ring of the guest's queue. The data
729 * written won't be seen by the guest until the next call to virtioCoreQueueSync()
730 *
731 *
732 * @param pDevIns The device instance (for reading).
733 * @param pVirtio Pointer to the shared virtio state.
734 * @param idxQueue Queue number
735 *
736 * @param pSgVirtReturn Points toscatter-gather buffer of virtual memory
737 * segments the caller is returning to the guest.
738 *
739 * @param pDescChain This contains the context of the scatter-gather
740 * buffer originally pulled from the queue.
741 *
742 * @param fFence If true, put up copy fence (memory barrier) after
743 * copying to guest phys. mem.
744 *
745 * @returns VBox status code.
746 * @retval VINF_SUCCESS Success
747 * @retval VERR_INVALID_STATE VirtIO not in ready state
748 * @retval VERR_NOT_AVAILABLE Queue is empty
749 */
750int virtioCoreR3QueuePut(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue, PRTSGBUF pSgVirtReturn,
751 PVIRTIO_DESC_CHAIN_T pDescChain, bool fFence)
752{
753 Assert(idxQueue < RT_ELEMENTS(pVirtio->virtqState));
754 PVIRTQSTATE pVirtq = &pVirtio->virtqState[idxQueue];
755 PVIRTIOSGBUF pSgPhysReturn = pDescChain->pSgPhysReturn;
756
757 AssertMsgReturn(IS_DRIVER_OK(pVirtio) /*&& pVirtio->uQueueEnable[idxQueue]*/,
758 ("Guest driver not in ready state.\n"), VERR_INVALID_STATE);
759
760 Log3Func(("Copying client data to %s, desc chain (head desc_idx %d)\n",
761 QUEUE_NAME(pVirtio, idxQueue), virtioReadUsedRingIdx(pDevIns, pVirtio, idxQueue)));
762
763 /*
764 * Copy s/g buf (virtual memory) to guest phys mem (IN direction). This virtual memory
765 * block will be small (fixed portion of response header + sense buffer area or
766 * control commands or error return values)... The bulk of req data xfers to phys mem
767 * is handled by client */
768
769 size_t cbCopy = 0;
770 size_t cbRemain = RTSgBufCalcTotalLength(pSgVirtReturn);
771 virtioCoreSgBufReset(pSgPhysReturn); /* Reset ptr because req data may have already been written */
772 while (cbRemain)
773 {
774 PVIRTIOSGSEG paSeg = &pSgPhysReturn->paSegs[pSgPhysReturn->idxSeg];
775 uint64_t dstSgStart = (uint64_t)paSeg->pGcSeg;
776 uint64_t dstSgLen = (uint64_t)paSeg->cbSeg;
777 uint64_t dstSgCur = (uint64_t)pSgPhysReturn->pGcSegCur;
778 cbCopy = RT_MIN((uint64_t)pSgVirtReturn->cbSegLeft, dstSgLen - (dstSgCur - dstSgStart));
779 PDMDevHlpPhysWrite(pDevIns, (RTGCPHYS)pSgPhysReturn->pGcSegCur, pSgVirtReturn->pvSegCur, cbCopy);
780 RTSgBufAdvance(pSgVirtReturn, cbCopy);
781 virtioCoreSgBufAdvance(pSgPhysReturn, cbCopy);
782 cbRemain -= cbCopy;
783 }
784
785 if (fFence)
786 RT_UNTRUSTED_NONVOLATILE_COPY_FENCE(); /* needed? */
787
788 /* If this write-ahead crosses threshold where the driver wants to get an event flag it */
789 if (pVirtio->uDriverFeatures & VIRTIO_F_EVENT_IDX)
790 if (pVirtq->uUsedIdx == virtioReadAvailUsedEvent(pDevIns, pVirtio, idxQueue))
791 pVirtq->fEventThresholdReached = true;
792
793 Assert(!(cbCopy >> 32));
794
795 /*
796 * Place used buffer's descriptor in used ring but don't update used ring's slot index.
797 * That will be done with a subsequent client call to virtioCoreQueueSync() */
798 virtioWriteUsedElem(pDevIns, pVirtio, idxQueue, pVirtq->uUsedIdx++, pDescChain->uHeadIdx, (uint32_t)cbCopy);
799
800 Log3Func((".... Copied %zu bytes to %u byte buffer, residual=%zu\n",
801 cbCopy, pDescChain->cbPhysReturn, pDescChain->cbPhysReturn - cbCopy));
802
803 Log6Func(("Write ahead used_idx=%u, %s used_idx=%u\n",
804 pVirtq->uUsedIdx, QUEUE_NAME(pVirtio, idxQueue), virtioReadUsedRingIdx(pDevIns, pVirtio, idxQueue)));
805
806 RTMemFree((void *)pDescChain->pSgPhysSend->paSegs);
807 RTMemFree(pDescChain->pSgPhysSend);
808 RTMemFree((void *)pSgPhysReturn->paSegs);
809 RTMemFree(pSgPhysReturn);
810 RTMemFree(pDescChain);
811
812 return VINF_SUCCESS;
813}
814
815#endif /* IN_RING3 */
816
817/**
818 * Updates the indicated virtq's "used ring" descriptor index to match the
819 * current write-head index, thus exposing the data added to the used ring by all
820 * virtioCoreR3QueuePut() calls since the last sync. This should be called after one or
821 * more virtioCoreR3QueuePut() calls to inform the guest driver there is data in the queue.
822 * Explicit notifications (e.g. interrupt or MSI-X) will be sent to the guest,
823 * depending on VirtIO features negotiated and conditions, otherwise the guest
824 * will detect the update by polling. (see VirtIO 1.0
825 * specification, Section 2.4 "Virtqueues").
826 *
827 * @param pDevIns The device instance.
828 * @param pVirtio Pointer to the shared virtio state.
829 * @param idxQueue Queue number
830 *
831 * @returns VBox status code.
832 * @retval VINF_SUCCESS Success
833 * @retval VERR_INVALID_STATE VirtIO not in ready state
834 */
835int virtioCoreQueueSync(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
836{
837 Assert(idxQueue < RT_ELEMENTS(pVirtio->virtqState));
838 PVIRTQSTATE pVirtq = &pVirtio->virtqState[idxQueue];
839
840 AssertMsgReturn(IS_DRIVER_OK(pVirtio) && pVirtio->uQueueEnable[idxQueue],
841 ("Guest driver not in ready state.\n"), VERR_INVALID_STATE);
842
843 Log6Func(("Updating %s used_idx from %u to %u\n",
844 QUEUE_NAME(pVirtio, idxQueue), virtioReadUsedRingIdx(pDevIns, pVirtio, idxQueue), pVirtq->uUsedIdx));
845
846 virtioWriteUsedRingIdx(pDevIns, pVirtio, idxQueue, pVirtq->uUsedIdx);
847 virtioNotifyGuestDriver(pDevIns, pVirtio, idxQueue, false);
848
849 return VINF_SUCCESS;
850}
851
852#ifdef IN_RING3
853/**
854 */
855static void virtioR3QueueNotified(PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC, uint16_t idxQueue, uint16_t uNotifyIdx)
856{
857 /* See VirtIO 1.0, section 4.1.5.2 It implies that idxQueue and uNotifyIdx should match.
858 * Disregarding this notification may cause throughput to stop, however there's no way to know
859 * which was queue was intended for wake-up if the two parameters disagree. */
860
861 AssertMsg(uNotifyIdx == idxQueue,
862 ("Guest kicked virtq %d's notify addr w/non-corresponding virtq idx %d\n",
863 idxQueue, uNotifyIdx));
864 RT_NOREF(uNotifyIdx);
865
866 AssertReturnVoid(idxQueue < RT_ELEMENTS(pVirtio->virtqState));
867 Log6Func(("%s\n", pVirtio->virtqState[idxQueue].szVirtqName));
868
869 /* Inform client */
870 pVirtioCC->pfnQueueNotified(pVirtio, pVirtioCC, idxQueue);
871}
872#endif /* IN_RING3 */
873
874/**
875 * Trigger MSI-X or INT# interrupt to notify guest of data added to used ring of
876 * the specified virtq, depending on the interrupt configuration of the device
877 * and depending on negotiated and realtime constraints flagged by the guest driver.
878 *
879 * See VirtIO 1.0 specification (section 2.4.7).
880 *
881 * @param pDevIns The device instance.
882 * @param pVirtio Pointer to the shared virtio state.
883 * @param idxQueue Queue to check for guest interrupt handling preference
884 * @param fForce Overrides idxQueue, forcing notification regardless of driver's
885 * notification preferences. This is a safeguard to prevent
886 * stalls upon resuming the VM. VirtIO 1.0 specification Section 4.1.5.5
887 * indicates spurious interrupts are harmless to guest driver's state,
888 * as they only cause the guest driver to [re]scan queues for work to do.
889 */
890static void virtioNotifyGuestDriver(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue, bool fForce)
891{
892
893 Assert(idxQueue < RT_ELEMENTS(pVirtio->virtqState));
894 PVIRTQSTATE pVirtq = &pVirtio->virtqState[idxQueue];
895
896 AssertMsgReturnVoid(IS_DRIVER_OK(pVirtio), ("Guest driver not in ready state.\n"));
897 if (pVirtio->uDriverFeatures & VIRTIO_F_EVENT_IDX)
898 {
899 if (pVirtq->fEventThresholdReached)
900 {
901 virtioKick(pDevIns, pVirtio, VIRTIO_ISR_VIRTQ_INTERRUPT, pVirtio->uQueueMsixVector[idxQueue], fForce);
902 pVirtq->fEventThresholdReached = false;
903 return;
904 }
905 Log6Func(("...skipping interrupt: VIRTIO_F_EVENT_IDX set but threshold not reached\n"));
906 }
907 else
908 {
909 /** If guest driver hasn't suppressed interrupts, interrupt */
910 if (fForce || !(virtioReadUsedFlags(pDevIns, pVirtio, idxQueue) & VIRTQ_AVAIL_F_NO_INTERRUPT))
911 {
912 virtioKick(pDevIns, pVirtio, VIRTIO_ISR_VIRTQ_INTERRUPT, pVirtio->uQueueMsixVector[idxQueue], fForce);
913 return;
914 }
915 Log6Func(("...skipping interrupt. Guest flagged VIRTQ_AVAIL_F_NO_INTERRUPT for queue\n"));
916 }
917}
918
919/**
920 * Raise interrupt or MSI-X
921 *
922 * @param pDevIns The device instance.
923 * @param pVirtio Pointer to the shared virtio state.
924 * @param uCause Interrupt cause bit mask to set in PCI ISR port.
925 * @param uVec MSI-X vector, if enabled
926 * @param uForce True of out-of-band
927 */
928static int virtioKick(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint8_t uCause, uint16_t uMsixVector, bool fForce)
929{
930 if (fForce)
931 Log6Func(("reason: resumed after suspend\n"));
932 else
933 if (uCause == VIRTIO_ISR_VIRTQ_INTERRUPT)
934 Log6Func(("reason: buffer added to 'used' ring.\n"));
935 else
936 if (uCause == VIRTIO_ISR_DEVICE_CONFIG)
937 Log6Func(("reason: device config change\n"));
938
939 if (!pVirtio->fMsiSupport)
940 {
941 pVirtio->uISR |= uCause;
942 PDMDevHlpPCISetIrq(pDevIns, 0, PDM_IRQ_LEVEL_HIGH);
943 }
944 else if (uMsixVector != VIRTIO_MSI_NO_VECTOR)
945 PDMDevHlpPCISetIrq(pDevIns, uMsixVector, 1);
946 return VINF_SUCCESS;
947}
948
949/**
950 * Lower interrupt (Called when guest reads ISR and when resetting)
951 *
952 * @param pDevIns The device instance.
953 */
954static void virtioLowerInterrupt(PPDMDEVINS pDevIns, uint16_t uMsixVector)
955{
956 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
957 if (!pVirtio->fMsiSupport)
958 PDMDevHlpPCISetIrq(pDevIns, 0, PDM_IRQ_LEVEL_LOW);
959 else if (uMsixVector != VIRTIO_MSI_NO_VECTOR)
960 PDMDevHlpPCISetIrq(pDevIns, pVirtio->uMsixConfig, PDM_IRQ_LEVEL_LOW);
961}
962
963
964
965/**
966 * Initiate orderly reset procedure. This is an exposed API for clients that might need it.
967 * Invoked by client to reset the device and driver (see VirtIO 1.0 section 2.1.1/2.1.2)
968 */
969void virtioCoreResetAll(PVIRTIOCORE pVirtio)
970{
971 LogFunc(("\n"));
972 pVirtio->uDeviceStatus |= VIRTIO_STATUS_DEVICE_NEEDS_RESET;
973 if (pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK)
974 {
975 pVirtio->fGenUpdatePending = true;
976 virtioKick(pVirtio->pDevIns, pVirtio, VIRTIO_ISR_DEVICE_CONFIG, pVirtio->uMsixConfig, false /* fForce */);
977 }
978}
979
980#ifdef IN_RING3
981static void virtioResetQueue(PVIRTIOCORE pVirtio, uint16_t idxQueue)
982{
983 Assert(idxQueue < RT_ELEMENTS(pVirtio->virtqState));
984 PVIRTQSTATE pVirtQ = &pVirtio->virtqState[idxQueue];
985 pVirtQ->uAvailIdx = 0;
986 pVirtQ->uUsedIdx = 0;
987 pVirtio->uQueueEnable[idxQueue] = false;
988 pVirtio->uQueueSize[idxQueue] = VIRTQ_MAX_SIZE;
989 pVirtio->uQueueNotifyOff[idxQueue] = idxQueue;
990 pVirtio->uQueueMsixVector[idxQueue] = idxQueue + 2;
991
992 if (!pVirtio->fMsiSupport) /* VirtIO 1.0, 4.1.4.3 and 4.1.5.1.2 */
993 pVirtio->uQueueMsixVector[idxQueue] = VIRTIO_MSI_NO_VECTOR;
994
995 virtioLowerInterrupt(pVirtio->pDevIns, pVirtio->uQueueMsixVector[idxQueue]);
996}
997
998static void virtioResetDevice(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio)
999{
1000 Log2Func(("\n"));
1001 pVirtio->uDeviceFeaturesSelect = 0;
1002 pVirtio->uDriverFeaturesSelect = 0;
1003 pVirtio->uConfigGeneration = 0;
1004 pVirtio->uDeviceStatus = 0;
1005 pVirtio->uISR = 0;
1006
1007 if (!pVirtio->fMsiSupport)
1008 virtioLowerInterrupt(pDevIns, 0);
1009 else
1010 {
1011 virtioLowerInterrupt(pDevIns, pVirtio->uMsixConfig);
1012 for (int i = 0; i < VIRTQ_MAX_CNT; i++)
1013 {
1014 virtioLowerInterrupt(pDevIns, pVirtio->uQueueMsixVector[i]);
1015 pVirtio->uQueueMsixVector[i];
1016 }
1017 }
1018
1019 if (!pVirtio->fMsiSupport) /* VirtIO 1.0, 4.1.4.3 and 4.1.5.1.2 */
1020 pVirtio->uMsixConfig = VIRTIO_MSI_NO_VECTOR;
1021
1022 for (uint16_t idxQueue = 0; idxQueue < VIRTQ_MAX_CNT; idxQueue++)
1023 virtioResetQueue(pVirtio, idxQueue);
1024}
1025
1026/**
1027 * Invoked by this implementation when guest driver resets the device.
1028 * The driver itself will not until the device has read the status change.
1029 */
1030static void virtioGuestR3WasReset(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC)
1031{
1032 LogFunc(("Guest reset the device\n"));
1033
1034 /* Let the client know */
1035 pVirtioCC->pfnStatusChanged(pVirtio, pVirtioCC, 0);
1036 virtioResetDevice(pDevIns, pVirtio);
1037}
1038#endif /* IN_RING3 */
1039
1040/**
1041 * Handle accesses to Common Configuration capability
1042 *
1043 * @returns VBox status code
1044 *
1045 * @param pDevIns The device instance.
1046 * @param pVirtio Pointer to the shared virtio state.
1047 * @param pVirtioCC Pointer to the current context virtio state.
1048 * @param fWrite Set if write access, clear if read access.
1049 * @param offCfg The common configuration capability offset.
1050 * @param cb Number of bytes to read or write
1051 * @param pv Pointer to location to write to or read from
1052 */
1053static int virtioCommonCfgAccessed(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC,
1054 int fWrite, uint32_t offCfg, unsigned cb, void *pv)
1055{
1056/**
1057 * This macro resolves to boolean true if the implied parameters, offCfg and cb,
1058 * match the field offset and size of a field in the Common Cfg struct, (or if
1059 * it is a 64-bit field, if it accesses either 32-bit part as a 32-bit access)
1060 * This is mandated by section 4.1.3.1 of the VirtIO 1.0 specification)
1061 *
1062 * @param member Member of VIRTIO_PCI_COMMON_CFG_T
1063 * @param offCfg Implied parameter: Offset into VIRTIO_PCI_COMMON_CFG_T
1064 * @param cb Implied parameter: Number of bytes to access
1065 * @result true or false
1066 */
1067#define MATCH_COMMON_CFG(member) \
1068 ( ( RT_SIZEOFMEMB(VIRTIO_PCI_COMMON_CFG_T, member) == 8 \
1069 && ( offCfg == RT_OFFSETOF(VIRTIO_PCI_COMMON_CFG_T, member) \
1070 || offCfg == RT_OFFSETOF(VIRTIO_PCI_COMMON_CFG_T, member) + sizeof(uint32_t)) \
1071 && cb == sizeof(uint32_t)) \
1072 || ( offCfg == RT_OFFSETOF(VIRTIO_PCI_COMMON_CFG_T, member) \
1073 && cb == RT_SIZEOFMEMB(VIRTIO_PCI_COMMON_CFG_T, member)) )
1074
1075#ifdef LOG_ENABLED
1076# define LOG_COMMON_CFG_ACCESS(member, a_offIntra) \
1077 virtioCoreLogMappedIoValue(__FUNCTION__, #member, RT_SIZEOFMEMB(VIRTIO_PCI_COMMON_CFG_T, member), \
1078 pv, cb, a_offIntra, fWrite, false, 0);
1079# define LOG_COMMON_CFG_ACCESS_INDEXED(member, idx, a_offIntra) \
1080 virtioCoreLogMappedIoValue(__FUNCTION__, #member, RT_SIZEOFMEMB(VIRTIO_PCI_COMMON_CFG_T, member), \
1081 pv, cb, a_offIntra, fWrite, true, idx);
1082#else
1083# define LOG_COMMON_CFG_ACCESS(member, a_offIntra) do { } while (0)
1084# define LOG_COMMON_CFG_ACCESS_INDEXED(member, idx, a_offIntra) do { } while (0)
1085#endif
1086
1087#define COMMON_CFG_ACCESSOR(member) \
1088 do \
1089 { \
1090 uint32_t offIntra = offCfg - RT_OFFSETOF(VIRTIO_PCI_COMMON_CFG_T, member); \
1091 if (fWrite) \
1092 memcpy((char *)&pVirtio->member + offIntra, (const char *)pv, cb); \
1093 else \
1094 memcpy(pv, (const char *)&pVirtio->member + offIntra, cb); \
1095 LOG_COMMON_CFG_ACCESS(member, offIntra); \
1096 } while(0)
1097
1098#define COMMON_CFG_ACCESSOR_INDEXED(member, idx) \
1099 do \
1100 { \
1101 uint32_t offIntra = offCfg - RT_OFFSETOF(VIRTIO_PCI_COMMON_CFG_T, member); \
1102 if (fWrite) \
1103 memcpy((char *)&pVirtio->member[idx] + offIntra, pv, cb); \
1104 else \
1105 memcpy(pv, (const char *)&pVirtio->member[idx] + offIntra, cb); \
1106 LOG_COMMON_CFG_ACCESS_INDEXED(member, idx, offIntra); \
1107 } while(0)
1108
1109#define COMMON_CFG_ACCESSOR_READONLY(member) \
1110 do \
1111 { \
1112 uint32_t offIntra = offCfg - RT_OFFSETOF(VIRTIO_PCI_COMMON_CFG_T, member); \
1113 if (fWrite) \
1114 LogFunc(("Guest attempted to write readonly virtio_pci_common_cfg.%s\n", #member)); \
1115 else \
1116 { \
1117 memcpy(pv, (const char *)&pVirtio->member + offIntra, cb); \
1118 LOG_COMMON_CFG_ACCESS(member, offIntra); \
1119 } \
1120 } while(0)
1121
1122#define COMMON_CFG_ACCESSOR_INDEXED_READONLY(member, idx) \
1123 do \
1124 { \
1125 uint32_t offIntra = offCfg - RT_OFFSETOF(VIRTIO_PCI_COMMON_CFG_T, member); \
1126 if (fWrite) \
1127 LogFunc(("Guest attempted to write readonly virtio_pci_common_cfg.%s[%d]\n", #member, idx)); \
1128 else \
1129 { \
1130 memcpy(pv, (char const *)&pVirtio->member[idx] + offIntra, cb); \
1131 LOG_COMMON_CFG_ACCESS_INDEXED(member, idx, offIntra); \
1132 } \
1133 } while(0)
1134
1135
1136 int rc = VINF_SUCCESS;
1137 uint64_t val;
1138 if (MATCH_COMMON_CFG(uDeviceFeatures))
1139 {
1140 if (fWrite) /* Guest WRITE pCommonCfg>uDeviceFeatures */
1141 {
1142 LogFunc(("Guest attempted to write readonly virtio_pci_common_cfg.device_feature\n"));
1143 return VINF_SUCCESS;
1144 }
1145 else /* Guest READ pCommonCfg->uDeviceFeatures */
1146 {
1147 switch (pVirtio->uDeviceFeaturesSelect)
1148 {
1149 case 0:
1150 val = pVirtio->uDeviceFeatures & UINT32_C(0xffffffff);
1151 memcpy(pv, &val, cb);
1152 LOG_COMMON_CFG_ACCESS(uDeviceFeatures, offCfg - RT_UOFFSETOF(VIRTIO_PCI_COMMON_CFG_T, uDeviceFeatures));
1153 break;
1154 case 1:
1155 val = pVirtio->uDeviceFeatures >> 32;
1156 memcpy(pv, &val, cb);
1157 LOG_COMMON_CFG_ACCESS(uDeviceFeatures, offCfg - RT_UOFFSETOF(VIRTIO_PCI_COMMON_CFG_T, uDeviceFeatures) + 4);
1158 break;
1159 default:
1160 LogFunc(("Guest read uDeviceFeatures with out of range selector (%#x), returning 0\n",
1161 pVirtio->uDeviceFeaturesSelect));
1162 return VINF_IOM_MMIO_UNUSED_00;
1163 }
1164 }
1165 }
1166 else if (MATCH_COMMON_CFG(uDriverFeatures))
1167 {
1168 if (fWrite) /* Guest WRITE pCommonCfg->udriverFeatures */
1169 {
1170 switch (pVirtio->uDriverFeaturesSelect)
1171 {
1172 case 0:
1173 memcpy(&pVirtio->uDriverFeatures, pv, cb);
1174 LOG_COMMON_CFG_ACCESS(uDriverFeatures, offCfg - RT_UOFFSETOF(VIRTIO_PCI_COMMON_CFG_T, uDriverFeatures));
1175 break;
1176 case 1:
1177 memcpy((char *)&pVirtio->uDriverFeatures + sizeof(uint32_t), pv, cb);
1178 LOG_COMMON_CFG_ACCESS(uDriverFeatures, offCfg - RT_UOFFSETOF(VIRTIO_PCI_COMMON_CFG_T, uDriverFeatures) + 4);
1179 break;
1180 default:
1181 LogFunc(("Guest wrote uDriverFeatures with out of range selector (%#x), returning 0\n",
1182 pVirtio->uDriverFeaturesSelect));
1183 return VINF_SUCCESS;
1184 }
1185 }
1186 else /* Guest READ pCommonCfg->udriverFeatures */
1187 {
1188 switch (pVirtio->uDriverFeaturesSelect)
1189 {
1190 case 0:
1191 val = pVirtio->uDriverFeatures & 0xffffffff;
1192 memcpy(pv, &val, cb);
1193 LOG_COMMON_CFG_ACCESS(uDriverFeatures, offCfg - RT_UOFFSETOF(VIRTIO_PCI_COMMON_CFG_T, uDriverFeatures));
1194 break;
1195 case 1:
1196 val = (pVirtio->uDriverFeatures >> 32) & 0xffffffff;
1197 memcpy(pv, &val, cb);
1198 LOG_COMMON_CFG_ACCESS(uDriverFeatures, offCfg - RT_UOFFSETOF(VIRTIO_PCI_COMMON_CFG_T, uDriverFeatures) + 4);
1199 break;
1200 default:
1201 LogFunc(("Guest read uDriverFeatures with out of range selector (%#x), returning 0\n",
1202 pVirtio->uDriverFeaturesSelect));
1203 return VINF_IOM_MMIO_UNUSED_00;
1204 }
1205 }
1206 }
1207 else if (MATCH_COMMON_CFG(uNumQueues))
1208 {
1209 if (fWrite)
1210 {
1211 Log2Func(("Guest attempted to write readonly virtio_pci_common_cfg.num_queues\n"));
1212 return VINF_SUCCESS;
1213 }
1214 else
1215 {
1216 *(uint16_t *)pv = VIRTQ_MAX_CNT;
1217 LOG_COMMON_CFG_ACCESS(uNumQueues, 0);
1218 }
1219 }
1220 else if (MATCH_COMMON_CFG(uDeviceStatus))
1221 {
1222 if (fWrite) /* Guest WRITE pCommonCfg->uDeviceStatus */
1223 {
1224 uint8_t const fNewStatus = *(uint8_t *)pv;
1225 Log6Func(("Guest wrote uDeviceStatus (%#x, was %#x, change #%x) ................ (",
1226 fNewStatus, pVirtio->uDeviceStatus, fNewStatus ^ pVirtio->uDeviceStatus));
1227 virtioLogDeviceStatus(fNewStatus);
1228 Log6((")\n"));
1229
1230 /* If the status changed or we were reset, we need to go to ring-3 as
1231 it requires notifying the parent device. */
1232 bool const fStatusChanged = (fNewStatus & VIRTIO_STATUS_DRIVER_OK)
1233 != (pVirtio->uPrevDeviceStatus & VIRTIO_STATUS_DRIVER_OK);
1234#ifndef IN_RING3
1235 if (fStatusChanged || fNewStatus == 0)
1236 {
1237 Log6Func(("=>ring3\n"));
1238 return VINF_IOM_R3_MMIO_WRITE;
1239 }
1240#endif
1241 pVirtio->uDeviceStatus = fNewStatus;
1242
1243#ifdef IN_RING3
1244 /*
1245 * Notify client only if status actually changed from last time and when we're reset.
1246 */
1247 if (pVirtio->uDeviceStatus == 0)
1248 virtioGuestR3WasReset(pDevIns, pVirtio, pVirtioCC);
1249 if (fStatusChanged)
1250 pVirtioCC->pfnStatusChanged(pVirtio, pVirtioCC, fNewStatus & VIRTIO_STATUS_DRIVER_OK);
1251#endif
1252 /*
1253 * Save the current status for the next write so we can see what changed.
1254 */
1255 pVirtio->uPrevDeviceStatus = pVirtio->uDeviceStatus;
1256 }
1257 else /* Guest READ pCommonCfg->uDeviceStatus */
1258 {
1259 Log6Func(("Guest read uDeviceStatus ................ ("));
1260 *(uint8_t *)pv = pVirtio->uDeviceStatus;
1261 virtioLogDeviceStatus(pVirtio->uDeviceStatus);
1262 Log6((")\n"));
1263 }
1264 }
1265 else
1266 if (MATCH_COMMON_CFG(uMsixConfig))
1267 COMMON_CFG_ACCESSOR(uMsixConfig);
1268 else
1269 if (MATCH_COMMON_CFG(uDeviceFeaturesSelect))
1270 COMMON_CFG_ACCESSOR(uDeviceFeaturesSelect);
1271 else
1272 if (MATCH_COMMON_CFG(uDriverFeaturesSelect))
1273 COMMON_CFG_ACCESSOR(uDriverFeaturesSelect);
1274 else
1275 if (MATCH_COMMON_CFG(uConfigGeneration))
1276 COMMON_CFG_ACCESSOR_READONLY(uConfigGeneration);
1277 else
1278 if (MATCH_COMMON_CFG(uQueueSelect))
1279 COMMON_CFG_ACCESSOR(uQueueSelect);
1280 else
1281 if (MATCH_COMMON_CFG(uQueueSize))
1282 COMMON_CFG_ACCESSOR_INDEXED(uQueueSize, pVirtio->uQueueSelect);
1283 else
1284 if (MATCH_COMMON_CFG(uQueueMsixVector))
1285 COMMON_CFG_ACCESSOR_INDEXED(uQueueMsixVector, pVirtio->uQueueSelect);
1286 else
1287 if (MATCH_COMMON_CFG(uQueueEnable))
1288 COMMON_CFG_ACCESSOR_INDEXED(uQueueEnable, pVirtio->uQueueSelect);
1289 else
1290 if (MATCH_COMMON_CFG(uQueueNotifyOff))
1291 COMMON_CFG_ACCESSOR_INDEXED_READONLY(uQueueNotifyOff, pVirtio->uQueueSelect);
1292 else
1293 if (MATCH_COMMON_CFG(aGCPhysQueueDesc))
1294 COMMON_CFG_ACCESSOR_INDEXED(aGCPhysQueueDesc, pVirtio->uQueueSelect);
1295 else
1296 if (MATCH_COMMON_CFG(aGCPhysQueueAvail))
1297 COMMON_CFG_ACCESSOR_INDEXED(aGCPhysQueueAvail, pVirtio->uQueueSelect);
1298 else
1299 if (MATCH_COMMON_CFG(aGCPhysQueueUsed))
1300 COMMON_CFG_ACCESSOR_INDEXED(aGCPhysQueueUsed, pVirtio->uQueueSelect);
1301 else
1302 {
1303 Log2Func(("Bad guest %s access to virtio_pci_common_cfg: offCfg=%#x (%d), cb=%d\n",
1304 fWrite ? "write" : "read ", offCfg, offCfg, cb));
1305 return fWrite ? VINF_SUCCESS : VINF_IOM_MMIO_UNUSED_00;
1306 }
1307
1308#undef COMMON_CFG_ACCESSOR_READONLY
1309#undef COMMON_CFG_ACCESSOR_INDEXED_READONLY
1310#undef COMMON_CFG_ACCESSOR_INDEXED
1311#undef COMMON_CFG_ACCESSOR
1312#undef LOG_COMMON_CFG_ACCESS_INDEXED
1313#undef LOG_COMMON_CFG_ACCESS
1314#undef MATCH_COMMON_CFG
1315#ifndef IN_RING3
1316 RT_NOREF(pDevIns, pVirtioCC);
1317#endif
1318 return rc;
1319}
1320
1321/**
1322 * @callback_method_impl{FNIOMMMIONEWREAD,
1323 * Memory mapped I/O Handler for PCI Capabilities read operations.}
1324 *
1325 * This MMIO handler specifically supports the VIRTIO_PCI_CAP_PCI_CFG capability defined
1326 * in the VirtIO 1.0 specification, section 4.1.4.7, and as such is limited to cb == 1, cb == 2, or cb==4 type reads.
1327 *
1328 */
1329static DECLCALLBACK(VBOXSTRICTRC) virtioMmioRead(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS off, void *pv, unsigned cb)
1330{
1331 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
1332 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
1333 AssertReturn(cb == 1 || cb == 2 || cb == 4, VERR_INVALID_PARAMETER);
1334 Assert(pVirtio == (PVIRTIOCORE)pvUser); RT_NOREF(pvUser);
1335
1336 uint32_t offIntra;
1337 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, offIntra, pVirtio->LocDeviceCap))
1338 {
1339#ifdef IN_RING3
1340 /*
1341 * Callback to client to manage device-specific configuration.
1342 */
1343 VBOXSTRICTRC rcStrict = pVirtioCC->pfnDevCapRead(pDevIns, offIntra, pv, cb);
1344
1345 /*
1346 * Additionally, anytime any part of the device-specific configuration (which our client maintains)
1347 * is READ it needs to be checked to see if it changed since the last time any part was read, in
1348 * order to maintain the config generation (see VirtIO 1.0 spec, section 4.1.4.3.1)
1349 */
1350 bool fDevSpecificFieldChanged = !!memcmp(pVirtioCC->pbDevSpecificCfg + offIntra,
1351 pVirtioCC->pbPrevDevSpecificCfg + offIntra,
1352 RT_MIN(cb, pVirtioCC->cbDevSpecificCfg - offIntra));
1353
1354 memcpy(pVirtioCC->pbPrevDevSpecificCfg, pVirtioCC->pbDevSpecificCfg, pVirtioCC->cbDevSpecificCfg);
1355
1356 if (pVirtio->fGenUpdatePending || fDevSpecificFieldChanged)
1357 {
1358 ++pVirtio->uConfigGeneration;
1359 Log6Func(("Bumped cfg. generation to %d because %s%s\n",
1360 pVirtio->uConfigGeneration,
1361 fDevSpecificFieldChanged ? "<dev cfg changed> " : "",
1362 pVirtio->fGenUpdatePending ? "<update was pending>" : ""));
1363 pVirtio->fGenUpdatePending = false;
1364 }
1365
1366 if (pVirtio->fMsiSupport)
1367 PDMDevHlpPCISetIrq(pDevIns, pVirtio->uMsixConfig, PDM_IRQ_LEVEL_LOW);
1368
1369 return rcStrict;
1370#else
1371 return VINF_IOM_R3_MMIO_READ;
1372#endif
1373 }
1374
1375 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, offIntra, pVirtio->LocCommonCfgCap))
1376 return virtioCommonCfgAccessed(pDevIns, pVirtio, pVirtioCC, false /* fWrite */, offIntra, cb, pv);
1377
1378 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, offIntra, pVirtio->LocIsrCap) && cb == sizeof(uint8_t))
1379 {
1380 *(uint8_t *)pv = pVirtio->uISR;
1381 Log6Func(("Read and clear ISR\n"));
1382 pVirtio->uISR = 0; /* VirtIO specification requires reads of ISR to clear it */
1383 virtioLowerInterrupt(pDevIns, 0);
1384 return VINF_SUCCESS;
1385 }
1386
1387 ASSERT_GUEST_MSG_FAILED(("Bad read access to mapped capabilities region: off=%RGp cb=%u\n", off, cb));
1388 return VINF_IOM_MMIO_UNUSED_00;
1389}
1390
1391/**
1392 * @callback_method_impl{FNIOMMMIONEWREAD,
1393 * Memory mapped I/O Handler for PCI Capabilities write operations.}
1394 *
1395 * This MMIO handler specifically supports the VIRTIO_PCI_CAP_PCI_CFG capability defined
1396 * in the VirtIO 1.0 specification, section 4.1.4.7, and as such is limited to cb == 1, cb == 2, or cb==4 type writes.
1397 */
1398static DECLCALLBACK(VBOXSTRICTRC) virtioMmioWrite(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS off, void const *pv, unsigned cb)
1399{
1400 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
1401 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
1402
1403 AssertReturn(cb == 1 || cb == 2 || cb == 4, VERR_INVALID_PARAMETER);
1404
1405 Assert(pVirtio == (PVIRTIOCORE)pvUser); RT_NOREF(pvUser);
1406
1407 uint32_t offIntra;
1408 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, offIntra, pVirtio->LocDeviceCap))
1409 {
1410#ifdef IN_RING3
1411 /*
1412 * Pass this MMIO write access back to the client to handle
1413 */
1414 return pVirtioCC->pfnDevCapWrite(pDevIns, offIntra, pv, cb);
1415#else
1416 return VINF_IOM_R3_MMIO_WRITE;
1417#endif
1418 }
1419
1420 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, offIntra, pVirtio->LocCommonCfgCap))
1421 return virtioCommonCfgAccessed(pDevIns, pVirtio, pVirtioCC, true /* fWrite */, offIntra, cb, (void *)pv);
1422
1423 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, offIntra, pVirtio->LocIsrCap) && cb == sizeof(uint8_t))
1424 {
1425 pVirtio->uISR = *(uint8_t *)pv;
1426 Log6Func(("Setting uISR = 0x%02x (virtq interrupt: %d, dev confg interrupt: %d)\n",
1427 pVirtio->uISR & 0xff,
1428 pVirtio->uISR & VIRTIO_ISR_VIRTQ_INTERRUPT,
1429 RT_BOOL(pVirtio->uISR & VIRTIO_ISR_DEVICE_CONFIG)));
1430 return VINF_SUCCESS;
1431 }
1432
1433 /* This *should* be guest driver dropping index of a new descriptor in avail ring */
1434 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, offIntra, pVirtio->LocNotifyCap) && cb == sizeof(uint16_t))
1435 {
1436#ifdef IN_RING3
1437 virtioR3QueueNotified(pVirtio, pVirtioCC, offIntra / VIRTIO_NOTIFY_OFFSET_MULTIPLIER, *(uint16_t *)pv);
1438 return VINF_SUCCESS;
1439#else
1440 return VINF_IOM_R3_MMIO_WRITE;
1441#endif
1442 }
1443
1444 ASSERT_GUEST_MSG_FAILED(("Bad write access to mapped capabilities region: off=%RGp pv=%#p{%.*Rhxs} cb=%u\n", off, pv, cb, pv, cb));
1445 return VINF_SUCCESS;
1446}
1447
1448#ifdef IN_RING3
1449
1450/**
1451 * @callback_method_impl{FNPCICONFIGREAD}
1452 */
1453static DECLCALLBACK(VBOXSTRICTRC) virtioR3PciConfigRead(PPDMDEVINS pDevIns, PPDMPCIDEV pPciDev,
1454 uint32_t uAddress, unsigned cb, uint32_t *pu32Value)
1455{
1456 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
1457 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
1458 RT_NOREF(pPciDev);
1459
1460 LogFlowFunc(("pDevIns=%p pPciDev=%p uAddress=%#x cb=%u pu32Value=%p\n",
1461 pDevIns, pPciDev, uAddress, cb, pu32Value));
1462 if (uAddress == pVirtio->uPciCfgDataOff)
1463 {
1464 /*
1465 * VirtIO 1.0 spec section 4.1.4.7 describes a required alternative access capability
1466 * whereby the guest driver can specify a bar, offset, and length via the PCI configuration space
1467 * (the virtio_pci_cfg_cap capability), and access data items.
1468 */
1469 uint32_t uLength = pVirtioCC->pPciCfgCap->pciCap.uLength;
1470 uint32_t uOffset = pVirtioCC->pPciCfgCap->pciCap.uOffset;
1471 uint8_t uBar = pVirtioCC->pPciCfgCap->pciCap.uBar;
1472
1473 if ( (uLength != 1 && uLength != 2 && uLength != 4)
1474 || cb != uLength
1475 || uBar != VIRTIO_REGION_PCI_CAP)
1476 {
1477 ASSERT_GUEST_MSG_FAILED(("Guest read virtio_pci_cfg_cap.pci_cfg_data using mismatching config. Ignoring\n"));
1478 *pu32Value = UINT32_MAX;
1479 return VINF_SUCCESS;
1480 }
1481
1482 VBOXSTRICTRC rcStrict = virtioMmioRead(pDevIns, pVirtio, uOffset, pu32Value, cb);
1483 Log2Func(("virtio: Guest read virtio_pci_cfg_cap.pci_cfg_data, bar=%d, offset=%d, length=%d, result=%d -> %Rrc\n",
1484 uBar, uOffset, uLength, *pu32Value, VBOXSTRICTRC_VAL(rcStrict)));
1485 return rcStrict;
1486 }
1487 return VINF_PDM_PCI_DO_DEFAULT;
1488}
1489
1490/**
1491 * @callback_method_impl{FNPCICONFIGWRITE}
1492 */
1493static DECLCALLBACK(VBOXSTRICTRC) virtioR3PciConfigWrite(PPDMDEVINS pDevIns, PPDMPCIDEV pPciDev,
1494 uint32_t uAddress, unsigned cb, uint32_t u32Value)
1495{
1496 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
1497 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
1498 RT_NOREF(pPciDev);
1499
1500 LogFlowFunc(("pDevIns=%p pPciDev=%p uAddress=%#x cb=%u u32Value=%#x\n", pDevIns, pPciDev, uAddress, cb, u32Value));
1501 if (uAddress == pVirtio->uPciCfgDataOff)
1502 {
1503 /* VirtIO 1.0 spec section 4.1.4.7 describes a required alternative access capability
1504 * whereby the guest driver can specify a bar, offset, and length via the PCI configuration space
1505 * (the virtio_pci_cfg_cap capability), and access data items. */
1506
1507 uint32_t uLength = pVirtioCC->pPciCfgCap->pciCap.uLength;
1508 uint32_t uOffset = pVirtioCC->pPciCfgCap->pciCap.uOffset;
1509 uint8_t uBar = pVirtioCC->pPciCfgCap->pciCap.uBar;
1510
1511 if ( (uLength != 1 && uLength != 2 && uLength != 4)
1512 || cb != uLength
1513 || uBar != VIRTIO_REGION_PCI_CAP)
1514 {
1515 ASSERT_GUEST_MSG_FAILED(("Guest write virtio_pci_cfg_cap.pci_cfg_data using mismatching config. Ignoring\n"));
1516 return VINF_SUCCESS;
1517 }
1518
1519 VBOXSTRICTRC rcStrict = virtioMmioWrite(pDevIns, pVirtio, uOffset, &u32Value, cb);
1520 Log2Func(("Guest wrote virtio_pci_cfg_cap.pci_cfg_data, bar=%d, offset=%x, length=%x, value=%d -> %Rrc\n",
1521 uBar, uOffset, uLength, u32Value, VBOXSTRICTRC_VAL(rcStrict)));
1522 return rcStrict;
1523 }
1524 return VINF_PDM_PCI_DO_DEFAULT;
1525}
1526
1527
1528/*********************************************************************************************************************************
1529* Saved state. *
1530*********************************************************************************************************************************/
1531
1532/**
1533 * Called from the FNSSMDEVSAVEEXEC function of the device.
1534 *
1535 * @param pVirtio Pointer to the shared virtio state.
1536 * @param pHlp The ring-3 device helpers.
1537 * @param pSSM The saved state handle.
1538 * @returns VBox status code.
1539 */
1540int virtioCoreR3SaveExec(PVIRTIOCORE pVirtio, PCPDMDEVHLPR3 pHlp, PSSMHANDLE pSSM)
1541{
1542 LogFunc(("\n"));
1543 pHlp->pfnSSMPutU64(pSSM, VIRTIO_SAVEDSTATE_MARKER);
1544 pHlp->pfnSSMPutU32(pSSM, VIRTIO_SAVEDSTATE_VERSION);
1545
1546 pHlp->pfnSSMPutBool(pSSM, pVirtio->fGenUpdatePending);
1547 pHlp->pfnSSMPutU8(pSSM, pVirtio->uDeviceStatus);
1548 pHlp->pfnSSMPutU8(pSSM, pVirtio->uConfigGeneration);
1549 pHlp->pfnSSMPutU8(pSSM, pVirtio->uPciCfgDataOff);
1550 pHlp->pfnSSMPutU8(pSSM, pVirtio->uISR);
1551 pHlp->pfnSSMPutU16(pSSM, pVirtio->uQueueSelect);
1552 pHlp->pfnSSMPutU32(pSSM, pVirtio->uDeviceFeaturesSelect);
1553 pHlp->pfnSSMPutU32(pSSM, pVirtio->uDriverFeaturesSelect);
1554 pHlp->pfnSSMPutU64(pSSM, pVirtio->uDriverFeatures);
1555
1556 for (uint32_t i = 0; i < VIRTQ_MAX_CNT; i++)
1557 {
1558 pHlp->pfnSSMPutGCPhys64(pSSM, pVirtio->aGCPhysQueueDesc[i]);
1559 pHlp->pfnSSMPutGCPhys64(pSSM, pVirtio->aGCPhysQueueAvail[i]);
1560 pHlp->pfnSSMPutGCPhys64(pSSM, pVirtio->aGCPhysQueueUsed[i]);
1561 pHlp->pfnSSMPutU16(pSSM, pVirtio->uQueueNotifyOff[i]);
1562 pHlp->pfnSSMPutU16(pSSM, pVirtio->uQueueMsixVector[i]);
1563 pHlp->pfnSSMPutU16(pSSM, pVirtio->uQueueEnable[i]);
1564 pHlp->pfnSSMPutU16(pSSM, pVirtio->uQueueSize[i]);
1565 pHlp->pfnSSMPutU16(pSSM, pVirtio->virtqState[i].uAvailIdx);
1566 pHlp->pfnSSMPutU16(pSSM, pVirtio->virtqState[i].uUsedIdx);
1567 int rc = pHlp->pfnSSMPutMem(pSSM, pVirtio->virtqState[i].szVirtqName, 32);
1568 AssertRCReturn(rc, rc);
1569 }
1570
1571 return VINF_SUCCESS;
1572}
1573
1574/**
1575 * Called from the FNSSMDEVLOADEXEC function of the device.
1576 *
1577 * @param pVirtio Pointer to the shared virtio state.
1578 * @param pHlp The ring-3 device helpers.
1579 * @param pSSM The saved state handle.
1580 * @returns VBox status code.
1581 */
1582int virtioCoreR3LoadExec(PVIRTIOCORE pVirtio, PCPDMDEVHLPR3 pHlp, PSSMHANDLE pSSM)
1583{
1584 LogFunc(("\n"));
1585 /*
1586 * Check the marker and (embedded) version number.
1587 */
1588 uint64_t uMarker = 0;
1589 int rc = pHlp->pfnSSMGetU64(pSSM, &uMarker);
1590 AssertRCReturn(rc, rc);
1591 if (uMarker != VIRTIO_SAVEDSTATE_MARKER)
1592 return pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
1593 N_("Expected marker value %#RX64 found %#RX64 instead"),
1594 VIRTIO_SAVEDSTATE_MARKER, uMarker);
1595 uint32_t uVersion = 0;
1596 rc = pHlp->pfnSSMGetU32(pSSM, &uVersion);
1597 AssertRCReturn(rc, rc);
1598 if (uVersion != VIRTIO_SAVEDSTATE_VERSION)
1599 return pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
1600 N_("Unsupported virtio version: %u"), uVersion);
1601 /*
1602 * Load the state.
1603 */
1604 pHlp->pfnSSMGetBool(pSSM, &pVirtio->fGenUpdatePending);
1605 pHlp->pfnSSMGetU8(pSSM, &pVirtio->uDeviceStatus);
1606 pHlp->pfnSSMGetU8(pSSM, &pVirtio->uConfigGeneration);
1607 pHlp->pfnSSMGetU8(pSSM, &pVirtio->uPciCfgDataOff);
1608 pHlp->pfnSSMGetU8(pSSM, &pVirtio->uISR);
1609 pHlp->pfnSSMGetU16(pSSM, &pVirtio->uQueueSelect);
1610 pHlp->pfnSSMGetU32(pSSM, &pVirtio->uDeviceFeaturesSelect);
1611 pHlp->pfnSSMGetU32(pSSM, &pVirtio->uDriverFeaturesSelect);
1612 pHlp->pfnSSMGetU64(pSSM, &pVirtio->uDriverFeatures);
1613
1614 for (uint32_t i = 0; i < VIRTQ_MAX_CNT; i++)
1615 {
1616 pHlp->pfnSSMGetGCPhys64(pSSM, &pVirtio->aGCPhysQueueDesc[i]);
1617 pHlp->pfnSSMGetGCPhys64(pSSM, &pVirtio->aGCPhysQueueAvail[i]);
1618 pHlp->pfnSSMGetGCPhys64(pSSM, &pVirtio->aGCPhysQueueUsed[i]);
1619 pHlp->pfnSSMGetU16(pSSM, &pVirtio->uQueueNotifyOff[i]);
1620 pHlp->pfnSSMGetU16(pSSM, &pVirtio->uQueueMsixVector[i]);
1621 pHlp->pfnSSMGetU16(pSSM, &pVirtio->uQueueEnable[i]);
1622 pHlp->pfnSSMGetU16(pSSM, &pVirtio->uQueueSize[i]);
1623 pHlp->pfnSSMGetU16(pSSM, &pVirtio->virtqState[i].uAvailIdx);
1624 pHlp->pfnSSMGetU16(pSSM, &pVirtio->virtqState[i].uUsedIdx);
1625 rc = pHlp->pfnSSMGetMem(pSSM, pVirtio->virtqState[i].szVirtqName,
1626 sizeof(pVirtio->virtqState[i].szVirtqName));
1627 AssertRCReturn(rc, rc);
1628 }
1629
1630 return VINF_SUCCESS;
1631}
1632
1633
1634/*********************************************************************************************************************************
1635* Device Level *
1636*********************************************************************************************************************************/
1637
1638/**
1639 * This must be called by the client to handle VM state changes
1640 * after the client takes care of its device-specific tasks for the state change.
1641 * (i.e. Reset, suspend, power-off, resume)
1642 *
1643 * @param pDevIns The device instance.
1644 * @param pVirtio Pointer to the shared virtio state.
1645 */
1646void virtioCoreR3VmStateChanged(PVIRTIOCORE pVirtio, VIRTIOVMSTATECHANGED enmState)
1647{
1648 LogFunc(("State changing to %s\n",
1649 virtioCoreGetStateChangeText(enmState)));
1650
1651 switch(enmState)
1652 {
1653 case kvirtIoVmStateChangedReset:
1654 virtioCoreResetAll(pVirtio);
1655 break;
1656 case kvirtIoVmStateChangedSuspend:
1657 break;
1658 case kvirtIoVmStateChangedPowerOff:
1659 break;
1660 case kvirtIoVmStateChangedResume:
1661 virtioNotifyGuestDriver(pVirtio->pDevIns, pVirtio, 0 /* idxQueue */, true /* fForce */);
1662 break;
1663 default:
1664 LogRelFunc(("Bad enum value"));
1665 return;
1666 }
1667}
1668
1669/**
1670 * This should be called from PDMDEVREGR3::pfnDestruct.
1671 *
1672 * @param pDevIns The device instance.
1673 * @param pVirtio Pointer to the shared virtio state.
1674 * @param pVirtioCC Pointer to the ring-3 virtio state.
1675 */
1676void virtioCoreR3Term(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC)
1677{
1678 if (pVirtioCC->pbPrevDevSpecificCfg)
1679 {
1680 RTMemFree(pVirtioCC->pbPrevDevSpecificCfg);
1681 pVirtioCC->pbPrevDevSpecificCfg = NULL;
1682 }
1683 RT_NOREF(pDevIns, pVirtio);
1684}
1685
1686
1687/**
1688 * Setup PCI device controller and Virtio state
1689 *
1690 * This should be called from PDMDEVREGR3::pfnConstruct.
1691 *
1692 * @param pDevIns The device instance.
1693 * @param pVirtio Pointer to the shared virtio state. This
1694 * must be the first member in the shared
1695 * device instance data!
1696 * @param pVirtioCC Pointer to the ring-3 virtio state. This
1697 * must be the first member in the ring-3
1698 * device instance data!
1699 * @param pPciParams Values to populate industry standard PCI Configuration Space data structure
1700 * @param pcszInstance Device instance name (format-specifier)
1701 * @param fDevSpecificFeatures VirtIO device-specific features offered by
1702 * client
1703 * @param cbDevSpecificCfg Size of virtio_pci_device_cap device-specific struct
1704 * @param pvDevSpecificCfg Address of client's dev-specific
1705 * configuration struct.
1706 */
1707int virtioCoreR3Init(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC, PVIRTIOPCIPARAMS pPciParams,
1708 const char *pcszInstance, uint64_t fDevSpecificFeatures, void *pvDevSpecificCfg, uint16_t cbDevSpecificCfg)
1709{
1710 /*
1711 * The pVirtio state must be the first member of the shared device instance
1712 * data, otherwise we cannot get our bearings in the PCI configuration callbacks.
1713 */
1714 AssertLogRelReturn(pVirtio == PDMINS_2_DATA(pDevIns, PVIRTIOCORE), VERR_STATE_CHANGED);
1715 AssertLogRelReturn(pVirtioCC == PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC), VERR_STATE_CHANGED);
1716
1717 pVirtio->pDevIns = pDevIns;
1718
1719 /*
1720 * Caller must initialize these.
1721 */
1722 AssertReturn(pVirtioCC->pfnStatusChanged, VERR_INVALID_POINTER);
1723 AssertReturn(pVirtioCC->pfnQueueNotified, VERR_INVALID_POINTER);
1724// AssertReturn(pVirtioCC->pfnDevCapRead, VERR_INVALID_POINTER);
1725// AssertReturn(pVirtioCC->pfnDevCapWrite, VERR_INVALID_POINTER);
1726
1727#if 0 /* Until pdmR3DvHlp_PCISetIrq() impl is fixed and Assert that limits vec to 0 is removed */
1728# ifdef VBOX_WITH_MSI_DEVICES
1729 pVirtio->fMsiSupport = true;
1730# endif
1731#endif
1732
1733 /*
1734 * The host features offered include both device-specific features
1735 * and reserved feature bits (device independent)
1736 */
1737 pVirtio->uDeviceFeatures = VIRTIO_F_VERSION_1
1738 | VIRTIO_DEV_INDEPENDENT_FEATURES_OFFERED
1739 | fDevSpecificFeatures;
1740
1741 RTStrCopy(pVirtio->szInstance, sizeof(pVirtio->szInstance), pcszInstance);
1742
1743 pVirtio->uDeviceStatus = 0;
1744 pVirtioCC->cbDevSpecificCfg = cbDevSpecificCfg;
1745 pVirtioCC->pbDevSpecificCfg = (uint8_t *)pvDevSpecificCfg;
1746 pVirtioCC->pbPrevDevSpecificCfg = (uint8_t *)RTMemDup(pvDevSpecificCfg, cbDevSpecificCfg);
1747 AssertLogRelReturn(pVirtioCC->pbPrevDevSpecificCfg, VERR_NO_MEMORY);
1748
1749 /* Set PCI config registers (assume 32-bit mode) */
1750 PPDMPCIDEV pPciDev = pDevIns->apPciDevs[0];
1751 PDMPCIDEV_ASSERT_VALID(pDevIns, pPciDev);
1752
1753 PDMPciDevSetRevisionId(pPciDev, DEVICE_PCI_REVISION_ID_VIRTIO);
1754 PDMPciDevSetVendorId(pPciDev, DEVICE_PCI_VENDOR_ID_VIRTIO);
1755 PDMPciDevSetSubSystemVendorId(pPciDev, DEVICE_PCI_VENDOR_ID_VIRTIO);
1756 PDMPciDevSetDeviceId(pPciDev, pPciParams->uDeviceId);
1757 PDMPciDevSetClassBase(pPciDev, pPciParams->uClassBase);
1758 PDMPciDevSetClassSub(pPciDev, pPciParams->uClassSub);
1759 PDMPciDevSetClassProg(pPciDev, pPciParams->uClassProg);
1760 PDMPciDevSetSubSystemId(pPciDev, pPciParams->uSubsystemId);
1761 PDMPciDevSetInterruptLine(pPciDev, pPciParams->uInterruptLine);
1762 PDMPciDevSetInterruptPin(pPciDev, pPciParams->uInterruptPin);
1763
1764 /* Register PCI device */
1765 int rc = PDMDevHlpPCIRegister(pDevIns, pPciDev);
1766 if (RT_FAILURE(rc))
1767 return PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio: cannot register PCI Device")); /* can we put params in this error? */
1768
1769 rc = PDMDevHlpPCIInterceptConfigAccesses(pDevIns, pPciDev, virtioR3PciConfigRead, virtioR3PciConfigWrite);
1770 AssertRCReturn(rc, rc);
1771
1772
1773 /* Construct & map PCI vendor-specific capabilities for virtio host negotiation with guest driver */
1774
1775 /* The following capability mapped via VirtIO 1.0: struct virtio_pci_cfg_cap (VIRTIO_PCI_CFG_CAP_T)
1776 * as a mandatory but suboptimal alternative interface to host device capabilities, facilitating
1777 * access the memory of any BAR. If the guest uses it (the VirtIO driver on Linux doesn't),
1778 * Unlike Common, Notify, ISR and Device capabilities, it is accessed directly via PCI Config region.
1779 * therefore does not contribute to the capabilities region (BAR) the other capabilities use.
1780 */
1781#define CFG_ADDR_2_IDX(addr) ((uint8_t)(((uintptr_t)(addr) - (uintptr_t)&pPciDev->abConfig[0])))
1782#define SET_PCI_CAP_LOC(a_pPciDev, a_pCfg, a_LocCap, a_uMmioLengthAlign) \
1783 do { \
1784 (a_LocCap).offMmio = (a_pCfg)->uOffset; \
1785 (a_LocCap).cbMmio = RT_ALIGN_T((a_pCfg)->uLength, a_uMmioLengthAlign, uint16_t); \
1786 (a_LocCap).offPci = (uint16_t)(uintptr_t)((uint8_t *)(a_pCfg) - &(a_pPciDev)->abConfig[0]); \
1787 (a_LocCap).cbPci = (a_pCfg)->uCapLen; \
1788 } while (0)
1789
1790 PVIRTIO_PCI_CAP_T pCfg;
1791 uint32_t cbRegion = 0;
1792
1793 /* Common capability (VirtIO 1.0 spec, section 4.1.4.3) */
1794 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[0x40];
1795 pCfg->uCfgType = VIRTIO_PCI_CAP_COMMON_CFG;
1796 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
1797 pCfg->uCapLen = sizeof(VIRTIO_PCI_CAP_T);
1798 pCfg->uCapNext = CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen;
1799 pCfg->uBar = VIRTIO_REGION_PCI_CAP;
1800 pCfg->uOffset = RT_ALIGN_32(0, 4); /* reminder, in case someone changes offset */
1801 pCfg->uLength = sizeof(VIRTIO_PCI_COMMON_CFG_T);
1802 cbRegion += pCfg->uLength;
1803 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocCommonCfgCap, 2);
1804 pVirtioCC->pCommonCfgCap = pCfg;
1805
1806 /*
1807 * Notify capability (VirtIO 1.0 spec, section 4.1.4.4). Note: uLength is based the choice
1808 * of this implementation that each queue's uQueueNotifyOff is set equal to (QueueSelect) ordinal
1809 * value of the queue
1810 */
1811 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[pCfg->uCapNext];
1812 pCfg->uCfgType = VIRTIO_PCI_CAP_NOTIFY_CFG;
1813 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
1814 pCfg->uCapLen = sizeof(VIRTIO_PCI_NOTIFY_CAP_T);
1815 pCfg->uCapNext = CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen;
1816 pCfg->uBar = VIRTIO_REGION_PCI_CAP;
1817 pCfg->uOffset = pVirtioCC->pCommonCfgCap->uOffset + pVirtioCC->pCommonCfgCap->uLength;
1818 pCfg->uOffset = RT_ALIGN_32(pCfg->uOffset, 4);
1819
1820
1821 pCfg->uLength = VIRTQ_MAX_CNT * VIRTIO_NOTIFY_OFFSET_MULTIPLIER + 2; /* will change in VirtIO 1.1 */
1822 cbRegion += pCfg->uLength;
1823 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocNotifyCap, 1);
1824 pVirtioCC->pNotifyCap = (PVIRTIO_PCI_NOTIFY_CAP_T)pCfg;
1825 pVirtioCC->pNotifyCap->uNotifyOffMultiplier = VIRTIO_NOTIFY_OFFSET_MULTIPLIER;
1826
1827 /* ISR capability (VirtIO 1.0 spec, section 4.1.4.5)
1828 *
1829 * VirtIO 1.0 spec says 8-bit, unaligned in MMIO space. Example/diagram
1830 * of spec shows it as a 32-bit field with upper bits 'reserved'
1831 * Will take spec words more literally than the diagram for now.
1832 */
1833 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[pCfg->uCapNext];
1834 pCfg->uCfgType = VIRTIO_PCI_CAP_ISR_CFG;
1835 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
1836 pCfg->uCapLen = sizeof(VIRTIO_PCI_CAP_T);
1837 pCfg->uCapNext = CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen;
1838 pCfg->uBar = VIRTIO_REGION_PCI_CAP;
1839 pCfg->uOffset = pVirtioCC->pNotifyCap->pciCap.uOffset + pVirtioCC->pNotifyCap->pciCap.uLength;
1840 pCfg->uOffset = RT_ALIGN_32(pCfg->uOffset, 4);
1841 pCfg->uLength = sizeof(uint8_t);
1842 cbRegion += pCfg->uLength;
1843 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocIsrCap, 4);
1844 pVirtioCC->pIsrCap = pCfg;
1845
1846 /* PCI Cfg capability (VirtIO 1.0 spec, section 4.1.4.7)
1847 * This capability doesn't get page-MMIO mapped. Instead uBar, uOffset and uLength are intercepted
1848 * by trapping PCI configuration I/O and get modulated by consumers to locate fetch and read/write
1849 * values from any region. NOTE: The linux driver not only doesn't use this feature, it will not
1850 * even list it as present if uLength isn't non-zero and also 4-byte-aligned as the linux driver is
1851 * initializing.
1852 */
1853 pVirtio->uPciCfgDataOff = pCfg->uCapNext + RT_OFFSETOF(VIRTIO_PCI_CFG_CAP_T, uPciCfgData);
1854 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[pCfg->uCapNext];
1855 pCfg->uCfgType = VIRTIO_PCI_CAP_PCI_CFG;
1856 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
1857 pCfg->uCapLen = sizeof(VIRTIO_PCI_CFG_CAP_T);
1858 pCfg->uCapNext = (pVirtio->fMsiSupport || pVirtioCC->pbDevSpecificCfg) ? CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen : 0;
1859 pCfg->uBar = 0;
1860 pCfg->uOffset = 0;
1861 pCfg->uLength = 0;
1862 cbRegion += pCfg->uLength;
1863 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocPciCfgCap, 1);
1864 pVirtioCC->pPciCfgCap = (PVIRTIO_PCI_CFG_CAP_T)pCfg;
1865
1866 if (pVirtioCC->pbDevSpecificCfg)
1867 {
1868 /* Following capability (via VirtIO 1.0, section 4.1.4.6). Client defines the
1869 * device-specific config fields struct and passes size to this constructor */
1870 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[pCfg->uCapNext];
1871 pCfg->uCfgType = VIRTIO_PCI_CAP_DEVICE_CFG;
1872 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
1873 pCfg->uCapLen = sizeof(VIRTIO_PCI_CAP_T);
1874 pCfg->uCapNext = pVirtio->fMsiSupport ? CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen : 0;
1875 pCfg->uBar = VIRTIO_REGION_PCI_CAP;
1876 pCfg->uOffset = pVirtioCC->pIsrCap->uOffset + pVirtioCC->pIsrCap->uLength;
1877 pCfg->uOffset = RT_ALIGN_32(pCfg->uOffset, 4);
1878 pCfg->uLength = cbDevSpecificCfg;
1879 cbRegion += pCfg->uLength;
1880 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocDeviceCap, 4);
1881 pVirtioCC->pDeviceCap = pCfg;
1882 }
1883 else
1884 Assert(pVirtio->LocDeviceCap.cbMmio == 0 && pVirtio->LocDeviceCap.cbPci == 0);
1885
1886 if (pVirtio->fMsiSupport)
1887 {
1888 PDMMSIREG aMsiReg;
1889 RT_ZERO(aMsiReg);
1890 aMsiReg.iMsixCapOffset = pCfg->uCapNext;
1891 aMsiReg.iMsixNextOffset = 0;
1892 aMsiReg.iMsixBar = VIRTIO_REGION_MSIX_CAP;
1893 aMsiReg.cMsixVectors = VBOX_MSIX_MAX_ENTRIES;
1894 rc = PDMDevHlpPCIRegisterMsi(pDevIns, &aMsiReg); /* see MsixR3init() */
1895 if (RT_FAILURE(rc))
1896 {
1897 /* See PDMDevHlp.cpp:pdmR3DevHlp_PCIRegisterMsi */
1898 LogFunc(("Failed to configure MSI-X (%Rrc). Reverting to INTx\n", rc));
1899 pVirtio->fMsiSupport = false;
1900 }
1901 else
1902 Log2Func(("Using MSI-X for guest driver notification\n"));
1903 }
1904 else
1905 LogFunc(("MSI-X not available for VBox, using INTx notification\n"));
1906
1907 /* Set offset to first capability and enable PCI dev capabilities */
1908 PDMPciDevSetCapabilityList(pPciDev, 0x40);
1909 PDMPciDevSetStatus(pPciDev, VBOX_PCI_STATUS_CAP_LIST);
1910
1911 /* Linux drivers/virtio/virtio_pci_modern.c tries to map at least a page for the
1912 * 'unknown' device-specific capability without querying the capability to figure
1913 * out size, so pad with an extra page
1914 */
1915 rc = PDMDevHlpPCIIORegionCreateMmio(pDevIns, VIRTIO_REGION_PCI_CAP, RT_ALIGN_32(cbRegion + PAGE_SIZE, PAGE_SIZE),
1916 PCI_ADDRESS_SPACE_MEM, virtioMmioWrite, virtioMmioRead, pVirtio,
1917 IOMMMIO_FLAGS_READ_PASSTHRU | IOMMMIO_FLAGS_WRITE_PASSTHRU, "virtio-scsi MMIO",
1918 &pVirtio->hMmioPciCap);
1919 AssertLogRelRCReturn(rc, PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio: cannot register PCI Capabilities address space")));
1920
1921 return rc;
1922}
1923
1924#else /* !IN_RING3 */
1925
1926/**
1927 * Sets up the core ring-0/raw-mode virtio bits.
1928 *
1929 * @returns VBox status code.
1930 * @param pDevIns The device instance.
1931 * @param pVirtio Pointer to the shared virtio state. This must be the first
1932 * member in the shared device instance data!
1933 * @param pVirtioCC Pointer to the current context virtio state. This must be the
1934 * first member in the currenct context's device instance data!
1935 */
1936int virtioCoreRZInit(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC)
1937{
1938 AssertLogRelReturn(pVirtio == PDMINS_2_DATA(pDevIns, PVIRTIOCORE), VERR_STATE_CHANGED);
1939 AssertLogRelReturn(pVirtioCC == PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC), VERR_STATE_CHANGED);
1940
1941 int rc = PDMDevHlpMmioSetUpContext(pDevIns, pVirtio->hMmioPciCap, virtioMmioWrite, virtioMmioRead, pVirtio);
1942 AssertRCReturn(rc, rc);
1943 return rc;
1944}
1945
1946#endif /* !IN_RING3 */
1947
Note: See TracBrowser for help on using the repository browser.

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