VirtualBox

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

最後變更 在這個檔案從83043是 83028,由 vboxsync 提交於 5 年 前

Network/DevVirtioNet_1_0.cpp: Fixed but in Virtio_1_0.cpp virtioWriteUsedFlags. Can now read guest MAC filter table properly.

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 83.8 KB
 
1/* $Id: Virtio_1_0.cpp 83028 2020-02-09 22:05:09Z 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-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.alldomusa.eu.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 VIRTQNAME(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 uAvailGuest = virtioReadAvailRingIdx(pDevIns, pVirtio, idxQueue);
177 bool fEmpty = uAvailGuest == pVirtio->virtqState[idxQueue].uAvailIdx;
178
179 Log6Func(("%s: uAvailGuest=%u uAvailIdx=%u. (%s)\n",
180 VIRTQNAME(pVirtio, idxQueue), uAvailGuest, pVirtio->virtqState[idxQueue].uAvailIdx,
181 fEmpty ? "Queue empty" : "Queue has available descriptors"));
182 return fEmpty;
183}
184
185#if 0 /* unused - Will be used when VIRTIO_F_EVENT_IDX optional feature is implemented, VirtIO 1.0, 2.4.7 */
186DECLINLINE(uint16_t) virtioReadAvailFlags(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
187{
188 uint16_t fFlags;
189 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
190 PDMDevHlpPCIPhysRead(pDevIns,
191 pVirtio->aGCPhysQueueAvail[idxQueue] + RT_UOFFSETOF(VIRTQ_AVAIL_T, fFlags),
192 &fFlags, sizeof(fFlags));
193 return fFlags;
194}
195#endif
196
197#ifdef IN_RING3
198DECLINLINE(uint16_t) virtioReadAvailUsedEvent(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
199{
200 uint16_t uUsedEventIdx;
201 /* VirtIO 1.0 uUsedEventIdx (used_event) immediately follows ring */
202 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
203 PDMDevHlpPCIPhysRead(pDevIns,
204 pVirtio->aGCPhysQueueAvail[idxQueue] + RT_UOFFSETOF_DYN(VIRTQ_AVAIL_T, auRing[pVirtio->uQueueSize[idxQueue]]),
205 &uUsedEventIdx, sizeof(uUsedEventIdx));
206 return uUsedEventIdx;
207}
208#endif
209
210/** @} */
211
212/** @name Accessors for virtq used ring
213 * @{
214 */
215
216#ifdef IN_RING3
217DECLINLINE(void) virtioWriteUsedElem(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue,
218 uint32_t usedIdx, uint32_t uDescIdx, uint32_t uLen)
219{
220 VIRTQ_USED_ELEM_T elem = { uDescIdx, uLen };
221 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
222 uint16_t const cQueueItems = RT_MAX(pVirtio->uQueueSize[idxQueue], 1); /* Make sure to avoid div-by-zero. */
223 PDMDevHlpPCIPhysWrite(pDevIns,
224 pVirtio->aGCPhysQueueUsed[idxQueue] + RT_UOFFSETOF_DYN(VIRTQ_USED_T, aRing[usedIdx % cQueueItems]),
225 &elem, sizeof(elem));
226}
227
228DECLINLINE(void) virtioWriteUsedFlags(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue, uint16_t fFlags)
229{
230 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
231 RT_UNTRUSTED_VALIDATED_FENCE(); /* VirtIO 1.0, Section 3.2.1.4.1 */
232 PDMDevHlpPCIPhysWrite(pDevIns,
233 pVirtio->aGCPhysQueueUsed[idxQueue] + RT_UOFFSETOF(VIRTQ_USED_T, fFlags),
234 &fFlags, sizeof(fFlags));
235}
236#endif
237
238DECLINLINE(void) virtioWriteUsedRingIdx(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue, uint16_t uIdx)
239{
240 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
241 PDMDevHlpPCIPhysWrite(pDevIns,
242 pVirtio->aGCPhysQueueUsed[idxQueue] + RT_UOFFSETOF(VIRTQ_USED_T, uIdx),
243 &uIdx, sizeof(uIdx));
244}
245
246#ifdef LOG_ENABLED
247DECLINLINE(uint16_t) virtioReadUsedRingIdx(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
248{
249 uint16_t uIdx = 0;
250 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
251 PDMDevHlpPCIPhysRead(pDevIns,
252 pVirtio->aGCPhysQueueUsed[idxQueue] + RT_UOFFSETOF(VIRTQ_USED_T, uIdx),
253 &uIdx, sizeof(uIdx));
254 return uIdx;
255}
256#endif
257
258DECLINLINE(uint16_t) virtioReadUsedFlags(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
259{
260 uint16_t fFlags = 0;
261 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
262 PDMDevHlpPCIPhysRead(pDevIns,
263 pVirtio->aGCPhysQueueUsed[idxQueue] + RT_UOFFSETOF(VIRTQ_USED_T, fFlags),
264 &fFlags, sizeof(fFlags));
265 return fFlags;
266}
267
268#if 0 /* unused - *May* be used when VIRTIO_F_EVENT_IDX optional feature is implemented VirtIO 1.0, 2.4.9.2*/
269DECLINLINE(void) virtioWriteUsedAvailEvent(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue, uint32_t uAvailEventIdx)
270{
271 /** VirtIO 1.0 uAvailEventIdx (avail_event) immediately follows ring */
272 AssertMsg(pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK, ("Called with guest driver not ready\n"));
273 PDMDevHlpPCIPhysWrite(pDevIns,
274 pVirtio->aGCPhysQueueUsed[idxQueue] + RT_UOFFSETOF_DYN(VIRTQ_USED_T, aRing[pVirtio->uQueueSize[idxQueue]]),
275 &uAvailEventIdx, sizeof(uAvailEventIdx));
276}
277#endif
278
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->gcPhysCur = paSegs[0].gcPhys;
294 pGcSgBuf->cbSegLeft = paSegs[0].cbSeg;
295 }
296 else
297 {
298 pGcSgBuf->gcPhysCur = 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->gcPhysCur >= (RTGCPHYS)pGcSgBuf->paSegs[pGcSgBuf->idxSeg].gcPhys
319 && (RTGCPHYS)pGcSgBuf->gcPhysCur + pGcSgBuf->cbSegLeft <=
320 (RTGCPHYS)pGcSgBuf->paSegs[pGcSgBuf->idxSeg].gcPhys + pGcSgBuf->paSegs[pGcSgBuf->idxSeg].cbSeg,
321 ("pGcSgBuf->idxSeg=%d pGcSgBuf->cSegs=%d pGcSgBuf->gcPhysCur=%p pGcSgBuf->cbSegLeft=%zd "
322 "pGcSgBuf->paSegs[%d].gcPhys=%p pGcSgBuf->paSegs[%d].cbSeg=%zd\n",
323 pGcSgBuf->idxSeg, pGcSgBuf->cSegs, pGcSgBuf->gcPhysCur, pGcSgBuf->cbSegLeft,
324 pGcSgBuf->idxSeg, pGcSgBuf->paSegs[pGcSgBuf->idxSeg].gcPhys, pGcSgBuf->idxSeg,
325 pGcSgBuf->paSegs[pGcSgBuf->idxSeg].cbSeg));
326
327 cbData = RT_MIN(*pcbData, pGcSgBuf->cbSegLeft);
328 pGcBuf = pGcSgBuf->gcPhysCur;
329 pGcSgBuf->cbSegLeft -= cbData;
330 if (!pGcSgBuf->cbSegLeft)
331 {
332 pGcSgBuf->idxSeg++;
333
334 if (pGcSgBuf->idxSeg < pGcSgBuf->cSegs)
335 {
336 pGcSgBuf->gcPhysCur = pGcSgBuf->paSegs[pGcSgBuf->idxSeg].gcPhys;
337 pGcSgBuf->cbSegLeft = pGcSgBuf->paSegs[pGcSgBuf->idxSeg].cbSeg;
338 }
339 *pcbData = cbData;
340 }
341 else
342 pGcSgBuf->gcPhysCur = pGcSgBuf->gcPhysCur + 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->gcPhysCur = pGcSgBuf->paSegs[0].gcPhys;
355 pGcSgBuf->cbSegLeft = pGcSgBuf->paSegs[0].cbSeg;
356 }
357 else
358 {
359 pGcSgBuf->gcPhysCur = 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/**
545 * Check if the associated queue is empty
546 *
547 * @param pDevIns The device instance (for reading).
548 * @param pVirtio Pointer to the shared virtio state.
549 * @param idxQueue Queue number
550 *
551 * @retval true Queue is empty or unavailable.
552 * @retval false Queue is available and has entries
553 */
554bool virtioCoreQueueIsEmpty(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
555{
556 if (pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK)
557 return virtqIsEmpty(pDevIns, pVirtio, idxQueue);
558 return true;
559}
560
561#ifdef IN_RING3
562
563
564int virtioCoreR3DescChainGet(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue,
565 uint16_t uHeadIdx, PPVIRTIO_DESC_CHAIN_T ppDescChain)
566{
567 AssertReturn(ppDescChain, VERR_INVALID_PARAMETER);
568
569 Assert(idxQueue < RT_ELEMENTS(pVirtio->virtqState));
570
571 PVIRTQSTATE pVirtq = &pVirtio->virtqState[idxQueue];
572
573 PVIRTIOSGSEG paSegsIn = (PVIRTIOSGSEG)RTMemAlloc(VIRTQ_MAX_SIZE * sizeof(VIRTIOSGSEG));
574 AssertReturn(paSegsIn, VERR_NO_MEMORY);
575
576 PVIRTIOSGSEG paSegsOut = (PVIRTIOSGSEG)RTMemAlloc(VIRTQ_MAX_SIZE * sizeof(VIRTIOSGSEG));
577 AssertReturn(paSegsOut, VERR_NO_MEMORY);
578
579 AssertMsgReturn(IS_DRIVER_OK(pVirtio) && pVirtio->uQueueEnable[idxQueue],
580 ("Guest driver not in ready state.\n"), VERR_INVALID_STATE);
581
582 uint16_t uDescIdx = uHeadIdx;
583
584 Log3Func(("%s DESC CHAIN: (head) desc_idx=%u\n", pVirtq->szVirtqName, uHeadIdx));
585 RT_NOREF(pVirtq);
586
587 VIRTQ_DESC_T desc;
588
589 uint32_t cbIn = 0, cbOut = 0, cSegsIn = 0, cSegsOut = 0;
590
591 do
592 {
593 PVIRTIOSGSEG pSeg;
594
595 /*
596 * Malicious guests may go beyond paSegsIn or paSegsOut boundaries by linking
597 * several descriptors into a loop. Since there is no legitimate way to get a sequences of
598 * linked descriptors exceeding the total number of descriptors in the ring (see @bugref{8620}),
599 * the following aborts I/O if breach and employs a simple log throttling algorithm to notify.
600 */
601 if (cSegsIn + cSegsOut >= VIRTQ_MAX_SIZE)
602 {
603 static volatile uint32_t s_cMessages = 0;
604 static volatile uint32_t s_cThreshold = 1;
605 if (ASMAtomicIncU32(&s_cMessages) == ASMAtomicReadU32(&s_cThreshold))
606 {
607 LogRelMax(64, ("Too many linked descriptors; check if the guest arranges descriptors in a loop.\n"));
608 if (ASMAtomicReadU32(&s_cMessages) != 1)
609 LogRelMax(64, ("(the above error has occured %u times so far)\n", ASMAtomicReadU32(&s_cMessages)));
610 ASMAtomicWriteU32(&s_cThreshold, ASMAtomicReadU32(&s_cThreshold) * 10);
611 }
612 break;
613 }
614 RT_UNTRUSTED_VALIDATED_FENCE();
615
616 virtioReadDesc(pDevIns, pVirtio, idxQueue, uDescIdx, &desc);
617
618 if (desc.fFlags & VIRTQ_DESC_F_WRITE)
619 {
620 Log3Func(("%s IN desc_idx=%u seg=%u addr=%RGp cb=%u\n", VIRTQNAME(pVirtio, idxQueue), uDescIdx, cSegsIn, desc.GCPhysBuf, desc.cb));
621 cbIn += desc.cb;
622 pSeg = &(paSegsIn[cSegsIn++]);
623 }
624 else
625 {
626 Log3Func(("%s OUT desc_idx=%u seg=%u addr=%RGp cb=%u\n", VIRTQNAME(pVirtio, idxQueue), uDescIdx, cSegsOut, desc.GCPhysBuf, desc.cb));
627 cbOut += desc.cb;
628 pSeg = &(paSegsOut[cSegsOut++]);
629 }
630
631 pSeg->gcPhys = desc.GCPhysBuf;
632 pSeg->cbSeg = desc.cb;
633
634 uDescIdx = desc.uDescIdxNext;
635 } while (desc.fFlags & VIRTQ_DESC_F_NEXT);
636
637 PVIRTIOSGBUF pSgPhysIn = (PVIRTIOSGBUF)RTMemAllocZ(sizeof(VIRTIOSGBUF));
638 AssertReturn(pSgPhysIn, VERR_NO_MEMORY);
639
640 virtioCoreSgBufInit(pSgPhysIn, paSegsIn, cSegsIn);
641
642 PVIRTIOSGBUF pSgPhysOut = (PVIRTIOSGBUF)RTMemAllocZ(sizeof(VIRTIOSGBUF));
643 AssertReturn(pSgPhysOut, VERR_NO_MEMORY);
644
645 virtioCoreSgBufInit(pSgPhysOut, paSegsOut, cSegsOut);
646
647 PVIRTIO_DESC_CHAIN_T pDescChain = (PVIRTIO_DESC_CHAIN_T)RTMemAllocZ(sizeof(VIRTIO_DESC_CHAIN_T));
648 AssertReturn(pDescChain, VERR_NO_MEMORY);
649
650 pDescChain->uHeadIdx = uHeadIdx;
651 pDescChain->cbPhysSend = cbOut;
652 pDescChain->pSgPhysSend = pSgPhysOut;
653 pDescChain->cbPhysReturn = cbIn;
654 pDescChain->pSgPhysReturn = pSgPhysIn;
655 *ppDescChain = pDescChain;
656
657 Log3Func(("%s -- segs OUT: %u (%u bytes) IN: %u (%u bytes) --\n", pVirtq->szVirtqName, cSegsOut, cbOut, cSegsIn, cbIn));
658
659 return VINF_SUCCESS;
660}
661
662/*
663 * Notifies guest (via ISR or MSI-X) of device configuration change
664 *
665 * @param pVirtio Pointer to the shared virtio state.
666 */
667void virtioCoreNotifyConfigChanged(PVIRTIOCORE pVirtio)
668{
669 virtioKick(pVirtio->pDevIns, pVirtio, VIRTIO_ISR_DEVICE_CONFIG, pVirtio->uMsixConfig, false);
670}
671
672/**
673 * Enable or Disable notification for the specified queue
674 *
675 * @param pVirtio Pointer to the shared virtio state.
676 * @param idxQueue Queue number
677 * @param fEnabled Selects notification mode (enabled or disabled)
678 */
679void virtioCoreQueueSetNotify(PVIRTIOCORE pVirtio, uint16_t idxQueue, bool fEnabled)
680{
681 if (pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK)
682 {
683 uint16_t fFlags = virtioReadUsedFlags(pVirtio->pDevIns, pVirtio, idxQueue);
684
685 if (fEnabled)
686 fFlags &= ~ VIRTQ_USED_F_NO_NOTIFY;
687 else
688 fFlags |= VIRTQ_USED_F_NO_NOTIFY;
689
690 virtioWriteUsedFlags(pVirtio->pDevIns, pVirtio, idxQueue, fFlags);
691 }
692}
693
694/**
695 * Initiate orderly reset procedure. This is an exposed API for clients that might need it.
696 * Invoked by client to reset the device and driver (see VirtIO 1.0 section 2.1.1/2.1.2)
697 *
698 * @param pVirtio Pointer to the virtio state.
699 */
700void virtioCoreResetAll(PVIRTIOCORE pVirtio)
701{
702 LogFunc(("\n"));
703 pVirtio->uDeviceStatus |= VIRTIO_STATUS_DEVICE_NEEDS_RESET;
704 if (pVirtio->uDeviceStatus & VIRTIO_STATUS_DRIVER_OK)
705 {
706 pVirtio->fGenUpdatePending = true;
707 virtioKick(pVirtio->pDevIns, pVirtio, VIRTIO_ISR_DEVICE_CONFIG, pVirtio->uMsixConfig, false /* fForce */);
708 }
709}
710/**
711 * Get count of new (e.g. pending) elements in available ring.
712 *
713 * @param pDevIns The device instance.
714 * @param pVirtio Pointer to the shared virtio state.
715 * @param idxQueue Queue number
716 *
717 * @returns how many entries have been added to ring as a delta of the consumer's
718 * avail index and the queue's guest-side current avail index.
719 */
720int virtioCoreR3QueuePendingCount(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
721{
722 uint16_t uAvailRingIdx = virtioReadAvailRingIdx(pDevIns, pVirtio, idxQueue);
723 uint16_t uNextAvailIdx = pVirtio->virtqState[idxQueue].uAvailIdx;
724 int16_t iDelta = uAvailRingIdx - uNextAvailIdx;
725 uint16_t uDelta = uAvailRingIdx - uNextAvailIdx;
726 return iDelta >= 0 ? uDelta : VIRTQ_MAX_CNT + uDelta;
727}
728/**
729 * Fetches descriptor chain using avail ring of indicated queue and converts the descriptor
730 * chain into its OUT (to device) and IN to guest components, but does NOT remove it from
731 * the 'avail' queue. I.e. doesn't advance the index. This can be used with virtioQueueSkip(),
732 * which *does* advance the avail index. Together they facilitate a mechanism that allows
733 * work with a queue element (descriptor chain) to be aborted if necessary, by not advancing
734 * the pointer, or, upon success calling the skip function (above) to move to the next element.
735 *
736 * Additionally it converts the OUT desc chain data to a contiguous virtual
737 * memory buffer for easy consumption by the caller. The caller must return the
738 * descriptor chain pointer via virtioCoreR3QueuePut() and then call virtioCoreQueueSync()
739 * at some point to return the data to the guest and complete the transaction.
740 *
741 * @param pDevIns The device instance.
742 * @param pVirtio Pointer to the shared virtio state.
743 * @param idxQueue Queue number
744 * @param ppDescChain Address to store pointer to descriptor chain that contains the
745 * pre-processed transaction information pulled from the virtq.
746 *
747 * @returns VBox status code:
748 * @retval VINF_SUCCESS Success
749 * @retval VERR_INVALID_STATE VirtIO not in ready state (asserted).
750 * @retval VERR_NOT_AVAILABLE If the queue is empty.
751 */
752
753int virtioCoreR3QueuePeek(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue,
754 PPVIRTIO_DESC_CHAIN_T ppDescChain)
755{
756 return virtioCoreR3QueueGet(pDevIns, pVirtio, idxQueue, ppDescChain, false);
757}
758
759/**
760 * Skip the next entry in the specified queue (typically used with virtioCoreR3QueuePeek())
761 *
762 * @param pVirtio Pointer to the virtio state.
763 * @param idxQueue Index of queue
764 */
765int virtioCoreR3QueueSkip(PVIRTIOCORE pVirtio, uint16_t idxQueue)
766{
767 Assert(idxQueue < RT_ELEMENTS(pVirtio->virtqState));
768 PVIRTQSTATE pVirtq = &pVirtio->virtqState[idxQueue];
769
770 AssertMsgReturn(IS_DRIVER_OK(pVirtio) && pVirtio->uQueueEnable[idxQueue],
771 ("Guest driver not in ready state.\n"), VERR_INVALID_STATE);
772
773 if (virtioCoreQueueIsEmpty(pVirtio->pDevIns, pVirtio, idxQueue))
774 return VERR_NOT_AVAILABLE;
775
776 Log2Func(("%s avail_idx=%u\n", pVirtq->szVirtqName, pVirtq->uAvailIdx));
777 pVirtq->uAvailIdx++;
778
779 return VINF_SUCCESS;
780}
781
782/**
783 * Fetches descriptor chain using avail ring of indicated queue and converts the descriptor
784 * chain into its OUT (to device) and IN to guest components.
785 *
786 * Additionally it converts the OUT desc chain data to a contiguous virtual
787 * memory buffer for easy consumption by the caller. The caller must return the
788 * descriptor chain pointer via virtioCoreR3QueuePut() and then call virtioCoreQueueSync()
789 * at some point to return the data to the guest and complete the transaction.
790 *
791 * @param pDevIns The device instance.
792 * @param pVirtio Pointer to the shared virtio state.
793 * @param idxQueue Queue number
794 * @param ppDescChain Address to store pointer to descriptor chain that contains the
795 * pre-processed transaction information pulled from the virtq.
796 * @param fRemove flags whether to remove desc chain from queue (false = peek)
797 *
798 * @returns VBox status code:
799 * @retval VINF_SUCCESS Success
800 * @retval VERR_INVALID_STATE VirtIO not in ready state (asserted).
801 * @retval VERR_NOT_AVAILABLE If the queue is empty.
802 */
803int virtioCoreR3QueueGet(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue,
804 PPVIRTIO_DESC_CHAIN_T ppDescChain, bool fRemove)
805{
806 PVIRTQSTATE pVirtq = &pVirtio->virtqState[idxQueue];
807
808 if (virtqIsEmpty(pDevIns, pVirtio, idxQueue))
809 return VERR_NOT_AVAILABLE;
810
811 uint16_t uHeadIdx = virtioReadAvailDescIdx(pDevIns, pVirtio, idxQueue, pVirtq->uAvailIdx);
812
813 if (fRemove)
814 pVirtq->uAvailIdx++;
815
816 int rc = virtioCoreR3DescChainGet(pDevIns, pVirtio, idxQueue, uHeadIdx, ppDescChain);
817 return rc;
818}
819
820/**
821 * Returns data to the guest to complete a transaction initiated by virtQueueGet().
822 *
823 * The caller passes in a pointer to a scatter-gather buffer of virtual memory segments
824 * and a pointer to the descriptor chain context originally derived from the pulled
825 * queue entry, and this function will write the virtual memory s/g buffer into the
826 * guest's physical memory free the descriptor chain. The caller handles the freeing
827 * (as needed) of the virtual memory buffer.
828 *
829 * @note This does a write-ahead to the used ring of the guest's queue. The data
830 * written won't be seen by the guest until the next call to virtioCoreQueueSync()
831 *
832 *
833 * @param pDevIns The device instance (for reading).
834 * @param pVirtio Pointer to the shared virtio state.
835 * @param idxQueue Queue number
836 *
837 * @param pSgVirtReturn Points to scatter-gather buffer of virtual memory
838 * segments the caller is returning to the guest.
839 *
840 * @param pDescChain This contains the context of the scatter-gather
841 * buffer originally pulled from the queue.
842 *
843 * @param fFence If true, put up copy fence (memory barrier) after
844 * copying to guest phys. mem.
845 *
846 * @returns VBox status code.
847 * @retval VINF_SUCCESS Success
848 * @retval VERR_INVALID_STATE VirtIO not in ready state
849 * @retval VERR_NOT_AVAILABLE Queue is empty
850 */
851int virtioCoreR3QueuePut(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue, PRTSGBUF pSgVirtReturn,
852 PVIRTIO_DESC_CHAIN_T pDescChain, bool fFence)
853{
854 Assert(idxQueue < RT_ELEMENTS(pVirtio->virtqState));
855 PVIRTQSTATE pVirtq = &pVirtio->virtqState[idxQueue];
856 PVIRTIOSGBUF pSgPhysReturn = pDescChain->pSgPhysReturn;
857
858 AssertMsgReturn(IS_DRIVER_OK(pVirtio) /*&& pVirtio->uQueueEnable[idxQueue]*/,
859 ("Guest driver not in ready state.\n"), VERR_INVALID_STATE);
860
861 Log3Func(("Copying client data to %s, desc chain (head desc_idx %d)\n",
862 VIRTQNAME(pVirtio, idxQueue), virtioReadUsedRingIdx(pDevIns, pVirtio, idxQueue)));
863
864 /*
865 * Copy s/g buf (virtual memory) to guest phys mem (IN direction). This virtual memory
866 * block will be small (fixed portion of response header + sense buffer area or
867 * control commands or error return values)... The bulk of req data xfers to phys mem
868 * is handled by client */
869
870 size_t cbCopy = 0;
871
872 if (pSgVirtReturn)
873 {
874 size_t cbRemain = RTSgBufCalcTotalLength(pSgVirtReturn);
875 virtioCoreSgBufReset(pSgPhysReturn); /* Reset ptr because req data may have already been written */
876 while (cbRemain)
877 {
878 PVIRTIOSGSEG paSeg = &pSgPhysReturn->paSegs[pSgPhysReturn->idxSeg];
879 uint64_t dstSgStart = (uint64_t)paSeg->gcPhys;
880 uint64_t dstSgLen = (uint64_t)paSeg->cbSeg;
881 uint64_t dstSgCur = (uint64_t)pSgPhysReturn->gcPhysCur;
882 cbCopy = RT_MIN((uint64_t)pSgVirtReturn->cbSegLeft, dstSgLen - (dstSgCur - dstSgStart));
883 PDMDevHlpPhysWrite(pDevIns, (RTGCPHYS)pSgPhysReturn->gcPhysCur, pSgVirtReturn->pvSegCur, cbCopy);
884 RTSgBufAdvance(pSgVirtReturn, cbCopy);
885 virtioCoreSgBufAdvance(pSgPhysReturn, cbCopy);
886 cbRemain -= cbCopy;
887 }
888
889 if (fFence)
890 RT_UNTRUSTED_NONVOLATILE_COPY_FENCE(); /* needed? */
891
892 Assert(!(cbCopy >> 32));
893 }
894
895
896 /* If this write-ahead crosses threshold where the driver wants to get an event flag it */
897 if (pVirtio->uDriverFeatures & VIRTIO_F_EVENT_IDX)
898 if (pVirtq->uUsedIdx == virtioReadAvailUsedEvent(pDevIns, pVirtio, idxQueue))
899 pVirtq->fEventThresholdReached = true;
900
901 /*
902 * Place used buffer's descriptor in used ring but don't update used ring's slot index.
903 * That will be done with a subsequent client call to virtioCoreQueueSync() */
904 virtioWriteUsedElem(pDevIns, pVirtio, idxQueue, pVirtq->uUsedIdx++, pDescChain->uHeadIdx, (uint32_t)cbCopy);
905
906 Log3Func((".... Copied %zu bytes to %u byte buffer, residual=%zu\n",
907 cbCopy, pDescChain->cbPhysReturn, pDescChain->cbPhysReturn - cbCopy));
908
909 Log6Func(("Write ahead used_idx=%u, %s used_idx=%u\n",
910 pVirtq->uUsedIdx, VIRTQNAME(pVirtio, idxQueue), virtioReadUsedRingIdx(pDevIns, pVirtio, idxQueue)));
911
912 RTMemFree((void *)pDescChain->pSgPhysSend->paSegs);
913 RTMemFree(pDescChain->pSgPhysSend);
914 RTMemFree((void *)pSgPhysReturn->paSegs);
915 RTMemFree(pSgPhysReturn);
916 RTMemFree(pDescChain);
917
918 return VINF_SUCCESS;
919}
920
921#endif /* IN_RING3 */
922
923/**
924 * Updates the indicated virtq's "used ring" descriptor index to match the
925 * current write-head index, thus exposing the data added to the used ring by all
926 * virtioCoreR3QueuePut() calls since the last sync. This should be called after one or
927 * more virtioCoreR3QueuePut() calls to inform the guest driver there is data in the queue.
928 * Explicit notifications (e.g. interrupt or MSI-X) will be sent to the guest,
929 * depending on VirtIO features negotiated and conditions, otherwise the guest
930 * will detect the update by polling. (see VirtIO 1.0
931 * specification, Section 2.4 "Virtqueues").
932 *
933 * @param pDevIns The device instance.
934 * @param pVirtio Pointer to the shared virtio state.
935 * @param idxQueue Queue number
936 *
937 * @returns VBox status code.
938 * @retval VINF_SUCCESS Success
939 * @retval VERR_INVALID_STATE VirtIO not in ready state
940 */
941int virtioCoreQueueSync(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue)
942{
943 Assert(idxQueue < RT_ELEMENTS(pVirtio->virtqState));
944 PVIRTQSTATE pVirtq = &pVirtio->virtqState[idxQueue];
945
946 AssertMsgReturn(IS_DRIVER_OK(pVirtio) && pVirtio->uQueueEnable[idxQueue],
947 ("Guest driver not in ready state.\n"), VERR_INVALID_STATE);
948
949 Log6Func(("Updating %s used_idx from %u to %u\n",
950 VIRTQNAME(pVirtio, idxQueue), virtioReadUsedRingIdx(pDevIns, pVirtio, idxQueue), pVirtq->uUsedIdx));
951
952 virtioWriteUsedRingIdx(pDevIns, pVirtio, idxQueue, pVirtq->uUsedIdx);
953 virtioNotifyGuestDriver(pDevIns, pVirtio, idxQueue, false);
954
955 return VINF_SUCCESS;
956}
957
958#ifdef IN_RING3
959/**
960 */
961static void virtioR3QueueNotified(PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC, uint16_t idxQueue, uint16_t uNotifyIdx)
962{
963 /* See VirtIO 1.0, section 4.1.5.2 It implies that idxQueue and uNotifyIdx should match.
964 * Disregarding this notification may cause throughput to stop, however there's no way to know
965 * which was queue was intended for wake-up if the two parameters disagree. */
966
967 AssertMsg(uNotifyIdx == idxQueue,
968 ("Guest kicked virtq %d's notify addr w/non-corresponding virtq idx %d\n",
969 idxQueue, uNotifyIdx));
970 RT_NOREF(uNotifyIdx);
971
972 AssertReturnVoid(idxQueue < RT_ELEMENTS(pVirtio->virtqState));
973 Log6Func(("%s\n", pVirtio->virtqState[idxQueue].szVirtqName));
974
975 /* Inform client */
976 pVirtioCC->pfnQueueNotified(pVirtio, pVirtioCC, idxQueue);
977}
978#endif /* IN_RING3 */
979
980/**
981 * Trigger MSI-X or INT# interrupt to notify guest of data added to used ring of
982 * the specified virtq, depending on the interrupt configuration of the device
983 * and depending on negotiated and realtime constraints flagged by the guest driver.
984 *
985 * See VirtIO 1.0 specification (section 2.4.7).
986 *
987 * @param pDevIns The device instance.
988 * @param pVirtio Pointer to the shared virtio state.
989 * @param idxQueue Queue to check for guest interrupt handling preference
990 * @param fForce Overrides idxQueue, forcing notification regardless of driver's
991 * notification preferences. This is a safeguard to prevent
992 * stalls upon resuming the VM. VirtIO 1.0 specification Section 4.1.5.5
993 * indicates spurious interrupts are harmless to guest driver's state,
994 * as they only cause the guest driver to [re]scan queues for work to do.
995 */
996static void virtioNotifyGuestDriver(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint16_t idxQueue, bool fForce)
997{
998
999 Assert(idxQueue < RT_ELEMENTS(pVirtio->virtqState));
1000 PVIRTQSTATE pVirtq = &pVirtio->virtqState[idxQueue];
1001
1002 AssertMsgReturnVoid(IS_DRIVER_OK(pVirtio), ("Guest driver not in ready state.\n"));
1003 if (pVirtio->uDriverFeatures & VIRTIO_F_EVENT_IDX)
1004 {
1005 if (pVirtq->fEventThresholdReached)
1006 {
1007 virtioKick(pDevIns, pVirtio, VIRTIO_ISR_VIRTQ_INTERRUPT, pVirtio->uQueueMsixVector[idxQueue], fForce);
1008 pVirtq->fEventThresholdReached = false;
1009 return;
1010 }
1011 Log6Func(("...skipping interrupt: VIRTIO_F_EVENT_IDX set but threshold not reached\n"));
1012 }
1013 else
1014 {
1015 /** If guest driver hasn't suppressed interrupts, interrupt */
1016 if (fForce || !(virtioReadUsedFlags(pDevIns, pVirtio, idxQueue) & VIRTQ_AVAIL_F_NO_INTERRUPT))
1017 {
1018 virtioKick(pDevIns, pVirtio, VIRTIO_ISR_VIRTQ_INTERRUPT, pVirtio->uQueueMsixVector[idxQueue], fForce);
1019 return;
1020 }
1021 Log6Func(("...skipping interrupt. Guest flagged VIRTQ_AVAIL_F_NO_INTERRUPT for queue\n"));
1022 }
1023}
1024
1025/**
1026 * Raise interrupt or MSI-X
1027 *
1028 * @param pDevIns The device instance.
1029 * @param pVirtio Pointer to the shared virtio state.
1030 * @param uCause Interrupt cause bit mask to set in PCI ISR port.
1031 * @param uVec MSI-X vector, if enabled
1032 * @param uForce True of out-of-band
1033 */
1034static int virtioKick(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, uint8_t uCause, uint16_t uMsixVector, bool fForce)
1035{
1036 if (fForce)
1037 Log6Func(("reason: resumed after suspend\n"));
1038 else
1039 if (uCause == VIRTIO_ISR_VIRTQ_INTERRUPT)
1040 Log6Func(("reason: buffer added to 'used' ring.\n"));
1041 else
1042 if (uCause == VIRTIO_ISR_DEVICE_CONFIG)
1043 Log6Func(("reason: device config change\n"));
1044
1045 if (!pVirtio->fMsiSupport)
1046 {
1047 pVirtio->uISR |= uCause;
1048 PDMDevHlpPCISetIrq(pDevIns, 0, PDM_IRQ_LEVEL_HIGH);
1049 }
1050 else if (uMsixVector != VIRTIO_MSI_NO_VECTOR)
1051 PDMDevHlpPCISetIrq(pDevIns, uMsixVector, 1);
1052 return VINF_SUCCESS;
1053}
1054
1055/**
1056 * Lower interrupt (Called when guest reads ISR and when resetting)
1057 *
1058 * @param pDevIns The device instance.
1059 */
1060static void virtioLowerInterrupt(PPDMDEVINS pDevIns, uint16_t uMsixVector)
1061{
1062 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
1063 if (!pVirtio->fMsiSupport)
1064 PDMDevHlpPCISetIrq(pDevIns, 0, PDM_IRQ_LEVEL_LOW);
1065 else if (uMsixVector != VIRTIO_MSI_NO_VECTOR)
1066 PDMDevHlpPCISetIrq(pDevIns, pVirtio->uMsixConfig, PDM_IRQ_LEVEL_LOW);
1067}
1068
1069#ifdef IN_RING3
1070static void virtioResetQueue(PVIRTIOCORE pVirtio, uint16_t idxQueue)
1071{
1072 Assert(idxQueue < RT_ELEMENTS(pVirtio->virtqState));
1073 PVIRTQSTATE pVirtQ = &pVirtio->virtqState[idxQueue];
1074 pVirtQ->uAvailIdx = 0;
1075 pVirtQ->uUsedIdx = 0;
1076 pVirtio->uQueueEnable[idxQueue] = false;
1077 pVirtio->uQueueSize[idxQueue] = VIRTQ_MAX_SIZE;
1078 pVirtio->uQueueNotifyOff[idxQueue] = idxQueue;
1079 pVirtio->uQueueMsixVector[idxQueue] = idxQueue + 2;
1080
1081 if (!pVirtio->fMsiSupport) /* VirtIO 1.0, 4.1.4.3 and 4.1.5.1.2 */
1082 pVirtio->uQueueMsixVector[idxQueue] = VIRTIO_MSI_NO_VECTOR;
1083
1084 virtioLowerInterrupt(pVirtio->pDevIns, pVirtio->uQueueMsixVector[idxQueue]);
1085}
1086
1087static void virtioResetDevice(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio)
1088{
1089 Log2Func(("\n"));
1090 pVirtio->uDeviceFeaturesSelect = 0;
1091 pVirtio->uDriverFeaturesSelect = 0;
1092 pVirtio->uConfigGeneration = 0;
1093 pVirtio->uDeviceStatus = 0;
1094 pVirtio->uISR = 0;
1095
1096 if (!pVirtio->fMsiSupport)
1097 virtioLowerInterrupt(pDevIns, 0);
1098 else
1099 {
1100 virtioLowerInterrupt(pDevIns, pVirtio->uMsixConfig);
1101 for (int i = 0; i < VIRTQ_MAX_CNT; i++)
1102 {
1103 virtioLowerInterrupt(pDevIns, pVirtio->uQueueMsixVector[i]);
1104 pVirtio->uQueueMsixVector[i];
1105 }
1106 }
1107
1108 if (!pVirtio->fMsiSupport) /* VirtIO 1.0, 4.1.4.3 and 4.1.5.1.2 */
1109 pVirtio->uMsixConfig = VIRTIO_MSI_NO_VECTOR;
1110
1111 for (uint16_t idxQueue = 0; idxQueue < VIRTQ_MAX_CNT; idxQueue++)
1112 virtioResetQueue(pVirtio, idxQueue);
1113}
1114
1115/**
1116 * Invoked by this implementation when guest driver resets the device.
1117 * The driver itself will not until the device has read the status change.
1118 */
1119static void virtioGuestR3WasReset(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC)
1120{
1121 LogFunc(("Guest reset the device\n"));
1122
1123 /* Let the client know */
1124 pVirtioCC->pfnStatusChanged(pVirtio, pVirtioCC, 0);
1125 virtioResetDevice(pDevIns, pVirtio);
1126}
1127#endif /* IN_RING3 */
1128
1129/**
1130 * Handle accesses to Common Configuration capability
1131 *
1132 * @returns VBox status code
1133 *
1134 * @param pDevIns The device instance.
1135 * @param pVirtio Pointer to the shared virtio state.
1136 * @param pVirtioCC Pointer to the current context virtio state.
1137 * @param fWrite Set if write access, clear if read access.
1138 * @param offCfg The common configuration capability offset.
1139 * @param cb Number of bytes to read or write
1140 * @param pv Pointer to location to write to or read from
1141 */
1142static int virtioCommonCfgAccessed(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC,
1143 int fWrite, uint32_t offCfg, unsigned cb, void *pv)
1144{
1145/**
1146 * This macro resolves to boolean true if the implied parameters, offCfg and cb,
1147 * match the field offset and size of a field in the Common Cfg struct, (or if
1148 * it is a 64-bit field, if it accesses either 32-bit part as a 32-bit access)
1149 * This is mandated by section 4.1.3.1 of the VirtIO 1.0 specification)
1150 *
1151 * @param member Member of VIRTIO_PCI_COMMON_CFG_T
1152 * @param offCfg Implied parameter: Offset into VIRTIO_PCI_COMMON_CFG_T
1153 * @param cb Implied parameter: Number of bytes to access
1154 * @result true or false
1155 */
1156#define MATCH_COMMON_CFG(member) \
1157 ( ( RT_SIZEOFMEMB(VIRTIO_PCI_COMMON_CFG_T, member) == 8 \
1158 && ( offCfg == RT_OFFSETOF(VIRTIO_PCI_COMMON_CFG_T, member) \
1159 || offCfg == RT_OFFSETOF(VIRTIO_PCI_COMMON_CFG_T, member) + sizeof(uint32_t)) \
1160 && cb == sizeof(uint32_t)) \
1161 || ( offCfg == RT_OFFSETOF(VIRTIO_PCI_COMMON_CFG_T, member) \
1162 && cb == RT_SIZEOFMEMB(VIRTIO_PCI_COMMON_CFG_T, member)) )
1163
1164#ifdef LOG_ENABLED
1165# define LOG_COMMON_CFG_ACCESS(member, a_offIntra) \
1166 if (LogIs7Enabled()) { \
1167 virtioCoreLogMappedIoValue(__FUNCTION__, #member, RT_SIZEOFMEMB(VIRTIO_PCI_COMMON_CFG_T, member), \
1168 pv, cb, a_offIntra, fWrite, false, 0); \
1169 }
1170# define LOG_COMMON_CFG_ACCESS_INDEXED(member, idx, a_offIntra) \
1171 if (LogIs7Enabled()) { \
1172 virtioCoreLogMappedIoValue(__FUNCTION__, #member, RT_SIZEOFMEMB(VIRTIO_PCI_COMMON_CFG_T, member), \
1173 pv, cb, a_offIntra, fWrite, true, idx); \
1174 }
1175#else
1176# define LOG_COMMON_CFG_ACCESS(member, a_offIntra) do { } while (0)
1177# define LOG_COMMON_CFG_ACCESS_INDEXED(member, idx, a_offIntra) do { } while (0)
1178#endif
1179
1180#define COMMON_CFG_ACCESSOR(member) \
1181 do \
1182 { \
1183 uint32_t offIntra = offCfg - RT_OFFSETOF(VIRTIO_PCI_COMMON_CFG_T, member); \
1184 if (fWrite) \
1185 memcpy((char *)&pVirtio->member + offIntra, (const char *)pv, cb); \
1186 else \
1187 memcpy(pv, (const char *)&pVirtio->member + offIntra, cb); \
1188 LOG_COMMON_CFG_ACCESS(member, offIntra); \
1189 } while(0)
1190
1191#define COMMON_CFG_ACCESSOR_INDEXED(member, idx) \
1192 do \
1193 { \
1194 uint32_t offIntra = offCfg - RT_OFFSETOF(VIRTIO_PCI_COMMON_CFG_T, member); \
1195 if (fWrite) \
1196 memcpy((char *)&pVirtio->member[idx] + offIntra, pv, cb); \
1197 else \
1198 memcpy(pv, (const char *)&pVirtio->member[idx] + offIntra, cb); \
1199 LOG_COMMON_CFG_ACCESS_INDEXED(member, idx, offIntra); \
1200 } while(0)
1201
1202#define COMMON_CFG_ACCESSOR_READONLY(member) \
1203 do \
1204 { \
1205 uint32_t offIntra = offCfg - RT_OFFSETOF(VIRTIO_PCI_COMMON_CFG_T, member); \
1206 if (fWrite) \
1207 LogFunc(("Guest attempted to write readonly virtio_pci_common_cfg.%s\n", #member)); \
1208 else \
1209 { \
1210 memcpy(pv, (const char *)&pVirtio->member + offIntra, cb); \
1211 LOG_COMMON_CFG_ACCESS(member, offIntra); \
1212 } \
1213 } while(0)
1214
1215#define COMMON_CFG_ACCESSOR_INDEXED_READONLY(member, idx) \
1216 do \
1217 { \
1218 uint32_t offIntra = offCfg - RT_OFFSETOF(VIRTIO_PCI_COMMON_CFG_T, member); \
1219 if (fWrite) \
1220 LogFunc(("Guest attempted to write readonly virtio_pci_common_cfg.%s[%d]\n", #member, idx)); \
1221 else \
1222 { \
1223 memcpy(pv, (char const *)&pVirtio->member[idx] + offIntra, cb); \
1224 LOG_COMMON_CFG_ACCESS_INDEXED(member, idx, offIntra); \
1225 } \
1226 } while(0)
1227
1228
1229 int rc = VINF_SUCCESS;
1230 uint64_t val;
1231 if (MATCH_COMMON_CFG(uDeviceFeatures))
1232 {
1233 if (fWrite) /* Guest WRITE pCommonCfg>uDeviceFeatures */
1234 {
1235 LogFunc(("Guest attempted to write readonly virtio_pci_common_cfg.device_feature\n"));
1236 return VINF_SUCCESS;
1237 }
1238 else /* Guest READ pCommonCfg->uDeviceFeatures */
1239 {
1240 switch (pVirtio->uDeviceFeaturesSelect)
1241 {
1242 case 0:
1243 val = pVirtio->uDeviceFeatures & UINT32_C(0xffffffff);
1244 memcpy(pv, &val, cb);
1245 LOG_COMMON_CFG_ACCESS(uDeviceFeatures, offCfg - RT_UOFFSETOF(VIRTIO_PCI_COMMON_CFG_T, uDeviceFeatures));
1246 break;
1247 case 1:
1248 val = pVirtio->uDeviceFeatures >> 32;
1249 memcpy(pv, &val, cb);
1250 LOG_COMMON_CFG_ACCESS(uDeviceFeatures, offCfg - RT_UOFFSETOF(VIRTIO_PCI_COMMON_CFG_T, uDeviceFeatures) + 4);
1251 break;
1252 default:
1253 LogFunc(("Guest read uDeviceFeatures with out of range selector (%#x), returning 0\n",
1254 pVirtio->uDeviceFeaturesSelect));
1255 return VINF_IOM_MMIO_UNUSED_00;
1256 }
1257 }
1258 }
1259 else if (MATCH_COMMON_CFG(uDriverFeatures))
1260 {
1261 if (fWrite) /* Guest WRITE pCommonCfg->udriverFeatures */
1262 {
1263 switch (pVirtio->uDriverFeaturesSelect)
1264 {
1265 case 0:
1266 memcpy(&pVirtio->uDriverFeatures, pv, cb);
1267 LOG_COMMON_CFG_ACCESS(uDriverFeatures, offCfg - RT_UOFFSETOF(VIRTIO_PCI_COMMON_CFG_T, uDriverFeatures));
1268 break;
1269 case 1:
1270 memcpy((char *)&pVirtio->uDriverFeatures + sizeof(uint32_t), pv, cb);
1271 LOG_COMMON_CFG_ACCESS(uDriverFeatures, offCfg - RT_UOFFSETOF(VIRTIO_PCI_COMMON_CFG_T, uDriverFeatures) + 4);
1272 break;
1273 default:
1274 LogFunc(("Guest wrote uDriverFeatures with out of range selector (%#x), returning 0\n",
1275 pVirtio->uDriverFeaturesSelect));
1276 return VINF_SUCCESS;
1277 }
1278 }
1279 else /* Guest READ pCommonCfg->udriverFeatures */
1280 {
1281 switch (pVirtio->uDriverFeaturesSelect)
1282 {
1283 case 0:
1284 val = pVirtio->uDriverFeatures & 0xffffffff;
1285 memcpy(pv, &val, cb);
1286 LOG_COMMON_CFG_ACCESS(uDriverFeatures, offCfg - RT_UOFFSETOF(VIRTIO_PCI_COMMON_CFG_T, uDriverFeatures));
1287 break;
1288 case 1:
1289 val = (pVirtio->uDriverFeatures >> 32) & 0xffffffff;
1290 memcpy(pv, &val, cb);
1291 LOG_COMMON_CFG_ACCESS(uDriverFeatures, offCfg - RT_UOFFSETOF(VIRTIO_PCI_COMMON_CFG_T, uDriverFeatures) + 4);
1292 break;
1293 default:
1294 LogFunc(("Guest read uDriverFeatures with out of range selector (%#x), returning 0\n",
1295 pVirtio->uDriverFeaturesSelect));
1296 return VINF_IOM_MMIO_UNUSED_00;
1297 }
1298 }
1299 }
1300 else if (MATCH_COMMON_CFG(uNumQueues))
1301 {
1302 if (fWrite)
1303 {
1304 Log2Func(("Guest attempted to write readonly virtio_pci_common_cfg.num_queues\n"));
1305 return VINF_SUCCESS;
1306 }
1307 else
1308 {
1309 *(uint16_t *)pv = VIRTQ_MAX_CNT;
1310 LOG_COMMON_CFG_ACCESS(uNumQueues, 0);
1311 }
1312 }
1313 else if (MATCH_COMMON_CFG(uDeviceStatus))
1314 {
1315 if (fWrite) /* Guest WRITE pCommonCfg->uDeviceStatus */
1316 {
1317 uint8_t const fNewStatus = *(uint8_t *)pv;
1318 Log7Func(("Guest wrote uDeviceStatus (%#x, was %#x, change #%x) ................ (",
1319 fNewStatus, pVirtio->uDeviceStatus, fNewStatus ^ pVirtio->uDeviceStatus));
1320 if (LogIs7Enabled())
1321 virtioLogDeviceStatus(fNewStatus);
1322 Log7((")\n"));
1323
1324 /* If the status changed or we were reset, we need to go to ring-3 as
1325 it requires notifying the parent device. */
1326 bool const fStatusChanged = (fNewStatus & VIRTIO_STATUS_DRIVER_OK)
1327 != (pVirtio->uPrevDeviceStatus & VIRTIO_STATUS_DRIVER_OK);
1328#ifndef IN_RING3
1329 if (fStatusChanged || fNewStatus == 0)
1330 {
1331 Log6Func(("=>ring3\n"));
1332 return VINF_IOM_R3_MMIO_WRITE;
1333 }
1334#endif
1335 pVirtio->uDeviceStatus = fNewStatus;
1336
1337#ifdef IN_RING3
1338 /*
1339 * Notify client only if status actually changed from last time and when we're reset.
1340 */
1341 if (pVirtio->uDeviceStatus == 0)
1342 virtioGuestR3WasReset(pDevIns, pVirtio, pVirtioCC);
1343 if (fStatusChanged)
1344 pVirtioCC->pfnStatusChanged(pVirtio, pVirtioCC, fNewStatus & VIRTIO_STATUS_DRIVER_OK);
1345#endif
1346 /*
1347 * Save the current status for the next write so we can see what changed.
1348 */
1349 pVirtio->uPrevDeviceStatus = pVirtio->uDeviceStatus;
1350 }
1351 else /* Guest READ pCommonCfg->uDeviceStatus */
1352 {
1353 Log7Func(("Guest read uDeviceStatus ................ ("));
1354 *(uint8_t *)pv = pVirtio->uDeviceStatus;
1355 if (LogIs7Enabled())
1356 virtioLogDeviceStatus(pVirtio->uDeviceStatus);
1357 Log7((")\n"));
1358 }
1359 }
1360 else
1361 if (MATCH_COMMON_CFG(uMsixConfig))
1362 COMMON_CFG_ACCESSOR(uMsixConfig);
1363 else
1364 if (MATCH_COMMON_CFG(uDeviceFeaturesSelect))
1365 COMMON_CFG_ACCESSOR(uDeviceFeaturesSelect);
1366 else
1367 if (MATCH_COMMON_CFG(uDriverFeaturesSelect))
1368 COMMON_CFG_ACCESSOR(uDriverFeaturesSelect);
1369 else
1370 if (MATCH_COMMON_CFG(uConfigGeneration))
1371 COMMON_CFG_ACCESSOR_READONLY(uConfigGeneration);
1372 else
1373 if (MATCH_COMMON_CFG(uQueueSelect))
1374 COMMON_CFG_ACCESSOR(uQueueSelect);
1375 else
1376 if (MATCH_COMMON_CFG(uQueueSize))
1377 COMMON_CFG_ACCESSOR_INDEXED(uQueueSize, pVirtio->uQueueSelect);
1378 else
1379 if (MATCH_COMMON_CFG(uQueueMsixVector))
1380 COMMON_CFG_ACCESSOR_INDEXED(uQueueMsixVector, pVirtio->uQueueSelect);
1381 else
1382 if (MATCH_COMMON_CFG(uQueueEnable))
1383 COMMON_CFG_ACCESSOR_INDEXED(uQueueEnable, pVirtio->uQueueSelect);
1384 else
1385 if (MATCH_COMMON_CFG(uQueueNotifyOff))
1386 COMMON_CFG_ACCESSOR_INDEXED_READONLY(uQueueNotifyOff, pVirtio->uQueueSelect);
1387 else
1388 if (MATCH_COMMON_CFG(aGCPhysQueueDesc))
1389 COMMON_CFG_ACCESSOR_INDEXED(aGCPhysQueueDesc, pVirtio->uQueueSelect);
1390 else
1391 if (MATCH_COMMON_CFG(aGCPhysQueueAvail))
1392 COMMON_CFG_ACCESSOR_INDEXED(aGCPhysQueueAvail, pVirtio->uQueueSelect);
1393 else
1394 if (MATCH_COMMON_CFG(aGCPhysQueueUsed))
1395 COMMON_CFG_ACCESSOR_INDEXED(aGCPhysQueueUsed, pVirtio->uQueueSelect);
1396 else
1397 {
1398 Log2Func(("Bad guest %s access to virtio_pci_common_cfg: offCfg=%#x (%d), cb=%d\n",
1399 fWrite ? "write" : "read ", offCfg, offCfg, cb));
1400 return fWrite ? VINF_SUCCESS : VINF_IOM_MMIO_UNUSED_00;
1401 }
1402
1403#undef COMMON_CFG_ACCESSOR_READONLY
1404#undef COMMON_CFG_ACCESSOR_INDEXED_READONLY
1405#undef COMMON_CFG_ACCESSOR_INDEXED
1406#undef COMMON_CFG_ACCESSOR
1407#undef LOG_COMMON_CFG_ACCESS_INDEXED
1408#undef LOG_COMMON_CFG_ACCESS
1409#undef MATCH_COMMON_CFG
1410#ifndef IN_RING3
1411 RT_NOREF(pDevIns, pVirtioCC);
1412#endif
1413 return rc;
1414}
1415
1416/**
1417 * @callback_method_impl{FNIOMMMIONEWREAD,
1418 * Memory mapped I/O Handler for PCI Capabilities read operations.}
1419 *
1420 * This MMIO handler specifically supports the VIRTIO_PCI_CAP_PCI_CFG capability defined
1421 * 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.
1422 *
1423 */
1424static DECLCALLBACK(VBOXSTRICTRC) virtioMmioRead(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS off, void *pv, unsigned cb)
1425{
1426 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
1427 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
1428 AssertReturn(cb == 1 || cb == 2 || cb == 4, VERR_INVALID_PARAMETER);
1429 Assert(pVirtio == (PVIRTIOCORE)pvUser); RT_NOREF(pvUser);
1430
1431 uint32_t offIntra;
1432 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, offIntra, pVirtio->LocDeviceCap))
1433 {
1434#ifdef IN_RING3
1435 /*
1436 * Callback to client to manage device-specific configuration.
1437 */
1438 VBOXSTRICTRC rcStrict = pVirtioCC->pfnDevCapRead(pDevIns, offIntra, pv, cb);
1439
1440 /*
1441 * Additionally, anytime any part of the device-specific configuration (which our client maintains)
1442 * is READ it needs to be checked to see if it changed since the last time any part was read, in
1443 * order to maintain the config generation (see VirtIO 1.0 spec, section 4.1.4.3.1)
1444 */
1445 bool fDevSpecificFieldChanged = !!memcmp(pVirtioCC->pbDevSpecificCfg + offIntra,
1446 pVirtioCC->pbPrevDevSpecificCfg + offIntra,
1447 RT_MIN(cb, pVirtioCC->cbDevSpecificCfg - offIntra));
1448
1449 memcpy(pVirtioCC->pbPrevDevSpecificCfg, pVirtioCC->pbDevSpecificCfg, pVirtioCC->cbDevSpecificCfg);
1450
1451 if (pVirtio->fGenUpdatePending || fDevSpecificFieldChanged)
1452 {
1453 ++pVirtio->uConfigGeneration;
1454 Log6Func(("Bumped cfg. generation to %d because %s%s\n",
1455 pVirtio->uConfigGeneration,
1456 fDevSpecificFieldChanged ? "<dev cfg changed> " : "",
1457 pVirtio->fGenUpdatePending ? "<update was pending>" : ""));
1458 pVirtio->fGenUpdatePending = false;
1459 }
1460
1461 virtioLowerInterrupt(pDevIns, 0);
1462 return rcStrict;
1463#else
1464 return VINF_IOM_R3_MMIO_READ;
1465#endif
1466 }
1467
1468 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, offIntra, pVirtio->LocCommonCfgCap))
1469 return virtioCommonCfgAccessed(pDevIns, pVirtio, pVirtioCC, false /* fWrite */, offIntra, cb, pv);
1470
1471 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, offIntra, pVirtio->LocIsrCap) && cb == sizeof(uint8_t))
1472 {
1473 *(uint8_t *)pv = pVirtio->uISR;
1474 Log6Func(("Read and clear ISR\n"));
1475 pVirtio->uISR = 0; /* VirtIO specification requires reads of ISR to clear it */
1476 virtioLowerInterrupt(pDevIns, 0);
1477 return VINF_SUCCESS;
1478 }
1479
1480 ASSERT_GUEST_MSG_FAILED(("Bad read access to mapped capabilities region: off=%RGp cb=%u\n", off, cb));
1481 return VINF_IOM_MMIO_UNUSED_00;
1482}
1483
1484/**
1485 * @callback_method_impl{FNIOMMMIONEWREAD,
1486 * Memory mapped I/O Handler for PCI Capabilities write operations.}
1487 *
1488 * This MMIO handler specifically supports the VIRTIO_PCI_CAP_PCI_CFG capability defined
1489 * in the VirtIO 1.0 specification, section 4.1.4.7, and as such is limited
1490 * to cb == 1, cb == 2, or cb==4 type writes.
1491 */
1492static DECLCALLBACK(VBOXSTRICTRC) virtioMmioWrite(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS off, void const *pv, unsigned cb)
1493{
1494 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
1495 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
1496
1497 AssertReturn(cb == 1 || cb == 2 || cb == 4, VERR_INVALID_PARAMETER);
1498
1499 Assert(pVirtio == (PVIRTIOCORE)pvUser); RT_NOREF(pvUser);
1500
1501 uint32_t offIntra;
1502 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, offIntra, pVirtio->LocDeviceCap))
1503 {
1504#ifdef IN_RING3
1505 /*
1506 * Pass this MMIO write access back to the client to handle
1507 */
1508 return pVirtioCC->pfnDevCapWrite(pDevIns, offIntra, pv, cb);
1509#else
1510 return VINF_IOM_R3_MMIO_WRITE;
1511#endif
1512 }
1513
1514 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, offIntra, pVirtio->LocCommonCfgCap))
1515 return virtioCommonCfgAccessed(pDevIns, pVirtio, pVirtioCC, true /* fWrite */, offIntra, cb, (void *)pv);
1516
1517 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, offIntra, pVirtio->LocIsrCap) && cb == sizeof(uint8_t))
1518 {
1519 pVirtio->uISR = *(uint8_t *)pv;
1520 Log6Func(("Setting uISR = 0x%02x (virtq interrupt: %d, dev confg interrupt: %d)\n",
1521 pVirtio->uISR & 0xff,
1522 pVirtio->uISR & VIRTIO_ISR_VIRTQ_INTERRUPT,
1523 RT_BOOL(pVirtio->uISR & VIRTIO_ISR_DEVICE_CONFIG)));
1524 return VINF_SUCCESS;
1525 }
1526
1527 /* This *should* be guest driver dropping index of a new descriptor in avail ring */
1528 if (MATCHES_VIRTIO_CAP_STRUCT(off, cb, offIntra, pVirtio->LocNotifyCap) && cb == sizeof(uint16_t))
1529 {
1530#ifdef IN_RING3
1531 virtioR3QueueNotified(pVirtio, pVirtioCC, offIntra / VIRTIO_NOTIFY_OFFSET_MULTIPLIER, *(uint16_t *)pv);
1532 return VINF_SUCCESS;
1533#else
1534 return VINF_IOM_R3_MMIO_WRITE;
1535#endif
1536 }
1537
1538 ASSERT_GUEST_MSG_FAILED(("Bad write access to mapped capabilities region: off=%RGp pv=%#p{%.*Rhxs} cb=%u\n", off, pv, cb, pv, cb));
1539 return VINF_SUCCESS;
1540}
1541
1542#ifdef IN_RING3
1543
1544/**
1545 * @callback_method_impl{FNPCICONFIGREAD}
1546 */
1547static DECLCALLBACK(VBOXSTRICTRC) virtioR3PciConfigRead(PPDMDEVINS pDevIns, PPDMPCIDEV pPciDev,
1548 uint32_t uAddress, unsigned cb, uint32_t *pu32Value)
1549{
1550 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
1551 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
1552 RT_NOREF(pPciDev);
1553
1554 Log7Func(("pDevIns=%p pPciDev=%p uAddress=%#x cb=%u pu32Value=%p\n",
1555 pDevIns, pPciDev, uAddress, cb, pu32Value));
1556 if (uAddress == pVirtio->uPciCfgDataOff)
1557 {
1558 /*
1559 * VirtIO 1.0 spec section 4.1.4.7 describes a required alternative access capability
1560 * whereby the guest driver can specify a bar, offset, and length via the PCI configuration space
1561 * (the virtio_pci_cfg_cap capability), and access data items.
1562 */
1563 uint32_t uLength = pVirtioCC->pPciCfgCap->pciCap.uLength;
1564 uint32_t uOffset = pVirtioCC->pPciCfgCap->pciCap.uOffset;
1565 uint8_t uBar = pVirtioCC->pPciCfgCap->pciCap.uBar;
1566
1567 if ( (uLength != 1 && uLength != 2 && uLength != 4)
1568 || cb != uLength
1569 || uBar != VIRTIO_REGION_PCI_CAP)
1570 {
1571 ASSERT_GUEST_MSG_FAILED(("Guest read virtio_pci_cfg_cap.pci_cfg_data using mismatching config. Ignoring\n"));
1572 *pu32Value = UINT32_MAX;
1573 return VINF_SUCCESS;
1574 }
1575
1576 VBOXSTRICTRC rcStrict = virtioMmioRead(pDevIns, pVirtio, uOffset, pu32Value, cb);
1577 Log2Func(("virtio: Guest read virtio_pci_cfg_cap.pci_cfg_data, bar=%d, offset=%d, length=%d, result=%d -> %Rrc\n",
1578 uBar, uOffset, uLength, *pu32Value, VBOXSTRICTRC_VAL(rcStrict)));
1579 return rcStrict;
1580 }
1581 return VINF_PDM_PCI_DO_DEFAULT;
1582}
1583
1584/**
1585 * @callback_method_impl{FNPCICONFIGWRITE}
1586 */
1587static DECLCALLBACK(VBOXSTRICTRC) virtioR3PciConfigWrite(PPDMDEVINS pDevIns, PPDMPCIDEV pPciDev,
1588 uint32_t uAddress, unsigned cb, uint32_t u32Value)
1589{
1590 PVIRTIOCORE pVirtio = PDMINS_2_DATA(pDevIns, PVIRTIOCORE);
1591 PVIRTIOCORECC pVirtioCC = PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC);
1592 RT_NOREF(pPciDev);
1593
1594 Log7Func(("pDevIns=%p pPciDev=%p uAddress=%#x cb=%u u32Value=%#x\n", pDevIns, pPciDev, uAddress, cb, u32Value));
1595 if (uAddress == pVirtio->uPciCfgDataOff)
1596 {
1597 /* VirtIO 1.0 spec section 4.1.4.7 describes a required alternative access capability
1598 * whereby the guest driver can specify a bar, offset, and length via the PCI configuration space
1599 * (the virtio_pci_cfg_cap capability), and access data items. */
1600
1601 uint32_t uLength = pVirtioCC->pPciCfgCap->pciCap.uLength;
1602 uint32_t uOffset = pVirtioCC->pPciCfgCap->pciCap.uOffset;
1603 uint8_t uBar = pVirtioCC->pPciCfgCap->pciCap.uBar;
1604
1605 if ( (uLength != 1 && uLength != 2 && uLength != 4)
1606 || cb != uLength
1607 || uBar != VIRTIO_REGION_PCI_CAP)
1608 {
1609 ASSERT_GUEST_MSG_FAILED(("Guest write virtio_pci_cfg_cap.pci_cfg_data using mismatching config. Ignoring\n"));
1610 return VINF_SUCCESS;
1611 }
1612
1613 VBOXSTRICTRC rcStrict = virtioMmioWrite(pDevIns, pVirtio, uOffset, &u32Value, cb);
1614 Log2Func(("Guest wrote virtio_pci_cfg_cap.pci_cfg_data, bar=%d, offset=%x, length=%x, value=%d -> %Rrc\n",
1615 uBar, uOffset, uLength, u32Value, VBOXSTRICTRC_VAL(rcStrict)));
1616 return rcStrict;
1617 }
1618 return VINF_PDM_PCI_DO_DEFAULT;
1619}
1620
1621
1622/*********************************************************************************************************************************
1623* Saved state. *
1624*********************************************************************************************************************************/
1625
1626/**
1627 * Called from the FNSSMDEVSAVEEXEC function of the device.
1628 *
1629 * @param pVirtio Pointer to the shared virtio state.
1630 * @param pHlp The ring-3 device helpers.
1631 * @param pSSM The saved state handle.
1632 * @returns VBox status code.
1633 */
1634int virtioCoreR3SaveExec(PVIRTIOCORE pVirtio, PCPDMDEVHLPR3 pHlp, PSSMHANDLE pSSM)
1635{
1636 LogFunc(("\n"));
1637 pHlp->pfnSSMPutU64(pSSM, VIRTIO_SAVEDSTATE_MARKER);
1638 pHlp->pfnSSMPutU32(pSSM, VIRTIO_SAVEDSTATE_VERSION);
1639
1640 pHlp->pfnSSMPutBool(pSSM, pVirtio->fGenUpdatePending);
1641 pHlp->pfnSSMPutU8(pSSM, pVirtio->uDeviceStatus);
1642 pHlp->pfnSSMPutU8(pSSM, pVirtio->uConfigGeneration);
1643 pHlp->pfnSSMPutU8(pSSM, pVirtio->uPciCfgDataOff);
1644 pHlp->pfnSSMPutU8(pSSM, pVirtio->uISR);
1645 pHlp->pfnSSMPutU16(pSSM, pVirtio->uQueueSelect);
1646 pHlp->pfnSSMPutU32(pSSM, pVirtio->uDeviceFeaturesSelect);
1647 pHlp->pfnSSMPutU32(pSSM, pVirtio->uDriverFeaturesSelect);
1648 pHlp->pfnSSMPutU64(pSSM, pVirtio->uDriverFeatures);
1649
1650 for (uint32_t i = 0; i < VIRTQ_MAX_CNT; i++)
1651 {
1652 pHlp->pfnSSMPutGCPhys64(pSSM, pVirtio->aGCPhysQueueDesc[i]);
1653 pHlp->pfnSSMPutGCPhys64(pSSM, pVirtio->aGCPhysQueueAvail[i]);
1654 pHlp->pfnSSMPutGCPhys64(pSSM, pVirtio->aGCPhysQueueUsed[i]);
1655 pHlp->pfnSSMPutU16(pSSM, pVirtio->uQueueNotifyOff[i]);
1656 pHlp->pfnSSMPutU16(pSSM, pVirtio->uQueueMsixVector[i]);
1657 pHlp->pfnSSMPutU16(pSSM, pVirtio->uQueueEnable[i]);
1658 pHlp->pfnSSMPutU16(pSSM, pVirtio->uQueueSize[i]);
1659 pHlp->pfnSSMPutU16(pSSM, pVirtio->virtqState[i].uAvailIdx);
1660 pHlp->pfnSSMPutU16(pSSM, pVirtio->virtqState[i].uUsedIdx);
1661 int rc = pHlp->pfnSSMPutMem(pSSM, pVirtio->virtqState[i].szVirtqName, 32);
1662 AssertRCReturn(rc, rc);
1663 }
1664
1665 return VINF_SUCCESS;
1666}
1667
1668/**
1669 * Called from the FNSSMDEVLOADEXEC function of the device.
1670 *
1671 * @param pVirtio Pointer to the shared virtio state.
1672 * @param pHlp The ring-3 device helpers.
1673 * @param pSSM The saved state handle.
1674 * @returns VBox status code.
1675 */
1676int virtioCoreR3LoadExec(PVIRTIOCORE pVirtio, PCPDMDEVHLPR3 pHlp, PSSMHANDLE pSSM)
1677{
1678 LogFunc(("\n"));
1679 /*
1680 * Check the marker and (embedded) version number.
1681 */
1682 uint64_t uMarker = 0;
1683 int rc = pHlp->pfnSSMGetU64(pSSM, &uMarker);
1684 AssertRCReturn(rc, rc);
1685 if (uMarker != VIRTIO_SAVEDSTATE_MARKER)
1686 return pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
1687 N_("Expected marker value %#RX64 found %#RX64 instead"),
1688 VIRTIO_SAVEDSTATE_MARKER, uMarker);
1689 uint32_t uVersion = 0;
1690 rc = pHlp->pfnSSMGetU32(pSSM, &uVersion);
1691 AssertRCReturn(rc, rc);
1692 if (uVersion != VIRTIO_SAVEDSTATE_VERSION)
1693 return pHlp->pfnSSMSetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
1694 N_("Unsupported virtio version: %u"), uVersion);
1695 /*
1696 * Load the state.
1697 */
1698 pHlp->pfnSSMGetBool(pSSM, &pVirtio->fGenUpdatePending);
1699 pHlp->pfnSSMGetU8(pSSM, &pVirtio->uDeviceStatus);
1700 pHlp->pfnSSMGetU8(pSSM, &pVirtio->uConfigGeneration);
1701 pHlp->pfnSSMGetU8(pSSM, &pVirtio->uPciCfgDataOff);
1702 pHlp->pfnSSMGetU8(pSSM, &pVirtio->uISR);
1703 pHlp->pfnSSMGetU16(pSSM, &pVirtio->uQueueSelect);
1704 pHlp->pfnSSMGetU32(pSSM, &pVirtio->uDeviceFeaturesSelect);
1705 pHlp->pfnSSMGetU32(pSSM, &pVirtio->uDriverFeaturesSelect);
1706 pHlp->pfnSSMGetU64(pSSM, &pVirtio->uDriverFeatures);
1707
1708 for (uint32_t i = 0; i < VIRTQ_MAX_CNT; i++)
1709 {
1710 pHlp->pfnSSMGetGCPhys64(pSSM, &pVirtio->aGCPhysQueueDesc[i]);
1711 pHlp->pfnSSMGetGCPhys64(pSSM, &pVirtio->aGCPhysQueueAvail[i]);
1712 pHlp->pfnSSMGetGCPhys64(pSSM, &pVirtio->aGCPhysQueueUsed[i]);
1713 pHlp->pfnSSMGetU16(pSSM, &pVirtio->uQueueNotifyOff[i]);
1714 pHlp->pfnSSMGetU16(pSSM, &pVirtio->uQueueMsixVector[i]);
1715 pHlp->pfnSSMGetU16(pSSM, &pVirtio->uQueueEnable[i]);
1716 pHlp->pfnSSMGetU16(pSSM, &pVirtio->uQueueSize[i]);
1717 pHlp->pfnSSMGetU16(pSSM, &pVirtio->virtqState[i].uAvailIdx);
1718 pHlp->pfnSSMGetU16(pSSM, &pVirtio->virtqState[i].uUsedIdx);
1719 rc = pHlp->pfnSSMGetMem(pSSM, pVirtio->virtqState[i].szVirtqName,
1720 sizeof(pVirtio->virtqState[i].szVirtqName));
1721 AssertRCReturn(rc, rc);
1722 }
1723
1724 return VINF_SUCCESS;
1725}
1726
1727
1728/*********************************************************************************************************************************
1729* Device Level *
1730*********************************************************************************************************************************/
1731
1732/**
1733 * This must be called by the client to handle VM state changes
1734 * after the client takes care of its device-specific tasks for the state change.
1735 * (i.e. Reset, suspend, power-off, resume)
1736 *
1737 * @param pDevIns The device instance.
1738 * @param pVirtio Pointer to the shared virtio state.
1739 */
1740void virtioCoreR3VmStateChanged(PVIRTIOCORE pVirtio, VIRTIOVMSTATECHANGED enmState)
1741{
1742 LogFunc(("State changing to %s\n",
1743 virtioCoreGetStateChangeText(enmState)));
1744
1745 switch(enmState)
1746 {
1747 case kvirtIoVmStateChangedReset:
1748 virtioCoreResetAll(pVirtio);
1749 break;
1750 case kvirtIoVmStateChangedSuspend:
1751 break;
1752 case kvirtIoVmStateChangedPowerOff:
1753 break;
1754 case kvirtIoVmStateChangedResume:
1755 virtioNotifyGuestDriver(pVirtio->pDevIns, pVirtio, 0 /* idxQueue */, true /* fForce */);
1756 break;
1757 default:
1758 LogRelFunc(("Bad enum value"));
1759 return;
1760 }
1761}
1762
1763/**
1764 * This should be called from PDMDEVREGR3::pfnDestruct.
1765 *
1766 * @param pDevIns The device instance.
1767 * @param pVirtio Pointer to the shared virtio state.
1768 * @param pVirtioCC Pointer to the ring-3 virtio state.
1769 */
1770void virtioCoreR3Term(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC)
1771{
1772 if (pVirtioCC->pbPrevDevSpecificCfg)
1773 {
1774 RTMemFree(pVirtioCC->pbPrevDevSpecificCfg);
1775 pVirtioCC->pbPrevDevSpecificCfg = NULL;
1776 }
1777 RT_NOREF(pDevIns, pVirtio);
1778}
1779
1780
1781/**
1782 * Setup PCI device controller and Virtio state
1783 *
1784 * This should be called from PDMDEVREGR3::pfnConstruct.
1785 *
1786 * @param pDevIns The device instance.
1787 * @param pVirtio Pointer to the shared virtio state. This
1788 * must be the first member in the shared
1789 * device instance data!
1790 * @param pVirtioCC Pointer to the ring-3 virtio state. This
1791 * must be the first member in the ring-3
1792 * device instance data!
1793 * @param pPciParams Values to populate industry standard PCI Configuration Space data structure
1794 * @param pcszInstance Device instance name (format-specifier)
1795 * @param fDevSpecificFeatures VirtIO device-specific features offered by
1796 * client
1797 * @param cbDevSpecificCfg Size of virtio_pci_device_cap device-specific struct
1798 * @param pvDevSpecificCfg Address of client's dev-specific
1799 * configuration struct.
1800 */
1801int virtioCoreR3Init(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC, PVIRTIOPCIPARAMS pPciParams,
1802 const char *pcszInstance, uint64_t fDevSpecificFeatures, void *pvDevSpecificCfg, uint16_t cbDevSpecificCfg)
1803{
1804 /*
1805 * The pVirtio state must be the first member of the shared device instance
1806 * data, otherwise we cannot get our bearings in the PCI configuration callbacks.
1807 */
1808 AssertLogRelReturn(pVirtio == PDMINS_2_DATA(pDevIns, PVIRTIOCORE), VERR_STATE_CHANGED);
1809 AssertLogRelReturn(pVirtioCC == PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC), VERR_STATE_CHANGED);
1810
1811 pVirtio->pDevIns = pDevIns;
1812
1813 /*
1814 * Caller must initialize these.
1815 */
1816 AssertReturn(pVirtioCC->pfnStatusChanged, VERR_INVALID_POINTER);
1817 AssertReturn(pVirtioCC->pfnQueueNotified, VERR_INVALID_POINTER);
1818// AssertReturn(pVirtioCC->pfnDevCapRead, VERR_INVALID_POINTER);
1819// AssertReturn(pVirtioCC->pfnDevCapWrite, VERR_INVALID_POINTER);
1820
1821#if 0 /* Until pdmR3DvHlp_PCISetIrq() impl is fixed and Assert that limits vec to 0 is removed */
1822# ifdef VBOX_WITH_MSI_DEVICES
1823 pVirtio->fMsiSupport = true;
1824# endif
1825#endif
1826
1827 /*
1828 * The host features offered include both device-specific features
1829 * and reserved feature bits (device independent)
1830 */
1831 pVirtio->uDeviceFeatures = VIRTIO_F_VERSION_1
1832 | VIRTIO_DEV_INDEPENDENT_FEATURES_OFFERED
1833 | fDevSpecificFeatures;
1834
1835 RTStrCopy(pVirtio->szInstance, sizeof(pVirtio->szInstance), pcszInstance);
1836
1837 pVirtio->uDeviceStatus = 0;
1838 pVirtioCC->cbDevSpecificCfg = cbDevSpecificCfg;
1839 pVirtioCC->pbDevSpecificCfg = (uint8_t *)pvDevSpecificCfg;
1840 pVirtioCC->pbPrevDevSpecificCfg = (uint8_t *)RTMemDup(pvDevSpecificCfg, cbDevSpecificCfg);
1841 AssertLogRelReturn(pVirtioCC->pbPrevDevSpecificCfg, VERR_NO_MEMORY);
1842
1843 /* Set PCI config registers (assume 32-bit mode) */
1844 PPDMPCIDEV pPciDev = pDevIns->apPciDevs[0];
1845 PDMPCIDEV_ASSERT_VALID(pDevIns, pPciDev);
1846
1847 PDMPciDevSetRevisionId(pPciDev, DEVICE_PCI_REVISION_ID_VIRTIO);
1848 PDMPciDevSetVendorId(pPciDev, DEVICE_PCI_VENDOR_ID_VIRTIO);
1849 PDMPciDevSetSubSystemVendorId(pPciDev, DEVICE_PCI_VENDOR_ID_VIRTIO);
1850 PDMPciDevSetDeviceId(pPciDev, pPciParams->uDeviceId);
1851 PDMPciDevSetClassBase(pPciDev, pPciParams->uClassBase);
1852 PDMPciDevSetClassSub(pPciDev, pPciParams->uClassSub);
1853 PDMPciDevSetClassProg(pPciDev, pPciParams->uClassProg);
1854 PDMPciDevSetSubSystemId(pPciDev, pPciParams->uSubsystemId);
1855 PDMPciDevSetInterruptLine(pPciDev, pPciParams->uInterruptLine);
1856 PDMPciDevSetInterruptPin(pPciDev, pPciParams->uInterruptPin);
1857
1858 /* Register PCI device */
1859 int rc = PDMDevHlpPCIRegister(pDevIns, pPciDev);
1860 if (RT_FAILURE(rc))
1861 return PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio: cannot register PCI Device")); /* can we put params in this error? */
1862
1863 rc = PDMDevHlpPCIInterceptConfigAccesses(pDevIns, pPciDev, virtioR3PciConfigRead, virtioR3PciConfigWrite);
1864 AssertRCReturn(rc, rc);
1865
1866
1867 /* Construct & map PCI vendor-specific capabilities for virtio host negotiation with guest driver */
1868
1869 /* The following capability mapped via VirtIO 1.0: struct virtio_pci_cfg_cap (VIRTIO_PCI_CFG_CAP_T)
1870 * as a mandatory but suboptimal alternative interface to host device capabilities, facilitating
1871 * access the memory of any BAR. If the guest uses it (the VirtIO driver on Linux doesn't),
1872 * Unlike Common, Notify, ISR and Device capabilities, it is accessed directly via PCI Config region.
1873 * therefore does not contribute to the capabilities region (BAR) the other capabilities use.
1874 */
1875#define CFG_ADDR_2_IDX(addr) ((uint8_t)(((uintptr_t)(addr) - (uintptr_t)&pPciDev->abConfig[0])))
1876#define SET_PCI_CAP_LOC(a_pPciDev, a_pCfg, a_LocCap, a_uMmioLengthAlign) \
1877 do { \
1878 (a_LocCap).offMmio = (a_pCfg)->uOffset; \
1879 (a_LocCap).cbMmio = RT_ALIGN_T((a_pCfg)->uLength, a_uMmioLengthAlign, uint16_t); \
1880 (a_LocCap).offPci = (uint16_t)(uintptr_t)((uint8_t *)(a_pCfg) - &(a_pPciDev)->abConfig[0]); \
1881 (a_LocCap).cbPci = (a_pCfg)->uCapLen; \
1882 } while (0)
1883
1884 PVIRTIO_PCI_CAP_T pCfg;
1885 uint32_t cbRegion = 0;
1886
1887 /* Common capability (VirtIO 1.0 spec, section 4.1.4.3) */
1888 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[0x40];
1889 pCfg->uCfgType = VIRTIO_PCI_CAP_COMMON_CFG;
1890 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
1891 pCfg->uCapLen = sizeof(VIRTIO_PCI_CAP_T);
1892 pCfg->uCapNext = CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen;
1893 pCfg->uBar = VIRTIO_REGION_PCI_CAP;
1894 pCfg->uOffset = RT_ALIGN_32(0, 4); /* reminder, in case someone changes offset */
1895 pCfg->uLength = sizeof(VIRTIO_PCI_COMMON_CFG_T);
1896 cbRegion += pCfg->uLength;
1897 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocCommonCfgCap, 2);
1898 pVirtioCC->pCommonCfgCap = pCfg;
1899
1900 /*
1901 * Notify capability (VirtIO 1.0 spec, section 4.1.4.4). Note: uLength is based the choice
1902 * of this implementation that each queue's uQueueNotifyOff is set equal to (QueueSelect) ordinal
1903 * value of the queue
1904 */
1905 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[pCfg->uCapNext];
1906 pCfg->uCfgType = VIRTIO_PCI_CAP_NOTIFY_CFG;
1907 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
1908 pCfg->uCapLen = sizeof(VIRTIO_PCI_NOTIFY_CAP_T);
1909 pCfg->uCapNext = CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen;
1910 pCfg->uBar = VIRTIO_REGION_PCI_CAP;
1911 pCfg->uOffset = pVirtioCC->pCommonCfgCap->uOffset + pVirtioCC->pCommonCfgCap->uLength;
1912 pCfg->uOffset = RT_ALIGN_32(pCfg->uOffset, 4);
1913
1914
1915 pCfg->uLength = VIRTQ_MAX_CNT * VIRTIO_NOTIFY_OFFSET_MULTIPLIER + 2; /* will change in VirtIO 1.1 */
1916 cbRegion += pCfg->uLength;
1917 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocNotifyCap, 1);
1918 pVirtioCC->pNotifyCap = (PVIRTIO_PCI_NOTIFY_CAP_T)pCfg;
1919 pVirtioCC->pNotifyCap->uNotifyOffMultiplier = VIRTIO_NOTIFY_OFFSET_MULTIPLIER;
1920
1921 /* ISR capability (VirtIO 1.0 spec, section 4.1.4.5)
1922 *
1923 * VirtIO 1.0 spec says 8-bit, unaligned in MMIO space. Example/diagram
1924 * of spec shows it as a 32-bit field with upper bits 'reserved'
1925 * Will take spec words more literally than the diagram for now.
1926 */
1927 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[pCfg->uCapNext];
1928 pCfg->uCfgType = VIRTIO_PCI_CAP_ISR_CFG;
1929 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
1930 pCfg->uCapLen = sizeof(VIRTIO_PCI_CAP_T);
1931 pCfg->uCapNext = CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen;
1932 pCfg->uBar = VIRTIO_REGION_PCI_CAP;
1933 pCfg->uOffset = pVirtioCC->pNotifyCap->pciCap.uOffset + pVirtioCC->pNotifyCap->pciCap.uLength;
1934 pCfg->uOffset = RT_ALIGN_32(pCfg->uOffset, 4);
1935 pCfg->uLength = sizeof(uint8_t);
1936 cbRegion += pCfg->uLength;
1937 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocIsrCap, 4);
1938 pVirtioCC->pIsrCap = pCfg;
1939
1940 /* PCI Cfg capability (VirtIO 1.0 spec, section 4.1.4.7)
1941 * This capability doesn't get page-MMIO mapped. Instead uBar, uOffset and uLength are intercepted
1942 * by trapping PCI configuration I/O and get modulated by consumers to locate fetch and read/write
1943 * values from any region. NOTE: The linux driver not only doesn't use this feature, it will not
1944 * even list it as present if uLength isn't non-zero and also 4-byte-aligned as the linux driver is
1945 * initializing.
1946 */
1947 pVirtio->uPciCfgDataOff = pCfg->uCapNext + RT_OFFSETOF(VIRTIO_PCI_CFG_CAP_T, uPciCfgData);
1948 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[pCfg->uCapNext];
1949 pCfg->uCfgType = VIRTIO_PCI_CAP_PCI_CFG;
1950 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
1951 pCfg->uCapLen = sizeof(VIRTIO_PCI_CFG_CAP_T);
1952 pCfg->uCapNext = (pVirtio->fMsiSupport || pVirtioCC->pbDevSpecificCfg) ? CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen : 0;
1953 pCfg->uBar = 0;
1954 pCfg->uOffset = 0;
1955 pCfg->uLength = 0;
1956 cbRegion += pCfg->uLength;
1957 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocPciCfgCap, 1);
1958 pVirtioCC->pPciCfgCap = (PVIRTIO_PCI_CFG_CAP_T)pCfg;
1959
1960 if (pVirtioCC->pbDevSpecificCfg)
1961 {
1962 /* Following capability (via VirtIO 1.0, section 4.1.4.6). Client defines the
1963 * device-specific config fields struct and passes size to this constructor */
1964 pCfg = (PVIRTIO_PCI_CAP_T)&pPciDev->abConfig[pCfg->uCapNext];
1965 pCfg->uCfgType = VIRTIO_PCI_CAP_DEVICE_CFG;
1966 pCfg->uCapVndr = VIRTIO_PCI_CAP_ID_VENDOR;
1967 pCfg->uCapLen = sizeof(VIRTIO_PCI_CAP_T);
1968 pCfg->uCapNext = pVirtio->fMsiSupport ? CFG_ADDR_2_IDX(pCfg) + pCfg->uCapLen : 0;
1969 pCfg->uBar = VIRTIO_REGION_PCI_CAP;
1970 pCfg->uOffset = pVirtioCC->pIsrCap->uOffset + pVirtioCC->pIsrCap->uLength;
1971 pCfg->uOffset = RT_ALIGN_32(pCfg->uOffset, 4);
1972 pCfg->uLength = cbDevSpecificCfg;
1973 cbRegion += pCfg->uLength;
1974 SET_PCI_CAP_LOC(pPciDev, pCfg, pVirtio->LocDeviceCap, 4);
1975 pVirtioCC->pDeviceCap = pCfg;
1976 }
1977 else
1978 Assert(pVirtio->LocDeviceCap.cbMmio == 0 && pVirtio->LocDeviceCap.cbPci == 0);
1979
1980 if (pVirtio->fMsiSupport)
1981 {
1982 PDMMSIREG aMsiReg;
1983 RT_ZERO(aMsiReg);
1984 aMsiReg.iMsixCapOffset = pCfg->uCapNext;
1985 aMsiReg.iMsixNextOffset = 0;
1986 aMsiReg.iMsixBar = VIRTIO_REGION_MSIX_CAP;
1987 aMsiReg.cMsixVectors = VBOX_MSIX_MAX_ENTRIES;
1988 rc = PDMDevHlpPCIRegisterMsi(pDevIns, &aMsiReg); /* see MsixR3init() */
1989 if (RT_FAILURE(rc))
1990 {
1991 /* See PDMDevHlp.cpp:pdmR3DevHlp_PCIRegisterMsi */
1992 LogFunc(("Failed to configure MSI-X (%Rrc). Reverting to INTx\n", rc));
1993 pVirtio->fMsiSupport = false;
1994 }
1995 else
1996 Log2Func(("Using MSI-X for guest driver notification\n"));
1997 }
1998 else
1999 LogFunc(("MSI-X not available for VBox, using INTx notification\n"));
2000
2001 /* Set offset to first capability and enable PCI dev capabilities */
2002 PDMPciDevSetCapabilityList(pPciDev, 0x40);
2003 PDMPciDevSetStatus(pPciDev, VBOX_PCI_STATUS_CAP_LIST);
2004
2005 /* Linux drivers/virtio/virtio_pci_modern.c tries to map at least a page for the
2006 * 'unknown' device-specific capability without querying the capability to figure
2007 * out size, so pad with an extra page
2008 */
2009 rc = PDMDevHlpPCIIORegionCreateMmio(pDevIns, VIRTIO_REGION_PCI_CAP, RT_ALIGN_32(cbRegion + PAGE_SIZE, PAGE_SIZE),
2010 PCI_ADDRESS_SPACE_MEM, virtioMmioWrite, virtioMmioRead, pVirtio,
2011 IOMMMIO_FLAGS_READ_PASSTHRU | IOMMMIO_FLAGS_WRITE_PASSTHRU, "virtio-scsi MMIO",
2012 &pVirtio->hMmioPciCap);
2013 AssertLogRelRCReturn(rc, PDMDEV_SET_ERROR(pDevIns, rc, N_("virtio: cannot register PCI Capabilities address space")));
2014
2015 return rc;
2016}
2017
2018#else /* !IN_RING3 */
2019
2020/**
2021 * Sets up the core ring-0/raw-mode virtio bits.
2022 *
2023 * @returns VBox status code.
2024 * @param pDevIns The device instance.
2025 * @param pVirtio Pointer to the shared virtio state. This must be the first
2026 * member in the shared device instance data!
2027 * @param pVirtioCC Pointer to the current context virtio state. This must be the
2028 * first member in the currenct context's device instance data!
2029 */
2030int virtioCoreRZInit(PPDMDEVINS pDevIns, PVIRTIOCORE pVirtio, PVIRTIOCORECC pVirtioCC)
2031{
2032 AssertLogRelReturn(pVirtio == PDMINS_2_DATA(pDevIns, PVIRTIOCORE), VERR_STATE_CHANGED);
2033 AssertLogRelReturn(pVirtioCC == PDMINS_2_DATA_CC(pDevIns, PVIRTIOCORECC), VERR_STATE_CHANGED);
2034
2035 int rc = PDMDevHlpMmioSetUpContext(pDevIns, pVirtio->hMmioPciCap, virtioMmioWrite, virtioMmioRead, pVirtio);
2036 AssertRCReturn(rc, rc);
2037 return rc;
2038}
2039
2040#endif /* !IN_RING3 */
2041
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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