VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR3/PGMPhys.cpp@ 95843

Last change on this file since 95843 was 94897, checked in by vboxsync, 3 years ago

VMM/PGMPhys: Missed one SUPR3PageAlloc call when doing host/guest page separation. bugref:9898

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 224.6 KB
Line 
1/* $Id: PGMPhys.cpp 94897 2022-05-06 13:06:04Z vboxsync $ */
2/** @file
3 * PGM - Page Manager and Monitor, Physical Memory Addressing.
4 */
5
6/*
7 * Copyright (C) 2006-2022 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_PGM_PHYS
23#define VBOX_WITHOUT_PAGING_BIT_FIELDS /* 64-bit bitfields are just asking for trouble. See @bugref{9841} and others. */
24#include <VBox/vmm/pgm.h>
25#include <VBox/vmm/iem.h>
26#include <VBox/vmm/iom.h>
27#include <VBox/vmm/mm.h>
28#include <VBox/vmm/nem.h>
29#include <VBox/vmm/stam.h>
30#include <VBox/vmm/pdmdev.h>
31#include "PGMInternal.h"
32#include <VBox/vmm/vmcc.h>
33
34#include "PGMInline.h"
35
36#include <VBox/sup.h>
37#include <VBox/param.h>
38#include <VBox/err.h>
39#include <VBox/log.h>
40#include <iprt/assert.h>
41#include <iprt/alloc.h>
42#include <iprt/asm.h>
43#ifdef VBOX_STRICT
44# include <iprt/crc.h>
45#endif
46#include <iprt/thread.h>
47#include <iprt/string.h>
48#include <iprt/system.h>
49
50
51/*********************************************************************************************************************************
52* Defined Constants And Macros *
53*********************************************************************************************************************************/
54/** The number of pages to free in one batch. */
55#define PGMPHYS_FREE_PAGE_BATCH_SIZE 128
56
57
58
59/*********************************************************************************************************************************
60* Reading and Writing Guest Pysical Memory *
61*********************************************************************************************************************************/
62
63/*
64 * PGMR3PhysReadU8-64
65 * PGMR3PhysWriteU8-64
66 */
67#define PGMPHYSFN_READNAME PGMR3PhysReadU8
68#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU8
69#define PGMPHYS_DATASIZE 1
70#define PGMPHYS_DATATYPE uint8_t
71#include "PGMPhysRWTmpl.h"
72
73#define PGMPHYSFN_READNAME PGMR3PhysReadU16
74#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU16
75#define PGMPHYS_DATASIZE 2
76#define PGMPHYS_DATATYPE uint16_t
77#include "PGMPhysRWTmpl.h"
78
79#define PGMPHYSFN_READNAME PGMR3PhysReadU32
80#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU32
81#define PGMPHYS_DATASIZE 4
82#define PGMPHYS_DATATYPE uint32_t
83#include "PGMPhysRWTmpl.h"
84
85#define PGMPHYSFN_READNAME PGMR3PhysReadU64
86#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU64
87#define PGMPHYS_DATASIZE 8
88#define PGMPHYS_DATATYPE uint64_t
89#include "PGMPhysRWTmpl.h"
90
91
92/**
93 * EMT worker for PGMR3PhysReadExternal.
94 */
95static DECLCALLBACK(int) pgmR3PhysReadExternalEMT(PVM pVM, PRTGCPHYS pGCPhys, void *pvBuf, size_t cbRead,
96 PGMACCESSORIGIN enmOrigin)
97{
98 VBOXSTRICTRC rcStrict = PGMPhysRead(pVM, *pGCPhys, pvBuf, cbRead, enmOrigin);
99 AssertMsg(rcStrict == VINF_SUCCESS, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict))); NOREF(rcStrict);
100 return VINF_SUCCESS;
101}
102
103
104/**
105 * Read from physical memory, external users.
106 *
107 * @returns VBox status code.
108 * @retval VINF_SUCCESS.
109 *
110 * @param pVM The cross context VM structure.
111 * @param GCPhys Physical address to read from.
112 * @param pvBuf Where to read into.
113 * @param cbRead How many bytes to read.
114 * @param enmOrigin Who is calling.
115 *
116 * @thread Any but EMTs.
117 */
118VMMR3DECL(int) PGMR3PhysReadExternal(PVM pVM, RTGCPHYS GCPhys, void *pvBuf, size_t cbRead, PGMACCESSORIGIN enmOrigin)
119{
120 VM_ASSERT_OTHER_THREAD(pVM);
121
122 AssertMsgReturn(cbRead > 0, ("don't even think about reading zero bytes!\n"), VINF_SUCCESS);
123 LogFlow(("PGMR3PhysReadExternal: %RGp %d\n", GCPhys, cbRead));
124
125 PGM_LOCK_VOID(pVM);
126
127 /*
128 * Copy loop on ram ranges.
129 */
130 PPGMRAMRANGE pRam = pgmPhysGetRangeAtOrAbove(pVM, GCPhys);
131 for (;;)
132 {
133 /* Inside range or not? */
134 if (pRam && GCPhys >= pRam->GCPhys)
135 {
136 /*
137 * Must work our way thru this page by page.
138 */
139 RTGCPHYS off = GCPhys - pRam->GCPhys;
140 while (off < pRam->cb)
141 {
142 unsigned iPage = off >> GUEST_PAGE_SHIFT;
143 PPGMPAGE pPage = &pRam->aPages[iPage];
144
145 /*
146 * If the page has an ALL access handler, we'll have to
147 * delegate the job to EMT.
148 */
149 if ( PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)
150 || PGM_PAGE_IS_SPECIAL_ALIAS_MMIO(pPage))
151 {
152 PGM_UNLOCK(pVM);
153
154 return VMR3ReqPriorityCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysReadExternalEMT, 5,
155 pVM, &GCPhys, pvBuf, cbRead, enmOrigin);
156 }
157 Assert(!PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage));
158
159 /*
160 * Simple stuff, go ahead.
161 */
162 size_t cb = GUEST_PAGE_SIZE - (off & GUEST_PAGE_OFFSET_MASK);
163 if (cb > cbRead)
164 cb = cbRead;
165 PGMPAGEMAPLOCK PgMpLck;
166 const void *pvSrc;
167 int rc = pgmPhysGCPhys2CCPtrInternalReadOnly(pVM, pPage, pRam->GCPhys + off, &pvSrc, &PgMpLck);
168 if (RT_SUCCESS(rc))
169 {
170 memcpy(pvBuf, pvSrc, cb);
171 pgmPhysReleaseInternalPageMappingLock(pVM, &PgMpLck);
172 }
173 else
174 {
175 AssertLogRelMsgFailed(("pgmPhysGCPhys2CCPtrInternalReadOnly failed on %RGp / %R[pgmpage] -> %Rrc\n",
176 pRam->GCPhys + off, pPage, rc));
177 memset(pvBuf, 0xff, cb);
178 }
179
180 /* next page */
181 if (cb >= cbRead)
182 {
183 PGM_UNLOCK(pVM);
184 return VINF_SUCCESS;
185 }
186 cbRead -= cb;
187 off += cb;
188 GCPhys += cb;
189 pvBuf = (char *)pvBuf + cb;
190 } /* walk pages in ram range. */
191 }
192 else
193 {
194 LogFlow(("PGMPhysRead: Unassigned %RGp size=%u\n", GCPhys, cbRead));
195
196 /*
197 * Unassigned address space.
198 */
199 size_t cb = pRam ? pRam->GCPhys - GCPhys : ~(size_t)0;
200 if (cb >= cbRead)
201 {
202 memset(pvBuf, 0xff, cbRead);
203 break;
204 }
205 memset(pvBuf, 0xff, cb);
206
207 cbRead -= cb;
208 pvBuf = (char *)pvBuf + cb;
209 GCPhys += cb;
210 }
211
212 /* Advance range if necessary. */
213 while (pRam && GCPhys > pRam->GCPhysLast)
214 pRam = pRam->CTX_SUFF(pNext);
215 } /* Ram range walk */
216
217 PGM_UNLOCK(pVM);
218
219 return VINF_SUCCESS;
220}
221
222
223/**
224 * EMT worker for PGMR3PhysWriteExternal.
225 */
226static DECLCALLBACK(int) pgmR3PhysWriteExternalEMT(PVM pVM, PRTGCPHYS pGCPhys, const void *pvBuf, size_t cbWrite,
227 PGMACCESSORIGIN enmOrigin)
228{
229 /** @todo VERR_EM_NO_MEMORY */
230 VBOXSTRICTRC rcStrict = PGMPhysWrite(pVM, *pGCPhys, pvBuf, cbWrite, enmOrigin);
231 AssertMsg(rcStrict == VINF_SUCCESS, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict))); NOREF(rcStrict);
232 return VINF_SUCCESS;
233}
234
235
236/**
237 * Write to physical memory, external users.
238 *
239 * @returns VBox status code.
240 * @retval VINF_SUCCESS.
241 * @retval VERR_EM_NO_MEMORY.
242 *
243 * @param pVM The cross context VM structure.
244 * @param GCPhys Physical address to write to.
245 * @param pvBuf What to write.
246 * @param cbWrite How many bytes to write.
247 * @param enmOrigin Who is calling.
248 *
249 * @thread Any but EMTs.
250 */
251VMMDECL(int) PGMR3PhysWriteExternal(PVM pVM, RTGCPHYS GCPhys, const void *pvBuf, size_t cbWrite, PGMACCESSORIGIN enmOrigin)
252{
253 VM_ASSERT_OTHER_THREAD(pVM);
254
255 AssertMsg(!pVM->pgm.s.fNoMorePhysWrites,
256 ("Calling PGMR3PhysWriteExternal after pgmR3Save()! GCPhys=%RGp cbWrite=%#x enmOrigin=%d\n",
257 GCPhys, cbWrite, enmOrigin));
258 AssertMsgReturn(cbWrite > 0, ("don't even think about writing zero bytes!\n"), VINF_SUCCESS);
259 LogFlow(("PGMR3PhysWriteExternal: %RGp %d\n", GCPhys, cbWrite));
260
261 PGM_LOCK_VOID(pVM);
262
263 /*
264 * Copy loop on ram ranges, stop when we hit something difficult.
265 */
266 PPGMRAMRANGE pRam = pgmPhysGetRangeAtOrAbove(pVM, GCPhys);
267 for (;;)
268 {
269 /* Inside range or not? */
270 if (pRam && GCPhys >= pRam->GCPhys)
271 {
272 /*
273 * Must work our way thru this page by page.
274 */
275 RTGCPTR off = GCPhys - pRam->GCPhys;
276 while (off < pRam->cb)
277 {
278 RTGCPTR iPage = off >> GUEST_PAGE_SHIFT;
279 PPGMPAGE pPage = &pRam->aPages[iPage];
280
281 /*
282 * Is the page problematic, we have to do the work on the EMT.
283 *
284 * Allocating writable pages and access handlers are
285 * problematic, write monitored pages are simple and can be
286 * dealt with here.
287 */
288 if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
289 || PGM_PAGE_GET_STATE(pPage) != PGM_PAGE_STATE_ALLOCATED
290 || PGM_PAGE_IS_SPECIAL_ALIAS_MMIO(pPage))
291 {
292 if ( PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED
293 && !PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
294 pgmPhysPageMakeWriteMonitoredWritable(pVM, pPage, GCPhys);
295 else
296 {
297 PGM_UNLOCK(pVM);
298
299 return VMR3ReqPriorityCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysWriteExternalEMT, 5,
300 pVM, &GCPhys, pvBuf, cbWrite, enmOrigin);
301 }
302 }
303 Assert(!PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage));
304
305 /*
306 * Simple stuff, go ahead.
307 */
308 size_t cb = GUEST_PAGE_SIZE - (off & GUEST_PAGE_OFFSET_MASK);
309 if (cb > cbWrite)
310 cb = cbWrite;
311 PGMPAGEMAPLOCK PgMpLck;
312 void *pvDst;
313 int rc = pgmPhysGCPhys2CCPtrInternal(pVM, pPage, pRam->GCPhys + off, &pvDst, &PgMpLck);
314 if (RT_SUCCESS(rc))
315 {
316 memcpy(pvDst, pvBuf, cb);
317 pgmPhysReleaseInternalPageMappingLock(pVM, &PgMpLck);
318 }
319 else
320 AssertLogRelMsgFailed(("pgmPhysGCPhys2CCPtrInternal failed on %RGp / %R[pgmpage] -> %Rrc\n",
321 pRam->GCPhys + off, pPage, rc));
322
323 /* next page */
324 if (cb >= cbWrite)
325 {
326 PGM_UNLOCK(pVM);
327 return VINF_SUCCESS;
328 }
329
330 cbWrite -= cb;
331 off += cb;
332 GCPhys += cb;
333 pvBuf = (const char *)pvBuf + cb;
334 } /* walk pages in ram range */
335 }
336 else
337 {
338 /*
339 * Unassigned address space, skip it.
340 */
341 if (!pRam)
342 break;
343 size_t cb = pRam->GCPhys - GCPhys;
344 if (cb >= cbWrite)
345 break;
346 cbWrite -= cb;
347 pvBuf = (const char *)pvBuf + cb;
348 GCPhys += cb;
349 }
350
351 /* Advance range if necessary. */
352 while (pRam && GCPhys > pRam->GCPhysLast)
353 pRam = pRam->CTX_SUFF(pNext);
354 } /* Ram range walk */
355
356 PGM_UNLOCK(pVM);
357 return VINF_SUCCESS;
358}
359
360
361/*********************************************************************************************************************************
362* Mapping Guest Physical Memory *
363*********************************************************************************************************************************/
364
365/**
366 * VMR3ReqCall worker for PGMR3PhysGCPhys2CCPtrExternal to make pages writable.
367 *
368 * @returns see PGMR3PhysGCPhys2CCPtrExternal
369 * @param pVM The cross context VM structure.
370 * @param pGCPhys Pointer to the guest physical address.
371 * @param ppv Where to store the mapping address.
372 * @param pLock Where to store the lock.
373 */
374static DECLCALLBACK(int) pgmR3PhysGCPhys2CCPtrDelegated(PVM pVM, PRTGCPHYS pGCPhys, void **ppv, PPGMPAGEMAPLOCK pLock)
375{
376 /*
377 * Just hand it to PGMPhysGCPhys2CCPtr and check that it's not a page with
378 * an access handler after it succeeds.
379 */
380 int rc = PGM_LOCK(pVM);
381 AssertRCReturn(rc, rc);
382
383 rc = PGMPhysGCPhys2CCPtr(pVM, *pGCPhys, ppv, pLock);
384 if (RT_SUCCESS(rc))
385 {
386 PPGMPAGEMAPTLBE pTlbe;
387 int rc2 = pgmPhysPageQueryTlbe(pVM, *pGCPhys, &pTlbe);
388 AssertFatalRC(rc2);
389 PPGMPAGE pPage = pTlbe->pPage;
390 if (PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage))
391 {
392 PGMPhysReleasePageMappingLock(pVM, pLock);
393 rc = VERR_PGM_PHYS_PAGE_RESERVED;
394 }
395 else if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
396#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
397 || pgmPoolIsDirtyPage(pVM, *pGCPhys)
398#endif
399 )
400 {
401 /* We *must* flush any corresponding pgm pool page here, otherwise we'll
402 * not be informed about writes and keep bogus gst->shw mappings around.
403 */
404 pgmPoolFlushPageByGCPhys(pVM, *pGCPhys);
405 Assert(!PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage));
406 /** @todo r=bird: return VERR_PGM_PHYS_PAGE_RESERVED here if it still has
407 * active handlers, see the PGMR3PhysGCPhys2CCPtrExternal docs. */
408 }
409 }
410
411 PGM_UNLOCK(pVM);
412 return rc;
413}
414
415
416/**
417 * Requests the mapping of a guest page into ring-3, external threads.
418 *
419 * When you're done with the page, call PGMPhysReleasePageMappingLock() ASAP to
420 * release it.
421 *
422 * This API will assume your intention is to write to the page, and will
423 * therefore replace shared and zero pages. If you do not intend to modify the
424 * page, use the PGMR3PhysGCPhys2CCPtrReadOnlyExternal() API.
425 *
426 * @returns VBox status code.
427 * @retval VINF_SUCCESS on success.
428 * @retval VERR_PGM_PHYS_PAGE_RESERVED it it's a valid page but has no physical
429 * backing or if the page has any active access handlers. The caller
430 * must fall back on using PGMR3PhysWriteExternal.
431 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if it's not a valid physical address.
432 *
433 * @param pVM The cross context VM structure.
434 * @param GCPhys The guest physical address of the page that should be mapped.
435 * @param ppv Where to store the address corresponding to GCPhys.
436 * @param pLock Where to store the lock information that PGMPhysReleasePageMappingLock needs.
437 *
438 * @remark Avoid calling this API from within critical sections (other than the
439 * PGM one) because of the deadlock risk when we have to delegating the
440 * task to an EMT.
441 * @thread Any.
442 */
443VMMR3DECL(int) PGMR3PhysGCPhys2CCPtrExternal(PVM pVM, RTGCPHYS GCPhys, void **ppv, PPGMPAGEMAPLOCK pLock)
444{
445 AssertPtr(ppv);
446 AssertPtr(pLock);
447
448 Assert(VM_IS_EMT(pVM) || !PGMIsLockOwner(pVM));
449
450 int rc = PGM_LOCK(pVM);
451 AssertRCReturn(rc, rc);
452
453 /*
454 * Query the Physical TLB entry for the page (may fail).
455 */
456 PPGMPAGEMAPTLBE pTlbe;
457 rc = pgmPhysPageQueryTlbe(pVM, GCPhys, &pTlbe);
458 if (RT_SUCCESS(rc))
459 {
460 PPGMPAGE pPage = pTlbe->pPage;
461 if (PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage))
462 rc = VERR_PGM_PHYS_PAGE_RESERVED;
463 else
464 {
465 /*
466 * If the page is shared, the zero page, or being write monitored
467 * it must be converted to an page that's writable if possible.
468 * We can only deal with write monitored pages here, the rest have
469 * to be on an EMT.
470 */
471 if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
472 || PGM_PAGE_GET_STATE(pPage) != PGM_PAGE_STATE_ALLOCATED
473#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
474 || pgmPoolIsDirtyPage(pVM, GCPhys)
475#endif
476 )
477 {
478 if ( PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED
479 && !PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
480#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
481 && !pgmPoolIsDirtyPage(pVM, GCPhys) /** @todo we're very likely doing this twice. */
482#endif
483 )
484 pgmPhysPageMakeWriteMonitoredWritable(pVM, pPage, GCPhys);
485 else
486 {
487 PGM_UNLOCK(pVM);
488
489 return VMR3ReqPriorityCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysGCPhys2CCPtrDelegated, 4,
490 pVM, &GCPhys, ppv, pLock);
491 }
492 }
493
494 /*
495 * Now, just perform the locking and calculate the return address.
496 */
497 PPGMPAGEMAP pMap = pTlbe->pMap;
498 if (pMap)
499 pMap->cRefs++;
500
501 unsigned cLocks = PGM_PAGE_GET_WRITE_LOCKS(pPage);
502 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
503 {
504 if (cLocks == 0)
505 pVM->pgm.s.cWriteLockedPages++;
506 PGM_PAGE_INC_WRITE_LOCKS(pPage);
507 }
508 else if (cLocks != PGM_PAGE_GET_WRITE_LOCKS(pPage))
509 {
510 PGM_PAGE_INC_WRITE_LOCKS(pPage);
511 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent write locked state!\n", GCPhys, pPage));
512 if (pMap)
513 pMap->cRefs++; /* Extra ref to prevent it from going away. */
514 }
515
516 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & GUEST_PAGE_OFFSET_MASK));
517 pLock->uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_WRITE;
518 pLock->pvMap = pMap;
519 }
520 }
521
522 PGM_UNLOCK(pVM);
523 return rc;
524}
525
526
527/**
528 * Requests the mapping of a guest page into ring-3, external threads.
529 *
530 * When you're done with the page, call PGMPhysReleasePageMappingLock() ASAP to
531 * release it.
532 *
533 * @returns VBox status code.
534 * @retval VINF_SUCCESS on success.
535 * @retval VERR_PGM_PHYS_PAGE_RESERVED it it's a valid page but has no physical
536 * backing or if the page as an active ALL access handler. The caller
537 * must fall back on using PGMPhysRead.
538 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if it's not a valid physical address.
539 *
540 * @param pVM The cross context VM structure.
541 * @param GCPhys The guest physical address of the page that should be mapped.
542 * @param ppv Where to store the address corresponding to GCPhys.
543 * @param pLock Where to store the lock information that PGMPhysReleasePageMappingLock needs.
544 *
545 * @remark Avoid calling this API from within critical sections (other than
546 * the PGM one) because of the deadlock risk.
547 * @thread Any.
548 */
549VMMR3DECL(int) PGMR3PhysGCPhys2CCPtrReadOnlyExternal(PVM pVM, RTGCPHYS GCPhys, void const **ppv, PPGMPAGEMAPLOCK pLock)
550{
551 int rc = PGM_LOCK(pVM);
552 AssertRCReturn(rc, rc);
553
554 /*
555 * Query the Physical TLB entry for the page (may fail).
556 */
557 PPGMPAGEMAPTLBE pTlbe;
558 rc = pgmPhysPageQueryTlbe(pVM, GCPhys, &pTlbe);
559 if (RT_SUCCESS(rc))
560 {
561 PPGMPAGE pPage = pTlbe->pPage;
562#if 1
563 /* MMIO pages doesn't have any readable backing. */
564 if (PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage))
565 rc = VERR_PGM_PHYS_PAGE_RESERVED;
566#else
567 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage))
568 rc = VERR_PGM_PHYS_PAGE_RESERVED;
569#endif
570 else
571 {
572 /*
573 * Now, just perform the locking and calculate the return address.
574 */
575 PPGMPAGEMAP pMap = pTlbe->pMap;
576 if (pMap)
577 pMap->cRefs++;
578
579 unsigned cLocks = PGM_PAGE_GET_READ_LOCKS(pPage);
580 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
581 {
582 if (cLocks == 0)
583 pVM->pgm.s.cReadLockedPages++;
584 PGM_PAGE_INC_READ_LOCKS(pPage);
585 }
586 else if (cLocks != PGM_PAGE_GET_READ_LOCKS(pPage))
587 {
588 PGM_PAGE_INC_READ_LOCKS(pPage);
589 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent readonly locked state!\n", GCPhys, pPage));
590 if (pMap)
591 pMap->cRefs++; /* Extra ref to prevent it from going away. */
592 }
593
594 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & GUEST_PAGE_OFFSET_MASK));
595 pLock->uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_READ;
596 pLock->pvMap = pMap;
597 }
598 }
599
600 PGM_UNLOCK(pVM);
601 return rc;
602}
603
604
605/**
606 * Requests the mapping of multiple guest page into ring-3, external threads.
607 *
608 * When you're done with the pages, call PGMPhysBulkReleasePageMappingLock()
609 * ASAP to release them.
610 *
611 * This API will assume your intention is to write to the pages, and will
612 * therefore replace shared and zero pages. If you do not intend to modify the
613 * pages, use the PGMR3PhysBulkGCPhys2CCPtrReadOnlyExternal() API.
614 *
615 * @returns VBox status code.
616 * @retval VINF_SUCCESS on success.
617 * @retval VERR_PGM_PHYS_PAGE_RESERVED if any of the pages has no physical
618 * backing or if any of the pages the page has any active access
619 * handlers. The caller must fall back on using PGMR3PhysWriteExternal.
620 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if @a paGCPhysPages contains
621 * an invalid physical address.
622 *
623 * @param pVM The cross context VM structure.
624 * @param cPages Number of pages to lock.
625 * @param paGCPhysPages The guest physical address of the pages that
626 * should be mapped (@a cPages entries).
627 * @param papvPages Where to store the ring-3 mapping addresses
628 * corresponding to @a paGCPhysPages.
629 * @param paLocks Where to store the locking information that
630 * pfnPhysBulkReleasePageMappingLock needs (@a cPages
631 * in length).
632 *
633 * @remark Avoid calling this API from within critical sections (other than the
634 * PGM one) because of the deadlock risk when we have to delegating the
635 * task to an EMT.
636 * @thread Any.
637 */
638VMMR3DECL(int) PGMR3PhysBulkGCPhys2CCPtrExternal(PVM pVM, uint32_t cPages, PCRTGCPHYS paGCPhysPages,
639 void **papvPages, PPGMPAGEMAPLOCK paLocks)
640{
641 Assert(cPages > 0);
642 AssertPtr(papvPages);
643 AssertPtr(paLocks);
644
645 Assert(VM_IS_EMT(pVM) || !PGMIsLockOwner(pVM));
646
647 int rc = PGM_LOCK(pVM);
648 AssertRCReturn(rc, rc);
649
650 /*
651 * Lock the pages one by one.
652 * The loop body is similar to PGMR3PhysGCPhys2CCPtrExternal.
653 */
654 int32_t cNextYield = 128;
655 uint32_t iPage;
656 for (iPage = 0; iPage < cPages; iPage++)
657 {
658 if (--cNextYield > 0)
659 { /* likely */ }
660 else
661 {
662 PGM_UNLOCK(pVM);
663 ASMNopPause();
664 PGM_LOCK_VOID(pVM);
665 cNextYield = 128;
666 }
667
668 /*
669 * Query the Physical TLB entry for the page (may fail).
670 */
671 PPGMPAGEMAPTLBE pTlbe;
672 rc = pgmPhysPageQueryTlbe(pVM, paGCPhysPages[iPage], &pTlbe);
673 if (RT_SUCCESS(rc))
674 { }
675 else
676 break;
677 PPGMPAGE pPage = pTlbe->pPage;
678
679 /*
680 * No MMIO or active access handlers.
681 */
682 if ( !PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage)
683 && !PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
684 { }
685 else
686 {
687 rc = VERR_PGM_PHYS_PAGE_RESERVED;
688 break;
689 }
690
691 /*
692 * The page must be in the allocated state and not be a dirty pool page.
693 * We can handle converting a write monitored page to an allocated one, but
694 * anything more complicated must be delegated to an EMT.
695 */
696 bool fDelegateToEmt = false;
697 if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_ALLOCATED)
698#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
699 fDelegateToEmt = pgmPoolIsDirtyPage(pVM, paGCPhysPages[iPage]);
700#else
701 fDelegateToEmt = false;
702#endif
703 else if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED)
704 {
705#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
706 if (!pgmPoolIsDirtyPage(pVM, paGCPhysPages[iPage]))
707 pgmPhysPageMakeWriteMonitoredWritable(pVM, pPage, paGCPhysPages[iPage]);
708 else
709 fDelegateToEmt = true;
710#endif
711 }
712 else
713 fDelegateToEmt = true;
714 if (!fDelegateToEmt)
715 { }
716 else
717 {
718 /* We could do this delegation in bulk, but considered too much work vs gain. */
719 PGM_UNLOCK(pVM);
720 rc = VMR3ReqPriorityCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysGCPhys2CCPtrDelegated, 4,
721 pVM, &paGCPhysPages[iPage], &papvPages[iPage], &paLocks[iPage]);
722 PGM_LOCK_VOID(pVM);
723 if (RT_FAILURE(rc))
724 break;
725 cNextYield = 128;
726 }
727
728 /*
729 * Now, just perform the locking and address calculation.
730 */
731 PPGMPAGEMAP pMap = pTlbe->pMap;
732 if (pMap)
733 pMap->cRefs++;
734
735 unsigned cLocks = PGM_PAGE_GET_WRITE_LOCKS(pPage);
736 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
737 {
738 if (cLocks == 0)
739 pVM->pgm.s.cWriteLockedPages++;
740 PGM_PAGE_INC_WRITE_LOCKS(pPage);
741 }
742 else if (cLocks != PGM_PAGE_GET_WRITE_LOCKS(pPage))
743 {
744 PGM_PAGE_INC_WRITE_LOCKS(pPage);
745 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent write locked state!\n", paGCPhysPages[iPage], pPage));
746 if (pMap)
747 pMap->cRefs++; /* Extra ref to prevent it from going away. */
748 }
749
750 papvPages[iPage] = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(paGCPhysPages[iPage] & GUEST_PAGE_OFFSET_MASK));
751 paLocks[iPage].uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_WRITE;
752 paLocks[iPage].pvMap = pMap;
753 }
754
755 PGM_UNLOCK(pVM);
756
757 /*
758 * On failure we must unlock any pages we managed to get already.
759 */
760 if (RT_FAILURE(rc) && iPage > 0)
761 PGMPhysBulkReleasePageMappingLocks(pVM, iPage, paLocks);
762
763 return rc;
764}
765
766
767/**
768 * Requests the mapping of multiple guest page into ring-3, for reading only,
769 * external threads.
770 *
771 * When you're done with the pages, call PGMPhysReleasePageMappingLock() ASAP
772 * to release them.
773 *
774 * @returns VBox status code.
775 * @retval VINF_SUCCESS on success.
776 * @retval VERR_PGM_PHYS_PAGE_RESERVED if any of the pages has no physical
777 * backing or if any of the pages the page has an active ALL access
778 * handler. The caller must fall back on using PGMR3PhysWriteExternal.
779 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if @a paGCPhysPages contains
780 * an invalid physical address.
781 *
782 * @param pVM The cross context VM structure.
783 * @param cPages Number of pages to lock.
784 * @param paGCPhysPages The guest physical address of the pages that
785 * should be mapped (@a cPages entries).
786 * @param papvPages Where to store the ring-3 mapping addresses
787 * corresponding to @a paGCPhysPages.
788 * @param paLocks Where to store the lock information that
789 * pfnPhysReleasePageMappingLock needs (@a cPages
790 * in length).
791 *
792 * @remark Avoid calling this API from within critical sections (other than
793 * the PGM one) because of the deadlock risk.
794 * @thread Any.
795 */
796VMMR3DECL(int) PGMR3PhysBulkGCPhys2CCPtrReadOnlyExternal(PVM pVM, uint32_t cPages, PCRTGCPHYS paGCPhysPages,
797 void const **papvPages, PPGMPAGEMAPLOCK paLocks)
798{
799 Assert(cPages > 0);
800 AssertPtr(papvPages);
801 AssertPtr(paLocks);
802
803 Assert(VM_IS_EMT(pVM) || !PGMIsLockOwner(pVM));
804
805 int rc = PGM_LOCK(pVM);
806 AssertRCReturn(rc, rc);
807
808 /*
809 * Lock the pages one by one.
810 * The loop body is similar to PGMR3PhysGCPhys2CCPtrReadOnlyExternal.
811 */
812 int32_t cNextYield = 256;
813 uint32_t iPage;
814 for (iPage = 0; iPage < cPages; iPage++)
815 {
816 if (--cNextYield > 0)
817 { /* likely */ }
818 else
819 {
820 PGM_UNLOCK(pVM);
821 ASMNopPause();
822 PGM_LOCK_VOID(pVM);
823 cNextYield = 256;
824 }
825
826 /*
827 * Query the Physical TLB entry for the page (may fail).
828 */
829 PPGMPAGEMAPTLBE pTlbe;
830 rc = pgmPhysPageQueryTlbe(pVM, paGCPhysPages[iPage], &pTlbe);
831 if (RT_SUCCESS(rc))
832 { }
833 else
834 break;
835 PPGMPAGE pPage = pTlbe->pPage;
836
837 /*
838 * No MMIO or active all access handlers, everything else can be accessed.
839 */
840 if ( !PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage)
841 && !PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage))
842 { }
843 else
844 {
845 rc = VERR_PGM_PHYS_PAGE_RESERVED;
846 break;
847 }
848
849 /*
850 * Now, just perform the locking and address calculation.
851 */
852 PPGMPAGEMAP pMap = pTlbe->pMap;
853 if (pMap)
854 pMap->cRefs++;
855
856 unsigned cLocks = PGM_PAGE_GET_READ_LOCKS(pPage);
857 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
858 {
859 if (cLocks == 0)
860 pVM->pgm.s.cReadLockedPages++;
861 PGM_PAGE_INC_READ_LOCKS(pPage);
862 }
863 else if (cLocks != PGM_PAGE_GET_READ_LOCKS(pPage))
864 {
865 PGM_PAGE_INC_READ_LOCKS(pPage);
866 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent readonly locked state!\n", paGCPhysPages[iPage], pPage));
867 if (pMap)
868 pMap->cRefs++; /* Extra ref to prevent it from going away. */
869 }
870
871 papvPages[iPage] = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(paGCPhysPages[iPage] & GUEST_PAGE_OFFSET_MASK));
872 paLocks[iPage].uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_READ;
873 paLocks[iPage].pvMap = pMap;
874 }
875
876 PGM_UNLOCK(pVM);
877
878 /*
879 * On failure we must unlock any pages we managed to get already.
880 */
881 if (RT_FAILURE(rc) && iPage > 0)
882 PGMPhysBulkReleasePageMappingLocks(pVM, iPage, paLocks);
883
884 return rc;
885}
886
887
888/**
889 * Converts a GC physical address to a HC ring-3 pointer, with some
890 * additional checks.
891 *
892 * @returns VBox status code.
893 * @retval VINF_SUCCESS on success.
894 * @retval VINF_PGM_PHYS_TLB_CATCH_WRITE and *ppv set if the page has a write
895 * access handler of some kind.
896 * @retval VERR_PGM_PHYS_TLB_CATCH_ALL if the page has a handler catching all
897 * accesses or is odd in any way.
898 * @retval VERR_PGM_PHYS_TLB_UNASSIGNED if the page doesn't exist.
899 *
900 * @param pVM The cross context VM structure.
901 * @param GCPhys The GC physical address to convert. Since this is only
902 * used for filling the REM TLB, the A20 mask must be
903 * applied before calling this API.
904 * @param fWritable Whether write access is required.
905 * @param ppv Where to store the pointer corresponding to GCPhys on
906 * success.
907 */
908VMMR3DECL(int) PGMR3PhysTlbGCPhys2Ptr(PVM pVM, RTGCPHYS GCPhys, bool fWritable, void **ppv)
909{
910 PGM_LOCK_VOID(pVM);
911 PGM_A20_ASSERT_MASKED(VMMGetCpu(pVM), GCPhys);
912
913 PPGMRAMRANGE pRam;
914 PPGMPAGE pPage;
915 int rc = pgmPhysGetPageAndRangeEx(pVM, GCPhys, &pPage, &pRam);
916 if (RT_SUCCESS(rc))
917 {
918 if (PGM_PAGE_IS_BALLOONED(pPage))
919 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
920 else if (!PGM_PAGE_HAS_ANY_HANDLERS(pPage))
921 rc = VINF_SUCCESS;
922 else
923 {
924 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)) /* catches MMIO */
925 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
926 else if (PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
927 {
928 /** @todo Handle TLB loads of virtual handlers so ./test.sh can be made to work
929 * in -norawr0 mode. */
930 if (fWritable)
931 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
932 }
933 else
934 {
935 /* Temporarily disabled physical handler(s), since the recompiler
936 doesn't get notified when it's reset we'll have to pretend it's
937 operating normally. */
938 if (pgmHandlerPhysicalIsAll(pVM, GCPhys))
939 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
940 else
941 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
942 }
943 }
944 if (RT_SUCCESS(rc))
945 {
946 int rc2;
947
948 /* Make sure what we return is writable. */
949 if (fWritable)
950 switch (PGM_PAGE_GET_STATE(pPage))
951 {
952 case PGM_PAGE_STATE_ALLOCATED:
953 break;
954 case PGM_PAGE_STATE_BALLOONED:
955 AssertFailed();
956 break;
957 case PGM_PAGE_STATE_ZERO:
958 case PGM_PAGE_STATE_SHARED:
959 if (rc == VINF_PGM_PHYS_TLB_CATCH_WRITE)
960 break;
961 RT_FALL_THRU();
962 case PGM_PAGE_STATE_WRITE_MONITORED:
963 rc2 = pgmPhysPageMakeWritable(pVM, pPage, GCPhys & ~(RTGCPHYS)GUEST_PAGE_OFFSET_MASK);
964 AssertLogRelRCReturn(rc2, rc2);
965 break;
966 }
967
968 /* Get a ring-3 mapping of the address. */
969 PPGMPAGER3MAPTLBE pTlbe;
970 rc2 = pgmPhysPageQueryTlbe(pVM, GCPhys, &pTlbe);
971 AssertLogRelRCReturn(rc2, rc2);
972 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & GUEST_PAGE_OFFSET_MASK));
973 /** @todo mapping/locking hell; this isn't horribly efficient since
974 * pgmPhysPageLoadIntoTlb will repeat the lookup we've done here. */
975
976 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage] *ppv=%p\n", GCPhys, rc, pPage, *ppv));
977 }
978 else
979 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage]\n", GCPhys, rc, pPage));
980
981 /* else: handler catching all access, no pointer returned. */
982 }
983 else
984 rc = VERR_PGM_PHYS_TLB_UNASSIGNED;
985
986 PGM_UNLOCK(pVM);
987 return rc;
988}
989
990
991
992/*********************************************************************************************************************************
993* RAM Range Management *
994*********************************************************************************************************************************/
995
996#define MAKE_LEAF(a_pNode) \
997 do { \
998 (a_pNode)->pLeftR3 = NIL_RTR3PTR; \
999 (a_pNode)->pRightR3 = NIL_RTR3PTR; \
1000 (a_pNode)->pLeftR0 = NIL_RTR0PTR; \
1001 (a_pNode)->pRightR0 = NIL_RTR0PTR; \
1002 } while (0)
1003
1004#define INSERT_LEFT(a_pParent, a_pNode) \
1005 do { \
1006 (a_pParent)->pLeftR3 = (a_pNode); \
1007 (a_pParent)->pLeftR0 = (a_pNode)->pSelfR0; \
1008 } while (0)
1009#define INSERT_RIGHT(a_pParent, a_pNode) \
1010 do { \
1011 (a_pParent)->pRightR3 = (a_pNode); \
1012 (a_pParent)->pRightR0 = (a_pNode)->pSelfR0; \
1013 } while (0)
1014
1015
1016/**
1017 * Recursive tree builder.
1018 *
1019 * @param ppRam Pointer to the iterator variable.
1020 * @param iDepth The current depth. Inserts a leaf node if 0.
1021 */
1022static PPGMRAMRANGE pgmR3PhysRebuildRamRangeSearchTreesRecursively(PPGMRAMRANGE *ppRam, int iDepth)
1023{
1024 PPGMRAMRANGE pRam;
1025 if (iDepth <= 0)
1026 {
1027 /*
1028 * Leaf node.
1029 */
1030 pRam = *ppRam;
1031 if (pRam)
1032 {
1033 *ppRam = pRam->pNextR3;
1034 MAKE_LEAF(pRam);
1035 }
1036 }
1037 else
1038 {
1039
1040 /*
1041 * Intermediate node.
1042 */
1043 PPGMRAMRANGE pLeft = pgmR3PhysRebuildRamRangeSearchTreesRecursively(ppRam, iDepth - 1);
1044
1045 pRam = *ppRam;
1046 if (!pRam)
1047 return pLeft;
1048 *ppRam = pRam->pNextR3;
1049 MAKE_LEAF(pRam);
1050 INSERT_LEFT(pRam, pLeft);
1051
1052 PPGMRAMRANGE pRight = pgmR3PhysRebuildRamRangeSearchTreesRecursively(ppRam, iDepth - 1);
1053 if (pRight)
1054 INSERT_RIGHT(pRam, pRight);
1055 }
1056 return pRam;
1057}
1058
1059
1060/**
1061 * Rebuilds the RAM range search trees.
1062 *
1063 * @param pVM The cross context VM structure.
1064 */
1065static void pgmR3PhysRebuildRamRangeSearchTrees(PVM pVM)
1066{
1067
1068 /*
1069 * Create the reasonably balanced tree in a sequential fashion.
1070 * For simplicity (laziness) we use standard recursion here.
1071 */
1072 int iDepth = 0;
1073 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
1074 PPGMRAMRANGE pRoot = pgmR3PhysRebuildRamRangeSearchTreesRecursively(&pRam, 0);
1075 while (pRam)
1076 {
1077 PPGMRAMRANGE pLeft = pRoot;
1078
1079 pRoot = pRam;
1080 pRam = pRam->pNextR3;
1081 MAKE_LEAF(pRoot);
1082 INSERT_LEFT(pRoot, pLeft);
1083
1084 PPGMRAMRANGE pRight = pgmR3PhysRebuildRamRangeSearchTreesRecursively(&pRam, iDepth);
1085 if (pRight)
1086 INSERT_RIGHT(pRoot, pRight);
1087 /** @todo else: rotate the tree. */
1088
1089 iDepth++;
1090 }
1091
1092 pVM->pgm.s.pRamRangeTreeR3 = pRoot;
1093 pVM->pgm.s.pRamRangeTreeR0 = pRoot ? pRoot->pSelfR0 : NIL_RTR0PTR;
1094
1095#ifdef VBOX_STRICT
1096 /*
1097 * Verify that the above code works.
1098 */
1099 unsigned cRanges = 0;
1100 for (pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1101 cRanges++;
1102 Assert(cRanges > 0);
1103
1104 unsigned cMaxDepth = ASMBitLastSetU32(cRanges);
1105 if ((1U << cMaxDepth) < cRanges)
1106 cMaxDepth++;
1107
1108 for (pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1109 {
1110 unsigned cDepth = 0;
1111 PPGMRAMRANGE pRam2 = pVM->pgm.s.pRamRangeTreeR3;
1112 for (;;)
1113 {
1114 if (pRam == pRam2)
1115 break;
1116 Assert(pRam2);
1117 if (pRam->GCPhys < pRam2->GCPhys)
1118 pRam2 = pRam2->pLeftR3;
1119 else
1120 pRam2 = pRam2->pRightR3;
1121 }
1122 AssertMsg(cDepth <= cMaxDepth, ("cDepth=%d cMaxDepth=%d\n", cDepth, cMaxDepth));
1123 }
1124#endif /* VBOX_STRICT */
1125}
1126
1127#undef MAKE_LEAF
1128#undef INSERT_LEFT
1129#undef INSERT_RIGHT
1130
1131/**
1132 * Relinks the RAM ranges using the pSelfRC and pSelfR0 pointers.
1133 *
1134 * Called when anything was relocated.
1135 *
1136 * @param pVM The cross context VM structure.
1137 */
1138void pgmR3PhysRelinkRamRanges(PVM pVM)
1139{
1140 PPGMRAMRANGE pCur;
1141
1142#ifdef VBOX_STRICT
1143 for (pCur = pVM->pgm.s.pRamRangesXR3; pCur; pCur = pCur->pNextR3)
1144 {
1145 Assert((pCur->GCPhys & GUEST_PAGE_OFFSET_MASK) == 0);
1146 Assert((pCur->GCPhysLast & GUEST_PAGE_OFFSET_MASK) == GUEST_PAGE_OFFSET_MASK);
1147 Assert((pCur->cb & GUEST_PAGE_OFFSET_MASK) == 0);
1148 Assert(pCur->cb == pCur->GCPhysLast - pCur->GCPhys + 1);
1149 for (PPGMRAMRANGE pCur2 = pVM->pgm.s.pRamRangesXR3; pCur2; pCur2 = pCur2->pNextR3)
1150 Assert( pCur2 == pCur
1151 || strcmp(pCur2->pszDesc, pCur->pszDesc)); /** @todo fix MMIO ranges!! */
1152 }
1153#endif
1154
1155 pCur = pVM->pgm.s.pRamRangesXR3;
1156 if (pCur)
1157 {
1158 pVM->pgm.s.pRamRangesXR0 = pCur->pSelfR0;
1159
1160 for (; pCur->pNextR3; pCur = pCur->pNextR3)
1161 pCur->pNextR0 = pCur->pNextR3->pSelfR0;
1162
1163 Assert(pCur->pNextR0 == NIL_RTR0PTR);
1164 }
1165 else
1166 {
1167 Assert(pVM->pgm.s.pRamRangesXR0 == NIL_RTR0PTR);
1168 }
1169 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
1170
1171 pgmR3PhysRebuildRamRangeSearchTrees(pVM);
1172}
1173
1174
1175/**
1176 * Links a new RAM range into the list.
1177 *
1178 * @param pVM The cross context VM structure.
1179 * @param pNew Pointer to the new list entry.
1180 * @param pPrev Pointer to the previous list entry. If NULL, insert as head.
1181 */
1182static void pgmR3PhysLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, PPGMRAMRANGE pPrev)
1183{
1184 AssertMsg(pNew->pszDesc, ("%RGp-%RGp\n", pNew->GCPhys, pNew->GCPhysLast));
1185
1186 PGM_LOCK_VOID(pVM);
1187
1188 PPGMRAMRANGE pRam = pPrev ? pPrev->pNextR3 : pVM->pgm.s.pRamRangesXR3;
1189 pNew->pNextR3 = pRam;
1190 pNew->pNextR0 = pRam ? pRam->pSelfR0 : NIL_RTR0PTR;
1191
1192 if (pPrev)
1193 {
1194 pPrev->pNextR3 = pNew;
1195 pPrev->pNextR0 = pNew->pSelfR0;
1196 }
1197 else
1198 {
1199 pVM->pgm.s.pRamRangesXR3 = pNew;
1200 pVM->pgm.s.pRamRangesXR0 = pNew->pSelfR0;
1201 }
1202 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
1203
1204 pgmR3PhysRebuildRamRangeSearchTrees(pVM);
1205 PGM_UNLOCK(pVM);
1206}
1207
1208
1209/**
1210 * Unlink an existing RAM range from the list.
1211 *
1212 * @param pVM The cross context VM structure.
1213 * @param pRam Pointer to the new list entry.
1214 * @param pPrev Pointer to the previous list entry. If NULL, insert as head.
1215 */
1216static void pgmR3PhysUnlinkRamRange2(PVM pVM, PPGMRAMRANGE pRam, PPGMRAMRANGE pPrev)
1217{
1218 Assert(pPrev ? pPrev->pNextR3 == pRam : pVM->pgm.s.pRamRangesXR3 == pRam);
1219
1220 PGM_LOCK_VOID(pVM);
1221
1222 PPGMRAMRANGE pNext = pRam->pNextR3;
1223 if (pPrev)
1224 {
1225 pPrev->pNextR3 = pNext;
1226 pPrev->pNextR0 = pNext ? pNext->pSelfR0 : NIL_RTR0PTR;
1227 }
1228 else
1229 {
1230 Assert(pVM->pgm.s.pRamRangesXR3 == pRam);
1231 pVM->pgm.s.pRamRangesXR3 = pNext;
1232 pVM->pgm.s.pRamRangesXR0 = pNext ? pNext->pSelfR0 : NIL_RTR0PTR;
1233 }
1234 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
1235
1236 pgmR3PhysRebuildRamRangeSearchTrees(pVM);
1237 PGM_UNLOCK(pVM);
1238}
1239
1240
1241/**
1242 * Unlink an existing RAM range from the list.
1243 *
1244 * @param pVM The cross context VM structure.
1245 * @param pRam Pointer to the new list entry.
1246 */
1247static void pgmR3PhysUnlinkRamRange(PVM pVM, PPGMRAMRANGE pRam)
1248{
1249 PGM_LOCK_VOID(pVM);
1250
1251 /* find prev. */
1252 PPGMRAMRANGE pPrev = NULL;
1253 PPGMRAMRANGE pCur = pVM->pgm.s.pRamRangesXR3;
1254 while (pCur != pRam)
1255 {
1256 pPrev = pCur;
1257 pCur = pCur->pNextR3;
1258 }
1259 AssertFatal(pCur);
1260
1261 pgmR3PhysUnlinkRamRange2(pVM, pRam, pPrev);
1262 PGM_UNLOCK(pVM);
1263}
1264
1265
1266/**
1267 * Gets the number of ram ranges.
1268 *
1269 * @returns Number of ram ranges. Returns UINT32_MAX if @a pVM is invalid.
1270 * @param pVM The cross context VM structure.
1271 */
1272VMMR3DECL(uint32_t) PGMR3PhysGetRamRangeCount(PVM pVM)
1273{
1274 VM_ASSERT_VALID_EXT_RETURN(pVM, UINT32_MAX);
1275
1276 PGM_LOCK_VOID(pVM);
1277 uint32_t cRamRanges = 0;
1278 for (PPGMRAMRANGE pCur = pVM->pgm.s.CTX_SUFF(pRamRangesX); pCur; pCur = pCur->CTX_SUFF(pNext))
1279 cRamRanges++;
1280 PGM_UNLOCK(pVM);
1281 return cRamRanges;
1282}
1283
1284
1285/**
1286 * Get information about a range.
1287 *
1288 * @returns VINF_SUCCESS or VERR_OUT_OF_RANGE.
1289 * @param pVM The cross context VM structure.
1290 * @param iRange The ordinal of the range.
1291 * @param pGCPhysStart Where to return the start of the range. Optional.
1292 * @param pGCPhysLast Where to return the address of the last byte in the
1293 * range. Optional.
1294 * @param ppszDesc Where to return the range description. Optional.
1295 * @param pfIsMmio Where to indicate that this is a pure MMIO range.
1296 * Optional.
1297 */
1298VMMR3DECL(int) PGMR3PhysGetRange(PVM pVM, uint32_t iRange, PRTGCPHYS pGCPhysStart, PRTGCPHYS pGCPhysLast,
1299 const char **ppszDesc, bool *pfIsMmio)
1300{
1301 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1302
1303 PGM_LOCK_VOID(pVM);
1304 uint32_t iCurRange = 0;
1305 for (PPGMRAMRANGE pCur = pVM->pgm.s.CTX_SUFF(pRamRangesX); pCur; pCur = pCur->CTX_SUFF(pNext), iCurRange++)
1306 if (iCurRange == iRange)
1307 {
1308 if (pGCPhysStart)
1309 *pGCPhysStart = pCur->GCPhys;
1310 if (pGCPhysLast)
1311 *pGCPhysLast = pCur->GCPhysLast;
1312 if (ppszDesc)
1313 *ppszDesc = pCur->pszDesc;
1314 if (pfIsMmio)
1315 *pfIsMmio = !!(pCur->fFlags & PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO);
1316
1317 PGM_UNLOCK(pVM);
1318 return VINF_SUCCESS;
1319 }
1320 PGM_UNLOCK(pVM);
1321 return VERR_OUT_OF_RANGE;
1322}
1323
1324
1325/*********************************************************************************************************************************
1326* RAM *
1327*********************************************************************************************************************************/
1328
1329/**
1330 * Frees the specified RAM page and replaces it with the ZERO page.
1331 *
1332 * This is used by ballooning, remapping MMIO2, RAM reset and state loading.
1333 *
1334 * @param pVM The cross context VM structure.
1335 * @param pReq Pointer to the request. This is NULL when doing a
1336 * bulk free in NEM memory mode.
1337 * @param pcPendingPages Where the number of pages waiting to be freed are
1338 * kept. This will normally be incremented. This is
1339 * NULL when doing a bulk free in NEM memory mode.
1340 * @param pPage Pointer to the page structure.
1341 * @param GCPhys The guest physical address of the page, if applicable.
1342 * @param enmNewType New page type for NEM notification, since several
1343 * callers will change the type upon successful return.
1344 *
1345 * @remarks The caller must own the PGM lock.
1346 */
1347int pgmPhysFreePage(PVM pVM, PGMMFREEPAGESREQ pReq, uint32_t *pcPendingPages, PPGMPAGE pPage, RTGCPHYS GCPhys,
1348 PGMPAGETYPE enmNewType)
1349{
1350 /*
1351 * Assert sanity.
1352 */
1353 PGM_LOCK_ASSERT_OWNER(pVM);
1354 if (RT_UNLIKELY( PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM
1355 && PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_ROM_SHADOW))
1356 {
1357 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
1358 return VMSetError(pVM, VERR_PGM_PHYS_NOT_RAM, RT_SRC_POS, "GCPhys=%RGp type=%d", GCPhys, PGM_PAGE_GET_TYPE(pPage));
1359 }
1360
1361 /** @todo What about ballooning of large pages??! */
1362 Assert( PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE
1363 && PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE_DISABLED);
1364
1365 if ( PGM_PAGE_IS_ZERO(pPage)
1366 || PGM_PAGE_IS_BALLOONED(pPage))
1367 return VINF_SUCCESS;
1368
1369 const uint32_t idPage = PGM_PAGE_GET_PAGEID(pPage);
1370 Log3(("pgmPhysFreePage: idPage=%#x GCPhys=%RGp pPage=%R[pgmpage]\n", idPage, GCPhys, pPage));
1371 if (RT_UNLIKELY(!PGM_IS_IN_NEM_MODE(pVM)
1372 ? idPage == NIL_GMM_PAGEID
1373 || idPage > GMM_PAGEID_LAST
1374 || PGM_PAGE_GET_CHUNKID(pPage) == NIL_GMM_CHUNKID
1375 : idPage != NIL_GMM_PAGEID))
1376 {
1377 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
1378 return VMSetError(pVM, VERR_PGM_PHYS_INVALID_PAGE_ID, RT_SRC_POS, "GCPhys=%RGp idPage=%#x", GCPhys, pPage);
1379 }
1380#ifdef VBOX_WITH_NATIVE_NEM
1381 const RTHCPHYS HCPhysPrev = PGM_PAGE_GET_HCPHYS(pPage);
1382#endif
1383
1384 /* update page count stats. */
1385 if (PGM_PAGE_IS_SHARED(pPage))
1386 pVM->pgm.s.cSharedPages--;
1387 else
1388 pVM->pgm.s.cPrivatePages--;
1389 pVM->pgm.s.cZeroPages++;
1390
1391 /* Deal with write monitored pages. */
1392 if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED)
1393 {
1394 PGM_PAGE_SET_WRITTEN_TO(pVM, pPage);
1395 pVM->pgm.s.cWrittenToPages++;
1396 }
1397
1398 /*
1399 * pPage = ZERO page.
1400 */
1401 PGM_PAGE_SET_HCPHYS(pVM, pPage, pVM->pgm.s.HCPhysZeroPg);
1402 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
1403 PGM_PAGE_SET_PAGEID(pVM, pPage, NIL_GMM_PAGEID);
1404 PGM_PAGE_SET_PDE_TYPE(pVM, pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
1405 PGM_PAGE_SET_PTE_INDEX(pVM, pPage, 0);
1406 PGM_PAGE_SET_TRACKING(pVM, pPage, 0);
1407
1408 /* Flush physical page map TLB entry. */
1409 pgmPhysInvalidatePageMapTLBEntry(pVM, GCPhys);
1410 IEMTlbInvalidateAllPhysicalAllCpus(pVM, NIL_VMCPUID); /// @todo move to the perform step.
1411
1412#ifdef VBOX_WITH_PGM_NEM_MODE
1413 /*
1414 * Skip the rest if we're doing a bulk free in NEM memory mode.
1415 */
1416 if (!pReq)
1417 return VINF_SUCCESS;
1418 AssertLogRelReturn(!pVM->pgm.s.fNemMode, VERR_PGM_NOT_SUPPORTED_FOR_NEM_MODE);
1419#endif
1420
1421#ifdef VBOX_WITH_NATIVE_NEM
1422 /* Notify NEM. */
1423 /** @todo Remove this one? */
1424 if (VM_IS_NEM_ENABLED(pVM))
1425 {
1426 uint8_t u2State = PGM_PAGE_GET_NEM_STATE(pPage);
1427 NEMHCNotifyPhysPageChanged(pVM, GCPhys, HCPhysPrev, pVM->pgm.s.HCPhysZeroPg, pVM->pgm.s.abZeroPg,
1428 pgmPhysPageCalcNemProtection(pPage, enmNewType), enmNewType, &u2State);
1429 PGM_PAGE_SET_NEM_STATE(pPage, u2State);
1430 }
1431#else
1432 RT_NOREF(enmNewType);
1433#endif
1434
1435 /*
1436 * Make sure it's not in the handy page array.
1437 */
1438 for (uint32_t i = pVM->pgm.s.cHandyPages; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
1439 {
1440 if (pVM->pgm.s.aHandyPages[i].idPage == idPage)
1441 {
1442 pVM->pgm.s.aHandyPages[i].HCPhysGCPhys = NIL_GMMPAGEDESC_PHYS;
1443 pVM->pgm.s.aHandyPages[i].fZeroed = false;
1444 pVM->pgm.s.aHandyPages[i].idPage = NIL_GMM_PAGEID;
1445 break;
1446 }
1447 if (pVM->pgm.s.aHandyPages[i].idSharedPage == idPage)
1448 {
1449 pVM->pgm.s.aHandyPages[i].idSharedPage = NIL_GMM_PAGEID;
1450 break;
1451 }
1452 }
1453
1454 /*
1455 * Push it onto the page array.
1456 */
1457 uint32_t iPage = *pcPendingPages;
1458 Assert(iPage < PGMPHYS_FREE_PAGE_BATCH_SIZE);
1459 *pcPendingPages += 1;
1460
1461 pReq->aPages[iPage].idPage = idPage;
1462
1463 if (iPage + 1 < PGMPHYS_FREE_PAGE_BATCH_SIZE)
1464 return VINF_SUCCESS;
1465
1466 /*
1467 * Flush the pages.
1468 */
1469 int rc = GMMR3FreePagesPerform(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE);
1470 if (RT_SUCCESS(rc))
1471 {
1472 GMMR3FreePagesRePrep(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
1473 *pcPendingPages = 0;
1474 }
1475 return rc;
1476}
1477
1478
1479/**
1480 * Frees a range of pages, replacing them with ZERO pages of the specified type.
1481 *
1482 * @returns VBox status code.
1483 * @param pVM The cross context VM structure.
1484 * @param pRam The RAM range in which the pages resides.
1485 * @param GCPhys The address of the first page.
1486 * @param GCPhysLast The address of the last page.
1487 * @param pvMmio2 Pointer to the ring-3 mapping of any MMIO2 memory that
1488 * will replace the pages we're freeing up.
1489 */
1490static int pgmR3PhysFreePageRange(PVM pVM, PPGMRAMRANGE pRam, RTGCPHYS GCPhys, RTGCPHYS GCPhysLast, void *pvMmio2)
1491{
1492 PGM_LOCK_ASSERT_OWNER(pVM);
1493
1494#ifdef VBOX_WITH_PGM_NEM_MODE
1495 /*
1496 * In simplified memory mode we don't actually free the memory,
1497 * we just unmap it and let NEM do any unlocking of it.
1498 */
1499 if (pVM->pgm.s.fNemMode)
1500 {
1501 Assert(VM_IS_NEM_ENABLED(pVM) || VM_IS_EXEC_ENGINE_IEM(pVM));
1502 uint8_t u2State = 0; /* (We don't support UINT8_MAX here.) */
1503 if (VM_IS_NEM_ENABLED(pVM))
1504 {
1505 uint32_t const fNemNotify = (pvMmio2 ? NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2 : 0) | NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE;
1506 int rc = NEMR3NotifyPhysMmioExMapEarly(pVM, GCPhys, GCPhysLast - GCPhys + 1, fNemNotify,
1507 pRam->pvR3 ? (uint8_t *)pRam->pvR3 + GCPhys - pRam->GCPhys : NULL,
1508 pvMmio2, &u2State, NULL /*puNemRange*/);
1509 AssertLogRelRCReturn(rc, rc);
1510 }
1511
1512 /* Iterate the pages. */
1513 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
1514 uint32_t cPagesLeft = ((GCPhysLast - GCPhys) >> GUEST_PAGE_SHIFT) + 1;
1515 while (cPagesLeft-- > 0)
1516 {
1517 int rc = pgmPhysFreePage(pVM, NULL, NULL, pPageDst, GCPhys, PGMPAGETYPE_MMIO);
1518 AssertLogRelRCReturn(rc, rc); /* We're done for if this goes wrong. */
1519
1520 PGM_PAGE_SET_TYPE(pVM, pPageDst, PGMPAGETYPE_MMIO);
1521 PGM_PAGE_SET_NEM_STATE(pPageDst, u2State);
1522
1523 GCPhys += GUEST_PAGE_SIZE;
1524 pPageDst++;
1525 }
1526 return VINF_SUCCESS;
1527 }
1528#else /* !VBOX_WITH_PGM_NEM_MODE */
1529 RT_NOREF(pvMmio2);
1530#endif /* !VBOX_WITH_PGM_NEM_MODE */
1531
1532 /*
1533 * Regular mode.
1534 */
1535 /* Prepare. */
1536 uint32_t cPendingPages = 0;
1537 PGMMFREEPAGESREQ pReq;
1538 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
1539 AssertLogRelRCReturn(rc, rc);
1540
1541#ifdef VBOX_WITH_NATIVE_NEM
1542 /* Tell NEM up-front. */
1543 uint8_t u2State = UINT8_MAX;
1544 if (VM_IS_NEM_ENABLED(pVM))
1545 {
1546 uint32_t const fNemNotify = (pvMmio2 ? NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2 : 0) | NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE;
1547 rc = NEMR3NotifyPhysMmioExMapEarly(pVM, GCPhys, GCPhysLast - GCPhys + 1, fNemNotify, NULL, pvMmio2,
1548 &u2State, NULL /*puNemRange*/);
1549 AssertLogRelRCReturnStmt(rc, GMMR3FreePagesCleanup(pReq), rc);
1550 }
1551#endif
1552
1553 /* Iterate the pages. */
1554 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
1555 uint32_t cPagesLeft = ((GCPhysLast - GCPhys) >> GUEST_PAGE_SHIFT) + 1;
1556 while (cPagesLeft-- > 0)
1557 {
1558 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPageDst, GCPhys, PGMPAGETYPE_MMIO);
1559 AssertLogRelRCReturn(rc, rc); /* We're done for if this goes wrong. */
1560
1561 PGM_PAGE_SET_TYPE(pVM, pPageDst, PGMPAGETYPE_MMIO);
1562#ifdef VBOX_WITH_NATIVE_NEM
1563 if (u2State != UINT8_MAX)
1564 PGM_PAGE_SET_NEM_STATE(pPageDst, u2State);
1565#endif
1566
1567 GCPhys += GUEST_PAGE_SIZE;
1568 pPageDst++;
1569 }
1570
1571 /* Finish pending and cleanup. */
1572 if (cPendingPages)
1573 {
1574 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
1575 AssertLogRelRCReturn(rc, rc);
1576 }
1577 GMMR3FreePagesCleanup(pReq);
1578
1579 return rc;
1580}
1581
1582
1583/**
1584 * PGMR3PhysRegisterRam worker that initializes and links a RAM range.
1585 *
1586 * In NEM mode, this will allocate the pages backing the RAM range and this may
1587 * fail. NEM registration may also fail. (In regular HM mode it won't fail.)
1588 *
1589 * @returns VBox status code.
1590 * @param pVM The cross context VM structure.
1591 * @param pNew The new RAM range.
1592 * @param GCPhys The address of the RAM range.
1593 * @param GCPhysLast The last address of the RAM range.
1594 * @param R0PtrNew Ditto for R0.
1595 * @param fFlags PGM_RAM_RANGE_FLAGS_FLOATING or zero.
1596 * @param pszDesc The description.
1597 * @param pPrev The previous RAM range (for linking).
1598 */
1599static int pgmR3PhysInitAndLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, RTGCPHYS GCPhys, RTGCPHYS GCPhysLast,
1600 RTR0PTR R0PtrNew, uint32_t fFlags, const char *pszDesc, PPGMRAMRANGE pPrev)
1601{
1602 /*
1603 * Initialize the range.
1604 */
1605 pNew->pSelfR0 = R0PtrNew;
1606 pNew->GCPhys = GCPhys;
1607 pNew->GCPhysLast = GCPhysLast;
1608 pNew->cb = GCPhysLast - GCPhys + 1;
1609 pNew->pszDesc = pszDesc;
1610 pNew->fFlags = fFlags;
1611 pNew->uNemRange = UINT32_MAX;
1612 pNew->pvR3 = NULL;
1613 pNew->paLSPages = NULL;
1614
1615 uint32_t const cPages = pNew->cb >> GUEST_PAGE_SHIFT;
1616#ifdef VBOX_WITH_PGM_NEM_MODE
1617 if (!pVM->pgm.s.fNemMode)
1618#endif
1619 {
1620 RTGCPHYS iPage = cPages;
1621 while (iPage-- > 0)
1622 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_RAM);
1623
1624 /* Update the page count stats. */
1625 pVM->pgm.s.cZeroPages += cPages;
1626 pVM->pgm.s.cAllPages += cPages;
1627 }
1628#ifdef VBOX_WITH_PGM_NEM_MODE
1629 else
1630 {
1631 int rc = SUPR3PageAlloc(RT_ALIGN_Z(pNew->cb, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT,
1632 pVM->pgm.s.fUseLargePages ? SUP_PAGE_ALLOC_F_LARGE_PAGES : 0, &pNew->pvR3);
1633 if (RT_FAILURE(rc))
1634 return rc;
1635
1636 RTGCPHYS iPage = cPages;
1637 while (iPage-- > 0)
1638 PGM_PAGE_INIT(&pNew->aPages[iPage], UINT64_C(0x0000fffffffff000), NIL_GMM_PAGEID,
1639 PGMPAGETYPE_RAM, PGM_PAGE_STATE_ALLOCATED);
1640
1641 /* Update the page count stats. */
1642 pVM->pgm.s.cPrivatePages += cPages;
1643 pVM->pgm.s.cAllPages += cPages;
1644 }
1645#endif
1646
1647 /*
1648 * Link it.
1649 */
1650 pgmR3PhysLinkRamRange(pVM, pNew, pPrev);
1651
1652#ifdef VBOX_WITH_NATIVE_NEM
1653 /*
1654 * Notify NEM now that it has been linked.
1655 */
1656 if (VM_IS_NEM_ENABLED(pVM))
1657 {
1658 uint8_t u2State = UINT8_MAX;
1659 int rc = NEMR3NotifyPhysRamRegister(pVM, GCPhys, pNew->cb, pNew->pvR3, &u2State, &pNew->uNemRange);
1660 if (RT_SUCCESS(rc))
1661 {
1662 if (u2State != UINT8_MAX)
1663 pgmPhysSetNemStateForPages(&pNew->aPages[0], cPages, u2State);
1664 }
1665 else
1666 pgmR3PhysUnlinkRamRange2(pVM, pNew, pPrev);
1667 return rc;
1668 }
1669#endif
1670 return VINF_SUCCESS;
1671}
1672
1673
1674/**
1675 * PGMR3PhysRegisterRam worker that registers a high chunk.
1676 *
1677 * @returns VBox status code.
1678 * @param pVM The cross context VM structure.
1679 * @param GCPhys The address of the RAM.
1680 * @param cRamPages The number of RAM pages to register.
1681 * @param iChunk The chunk number.
1682 * @param pszDesc The RAM range description.
1683 * @param ppPrev Previous RAM range pointer. In/Out.
1684 */
1685static int pgmR3PhysRegisterHighRamChunk(PVM pVM, RTGCPHYS GCPhys, uint32_t cRamPages, uint32_t iChunk,
1686 const char *pszDesc, PPGMRAMRANGE *ppPrev)
1687{
1688 const char *pszDescChunk = iChunk == 0
1689 ? pszDesc
1690 : MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s (#%u)", pszDesc, iChunk + 1);
1691 AssertReturn(pszDescChunk, VERR_NO_MEMORY);
1692
1693 /*
1694 * Allocate memory for the new chunk.
1695 */
1696 size_t const cChunkPages = RT_ALIGN_Z(RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cRamPages]), HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
1697 PSUPPAGE paChunkPages = (PSUPPAGE)RTMemTmpAllocZ(sizeof(SUPPAGE) * cChunkPages);
1698 AssertReturn(paChunkPages, VERR_NO_TMP_MEMORY);
1699 RTR0PTR R0PtrChunk = NIL_RTR0PTR;
1700 void *pvChunk = NULL;
1701 int rc = SUPR3PageAllocEx(cChunkPages, 0 /*fFlags*/, &pvChunk, &R0PtrChunk, paChunkPages);
1702 if (RT_SUCCESS(rc))
1703 {
1704 Assert(R0PtrChunk != NIL_RTR0PTR || PGM_IS_IN_NEM_MODE(pVM));
1705 memset(pvChunk, 0, cChunkPages << HOST_PAGE_SHIFT);
1706
1707 PPGMRAMRANGE pNew = (PPGMRAMRANGE)pvChunk;
1708
1709 /*
1710 * Ok, init and link the range.
1711 */
1712 rc = pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhys + ((RTGCPHYS)cRamPages << GUEST_PAGE_SHIFT) - 1,
1713 R0PtrChunk, PGM_RAM_RANGE_FLAGS_FLOATING, pszDescChunk, *ppPrev);
1714 if (RT_SUCCESS(rc))
1715 *ppPrev = pNew;
1716
1717 if (RT_FAILURE(rc))
1718 SUPR3PageFreeEx(pvChunk, cChunkPages);
1719 }
1720
1721 RTMemTmpFree(paChunkPages);
1722 return rc;
1723}
1724
1725
1726/**
1727 * Sets up a range RAM.
1728 *
1729 * This will check for conflicting registrations, make a resource
1730 * reservation for the memory (with GMM), and setup the per-page
1731 * tracking structures (PGMPAGE).
1732 *
1733 * @returns VBox status code.
1734 * @param pVM The cross context VM structure.
1735 * @param GCPhys The physical address of the RAM.
1736 * @param cb The size of the RAM.
1737 * @param pszDesc The description - not copied, so, don't free or change it.
1738 */
1739VMMR3DECL(int) PGMR3PhysRegisterRam(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, const char *pszDesc)
1740{
1741 /*
1742 * Validate input.
1743 */
1744 Log(("PGMR3PhysRegisterRam: GCPhys=%RGp cb=%RGp pszDesc=%s\n", GCPhys, cb, pszDesc));
1745 AssertReturn(RT_ALIGN_T(GCPhys, GUEST_PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
1746 AssertReturn(RT_ALIGN_T(cb, GUEST_PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
1747 AssertReturn(cb > 0, VERR_INVALID_PARAMETER);
1748 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
1749 AssertMsgReturn(GCPhysLast > GCPhys, ("The range wraps! GCPhys=%RGp cb=%RGp\n", GCPhys, cb), VERR_INVALID_PARAMETER);
1750 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
1751 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1752
1753 PGM_LOCK_VOID(pVM);
1754
1755 /*
1756 * Find range location and check for conflicts.
1757 */
1758 PPGMRAMRANGE pPrev = NULL;
1759 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
1760 while (pRam && GCPhysLast >= pRam->GCPhys)
1761 {
1762 AssertLogRelMsgReturnStmt( GCPhysLast < pRam->GCPhys
1763 || GCPhys > pRam->GCPhysLast,
1764 ("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
1765 GCPhys, GCPhysLast, pszDesc, pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
1766 PGM_UNLOCK(pVM), VERR_PGM_RAM_CONFLICT);
1767
1768 /* next */
1769 pPrev = pRam;
1770 pRam = pRam->pNextR3;
1771 }
1772
1773 /*
1774 * Register it with GMM (the API bitches).
1775 */
1776 const RTGCPHYS cPages = cb >> GUEST_PAGE_SHIFT;
1777 int rc = MMR3IncreaseBaseReservation(pVM, cPages);
1778 if (RT_FAILURE(rc))
1779 {
1780 PGM_UNLOCK(pVM);
1781 return rc;
1782 }
1783
1784 if ( GCPhys >= _4G
1785 && cPages > 256)
1786 {
1787 /*
1788 * The PGMRAMRANGE structures for the high memory can get very big.
1789 * There used to be some limitations on SUPR3PageAllocEx allocation
1790 * sizes, so traditionally we limited this to 16MB chunks. These days
1791 * we do ~64 MB chunks each covering 16GB of guest RAM, making sure
1792 * each range is a multiple of 1GB to enable eager hosts to use 1GB
1793 * pages in NEM mode.
1794 *
1795 * See also pgmR3PhysMmio2CalcChunkCount.
1796 */
1797 uint32_t const cPagesPerChunk = _4M;
1798 Assert(RT_ALIGN_32(cPagesPerChunk, X86_PD_PAE_SHIFT - X86_PAGE_SHIFT)); /* NEM large page requirement: 1GB pages. */
1799
1800 RTGCPHYS cPagesLeft = cPages;
1801 RTGCPHYS GCPhysChunk = GCPhys;
1802 uint32_t iChunk = 0;
1803 while (cPagesLeft > 0)
1804 {
1805 uint32_t cPagesInChunk = cPagesLeft;
1806 if (cPagesInChunk > cPagesPerChunk)
1807 cPagesInChunk = cPagesPerChunk;
1808
1809 rc = pgmR3PhysRegisterHighRamChunk(pVM, GCPhysChunk, cPagesInChunk, iChunk, pszDesc, &pPrev);
1810 AssertRCReturn(rc, rc);
1811
1812 /* advance */
1813 GCPhysChunk += (RTGCPHYS)cPagesInChunk << GUEST_PAGE_SHIFT;
1814 cPagesLeft -= cPagesInChunk;
1815 iChunk++;
1816 }
1817 }
1818 else
1819 {
1820 /*
1821 * Allocate, initialize and link the new RAM range.
1822 */
1823 const size_t cbRamRange = RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPages]);
1824 PPGMRAMRANGE pNew = NULL;
1825 RTR0PTR pNewR0 = NIL_RTR0PTR;
1826 rc = SUPR3PageAllocEx(RT_ALIGN_Z(cbRamRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT, 0 /*fFlags*/,
1827 (void **)&pNew, &pNewR0, NULL /*paPages*/);
1828 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc cbRamRange=%zu\n", rc, cbRamRange), rc);
1829
1830 rc = pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhysLast, pNewR0, 0 /*fFlags*/, pszDesc, pPrev);
1831 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc cbRamRange=%zu\n", rc, cbRamRange), rc);
1832 }
1833 pgmPhysInvalidatePageMapTLB(pVM);
1834
1835 PGM_UNLOCK(pVM);
1836 return rc;
1837}
1838
1839
1840/**
1841 * Worker called by PGMR3InitFinalize if we're configured to pre-allocate RAM.
1842 *
1843 * We do this late in the init process so that all the ROM and MMIO ranges have
1844 * been registered already and we don't go wasting memory on them.
1845 *
1846 * @returns VBox status code.
1847 *
1848 * @param pVM The cross context VM structure.
1849 */
1850int pgmR3PhysRamPreAllocate(PVM pVM)
1851{
1852 Assert(pVM->pgm.s.fRamPreAlloc);
1853 Log(("pgmR3PhysRamPreAllocate: enter\n"));
1854#ifdef VBOX_WITH_PGM_NEM_MODE
1855 AssertLogRelReturn(!pVM->pgm.s.fNemMode, VERR_PGM_NOT_SUPPORTED_FOR_NEM_MODE);
1856#endif
1857
1858 /*
1859 * Walk the RAM ranges and allocate all RAM pages, halt at
1860 * the first allocation error.
1861 */
1862 uint64_t cPages = 0;
1863 uint64_t NanoTS = RTTimeNanoTS();
1864 PGM_LOCK_VOID(pVM);
1865 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1866 {
1867 PPGMPAGE pPage = &pRam->aPages[0];
1868 RTGCPHYS GCPhys = pRam->GCPhys;
1869 uint32_t cLeft = pRam->cb >> GUEST_PAGE_SHIFT;
1870 while (cLeft-- > 0)
1871 {
1872 if (PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM)
1873 {
1874 switch (PGM_PAGE_GET_STATE(pPage))
1875 {
1876 case PGM_PAGE_STATE_ZERO:
1877 {
1878 int rc = pgmPhysAllocPage(pVM, pPage, GCPhys);
1879 if (RT_FAILURE(rc))
1880 {
1881 LogRel(("PGM: RAM Pre-allocation failed at %RGp (in %s) with rc=%Rrc\n", GCPhys, pRam->pszDesc, rc));
1882 PGM_UNLOCK(pVM);
1883 return rc;
1884 }
1885 cPages++;
1886 break;
1887 }
1888
1889 case PGM_PAGE_STATE_BALLOONED:
1890 case PGM_PAGE_STATE_ALLOCATED:
1891 case PGM_PAGE_STATE_WRITE_MONITORED:
1892 case PGM_PAGE_STATE_SHARED:
1893 /* nothing to do here. */
1894 break;
1895 }
1896 }
1897
1898 /* next */
1899 pPage++;
1900 GCPhys += GUEST_PAGE_SIZE;
1901 }
1902 }
1903 PGM_UNLOCK(pVM);
1904 NanoTS = RTTimeNanoTS() - NanoTS;
1905
1906 LogRel(("PGM: Pre-allocated %llu pages in %llu ms\n", cPages, NanoTS / 1000000));
1907 Log(("pgmR3PhysRamPreAllocate: returns VINF_SUCCESS\n"));
1908 return VINF_SUCCESS;
1909}
1910
1911
1912/**
1913 * Checks shared page checksums.
1914 *
1915 * @param pVM The cross context VM structure.
1916 */
1917void pgmR3PhysAssertSharedPageChecksums(PVM pVM)
1918{
1919#ifdef VBOX_STRICT
1920 PGM_LOCK_VOID(pVM);
1921
1922 if (pVM->pgm.s.cSharedPages > 0)
1923 {
1924 /*
1925 * Walk the ram ranges.
1926 */
1927 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1928 {
1929 uint32_t iPage = pRam->cb >> GUEST_PAGE_SHIFT;
1930 AssertMsg(((RTGCPHYS)iPage << GUEST_PAGE_SHIFT) == pRam->cb,
1931 ("%RGp %RGp\n", (RTGCPHYS)iPage << GUEST_PAGE_SHIFT, pRam->cb));
1932
1933 while (iPage-- > 0)
1934 {
1935 PPGMPAGE pPage = &pRam->aPages[iPage];
1936 if (PGM_PAGE_IS_SHARED(pPage))
1937 {
1938 uint32_t u32Checksum = pPage->s.u2Unused0/* | ((uint32_t)pPage->s.u2Unused1 << 8)*/;
1939 if (!u32Checksum)
1940 {
1941 RTGCPHYS GCPhysPage = pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT);
1942 void const *pvPage;
1943 int rc = pgmPhysPageMapReadOnly(pVM, pPage, GCPhysPage, &pvPage);
1944 if (RT_SUCCESS(rc))
1945 {
1946 uint32_t u32Checksum2 = RTCrc32(pvPage, GUEST_PAGE_SIZE);
1947# if 0
1948 AssertMsg((u32Checksum2 & /*UINT32_C(0x00000303)*/ 0x3) == u32Checksum, ("GCPhysPage=%RGp\n", GCPhysPage));
1949# else
1950 if ((u32Checksum2 & /*UINT32_C(0x00000303)*/ 0x3) == u32Checksum)
1951 LogFlow(("shpg %#x @ %RGp %#x [OK]\n", PGM_PAGE_GET_PAGEID(pPage), GCPhysPage, u32Checksum2));
1952 else
1953 AssertMsgFailed(("shpg %#x @ %RGp %#x\n", PGM_PAGE_GET_PAGEID(pPage), GCPhysPage, u32Checksum2));
1954# endif
1955 }
1956 else
1957 AssertRC(rc);
1958 }
1959 }
1960
1961 } /* for each page */
1962
1963 } /* for each ram range */
1964 }
1965
1966 PGM_UNLOCK(pVM);
1967#endif /* VBOX_STRICT */
1968 NOREF(pVM);
1969}
1970
1971
1972/**
1973 * Resets the physical memory state.
1974 *
1975 * ASSUMES that the caller owns the PGM lock.
1976 *
1977 * @returns VBox status code.
1978 * @param pVM The cross context VM structure.
1979 */
1980int pgmR3PhysRamReset(PVM pVM)
1981{
1982 PGM_LOCK_ASSERT_OWNER(pVM);
1983
1984 /* Reset the memory balloon. */
1985 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
1986 AssertRC(rc);
1987
1988#ifdef VBOX_WITH_PAGE_SHARING
1989 /* Clear all registered shared modules. */
1990 pgmR3PhysAssertSharedPageChecksums(pVM);
1991 rc = GMMR3ResetSharedModules(pVM);
1992 AssertRC(rc);
1993#endif
1994 /* Reset counters. */
1995 pVM->pgm.s.cReusedSharedPages = 0;
1996 pVM->pgm.s.cBalloonedPages = 0;
1997
1998 return VINF_SUCCESS;
1999}
2000
2001
2002/**
2003 * Resets (zeros) the RAM after all devices and components have been reset.
2004 *
2005 * ASSUMES that the caller owns the PGM lock.
2006 *
2007 * @returns VBox status code.
2008 * @param pVM The cross context VM structure.
2009 */
2010int pgmR3PhysRamZeroAll(PVM pVM)
2011{
2012 PGM_LOCK_ASSERT_OWNER(pVM);
2013
2014 /*
2015 * We batch up pages that should be freed instead of calling GMM for
2016 * each and every one of them.
2017 */
2018 uint32_t cPendingPages = 0;
2019 PGMMFREEPAGESREQ pReq;
2020 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2021 AssertLogRelRCReturn(rc, rc);
2022
2023 /*
2024 * Walk the ram ranges.
2025 */
2026 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
2027 {
2028 uint32_t iPage = pRam->cb >> GUEST_PAGE_SHIFT;
2029 AssertMsg(((RTGCPHYS)iPage << GUEST_PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << GUEST_PAGE_SHIFT, pRam->cb));
2030
2031 if ( !pVM->pgm.s.fRamPreAlloc
2032#ifdef VBOX_WITH_PGM_NEM_MODE
2033 && !pVM->pgm.s.fNemMode
2034#endif
2035 && pVM->pgm.s.fZeroRamPagesOnReset)
2036 {
2037 /* Replace all RAM pages by ZERO pages. */
2038 while (iPage-- > 0)
2039 {
2040 PPGMPAGE pPage = &pRam->aPages[iPage];
2041 switch (PGM_PAGE_GET_TYPE(pPage))
2042 {
2043 case PGMPAGETYPE_RAM:
2044 /* Do not replace pages part of a 2 MB continuous range
2045 with zero pages, but zero them instead. */
2046 if ( PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE
2047 || PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE_DISABLED)
2048 {
2049 void *pvPage;
2050 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), &pvPage);
2051 AssertLogRelRCReturn(rc, rc);
2052 RT_BZERO(pvPage, GUEST_PAGE_SIZE);
2053 }
2054 else if (PGM_PAGE_IS_BALLOONED(pPage))
2055 {
2056 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
2057 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
2058 }
2059 else if (!PGM_PAGE_IS_ZERO(pPage))
2060 {
2061 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage,
2062 pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), PGMPAGETYPE_RAM);
2063 AssertLogRelRCReturn(rc, rc);
2064 }
2065 break;
2066
2067 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2068 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO: /** @todo perhaps leave the special page alone? I don't think VT-x copes with this code. */
2069 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT),
2070 pRam, true /*fDoAccounting*/);
2071 break;
2072
2073 case PGMPAGETYPE_MMIO2:
2074 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
2075 case PGMPAGETYPE_ROM:
2076 case PGMPAGETYPE_MMIO:
2077 break;
2078 default:
2079 AssertFailed();
2080 }
2081 } /* for each page */
2082 }
2083 else
2084 {
2085 /* Zero the memory. */
2086 while (iPage-- > 0)
2087 {
2088 PPGMPAGE pPage = &pRam->aPages[iPage];
2089 switch (PGM_PAGE_GET_TYPE(pPage))
2090 {
2091 case PGMPAGETYPE_RAM:
2092 switch (PGM_PAGE_GET_STATE(pPage))
2093 {
2094 case PGM_PAGE_STATE_ZERO:
2095 break;
2096
2097 case PGM_PAGE_STATE_BALLOONED:
2098 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
2099 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
2100 break;
2101
2102 case PGM_PAGE_STATE_SHARED:
2103 case PGM_PAGE_STATE_WRITE_MONITORED:
2104 rc = pgmPhysPageMakeWritable(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT));
2105 AssertLogRelRCReturn(rc, rc);
2106 RT_FALL_THRU();
2107
2108 case PGM_PAGE_STATE_ALLOCATED:
2109 if (pVM->pgm.s.fZeroRamPagesOnReset)
2110 {
2111 void *pvPage;
2112 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), &pvPage);
2113 AssertLogRelRCReturn(rc, rc);
2114 RT_BZERO(pvPage, GUEST_PAGE_SIZE);
2115 }
2116 break;
2117 }
2118 break;
2119
2120 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2121 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO: /** @todo perhaps leave the special page alone? I don't think VT-x copes with this code. */
2122 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT),
2123 pRam, true /*fDoAccounting*/);
2124 break;
2125
2126 case PGMPAGETYPE_MMIO2:
2127 case PGMPAGETYPE_ROM_SHADOW:
2128 case PGMPAGETYPE_ROM:
2129 case PGMPAGETYPE_MMIO:
2130 break;
2131 default:
2132 AssertFailed();
2133
2134 }
2135 } /* for each page */
2136 }
2137
2138 }
2139
2140 /*
2141 * Finish off any pages pending freeing.
2142 */
2143 if (cPendingPages)
2144 {
2145 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2146 AssertLogRelRCReturn(rc, rc);
2147 }
2148 GMMR3FreePagesCleanup(pReq);
2149 return VINF_SUCCESS;
2150}
2151
2152
2153/**
2154 * Frees all RAM during VM termination
2155 *
2156 * ASSUMES that the caller owns the PGM lock.
2157 *
2158 * @returns VBox status code.
2159 * @param pVM The cross context VM structure.
2160 */
2161int pgmR3PhysRamTerm(PVM pVM)
2162{
2163 PGM_LOCK_ASSERT_OWNER(pVM);
2164
2165 /* Reset the memory balloon. */
2166 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
2167 AssertRC(rc);
2168
2169#ifdef VBOX_WITH_PAGE_SHARING
2170 /*
2171 * Clear all registered shared modules.
2172 */
2173 pgmR3PhysAssertSharedPageChecksums(pVM);
2174 rc = GMMR3ResetSharedModules(pVM);
2175 AssertRC(rc);
2176
2177 /*
2178 * Flush the handy pages updates to make sure no shared pages are hiding
2179 * in there. (Not unlikely if the VM shuts down, apparently.)
2180 */
2181# ifdef VBOX_WITH_PGM_NEM_MODE
2182 if (!pVM->pgm.s.fNemMode)
2183# endif
2184 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_FLUSH_HANDY_PAGES, 0, NULL);
2185#endif
2186
2187 /*
2188 * We batch up pages that should be freed instead of calling GMM for
2189 * each and every one of them.
2190 */
2191 uint32_t cPendingPages = 0;
2192 PGMMFREEPAGESREQ pReq;
2193 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2194 AssertLogRelRCReturn(rc, rc);
2195
2196 /*
2197 * Walk the ram ranges.
2198 */
2199 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
2200 {
2201 uint32_t iPage = pRam->cb >> GUEST_PAGE_SHIFT;
2202 AssertMsg(((RTGCPHYS)iPage << GUEST_PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << GUEST_PAGE_SHIFT, pRam->cb));
2203
2204 while (iPage-- > 0)
2205 {
2206 PPGMPAGE pPage = &pRam->aPages[iPage];
2207 switch (PGM_PAGE_GET_TYPE(pPage))
2208 {
2209 case PGMPAGETYPE_RAM:
2210 /* Free all shared pages. Private pages are automatically freed during GMM VM cleanup. */
2211 /** @todo change this to explicitly free private pages here. */
2212 if (PGM_PAGE_IS_SHARED(pPage))
2213 {
2214 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage,
2215 pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), PGMPAGETYPE_RAM);
2216 AssertLogRelRCReturn(rc, rc);
2217 }
2218 break;
2219
2220 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2221 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO:
2222 case PGMPAGETYPE_MMIO2:
2223 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
2224 case PGMPAGETYPE_ROM:
2225 case PGMPAGETYPE_MMIO:
2226 break;
2227 default:
2228 AssertFailed();
2229 }
2230 } /* for each page */
2231 }
2232
2233 /*
2234 * Finish off any pages pending freeing.
2235 */
2236 if (cPendingPages)
2237 {
2238 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2239 AssertLogRelRCReturn(rc, rc);
2240 }
2241 GMMR3FreePagesCleanup(pReq);
2242 return VINF_SUCCESS;
2243}
2244
2245
2246
2247/*********************************************************************************************************************************
2248* MMIO *
2249*********************************************************************************************************************************/
2250
2251/**
2252 * This is the interface IOM is using to register an MMIO region.
2253 *
2254 * It will check for conflicts and ensure that a RAM range structure
2255 * is present before calling the PGMR3HandlerPhysicalRegister API to
2256 * register the callbacks.
2257 *
2258 * @returns VBox status code.
2259 *
2260 * @param pVM The cross context VM structure.
2261 * @param GCPhys The start of the MMIO region.
2262 * @param cb The size of the MMIO region.
2263 * @param hType The physical access handler type registration.
2264 * @param uUser The user argument.
2265 * @param pszDesc The description of the MMIO region.
2266 */
2267VMMR3DECL(int) PGMR3PhysMMIORegister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMPHYSHANDLERTYPE hType,
2268 uint64_t uUser, const char *pszDesc)
2269{
2270 /*
2271 * Assert on some assumption.
2272 */
2273 VM_ASSERT_EMT(pVM);
2274 AssertReturn(!(cb & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2275 AssertReturn(!(GCPhys & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2276 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
2277 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
2278#ifdef VBOX_STRICT
2279 PCPGMPHYSHANDLERTYPEINT pType = pgmHandlerPhysicalTypeHandleToPtr(pVM, hType);
2280 Assert(pType);
2281 Assert(pType->enmKind == PGMPHYSHANDLERKIND_MMIO);
2282#endif
2283
2284 int rc = PGM_LOCK(pVM);
2285 AssertRCReturn(rc, rc);
2286
2287 /*
2288 * Make sure there's a RAM range structure for the region.
2289 */
2290 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2291 bool fRamExists = false;
2292 PPGMRAMRANGE pRamPrev = NULL;
2293 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
2294 while (pRam && GCPhysLast >= pRam->GCPhys)
2295 {
2296 if ( GCPhysLast >= pRam->GCPhys
2297 && GCPhys <= pRam->GCPhysLast)
2298 {
2299 /* Simplification: all within the same range. */
2300 AssertLogRelMsgReturnStmt( GCPhys >= pRam->GCPhys
2301 && GCPhysLast <= pRam->GCPhysLast,
2302 ("%RGp-%RGp (MMIO/%s) falls partly outside %RGp-%RGp (%s)\n",
2303 GCPhys, GCPhysLast, pszDesc,
2304 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
2305 PGM_UNLOCK(pVM),
2306 VERR_PGM_RAM_CONFLICT);
2307
2308 /* Check that it's all RAM or MMIO pages. */
2309 PCPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
2310 uint32_t cLeft = cb >> GUEST_PAGE_SHIFT;
2311 while (cLeft-- > 0)
2312 {
2313 AssertLogRelMsgReturnStmt( PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM
2314 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO,
2315 ("%RGp-%RGp (MMIO/%s): %RGp is not a RAM or MMIO page - type=%d desc=%s\n",
2316 GCPhys, GCPhysLast, pszDesc, pRam->GCPhys, PGM_PAGE_GET_TYPE(pPage), pRam->pszDesc),
2317 PGM_UNLOCK(pVM),
2318 VERR_PGM_RAM_CONFLICT);
2319 pPage++;
2320 }
2321
2322 /* Looks good. */
2323 fRamExists = true;
2324 break;
2325 }
2326
2327 /* next */
2328 pRamPrev = pRam;
2329 pRam = pRam->pNextR3;
2330 }
2331 PPGMRAMRANGE pNew;
2332 if (fRamExists)
2333 {
2334 pNew = NULL;
2335
2336 /*
2337 * Make all the pages in the range MMIO/ZERO pages, freeing any
2338 * RAM pages currently mapped here. This might not be 100% correct
2339 * for PCI memory, but we're doing the same thing for MMIO2 pages.
2340 */
2341 rc = pgmR3PhysFreePageRange(pVM, pRam, GCPhys, GCPhysLast, NULL);
2342 AssertRCReturnStmt(rc, PGM_UNLOCK(pVM), rc);
2343
2344 /* Force a PGM pool flush as guest ram references have been changed. */
2345 /** @todo not entirely SMP safe; assuming for now the guest takes
2346 * care of this internally (not touch mapped mmio while changing the
2347 * mapping). */
2348 PVMCPU pVCpu = VMMGetCpu(pVM);
2349 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2350 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2351 }
2352 else
2353 {
2354 /*
2355 * No RAM range, insert an ad hoc one.
2356 *
2357 * Note that we don't have to tell REM about this range because
2358 * PGMHandlerPhysicalRegisterEx will do that for us.
2359 */
2360 Log(("PGMR3PhysMMIORegister: Adding ad hoc MMIO range for %RGp-%RGp %s\n", GCPhys, GCPhysLast, pszDesc));
2361
2362 /* Alloc. */
2363 const uint32_t cPages = cb >> GUEST_PAGE_SHIFT;
2364 const size_t cbRamRange = RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPages]);
2365 const size_t cRangePages = RT_ALIGN_Z(cbRamRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
2366 RTR0PTR pNewR0 = NIL_RTR0PTR;
2367 rc = SUPR3PageAllocEx(cRangePages, 0 /*fFlags*/, (void **)&pNew, &pNewR0, NULL /*paPages*/);
2368 AssertLogRelMsgRCReturnStmt(rc, ("cbRamRange=%zu\n", cbRamRange), PGM_UNLOCK(pVM), rc);
2369
2370#ifdef VBOX_WITH_NATIVE_NEM
2371 /* Notify NEM. */
2372 uint8_t u2State = 0; /* (must have valid state as there can't be anything to preserve) */
2373 if (VM_IS_NEM_ENABLED(pVM))
2374 {
2375 rc = NEMR3NotifyPhysMmioExMapEarly(pVM, GCPhys, cPages << GUEST_PAGE_SHIFT, 0 /*fFlags*/, NULL, NULL,
2376 &u2State, &pNew->uNemRange);
2377 AssertLogRelRCReturnStmt(rc, SUPR3PageFreeEx(pNew, cRangePages), rc);
2378 }
2379#endif
2380
2381 /* Initialize the range. */
2382 pNew->pSelfR0 = pNewR0;
2383 pNew->GCPhys = GCPhys;
2384 pNew->GCPhysLast = GCPhysLast;
2385 pNew->cb = cb;
2386 pNew->pszDesc = pszDesc;
2387 pNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO;
2388 pNew->pvR3 = NULL;
2389 pNew->paLSPages = NULL;
2390
2391 uint32_t iPage = cPages;
2392 while (iPage-- > 0)
2393 {
2394 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_MMIO);
2395#ifdef VBOX_WITH_NATIVE_NEM
2396 PGM_PAGE_SET_NEM_STATE(&pNew->aPages[iPage], u2State);
2397#endif
2398 }
2399 Assert(PGM_PAGE_GET_TYPE(&pNew->aPages[0]) == PGMPAGETYPE_MMIO);
2400
2401 /* update the page count stats. */
2402 pVM->pgm.s.cPureMmioPages += cPages;
2403 pVM->pgm.s.cAllPages += cPages;
2404
2405 /* link it */
2406 pgmR3PhysLinkRamRange(pVM, pNew, pRamPrev);
2407 }
2408
2409 /*
2410 * Register the access handler.
2411 */
2412 rc = PGMHandlerPhysicalRegister(pVM, GCPhys, GCPhysLast, hType, uUser, pszDesc);
2413 if (RT_SUCCESS(rc))
2414 {
2415#ifdef VBOX_WITH_NATIVE_NEM
2416 /* Late NEM notification. */
2417 if (VM_IS_NEM_ENABLED(pVM))
2418 {
2419 uint32_t const fNemNotify = (fRamExists ? NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE : 0);
2420 rc = NEMR3NotifyPhysMmioExMapLate(pVM, GCPhys, GCPhysLast - GCPhys + 1, fNemNotify,
2421 fRamExists ? (uint8_t *)pRam->pvR3 + (uintptr_t)(GCPhys - pRam->GCPhys) : NULL,
2422 NULL, !fRamExists ? &pRam->uNemRange : NULL);
2423 AssertLogRelRCReturn(rc, rc);
2424 }
2425#endif
2426 }
2427 /** @todo the phys handler failure handling isn't complete, esp. wrt NEM. */
2428 else if (!fRamExists)
2429 {
2430 pVM->pgm.s.cPureMmioPages -= cb >> GUEST_PAGE_SHIFT;
2431 pVM->pgm.s.cAllPages -= cb >> GUEST_PAGE_SHIFT;
2432
2433 /* remove the ad hoc range. */
2434 pgmR3PhysUnlinkRamRange2(pVM, pNew, pRamPrev);
2435 pNew->cb = pNew->GCPhys = pNew->GCPhysLast = NIL_RTGCPHYS;
2436 SUPR3PageFreeEx(pRam, RT_ALIGN_Z(RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cb >> GUEST_PAGE_SHIFT]),
2437 HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT);
2438 }
2439 pgmPhysInvalidatePageMapTLB(pVM);
2440
2441 PGM_UNLOCK(pVM);
2442 return rc;
2443}
2444
2445
2446/**
2447 * This is the interface IOM is using to register an MMIO region.
2448 *
2449 * It will take care of calling PGMHandlerPhysicalDeregister and clean up
2450 * any ad hoc PGMRAMRANGE left behind.
2451 *
2452 * @returns VBox status code.
2453 * @param pVM The cross context VM structure.
2454 * @param GCPhys The start of the MMIO region.
2455 * @param cb The size of the MMIO region.
2456 */
2457VMMR3DECL(int) PGMR3PhysMMIODeregister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb)
2458{
2459 VM_ASSERT_EMT(pVM);
2460
2461 int rc = PGM_LOCK(pVM);
2462 AssertRCReturn(rc, rc);
2463
2464 /*
2465 * First deregister the handler, then check if we should remove the ram range.
2466 */
2467 rc = PGMHandlerPhysicalDeregister(pVM, GCPhys);
2468 if (RT_SUCCESS(rc))
2469 {
2470 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2471 PPGMRAMRANGE pRamPrev = NULL;
2472 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
2473 while (pRam && GCPhysLast >= pRam->GCPhys)
2474 {
2475 /** @todo We're being a bit too careful here. rewrite. */
2476 if ( GCPhysLast == pRam->GCPhysLast
2477 && GCPhys == pRam->GCPhys)
2478 {
2479 Assert(pRam->cb == cb);
2480
2481 /*
2482 * See if all the pages are dead MMIO pages.
2483 */
2484 uint32_t const cGuestPages = cb >> GUEST_PAGE_SHIFT;
2485 bool fAllMMIO = true;
2486 uint32_t iPage = 0;
2487 uint32_t cLeft = cGuestPages;
2488 while (cLeft-- > 0)
2489 {
2490 PPGMPAGE pPage = &pRam->aPages[iPage];
2491 if ( !PGM_PAGE_IS_MMIO_OR_ALIAS(pPage)
2492 /*|| not-out-of-action later */)
2493 {
2494 fAllMMIO = false;
2495 AssertMsgFailed(("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), pPage));
2496 break;
2497 }
2498 Assert( PGM_PAGE_IS_ZERO(pPage)
2499 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO2_ALIAS_MMIO
2500 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_SPECIAL_ALIAS_MMIO);
2501 pPage++;
2502 }
2503 if (fAllMMIO)
2504 {
2505 /*
2506 * Ad-hoc range, unlink and free it.
2507 */
2508 Log(("PGMR3PhysMMIODeregister: Freeing ad hoc MMIO range for %RGp-%RGp %s\n",
2509 GCPhys, GCPhysLast, pRam->pszDesc));
2510 /** @todo check the ad-hoc flags? */
2511
2512#ifdef VBOX_WITH_NATIVE_NEM
2513 if (VM_IS_NEM_ENABLED(pVM)) /* Notify REM before we unlink the range. */
2514 {
2515 rc = NEMR3NotifyPhysMmioExUnmap(pVM, GCPhys, GCPhysLast - GCPhys + 1, 0 /*fFlags*/,
2516 NULL, NULL, NULL, &pRam->uNemRange);
2517 AssertLogRelRCReturn(rc, rc);
2518 }
2519#endif
2520
2521 pVM->pgm.s.cAllPages -= cGuestPages;
2522 pVM->pgm.s.cPureMmioPages -= cGuestPages;
2523
2524 pgmR3PhysUnlinkRamRange2(pVM, pRam, pRamPrev);
2525 const uint32_t cPages = pRam->cb >> GUEST_PAGE_SHIFT;
2526 const size_t cbRamRange = RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPages]);
2527 pRam->cb = pRam->GCPhys = pRam->GCPhysLast = NIL_RTGCPHYS;
2528 SUPR3PageFreeEx(pRam, RT_ALIGN_Z(cbRamRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT);
2529 break;
2530 }
2531 }
2532
2533 /*
2534 * Range match? It will all be within one range (see PGMAllHandler.cpp).
2535 */
2536 if ( GCPhysLast >= pRam->GCPhys
2537 && GCPhys <= pRam->GCPhysLast)
2538 {
2539 Assert(GCPhys >= pRam->GCPhys);
2540 Assert(GCPhysLast <= pRam->GCPhysLast);
2541
2542 /*
2543 * Turn the pages back into RAM pages.
2544 */
2545 uint32_t iPage = (GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT;
2546 uint32_t cLeft = cb >> GUEST_PAGE_SHIFT;
2547 while (cLeft--)
2548 {
2549 PPGMPAGE pPage = &pRam->aPages[iPage];
2550 AssertMsg( (PGM_PAGE_IS_MMIO(pPage) && PGM_PAGE_IS_ZERO(pPage))
2551 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO2_ALIAS_MMIO
2552 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_SPECIAL_ALIAS_MMIO,
2553 ("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), pPage));
2554 if (PGM_PAGE_IS_MMIO_OR_ALIAS(pPage))
2555 PGM_PAGE_SET_TYPE(pVM, pPage, PGMPAGETYPE_RAM);
2556 iPage++;
2557 }
2558
2559#ifdef VBOX_WITH_NATIVE_NEM
2560 /* Notify REM (failure will probably leave things in a non-working state). */
2561 if (VM_IS_NEM_ENABLED(pVM))
2562 {
2563 uint8_t u2State = UINT8_MAX;
2564 rc = NEMR3NotifyPhysMmioExUnmap(pVM, GCPhys, GCPhysLast - GCPhys + 1, NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE,
2565 pRam->pvR3 ? (uint8_t *)pRam->pvR3 + GCPhys - pRam->GCPhys : NULL,
2566 NULL, &u2State, &pRam->uNemRange);
2567 AssertLogRelRCReturn(rc, rc);
2568 if (u2State != UINT8_MAX)
2569 pgmPhysSetNemStateForPages(&pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT],
2570 cb >> GUEST_PAGE_SHIFT, u2State);
2571 }
2572#endif
2573 break;
2574 }
2575
2576 /* next */
2577 pRamPrev = pRam;
2578 pRam = pRam->pNextR3;
2579 }
2580 }
2581
2582 /* Force a PGM pool flush as guest ram references have been changed. */
2583 /** @todo Not entirely SMP safe; assuming for now the guest takes care of
2584 * this internally (not touch mapped mmio while changing the mapping). */
2585 PVMCPU pVCpu = VMMGetCpu(pVM);
2586 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2587 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2588
2589 pgmPhysInvalidatePageMapTLB(pVM);
2590 pgmPhysInvalidRamRangeTlbs(pVM);
2591 PGM_UNLOCK(pVM);
2592 return rc;
2593}
2594
2595
2596
2597/*********************************************************************************************************************************
2598* MMIO2 *
2599*********************************************************************************************************************************/
2600
2601/**
2602 * Locate a MMIO2 range.
2603 *
2604 * @returns Pointer to the MMIO2 range.
2605 * @param pVM The cross context VM structure.
2606 * @param pDevIns The device instance owning the region.
2607 * @param iSubDev The sub-device number.
2608 * @param iRegion The region.
2609 * @param hMmio2 Handle to look up. If NIL, use the @a iSubDev and
2610 * @a iRegion.
2611 */
2612DECLINLINE(PPGMREGMMIO2RANGE) pgmR3PhysMmio2Find(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev,
2613 uint32_t iRegion, PGMMMIO2HANDLE hMmio2)
2614{
2615 if (hMmio2 != NIL_PGMMMIO2HANDLE)
2616 {
2617 if (hMmio2 <= RT_ELEMENTS(pVM->pgm.s.apMmio2RangesR3) && hMmio2 != 0)
2618 {
2619 PPGMREGMMIO2RANGE pCur = pVM->pgm.s.apMmio2RangesR3[hMmio2 - 1];
2620 if (pCur && pCur->pDevInsR3 == pDevIns)
2621 {
2622 Assert(pCur->idMmio2 == hMmio2);
2623 AssertReturn(pCur->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK, NULL);
2624 return pCur;
2625 }
2626 Assert(!pCur);
2627 }
2628 for (PPGMREGMMIO2RANGE pCur = pVM->pgm.s.pRegMmioRangesR3; pCur; pCur = pCur->pNextR3)
2629 if (pCur->idMmio2 == hMmio2)
2630 {
2631 AssertBreak(pCur->pDevInsR3 == pDevIns);
2632 AssertReturn(pCur->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK, NULL);
2633 return pCur;
2634 }
2635 }
2636 else
2637 {
2638 /*
2639 * Search the list. There shouldn't be many entries.
2640 */
2641 /** @todo Optimize this lookup! There may now be many entries and it'll
2642 * become really slow when doing MMR3HyperMapMMIO2 and similar. */
2643 for (PPGMREGMMIO2RANGE pCur = pVM->pgm.s.pRegMmioRangesR3; pCur; pCur = pCur->pNextR3)
2644 if ( pCur->pDevInsR3 == pDevIns
2645 && pCur->iRegion == iRegion
2646 && pCur->iSubDev == iSubDev)
2647 return pCur;
2648 }
2649 return NULL;
2650}
2651
2652
2653/**
2654 * Worker for PGMR3PhysMmio2ControlDirtyPageTracking and PGMR3PhysMmio2Map.
2655 */
2656static int pgmR3PhysMmio2EnableDirtyPageTracing(PVM pVM, PPGMREGMMIO2RANGE pFirstMmio2)
2657{
2658 int rc = VINF_SUCCESS;
2659 for (PPGMREGMMIO2RANGE pCurMmio2 = pFirstMmio2; pCurMmio2; pCurMmio2 = pCurMmio2->pNextR3)
2660 {
2661 Assert(!(pCurMmio2->fFlags & PGMREGMMIO2RANGE_F_IS_TRACKING));
2662 int rc2 = pgmHandlerPhysicalExRegister(pVM, pCurMmio2->pPhysHandlerR3, pCurMmio2->RamRange.GCPhys,
2663 pCurMmio2->RamRange.GCPhysLast);
2664 AssertLogRelMsgRC(rc2, ("%#RGp-%#RGp %s failed -> %Rrc\n", pCurMmio2->RamRange.GCPhys, pCurMmio2->RamRange.GCPhysLast,
2665 pCurMmio2->RamRange.pszDesc, rc2));
2666 if (RT_SUCCESS(rc2))
2667 pCurMmio2->fFlags |= PGMREGMMIO2RANGE_F_IS_TRACKING;
2668 else if (RT_SUCCESS(rc))
2669 rc = rc2;
2670 if (pCurMmio2->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
2671 return rc;
2672 }
2673 AssertFailed();
2674 return rc;
2675}
2676
2677
2678/**
2679 * Worker for PGMR3PhysMmio2ControlDirtyPageTracking and PGMR3PhysMmio2Unmap.
2680 */
2681static int pgmR3PhysMmio2DisableDirtyPageTracing(PVM pVM, PPGMREGMMIO2RANGE pFirstMmio2)
2682{
2683 for (PPGMREGMMIO2RANGE pCurMmio2 = pFirstMmio2; pCurMmio2; pCurMmio2 = pCurMmio2->pNextR3)
2684 {
2685 if (pCurMmio2->fFlags & PGMREGMMIO2RANGE_F_IS_TRACKING)
2686 {
2687 int rc2 = pgmHandlerPhysicalExDeregister(pVM, pCurMmio2->pPhysHandlerR3);
2688 AssertLogRelMsgRC(rc2, ("%#RGp-%#RGp %s failed -> %Rrc\n", pCurMmio2->RamRange.GCPhys, pCurMmio2->RamRange.GCPhysLast,
2689 pCurMmio2->RamRange.pszDesc, rc2));
2690 pCurMmio2->fFlags &= ~PGMREGMMIO2RANGE_F_IS_TRACKING;
2691 }
2692 if (pCurMmio2->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
2693 return VINF_SUCCESS;
2694 }
2695 AssertFailed();
2696 return VINF_SUCCESS;
2697
2698}
2699
2700
2701/**
2702 * Calculates the number of chunks
2703 *
2704 * @returns Number of registration chunk needed.
2705 * @param pVM The cross context VM structure.
2706 * @param cb The size of the MMIO/MMIO2 range.
2707 * @param pcPagesPerChunk Where to return the number of pages tracked by each
2708 * chunk. Optional.
2709 * @param pcbChunk Where to return the guest mapping size for a chunk.
2710 */
2711static uint16_t pgmR3PhysMmio2CalcChunkCount(PVM pVM, RTGCPHYS cb, uint32_t *pcPagesPerChunk, uint32_t *pcbChunk)
2712{
2713 RT_NOREF_PV(pVM); /* without raw mode */
2714
2715 /*
2716 * This is the same calculation as PGMR3PhysRegisterRam does, except we'll be
2717 * needing a few bytes extra the PGMREGMMIO2RANGE structure.
2718 *
2719 * Note! In additions, we've got a 24 bit sub-page range for MMIO2 ranges, leaving
2720 * us with an absolute maximum of 16777215 pages per chunk (close to 64 GB).
2721 */
2722 uint32_t const cPagesPerChunk = _4M;
2723 Assert(RT_ALIGN_32(cPagesPerChunk, X86_PD_PAE_SHIFT - X86_PAGE_SHIFT)); /* NEM large page requirement: 1GB pages. */
2724 uint32_t const cbChunk = RT_UOFFSETOF_DYN(PGMREGMMIO2RANGE, RamRange.aPages[cPagesPerChunk]);
2725 AssertRelease(cPagesPerChunk < _16M);
2726
2727 if (pcbChunk)
2728 *pcbChunk = cbChunk;
2729 if (pcPagesPerChunk)
2730 *pcPagesPerChunk = cPagesPerChunk;
2731
2732 /* Calc the number of chunks we need. */
2733 RTGCPHYS const cGuestPages = cb >> GUEST_PAGE_SHIFT;
2734 uint16_t cChunks = (uint16_t)((cGuestPages + cPagesPerChunk - 1) / cPagesPerChunk);
2735 AssertRelease((RTGCPHYS)cChunks * cPagesPerChunk >= cGuestPages);
2736 return cChunks;
2737}
2738
2739
2740/**
2741 * Worker for PGMR3PhysMMIO2Register that allocates and the PGMREGMMIO2RANGE
2742 * structures and does basic initialization.
2743 *
2744 * Caller must set type specfic members and initialize the PGMPAGE structures.
2745 *
2746 * This was previously also used by PGMR3PhysMmio2PreRegister, a function for
2747 * pre-registering MMIO that was later (6.1) replaced by a new handle based IOM
2748 * interface. The reference to caller and type above is purely historical.
2749 *
2750 * @returns VBox status code.
2751 * @param pVM The cross context VM structure.
2752 * @param pDevIns The device instance owning the region.
2753 * @param iSubDev The sub-device number (internal PCI config number).
2754 * @param iRegion The region number. If the MMIO2 memory is a PCI
2755 * I/O region this number has to be the number of that
2756 * region. Otherwise it can be any number safe
2757 * UINT8_MAX.
2758 * @param cb The size of the region. Must be page aligned.
2759 * @param fFlags PGMPHYS_MMIO2_FLAGS_XXX.
2760 * @param idMmio2 The MMIO2 ID for the first chunk.
2761 * @param pszDesc The description.
2762 * @param ppHeadRet Where to return the pointer to the first
2763 * registration chunk.
2764 *
2765 * @thread EMT
2766 */
2767static int pgmR3PhysMmio2Create(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS cb, uint32_t fFlags,
2768 uint8_t idMmio2, const char *pszDesc, PPGMREGMMIO2RANGE *ppHeadRet)
2769{
2770 /*
2771 * Figure out how many chunks we need and of which size.
2772 */
2773 uint32_t cPagesPerChunk;
2774 uint16_t cChunks = pgmR3PhysMmio2CalcChunkCount(pVM, cb, &cPagesPerChunk, NULL);
2775 AssertReturn(cChunks, VERR_PGM_PHYS_MMIO_EX_IPE);
2776
2777 /*
2778 * Allocate the chunks.
2779 */
2780 PPGMREGMMIO2RANGE *ppNext = ppHeadRet;
2781 *ppNext = NULL;
2782
2783 int rc = VINF_SUCCESS;
2784 uint32_t cPagesLeft = cb >> GUEST_PAGE_SHIFT;
2785 for (uint16_t iChunk = 0; iChunk < cChunks && RT_SUCCESS(rc); iChunk++, idMmio2++)
2786 {
2787 /*
2788 * We currently do a single RAM range for the whole thing. This will
2789 * probably have to change once someone needs really large MMIO regions,
2790 * as we will be running into SUPR3PageAllocEx limitations and such.
2791 */
2792 const uint32_t cPagesTrackedByChunk = RT_MIN(cPagesLeft, cPagesPerChunk);
2793 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIO2RANGE, RamRange.aPages[cPagesTrackedByChunk]);
2794 PPGMREGMMIO2RANGE pNew = NULL;
2795
2796 /*
2797 * Allocate memory for the registration structure.
2798 */
2799 size_t const cChunkPages = RT_ALIGN_Z(cbRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
2800 size_t const cbChunk = (1 + cChunkPages + 1) << HOST_PAGE_SHIFT;
2801 AssertLogRelBreakStmt(cbChunk == (uint32_t)cbChunk, rc = VERR_OUT_OF_RANGE);
2802 RTR0PTR R0PtrChunk = NIL_RTR0PTR;
2803 void *pvChunk = NULL;
2804 rc = SUPR3PageAllocEx(cChunkPages, 0 /*fFlags*/, &pvChunk, &R0PtrChunk, NULL /*paPages*/);
2805 AssertLogRelMsgRCBreak(rc, ("rc=%Rrc, cChunkPages=%#zx\n", rc, cChunkPages));
2806
2807 Assert(R0PtrChunk != NIL_RTR0PTR || PGM_IS_IN_NEM_MODE(pVM));
2808 RT_BZERO(pvChunk, cChunkPages << HOST_PAGE_SHIFT);
2809
2810 pNew = (PPGMREGMMIO2RANGE)pvChunk;
2811 pNew->RamRange.fFlags = PGM_RAM_RANGE_FLAGS_FLOATING;
2812 pNew->RamRange.pSelfR0 = R0PtrChunk + RT_UOFFSETOF(PGMREGMMIO2RANGE, RamRange);
2813
2814 /*
2815 * Initialize the registration structure (caller does specific bits).
2816 */
2817 pNew->pDevInsR3 = pDevIns;
2818 //pNew->pvR3 = NULL;
2819 //pNew->pNext = NULL;
2820 if (iChunk == 0)
2821 pNew->fFlags |= PGMREGMMIO2RANGE_F_FIRST_CHUNK;
2822 if (iChunk + 1 == cChunks)
2823 pNew->fFlags |= PGMREGMMIO2RANGE_F_LAST_CHUNK;
2824 if (fFlags & PGMPHYS_MMIO2_FLAGS_TRACK_DIRTY_PAGES)
2825 pNew->fFlags |= PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES;
2826 pNew->iSubDev = iSubDev;
2827 pNew->iRegion = iRegion;
2828 pNew->idSavedState = UINT8_MAX;
2829 pNew->idMmio2 = idMmio2;
2830 //pNew->pPhysHandlerR3 = NULL;
2831 //pNew->paLSPages = NULL;
2832 pNew->RamRange.GCPhys = NIL_RTGCPHYS;
2833 pNew->RamRange.GCPhysLast = NIL_RTGCPHYS;
2834 pNew->RamRange.pszDesc = pszDesc;
2835 pNew->RamRange.cb = pNew->cbReal = (RTGCPHYS)cPagesTrackedByChunk << X86_PAGE_SHIFT;
2836 pNew->RamRange.fFlags |= PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO_EX;
2837 pNew->RamRange.uNemRange = UINT32_MAX;
2838 //pNew->RamRange.pvR3 = NULL;
2839 //pNew->RamRange.paLSPages = NULL;
2840
2841 *ppNext = pNew;
2842 ASMCompilerBarrier();
2843 cPagesLeft -= cPagesTrackedByChunk;
2844 ppNext = &pNew->pNextR3;
2845
2846 /*
2847 * Pre-allocate a handler if we're tracking dirty pages, unless NEM takes care of this.
2848 */
2849 if ( (fFlags & PGMPHYS_MMIO2_FLAGS_TRACK_DIRTY_PAGES)
2850#ifdef VBOX_WITH_PGM_NEM_MODE
2851 && (!VM_IS_NEM_ENABLED(pVM) || !NEMR3IsMmio2DirtyPageTrackingSupported(pVM))
2852#endif
2853 )
2854
2855 {
2856 rc = pgmHandlerPhysicalExCreate(pVM, pVM->pgm.s.hMmio2DirtyPhysHandlerType, idMmio2, pszDesc, &pNew->pPhysHandlerR3);
2857 AssertLogRelMsgRCBreak(rc, ("idMmio2=%zu\n", idMmio2));
2858 }
2859 }
2860 Assert(cPagesLeft == 0);
2861
2862 if (RT_SUCCESS(rc))
2863 {
2864 Assert((*ppHeadRet)->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK);
2865 return VINF_SUCCESS;
2866 }
2867
2868 /*
2869 * Free floating ranges.
2870 */
2871 while (*ppHeadRet)
2872 {
2873 PPGMREGMMIO2RANGE pFree = *ppHeadRet;
2874 *ppHeadRet = pFree->pNextR3;
2875
2876 if (pFree->pPhysHandlerR3)
2877 {
2878 pgmHandlerPhysicalExDestroy(pVM, pFree->pPhysHandlerR3);
2879 pFree->pPhysHandlerR3 = NULL;
2880 }
2881
2882 if (pFree->RamRange.fFlags & PGM_RAM_RANGE_FLAGS_FLOATING)
2883 {
2884 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIO2RANGE,
2885 RamRange.aPages[pFree->RamRange.cb >> X86_PAGE_SHIFT]);
2886 size_t const cChunkPages = RT_ALIGN_Z(cbRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
2887 SUPR3PageFreeEx(pFree, cChunkPages);
2888 }
2889 }
2890
2891 return rc;
2892}
2893
2894
2895/**
2896 * Common worker PGMR3PhysMmio2PreRegister & PGMR3PhysMMIO2Register that links a
2897 * complete registration entry into the lists and lookup tables.
2898 *
2899 * @param pVM The cross context VM structure.
2900 * @param pNew The new MMIO / MMIO2 registration to link.
2901 */
2902static void pgmR3PhysMmio2Link(PVM pVM, PPGMREGMMIO2RANGE pNew)
2903{
2904 Assert(pNew->idMmio2 != UINT8_MAX);
2905
2906 /*
2907 * Link it into the list (order doesn't matter, so insert it at the head).
2908 *
2909 * Note! The range we're linking may consist of multiple chunks, so we
2910 * have to find the last one.
2911 */
2912 PPGMREGMMIO2RANGE pLast = pNew;
2913 for (pLast = pNew; ; pLast = pLast->pNextR3)
2914 {
2915 if (pLast->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
2916 break;
2917 Assert(pLast->pNextR3);
2918 Assert(pLast->pNextR3->pDevInsR3 == pNew->pDevInsR3);
2919 Assert(pLast->pNextR3->iSubDev == pNew->iSubDev);
2920 Assert(pLast->pNextR3->iRegion == pNew->iRegion);
2921 Assert(pLast->pNextR3->idMmio2 == pLast->idMmio2 + 1);
2922 }
2923
2924 PGM_LOCK_VOID(pVM);
2925
2926 /* Link in the chain of ranges at the head of the list. */
2927 pLast->pNextR3 = pVM->pgm.s.pRegMmioRangesR3;
2928 pVM->pgm.s.pRegMmioRangesR3 = pNew;
2929
2930 /* Insert the MMIO2 range/page IDs. */
2931 uint8_t idMmio2 = pNew->idMmio2;
2932 for (;;)
2933 {
2934 Assert(pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] == NULL);
2935 Assert(pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] == NIL_RTR0PTR);
2936 pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] = pNew;
2937 pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] = pNew->RamRange.pSelfR0 - RT_UOFFSETOF(PGMREGMMIO2RANGE, RamRange);
2938 if (pNew->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
2939 break;
2940 pNew = pNew->pNextR3;
2941 idMmio2++;
2942 }
2943
2944 pgmPhysInvalidatePageMapTLB(pVM);
2945 PGM_UNLOCK(pVM);
2946}
2947
2948
2949/**
2950 * Allocate and register an MMIO2 region.
2951 *
2952 * As mentioned elsewhere, MMIO2 is just RAM spelled differently. It's RAM
2953 * associated with a device. It is also non-shared memory with a permanent
2954 * ring-3 mapping and page backing (presently).
2955 *
2956 * A MMIO2 range may overlap with base memory if a lot of RAM is configured for
2957 * the VM, in which case we'll drop the base memory pages. Presently we will
2958 * make no attempt to preserve anything that happens to be present in the base
2959 * memory that is replaced, this is of course incorrect but it's too much
2960 * effort.
2961 *
2962 * @returns VBox status code.
2963 * @retval VINF_SUCCESS on success, *ppv pointing to the R3 mapping of the
2964 * memory.
2965 * @retval VERR_ALREADY_EXISTS if the region already exists.
2966 *
2967 * @param pVM The cross context VM structure.
2968 * @param pDevIns The device instance owning the region.
2969 * @param iSubDev The sub-device number.
2970 * @param iRegion The region number. If the MMIO2 memory is a PCI
2971 * I/O region this number has to be the number of that
2972 * region. Otherwise it can be any number save
2973 * UINT8_MAX.
2974 * @param cb The size of the region. Must be page aligned.
2975 * @param fFlags Reserved for future use, must be zero.
2976 * @param pszDesc The description.
2977 * @param ppv Where to store the pointer to the ring-3 mapping of
2978 * the memory.
2979 * @param phRegion Where to return the MMIO2 region handle. Optional.
2980 * @thread EMT
2981 */
2982VMMR3_INT_DECL(int) PGMR3PhysMmio2Register(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS cb,
2983 uint32_t fFlags, const char *pszDesc, void **ppv, PGMMMIO2HANDLE *phRegion)
2984{
2985 /*
2986 * Validate input.
2987 */
2988 AssertPtrReturn(ppv, VERR_INVALID_POINTER);
2989 *ppv = NULL;
2990 if (phRegion)
2991 {
2992 AssertPtrReturn(phRegion, VERR_INVALID_POINTER);
2993 *phRegion = NIL_PGMMMIO2HANDLE;
2994 }
2995 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2996 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2997 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
2998 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2999 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
3000 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
3001 AssertReturn(pgmR3PhysMmio2Find(pVM, pDevIns, iSubDev, iRegion, NIL_PGMMMIO2HANDLE) == NULL, VERR_ALREADY_EXISTS);
3002 AssertReturn(!(cb & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3003 AssertReturn(cb, VERR_INVALID_PARAMETER);
3004 AssertReturn(!(fFlags & ~PGMPHYS_MMIO2_FLAGS_VALID_MASK), VERR_INVALID_FLAGS);
3005
3006 const uint32_t cGuestPages = cb >> GUEST_PAGE_SHIFT;
3007 AssertLogRelReturn(((RTGCPHYS)cGuestPages << GUEST_PAGE_SHIFT) == cb, VERR_INVALID_PARAMETER);
3008 AssertLogRelReturn(cGuestPages <= (MM_MMIO_64_MAX >> X86_PAGE_SHIFT), VERR_OUT_OF_RANGE);
3009 AssertLogRelReturn(cGuestPages <= PGM_MMIO2_MAX_PAGE_COUNT, VERR_OUT_OF_RANGE);
3010
3011 /*
3012 * For the 2nd+ instance, mangle the description string so it's unique.
3013 */
3014 if (pDevIns->iInstance > 0) /** @todo Move to PDMDevHlp.cpp and use a real string cache. */
3015 {
3016 pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s [%u]", pszDesc, pDevIns->iInstance);
3017 if (!pszDesc)
3018 return VERR_NO_MEMORY;
3019 }
3020
3021 /*
3022 * Allocate an MMIO2 range ID (not freed on failure).
3023 *
3024 * The zero ID is not used as it could be confused with NIL_GMM_PAGEID, so
3025 * the IDs goes from 1 thru PGM_MMIO2_MAX_RANGES.
3026 */
3027 unsigned cChunks = pgmR3PhysMmio2CalcChunkCount(pVM, cb, NULL, NULL);
3028
3029 PGM_LOCK_VOID(pVM);
3030 AssertCompile(PGM_MMIO2_MAX_RANGES < 255);
3031 uint8_t const idMmio2 = pVM->pgm.s.cMmio2Regions + 1;
3032 unsigned const cNewMmio2Regions = pVM->pgm.s.cMmio2Regions + cChunks;
3033 if (cNewMmio2Regions > PGM_MMIO2_MAX_RANGES)
3034 {
3035 PGM_UNLOCK(pVM);
3036 AssertLogRelFailedReturn(VERR_PGM_TOO_MANY_MMIO2_RANGES);
3037 }
3038 pVM->pgm.s.cMmio2Regions = cNewMmio2Regions;
3039 PGM_UNLOCK(pVM);
3040
3041 /*
3042 * Try reserve and allocate the backing memory first as this is what is
3043 * most likely to fail.
3044 */
3045 int rc = MMR3AdjustFixedReservation(pVM, cGuestPages, pszDesc);
3046 if (RT_SUCCESS(rc))
3047 {
3048 const uint32_t cHostPages = RT_ALIGN_T(cb, HOST_PAGE_SIZE, RTGCPHYS) >> HOST_PAGE_SHIFT;
3049 PSUPPAGE paPages = (PSUPPAGE)RTMemTmpAlloc(cHostPages * sizeof(SUPPAGE));
3050 if (RT_SUCCESS(rc))
3051 {
3052 void *pvPages = NULL;
3053#ifndef VBOX_WITH_LINEAR_HOST_PHYS_MEM
3054 RTR0PTR pvPagesR0 = NIL_RTR0PTR;
3055#endif
3056#ifdef VBOX_WITH_PGM_NEM_MODE
3057 if (PGM_IS_IN_NEM_MODE(pVM))
3058 rc = SUPR3PageAlloc(cHostPages, pVM->pgm.s.fUseLargePages ? SUP_PAGE_ALLOC_F_LARGE_PAGES : 0, &pvPages);
3059 else
3060#endif
3061 {
3062#ifndef VBOX_WITH_LINEAR_HOST_PHYS_MEM
3063 rc = SUPR3PageAllocEx(cHostPages, 0 /*fFlags*/, &pvPages, &pvPagesR0, paPages);
3064#else
3065 rc = SUPR3PageAllocEx(cHostPages, 0 /*fFlags*/, &pvPages, NULL /*pR0Ptr*/, paPages);
3066#endif
3067 }
3068 if (RT_SUCCESS(rc))
3069 {
3070 memset(pvPages, 0, cGuestPages * GUEST_PAGE_SIZE);
3071
3072 /*
3073 * Create the registered MMIO range record for it.
3074 */
3075 PPGMREGMMIO2RANGE pNew;
3076 rc = pgmR3PhysMmio2Create(pVM, pDevIns, iSubDev, iRegion, cb, fFlags, idMmio2, pszDesc, &pNew);
3077 if (RT_SUCCESS(rc))
3078 {
3079 if (phRegion)
3080 *phRegion = idMmio2; /* The ID of the first chunk. */
3081
3082 uint32_t iSrcPage = 0;
3083 uint8_t *pbCurPages = (uint8_t *)pvPages;
3084 for (PPGMREGMMIO2RANGE pCur = pNew; pCur; pCur = pCur->pNextR3)
3085 {
3086 pCur->pvR3 = pbCurPages;
3087#ifndef VBOX_WITH_LINEAR_HOST_PHYS_MEM
3088 pCur->pvR0 = pvPagesR0 + (iSrcPage << GUEST_PAGE_SHIFT);
3089#endif
3090 pCur->RamRange.pvR3 = pbCurPages;
3091
3092 uint32_t iDstPage = pCur->RamRange.cb >> GUEST_PAGE_SHIFT;
3093#ifdef VBOX_WITH_PGM_NEM_MODE
3094 if (PGM_IS_IN_NEM_MODE(pVM))
3095 while (iDstPage-- > 0)
3096 PGM_PAGE_INIT(&pNew->RamRange.aPages[iDstPage], UINT64_C(0x0000ffffffff0000),
3097 PGM_MMIO2_PAGEID_MAKE(idMmio2, iDstPage),
3098 PGMPAGETYPE_MMIO2, PGM_PAGE_STATE_ALLOCATED);
3099 else
3100#endif
3101 {
3102 AssertRelease(HOST_PAGE_SHIFT == GUEST_PAGE_SHIFT);
3103 while (iDstPage-- > 0)
3104 PGM_PAGE_INIT(&pNew->RamRange.aPages[iDstPage], paPages[iDstPage + iSrcPage].Phys,
3105 PGM_MMIO2_PAGEID_MAKE(idMmio2, iDstPage),
3106 PGMPAGETYPE_MMIO2, PGM_PAGE_STATE_ALLOCATED);
3107 }
3108
3109 /* advance. */
3110 iSrcPage += pCur->RamRange.cb >> GUEST_PAGE_SHIFT;
3111 pbCurPages += pCur->RamRange.cb;
3112 }
3113
3114 RTMemTmpFree(paPages);
3115
3116 /*
3117 * Update the page count stats, link the registration and we're done.
3118 */
3119 pVM->pgm.s.cAllPages += cGuestPages;
3120 pVM->pgm.s.cPrivatePages += cGuestPages;
3121
3122 pgmR3PhysMmio2Link(pVM, pNew);
3123
3124 *ppv = pvPages;
3125 return VINF_SUCCESS;
3126 }
3127
3128 SUPR3PageFreeEx(pvPages, cHostPages);
3129 }
3130 }
3131 RTMemTmpFree(paPages);
3132 MMR3AdjustFixedReservation(pVM, -(int32_t)cGuestPages, pszDesc);
3133 }
3134 if (pDevIns->iInstance > 0)
3135 MMR3HeapFree((void *)pszDesc);
3136 return rc;
3137}
3138
3139
3140/**
3141 * Deregisters and frees an MMIO2 region.
3142 *
3143 * Any physical access handlers registered for the region must be deregistered
3144 * before calling this function.
3145 *
3146 * @returns VBox status code.
3147 * @param pVM The cross context VM structure.
3148 * @param pDevIns The device instance owning the region.
3149 * @param hMmio2 The MMIO2 handle to deregister, or NIL if all
3150 * regions for the given device is to be deregistered.
3151 */
3152VMMR3_INT_DECL(int) PGMR3PhysMmio2Deregister(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2)
3153{
3154 /*
3155 * Validate input.
3156 */
3157 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3158 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3159
3160 /*
3161 * The loop here scanning all registrations will make sure that multi-chunk ranges
3162 * get properly deregistered, though it's original purpose was the wildcard iRegion.
3163 */
3164 PGM_LOCK_VOID(pVM);
3165 int rc = VINF_SUCCESS;
3166 unsigned cFound = 0;
3167 PPGMREGMMIO2RANGE pPrev = NULL;
3168 PPGMREGMMIO2RANGE pCur = pVM->pgm.s.pRegMmioRangesR3;
3169 while (pCur)
3170 {
3171 uint32_t const fFlags = pCur->fFlags;
3172 if ( pCur->pDevInsR3 == pDevIns
3173 && ( hMmio2 == NIL_PGMMMIO2HANDLE
3174 || pCur->idMmio2 == hMmio2))
3175 {
3176 cFound++;
3177
3178 /*
3179 * Unmap it if it's mapped.
3180 */
3181 if (fFlags & PGMREGMMIO2RANGE_F_MAPPED)
3182 {
3183 int rc2 = PGMR3PhysMmio2Unmap(pVM, pCur->pDevInsR3, pCur->idMmio2, pCur->RamRange.GCPhys);
3184 AssertRC(rc2);
3185 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3186 rc = rc2;
3187 }
3188
3189 /*
3190 * Unlink it
3191 */
3192 PPGMREGMMIO2RANGE pNext = pCur->pNextR3;
3193 if (pPrev)
3194 pPrev->pNextR3 = pNext;
3195 else
3196 pVM->pgm.s.pRegMmioRangesR3 = pNext;
3197 pCur->pNextR3 = NULL;
3198
3199 uint8_t idMmio2 = pCur->idMmio2;
3200 Assert(idMmio2 <= RT_ELEMENTS(pVM->pgm.s.apMmio2RangesR3));
3201 if (idMmio2 <= RT_ELEMENTS(pVM->pgm.s.apMmio2RangesR3))
3202 {
3203 Assert(pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] == pCur);
3204 pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] = NULL;
3205 pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] = NIL_RTR0PTR;
3206 }
3207
3208 /*
3209 * Free the memory.
3210 */
3211 uint32_t const cGuestPages = pCur->cbReal >> GUEST_PAGE_SHIFT;
3212 uint32_t const cHostPages = RT_ALIGN_T(pCur->cbReal, HOST_PAGE_SIZE, RTGCPHYS) >> HOST_PAGE_SHIFT;
3213#ifdef VBOX_WITH_PGM_NEM_MODE
3214 if (!pVM->pgm.s.fNemMode)
3215#endif
3216 {
3217 int rc2 = SUPR3PageFreeEx(pCur->pvR3, cHostPages);
3218 AssertRC(rc2);
3219 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3220 rc = rc2;
3221
3222 rc2 = MMR3AdjustFixedReservation(pVM, -(int32_t)cGuestPages, pCur->RamRange.pszDesc);
3223 AssertRC(rc2);
3224 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3225 rc = rc2;
3226 }
3227#ifdef VBOX_WITH_PGM_NEM_MODE
3228 else
3229 {
3230 int rc2 = SUPR3PageFreeEx(pCur->pvR3, cHostPages);
3231 AssertRC(rc2);
3232 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3233 rc = rc2;
3234 }
3235#endif
3236
3237 if (pCur->pPhysHandlerR3)
3238 {
3239 pgmHandlerPhysicalExDestroy(pVM, pCur->pPhysHandlerR3);
3240 pCur->pPhysHandlerR3 = NULL;
3241 }
3242
3243 /* we're leaking hyper memory here if done at runtime. */
3244#ifdef VBOX_STRICT
3245 VMSTATE const enmState = VMR3GetState(pVM);
3246 AssertMsg( enmState == VMSTATE_POWERING_OFF
3247 || enmState == VMSTATE_POWERING_OFF_LS
3248 || enmState == VMSTATE_OFF
3249 || enmState == VMSTATE_OFF_LS
3250 || enmState == VMSTATE_DESTROYING
3251 || enmState == VMSTATE_TERMINATED
3252 || enmState == VMSTATE_CREATING
3253 , ("%s\n", VMR3GetStateName(enmState)));
3254#endif
3255
3256 if (pCur->RamRange.fFlags & PGM_RAM_RANGE_FLAGS_FLOATING)
3257 {
3258 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIO2RANGE, RamRange.aPages[cGuestPages]);
3259 size_t const cChunkPages = RT_ALIGN_Z(cbRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
3260 SUPR3PageFreeEx(pCur, cChunkPages);
3261 }
3262 /*else
3263 {
3264 rc = MMHyperFree(pVM, pCur); - does not work, see the alloc call.
3265 AssertRCReturn(rc, rc);
3266 } */
3267
3268
3269 /* update page count stats */
3270 pVM->pgm.s.cAllPages -= cGuestPages;
3271 pVM->pgm.s.cPrivatePages -= cGuestPages;
3272
3273 /* next */
3274 pCur = pNext;
3275 if (hMmio2 != NIL_PGMMMIO2HANDLE)
3276 {
3277 if (fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3278 break;
3279 hMmio2++;
3280 Assert(pCur->idMmio2 == hMmio2);
3281 Assert(pCur->pDevInsR3 == pDevIns);
3282 Assert(!(pCur->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK));
3283 }
3284 }
3285 else
3286 {
3287 pPrev = pCur;
3288 pCur = pCur->pNextR3;
3289 }
3290 }
3291 pgmPhysInvalidatePageMapTLB(pVM);
3292 PGM_UNLOCK(pVM);
3293 return !cFound && hMmio2 != NIL_PGMMMIO2HANDLE ? VERR_NOT_FOUND : rc;
3294}
3295
3296
3297/**
3298 * Maps a MMIO2 region.
3299 *
3300 * This is typically done when a guest / the bios / state loading changes the
3301 * PCI config. The replacing of base memory has the same restrictions as during
3302 * registration, of course.
3303 *
3304 * @returns VBox status code.
3305 *
3306 * @param pVM The cross context VM structure.
3307 * @param pDevIns The device instance owning the region.
3308 * @param hMmio2 The handle of the region to map.
3309 * @param GCPhys The guest-physical address to be remapped.
3310 */
3311VMMR3_INT_DECL(int) PGMR3PhysMmio2Map(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, RTGCPHYS GCPhys)
3312{
3313 /*
3314 * Validate input.
3315 *
3316 * Note! It's safe to walk the MMIO/MMIO2 list since registrations only
3317 * happens during VM construction.
3318 */
3319 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3320 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3321 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
3322 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
3323 AssertReturn(!(GCPhys & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3324 AssertReturn(hMmio2 != NIL_PGMMMIO2HANDLE, VERR_INVALID_HANDLE);
3325
3326 PPGMREGMMIO2RANGE pFirstMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3327 AssertReturn(pFirstMmio, VERR_NOT_FOUND);
3328 Assert(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK);
3329
3330 PPGMREGMMIO2RANGE pLastMmio = pFirstMmio;
3331 RTGCPHYS cbRange = 0;
3332 for (;;)
3333 {
3334 AssertReturn(!(pLastMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED), VERR_WRONG_ORDER);
3335 Assert(pLastMmio->RamRange.GCPhys == NIL_RTGCPHYS);
3336 Assert(pLastMmio->RamRange.GCPhysLast == NIL_RTGCPHYS);
3337 Assert(pLastMmio->pDevInsR3 == pFirstMmio->pDevInsR3);
3338 Assert(pLastMmio->iSubDev == pFirstMmio->iSubDev);
3339 Assert(pLastMmio->iRegion == pFirstMmio->iRegion);
3340 cbRange += pLastMmio->RamRange.cb;
3341 if (pLastMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3342 break;
3343 pLastMmio = pLastMmio->pNextR3;
3344 }
3345
3346 RTGCPHYS GCPhysLast = GCPhys + cbRange - 1;
3347 AssertLogRelReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
3348
3349 /*
3350 * Find our location in the ram range list, checking for restriction
3351 * we don't bother implementing yet (partially overlapping, multiple
3352 * ram ranges).
3353 */
3354 PGM_LOCK_VOID(pVM);
3355
3356 AssertReturnStmt(!(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED), PGM_UNLOCK(pVM), VERR_WRONG_ORDER);
3357
3358 bool fRamExists = false;
3359 PPGMRAMRANGE pRamPrev = NULL;
3360 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
3361 while (pRam && GCPhysLast >= pRam->GCPhys)
3362 {
3363 if ( GCPhys <= pRam->GCPhysLast
3364 && GCPhysLast >= pRam->GCPhys)
3365 {
3366 /* Completely within? */
3367 AssertLogRelMsgReturnStmt( GCPhys >= pRam->GCPhys
3368 && GCPhysLast <= pRam->GCPhysLast,
3369 ("%RGp-%RGp (MMIOEx/%s) falls partly outside %RGp-%RGp (%s)\n",
3370 GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc,
3371 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
3372 PGM_UNLOCK(pVM),
3373 VERR_PGM_RAM_CONFLICT);
3374
3375 /* Check that all the pages are RAM pages. */
3376 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
3377 uint32_t cPagesLeft = cbRange >> GUEST_PAGE_SHIFT;
3378 while (cPagesLeft-- > 0)
3379 {
3380 AssertLogRelMsgReturnStmt(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
3381 ("%RGp isn't a RAM page (%d) - mapping %RGp-%RGp (MMIO2/%s).\n",
3382 GCPhys, PGM_PAGE_GET_TYPE(pPage), GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc),
3383 PGM_UNLOCK(pVM),
3384 VERR_PGM_RAM_CONFLICT);
3385 pPage++;
3386 }
3387
3388 /* There can only be one MMIO/MMIO2 chunk matching here! */
3389 AssertLogRelMsgReturnStmt(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK,
3390 ("%RGp-%RGp (MMIOEx/%s, flags %#X) consists of multiple chunks whereas the RAM somehow doesn't!\n",
3391 GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc, pFirstMmio->fFlags),
3392 PGM_UNLOCK(pVM),
3393 VERR_PGM_PHYS_MMIO_EX_IPE);
3394
3395 fRamExists = true;
3396 break;
3397 }
3398
3399 /* next */
3400 pRamPrev = pRam;
3401 pRam = pRam->pNextR3;
3402 }
3403 Log(("PGMR3PhysMmio2Map: %RGp-%RGp fRamExists=%RTbool %s\n", GCPhys, GCPhysLast, fRamExists, pFirstMmio->RamRange.pszDesc));
3404
3405
3406 /*
3407 * Make the changes.
3408 */
3409 RTGCPHYS GCPhysCur = GCPhys;
3410 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3411 {
3412 pCurMmio->RamRange.GCPhys = GCPhysCur;
3413 pCurMmio->RamRange.GCPhysLast = GCPhysCur + pCurMmio->RamRange.cb - 1;
3414 if (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3415 {
3416 Assert(pCurMmio->RamRange.GCPhysLast == GCPhysLast);
3417 break;
3418 }
3419 GCPhysCur += pCurMmio->RamRange.cb;
3420 }
3421
3422 if (fRamExists)
3423 {
3424 /*
3425 * Make all the pages in the range MMIO/ZERO pages, freeing any
3426 * RAM pages currently mapped here. This might not be 100% correct
3427 * for PCI memory, but we're doing the same thing for MMIO2 pages.
3428 *
3429 * We replace these MMIO/ZERO pages with real pages in the MMIO2 case.
3430 */
3431 Assert(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK); /* Only one chunk */
3432 Assert(pFirstMmio->pvR3 == pFirstMmio->RamRange.pvR3);
3433 Assert(pFirstMmio->RamRange.pvR3 != NULL);
3434
3435#ifdef VBOX_WITH_PGM_NEM_MODE
3436 /* We cannot mix MMIO2 into a RAM range in simplified memory mode because pRam->pvR3 can't point
3437 both at the RAM and MMIO2, so we won't ever write & read from the actual MMIO2 memory if we try. */
3438 AssertLogRelMsgReturn(!pVM->pgm.s.fNemMode, ("%s at %RGp-%RGp\n", pFirstMmio->RamRange.pszDesc, GCPhys, GCPhysLast),
3439 VERR_PGM_NOT_SUPPORTED_FOR_NEM_MODE);
3440#endif
3441
3442 int rc = pgmR3PhysFreePageRange(pVM, pRam, GCPhys, GCPhysLast, pFirstMmio->RamRange.pvR3);
3443 AssertRCReturnStmt(rc, PGM_UNLOCK(pVM), rc);
3444
3445 /* Replace the pages, freeing all present RAM pages. */
3446 PPGMPAGE pPageSrc = &pFirstMmio->RamRange.aPages[0];
3447 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
3448 uint32_t cPagesLeft = pFirstMmio->RamRange.cb >> GUEST_PAGE_SHIFT;
3449 while (cPagesLeft-- > 0)
3450 {
3451 Assert(PGM_PAGE_IS_MMIO(pPageDst));
3452
3453 RTHCPHYS const HCPhys = PGM_PAGE_GET_HCPHYS(pPageSrc);
3454 uint32_t const idPage = PGM_PAGE_GET_PAGEID(pPageSrc);
3455 PGM_PAGE_SET_PAGEID(pVM, pPageDst, idPage);
3456 PGM_PAGE_SET_HCPHYS(pVM, pPageDst, HCPhys);
3457 PGM_PAGE_SET_TYPE(pVM, pPageDst, PGMPAGETYPE_MMIO2);
3458 PGM_PAGE_SET_STATE(pVM, pPageDst, PGM_PAGE_STATE_ALLOCATED);
3459 PGM_PAGE_SET_PDE_TYPE(pVM, pPageDst, PGM_PAGE_PDE_TYPE_DONTCARE);
3460 PGM_PAGE_SET_PTE_INDEX(pVM, pPageDst, 0);
3461 PGM_PAGE_SET_TRACKING(pVM, pPageDst, 0);
3462 /* NEM state is set by pgmR3PhysFreePageRange. */
3463
3464 pVM->pgm.s.cZeroPages--;
3465 GCPhys += GUEST_PAGE_SIZE;
3466 pPageSrc++;
3467 pPageDst++;
3468 }
3469
3470 /* Flush physical page map TLB. */
3471 pgmPhysInvalidatePageMapTLB(pVM);
3472
3473 /* Force a PGM pool flush as guest ram references have been changed. */
3474 /** @todo not entirely SMP safe; assuming for now the guest takes care of
3475 * this internally (not touch mapped mmio while changing the mapping). */
3476 PVMCPU pVCpu = VMMGetCpu(pVM);
3477 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
3478 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
3479 }
3480 else
3481 {
3482 /*
3483 * No RAM range, insert the ones prepared during registration.
3484 */
3485 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3486 {
3487#ifdef VBOX_WITH_NATIVE_NEM
3488 /* Tell NEM and get the new NEM state for the pages. */
3489 uint8_t u2NemState = 0;
3490 if (VM_IS_NEM_ENABLED(pVM))
3491 {
3492 int rc = NEMR3NotifyPhysMmioExMapEarly(pVM, pCurMmio->RamRange.GCPhys,
3493 pCurMmio->RamRange.GCPhysLast - pCurMmio->RamRange.GCPhys + 1,
3494 NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2
3495 | (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES
3496 ? NEM_NOTIFY_PHYS_MMIO_EX_F_TRACK_DIRTY_PAGES : 0),
3497 NULL /*pvRam*/, pCurMmio->RamRange.pvR3,
3498 &u2NemState, &pCurMmio->RamRange.uNemRange);
3499 AssertLogRelRCReturnStmt(rc, PGM_UNLOCK(pVM), rc);
3500 }
3501#endif
3502
3503 /* Clear the tracking data of pages we're going to reactivate. */
3504 PPGMPAGE pPageSrc = &pCurMmio->RamRange.aPages[0];
3505 uint32_t cPagesLeft = pCurMmio->RamRange.cb >> GUEST_PAGE_SHIFT;
3506 while (cPagesLeft-- > 0)
3507 {
3508 PGM_PAGE_SET_TRACKING(pVM, pPageSrc, 0);
3509 PGM_PAGE_SET_PTE_INDEX(pVM, pPageSrc, 0);
3510#ifdef VBOX_WITH_NATIVE_NEM
3511 PGM_PAGE_SET_NEM_STATE(pPageSrc, u2NemState);
3512#endif
3513 pPageSrc++;
3514 }
3515
3516 /* link in the ram range */
3517 pgmR3PhysLinkRamRange(pVM, &pCurMmio->RamRange, pRamPrev);
3518
3519 if (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3520 {
3521 Assert(pCurMmio->RamRange.GCPhysLast == GCPhysLast);
3522 break;
3523 }
3524 pRamPrev = &pCurMmio->RamRange;
3525 }
3526 }
3527
3528 /*
3529 * If the range have dirty page monitoring enabled, enable that.
3530 *
3531 * We ignore failures here for now because if we fail, the whole mapping
3532 * will have to be reversed and we'll end up with nothing at all on the
3533 * screen and a grumpy guest, whereas if we just go on, we'll only have
3534 * visual distortions to gripe about. There will be something in the
3535 * release log.
3536 */
3537 if ( pFirstMmio->pPhysHandlerR3
3538 && (pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
3539 pgmR3PhysMmio2EnableDirtyPageTracing(pVM, pFirstMmio);
3540
3541 /*
3542 * We're good, set the flags and invalid the mapping TLB.
3543 */
3544 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3545 {
3546 pCurMmio->fFlags |= PGMREGMMIO2RANGE_F_MAPPED;
3547 if (fRamExists)
3548 pCurMmio->fFlags |= PGMREGMMIO2RANGE_F_OVERLAPPING;
3549 else
3550 pCurMmio->fFlags &= ~PGMREGMMIO2RANGE_F_OVERLAPPING;
3551 if (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3552 break;
3553 }
3554 pgmPhysInvalidatePageMapTLB(pVM);
3555
3556#ifdef VBOX_WITH_NATIVE_NEM
3557 /*
3558 * Late NEM notification.
3559 */
3560 if (VM_IS_NEM_ENABLED(pVM))
3561 {
3562 int rc;
3563 uint32_t fNemFlags = NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2;
3564 if (pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES)
3565 fNemFlags |= NEM_NOTIFY_PHYS_MMIO_EX_F_TRACK_DIRTY_PAGES;
3566 if (fRamExists)
3567 rc = NEMR3NotifyPhysMmioExMapLate(pVM, GCPhys, GCPhysLast - GCPhys + 1, fNemFlags | NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE,
3568 pRam->pvR3 ? (uint8_t *)pRam->pvR3 + GCPhys - pRam->GCPhys : NULL, pFirstMmio->pvR3,
3569 NULL /*puNemRange*/);
3570 else
3571 {
3572 rc = VINF_SUCCESS;
3573 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3574 {
3575 rc = NEMR3NotifyPhysMmioExMapLate(pVM, pCurMmio->RamRange.GCPhys, pCurMmio->RamRange.cb, fNemFlags,
3576 NULL, pCurMmio->RamRange.pvR3, &pCurMmio->RamRange.uNemRange);
3577 if ((pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK) || RT_FAILURE(rc))
3578 break;
3579 }
3580 }
3581 AssertLogRelRCReturnStmt(rc, PGMR3PhysMmio2Unmap(pVM, pDevIns, hMmio2, GCPhys); PGM_UNLOCK(pVM), rc);
3582 }
3583#endif
3584
3585 PGM_UNLOCK(pVM);
3586
3587 return VINF_SUCCESS;
3588}
3589
3590
3591/**
3592 * Unmaps an MMIO2 region.
3593 *
3594 * This is typically done when a guest / the bios / state loading changes the
3595 * PCI config. The replacing of base memory has the same restrictions as during
3596 * registration, of course.
3597 */
3598VMMR3_INT_DECL(int) PGMR3PhysMmio2Unmap(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, RTGCPHYS GCPhys)
3599{
3600 /*
3601 * Validate input
3602 */
3603 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3604 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3605 AssertReturn(hMmio2 != NIL_PGMMMIO2HANDLE, VERR_INVALID_HANDLE);
3606 if (GCPhys != NIL_RTGCPHYS)
3607 {
3608 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
3609 AssertReturn(!(GCPhys & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3610 }
3611
3612 PPGMREGMMIO2RANGE pFirstMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3613 AssertReturn(pFirstMmio, VERR_NOT_FOUND);
3614 Assert(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK);
3615
3616 int rc = PGM_LOCK(pVM);
3617 AssertRCReturn(rc, rc);
3618
3619 PPGMREGMMIO2RANGE pLastMmio = pFirstMmio;
3620 RTGCPHYS cbRange = 0;
3621 for (;;)
3622 {
3623 AssertReturnStmt(pLastMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED, PGM_UNLOCK(pVM), VERR_WRONG_ORDER);
3624 AssertReturnStmt(pLastMmio->RamRange.GCPhys == GCPhys + cbRange || GCPhys == NIL_RTGCPHYS, PGM_UNLOCK(pVM), VERR_INVALID_PARAMETER);
3625 Assert(pLastMmio->pDevInsR3 == pFirstMmio->pDevInsR3);
3626 Assert(pLastMmio->iSubDev == pFirstMmio->iSubDev);
3627 Assert(pLastMmio->iRegion == pFirstMmio->iRegion);
3628 cbRange += pLastMmio->RamRange.cb;
3629 if (pLastMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3630 break;
3631 pLastMmio = pLastMmio->pNextR3;
3632 }
3633
3634 Log(("PGMR3PhysMmio2Unmap: %RGp-%RGp %s\n",
3635 pFirstMmio->RamRange.GCPhys, pLastMmio->RamRange.GCPhysLast, pFirstMmio->RamRange.pszDesc));
3636
3637 uint16_t const fOldFlags = pFirstMmio->fFlags;
3638 AssertReturnStmt(fOldFlags & PGMREGMMIO2RANGE_F_MAPPED, PGM_UNLOCK(pVM), VERR_WRONG_ORDER);
3639
3640 /*
3641 * If monitoring dirty pages, we must deregister the handlers first.
3642 */
3643 if ( pFirstMmio->pPhysHandlerR3
3644 && (fOldFlags & PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
3645 pgmR3PhysMmio2DisableDirtyPageTracing(pVM, pFirstMmio);
3646
3647 /*
3648 * Unmap it.
3649 */
3650 int rcRet = VINF_SUCCESS;
3651#ifdef VBOX_WITH_NATIVE_NEM
3652 uint32_t const fNemFlags = NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2
3653 | (fOldFlags & PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES
3654 ? NEM_NOTIFY_PHYS_MMIO_EX_F_TRACK_DIRTY_PAGES : 0);
3655#endif
3656 if (fOldFlags & PGMREGMMIO2RANGE_F_OVERLAPPING)
3657 {
3658 /*
3659 * We've replaced RAM, replace with zero pages.
3660 *
3661 * Note! This is where we might differ a little from a real system, because
3662 * it's likely to just show the RAM pages as they were before the
3663 * MMIO/MMIO2 region was mapped here.
3664 */
3665 /* Only one chunk allowed when overlapping! */
3666 Assert(fOldFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK);
3667
3668 /* Restore the RAM pages we've replaced. */
3669 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
3670 while (pRam->GCPhys > pFirstMmio->RamRange.GCPhysLast)
3671 pRam = pRam->pNextR3;
3672
3673 PPGMPAGE pPageDst = &pRam->aPages[(pFirstMmio->RamRange.GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
3674 uint32_t cPagesLeft = pFirstMmio->RamRange.cb >> GUEST_PAGE_SHIFT;
3675 pVM->pgm.s.cZeroPages += cPagesLeft; /** @todo not correct for NEM mode */
3676
3677#ifdef VBOX_WITH_NATIVE_NEM
3678 if (VM_IS_NEM_ENABLED(pVM)) /* Notify NEM. Note! we cannot be here in simple memory mode, see mapping function. */
3679 {
3680 uint8_t u2State = UINT8_MAX;
3681 rc = NEMR3NotifyPhysMmioExUnmap(pVM, pFirstMmio->RamRange.GCPhys, pFirstMmio->RamRange.cb,
3682 fNemFlags | NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE,
3683 pRam->pvR3
3684 ? (uint8_t *)pRam->pvR3 + pFirstMmio->RamRange.GCPhys - pRam->GCPhys : NULL,
3685 pFirstMmio->pvR3, &u2State, &pRam->uNemRange);
3686 AssertRCStmt(rc, rcRet = rc);
3687 if (u2State != UINT8_MAX)
3688 pgmPhysSetNemStateForPages(pPageDst, cPagesLeft, u2State);
3689 }
3690#endif
3691
3692 while (cPagesLeft-- > 0)
3693 {
3694 PGM_PAGE_INIT_ZERO(pPageDst, pVM, PGMPAGETYPE_RAM);
3695 pPageDst++;
3696 }
3697
3698 /* Flush physical page map TLB. */
3699 pgmPhysInvalidatePageMapTLB(pVM);
3700
3701 /* Update range state. */
3702 pFirstMmio->RamRange.GCPhys = NIL_RTGCPHYS;
3703 pFirstMmio->RamRange.GCPhysLast = NIL_RTGCPHYS;
3704 pFirstMmio->fFlags &= ~(PGMREGMMIO2RANGE_F_OVERLAPPING | PGMREGMMIO2RANGE_F_MAPPED);
3705 }
3706 else
3707 {
3708 /*
3709 * Unlink the chunks related to the MMIO/MMIO2 region.
3710 */
3711 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3712 {
3713#ifdef VBOX_WITH_NATIVE_NEM
3714 if (VM_IS_NEM_ENABLED(pVM)) /* Notify NEM. */
3715 {
3716 uint8_t u2State = UINT8_MAX;
3717 rc = NEMR3NotifyPhysMmioExUnmap(pVM, pCurMmio->RamRange.GCPhys, pCurMmio->RamRange.cb, fNemFlags,
3718 NULL, pCurMmio->pvR3, &u2State, &pCurMmio->RamRange.uNemRange);
3719 AssertRCStmt(rc, rcRet = rc);
3720 if (u2State != UINT8_MAX)
3721 pgmPhysSetNemStateForPages(pCurMmio->RamRange.aPages, pCurMmio->RamRange.cb >> GUEST_PAGE_SHIFT, u2State);
3722 }
3723#endif
3724 pgmR3PhysUnlinkRamRange(pVM, &pCurMmio->RamRange);
3725 pCurMmio->RamRange.GCPhys = NIL_RTGCPHYS;
3726 pCurMmio->RamRange.GCPhysLast = NIL_RTGCPHYS;
3727 pCurMmio->fFlags &= ~(PGMREGMMIO2RANGE_F_OVERLAPPING | PGMREGMMIO2RANGE_F_MAPPED);
3728 if (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3729 break;
3730 }
3731 }
3732
3733 /* Force a PGM pool flush as guest ram references have been changed. */
3734 /** @todo not entirely SMP safe; assuming for now the guest takes care
3735 * of this internally (not touch mapped mmio while changing the
3736 * mapping). */
3737 PVMCPU pVCpu = VMMGetCpu(pVM);
3738 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
3739 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
3740
3741 pgmPhysInvalidatePageMapTLB(pVM);
3742 pgmPhysInvalidRamRangeTlbs(pVM);
3743
3744 PGM_UNLOCK(pVM);
3745 return rcRet;
3746}
3747
3748
3749/**
3750 * Reduces the mapping size of a MMIO2 region.
3751 *
3752 * This is mainly for dealing with old saved states after changing the default
3753 * size of a mapping region. See PGMDevHlpMMIOExReduce and
3754 * PDMPCIDEV::pfnRegionLoadChangeHookR3.
3755 *
3756 * The region must not currently be mapped when making this call. The VM state
3757 * must be state restore or VM construction.
3758 *
3759 * @returns VBox status code.
3760 * @param pVM The cross context VM structure.
3761 * @param pDevIns The device instance owning the region.
3762 * @param hMmio2 The handle of the region to reduce.
3763 * @param cbRegion The new mapping size.
3764 */
3765VMMR3_INT_DECL(int) PGMR3PhysMmio2Reduce(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, RTGCPHYS cbRegion)
3766{
3767 /*
3768 * Validate input
3769 */
3770 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3771 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3772 AssertReturn(hMmio2 != NIL_PGMMMIO2HANDLE, VERR_INVALID_HANDLE);
3773 AssertReturn(cbRegion >= X86_PAGE_SIZE, VERR_INVALID_PARAMETER);
3774 AssertReturn(!(cbRegion & X86_PAGE_OFFSET_MASK), VERR_UNSUPPORTED_ALIGNMENT);
3775 VMSTATE enmVmState = VMR3GetState(pVM);
3776 AssertLogRelMsgReturn( enmVmState == VMSTATE_CREATING
3777 || enmVmState == VMSTATE_LOADING,
3778 ("enmVmState=%d (%s)\n", enmVmState, VMR3GetStateName(enmVmState)),
3779 VERR_VM_INVALID_VM_STATE);
3780
3781 int rc = PGM_LOCK(pVM);
3782 AssertRCReturn(rc, rc);
3783
3784 PPGMREGMMIO2RANGE pFirstMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3785 if (pFirstMmio)
3786 {
3787 Assert(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK);
3788 if (!(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED))
3789 {
3790 /*
3791 * NOTE! Current implementation does not support multiple ranges.
3792 * Implement when there is a real world need and thus a testcase.
3793 */
3794 AssertLogRelMsgStmt(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK,
3795 ("%s: %#x\n", pFirstMmio->RamRange.pszDesc, pFirstMmio->fFlags),
3796 rc = VERR_NOT_SUPPORTED);
3797 if (RT_SUCCESS(rc))
3798 {
3799 /*
3800 * Make the change.
3801 */
3802 Log(("PGMR3PhysMmio2Reduce: %s changes from %RGp bytes (%RGp) to %RGp bytes.\n",
3803 pFirstMmio->RamRange.pszDesc, pFirstMmio->RamRange.cb, pFirstMmio->cbReal, cbRegion));
3804
3805 AssertLogRelMsgStmt(cbRegion <= pFirstMmio->cbReal,
3806 ("%s: cbRegion=%#RGp cbReal=%#RGp\n", pFirstMmio->RamRange.pszDesc, cbRegion, pFirstMmio->cbReal),
3807 rc = VERR_OUT_OF_RANGE);
3808 if (RT_SUCCESS(rc))
3809 {
3810 pFirstMmio->RamRange.cb = cbRegion;
3811 }
3812 }
3813 }
3814 else
3815 rc = VERR_WRONG_ORDER;
3816 }
3817 else
3818 rc = VERR_NOT_FOUND;
3819
3820 PGM_UNLOCK(pVM);
3821 return rc;
3822}
3823
3824
3825/**
3826 * Validates @a hMmio2, making sure it belongs to @a pDevIns.
3827 *
3828 * @returns VBox status code.
3829 * @param pVM The cross context VM structure.
3830 * @param pDevIns The device which allegedly owns @a hMmio2.
3831 * @param hMmio2 The handle to validate.
3832 */
3833VMMR3_INT_DECL(int) PGMR3PhysMmio2ValidateHandle(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2)
3834{
3835 /*
3836 * Validate input
3837 */
3838 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3839 AssertPtrReturn(pDevIns, VERR_INVALID_POINTER);
3840
3841 /*
3842 * Just do this the simple way. No need for locking as this is only taken at
3843 */
3844 PGM_LOCK_VOID(pVM);
3845 PPGMREGMMIO2RANGE pFirstMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3846 PGM_UNLOCK(pVM);
3847 AssertReturn(pFirstMmio, VERR_INVALID_HANDLE);
3848 AssertReturn(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK, VERR_INVALID_HANDLE);
3849 return VINF_SUCCESS;
3850}
3851
3852
3853/**
3854 * Gets the mapping address of an MMIO2 region.
3855 *
3856 * @returns Mapping address, NIL_RTGCPHYS if not mapped or invalid handle.
3857 *
3858 * @param pVM The cross context VM structure.
3859 * @param pDevIns The device owning the MMIO2 handle.
3860 * @param hMmio2 The region handle.
3861 */
3862VMMR3_INT_DECL(RTGCPHYS) PGMR3PhysMmio2GetMappingAddress(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2)
3863{
3864 AssertPtrReturn(pDevIns, NIL_RTGCPHYS);
3865
3866 PPGMREGMMIO2RANGE pFirstRegMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3867 AssertReturn(pFirstRegMmio, NIL_RTGCPHYS);
3868
3869 if (pFirstRegMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED)
3870 return pFirstRegMmio->RamRange.GCPhys;
3871 return NIL_RTGCPHYS;
3872}
3873
3874
3875/**
3876 * Worker for PGMR3PhysMmio2QueryAndResetDirtyBitmap.
3877 *
3878 * Called holding the PGM lock.
3879 */
3880static int pgmR3PhysMmio2QueryAndResetDirtyBitmapLocked(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2,
3881 void *pvBitmap, size_t cbBitmap)
3882{
3883 /*
3884 * Continue validation.
3885 */
3886 PPGMREGMMIO2RANGE pFirstRegMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3887 AssertReturn(pFirstRegMmio, VERR_INVALID_HANDLE);
3888 AssertReturn( (pFirstRegMmio->fFlags & (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK))
3889 == (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK),
3890 VERR_INVALID_FUNCTION);
3891 AssertReturn(pDevIns == pFirstRegMmio->pDevInsR3, VERR_NOT_OWNER);
3892
3893 RTGCPHYS cbTotal = 0;
3894 uint16_t fTotalDirty = 0;
3895 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio;;)
3896 {
3897 cbTotal += pCur->RamRange.cb; /* Not using cbReal here, because NEM is not in on the creating, only the mapping. */
3898 fTotalDirty |= pCur->fFlags;
3899 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3900 break;
3901 pCur = pCur->pNextR3;
3902 AssertPtrReturn(pCur, VERR_INTERNAL_ERROR_5);
3903 AssertReturn( (pCur->fFlags & (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK))
3904 == PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES,
3905 VERR_INTERNAL_ERROR_4);
3906 }
3907 size_t const cbTotalBitmap = RT_ALIGN_T(cbTotal, GUEST_PAGE_SIZE * 64, RTGCPHYS) / GUEST_PAGE_SIZE / 8;
3908
3909 if (cbBitmap)
3910 {
3911 AssertPtrReturn(pvBitmap, VERR_INVALID_POINTER);
3912 AssertReturn(RT_ALIGN_P(pvBitmap, sizeof(uint64_t)) == pvBitmap, VERR_INVALID_POINTER);
3913 AssertReturn(cbBitmap == cbTotalBitmap, VERR_INVALID_PARAMETER);
3914 }
3915
3916 /*
3917 * Do the work.
3918 */
3919 int rc = VINF_SUCCESS;
3920 if (pvBitmap)
3921 {
3922#ifdef VBOX_WITH_PGM_NEM_MODE
3923 if (pFirstRegMmio->pPhysHandlerR3 == NULL)
3924 {
3925/** @todo This does not integrate at all with --execute-all-in-iem, leaving the
3926 * screen blank when using it together with --driverless. Fixing this won't be
3927 * entirely easy as we take the PGM_PAGE_HNDL_PHYS_STATE_DISABLED page status to
3928 * mean a dirty page. */
3929 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_INTERNAL_ERROR_4);
3930 uint8_t *pbBitmap = (uint8_t *)pvBitmap;
3931 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
3932 {
3933 size_t const cbBitmapChunk = pCur->RamRange.cb / GUEST_PAGE_SIZE / 8;
3934 Assert((RTGCPHYS)cbBitmapChunk * GUEST_PAGE_SIZE * 8 == pCur->RamRange.cb);
3935 int rc2 = NEMR3PhysMmio2QueryAndResetDirtyBitmap(pVM, pCur->RamRange.GCPhys, pCur->RamRange.cb,
3936 pCur->RamRange.uNemRange, pbBitmap, cbBitmapChunk);
3937 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3938 rc = rc2;
3939 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3940 break;
3941 pbBitmap += pCur->RamRange.cb / GUEST_PAGE_SIZE / 8;
3942 }
3943 }
3944 else
3945#endif
3946 if (fTotalDirty & PGMREGMMIO2RANGE_F_IS_DIRTY)
3947 {
3948 if ( (pFirstRegMmio->fFlags & (PGMREGMMIO2RANGE_F_MAPPED | PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
3949 == (PGMREGMMIO2RANGE_F_MAPPED | PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
3950 {
3951 /*
3952 * Reset each chunk, gathering dirty bits.
3953 */
3954 RT_BZERO(pvBitmap, cbBitmap); /* simpler for now. */
3955 uint32_t iPageNo = 0;
3956 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
3957 {
3958 if (pCur->fFlags & PGMREGMMIO2RANGE_F_IS_DIRTY)
3959 {
3960 int rc2 = pgmHandlerPhysicalResetMmio2WithBitmap(pVM, pCur->RamRange.GCPhys, pvBitmap, iPageNo);
3961 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3962 rc = rc2;
3963 pCur->fFlags &= ~PGMREGMMIO2RANGE_F_IS_DIRTY;
3964 }
3965 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3966 break;
3967 iPageNo += pCur->RamRange.cb >> GUEST_PAGE_SHIFT;
3968 }
3969 }
3970 else
3971 {
3972 /*
3973 * If not mapped or tracking is disabled, we return the
3974 * PGMREGMMIO2RANGE_F_IS_DIRTY status for all pages. We cannot
3975 * get more accurate data than that after unmapping or disabling.
3976 */
3977 RT_BZERO(pvBitmap, cbBitmap);
3978 uint32_t iPageNo = 0;
3979 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
3980 {
3981 if (pCur->fFlags & PGMREGMMIO2RANGE_F_IS_DIRTY)
3982 {
3983 ASMBitSetRange(pvBitmap, iPageNo, iPageNo + (pCur->RamRange.cb >> GUEST_PAGE_SHIFT));
3984 pCur->fFlags &= ~PGMREGMMIO2RANGE_F_IS_DIRTY;
3985 }
3986 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3987 break;
3988 iPageNo += pCur->RamRange.cb >> GUEST_PAGE_SHIFT;
3989 }
3990 }
3991 }
3992 /*
3993 * No dirty chunks.
3994 */
3995 else
3996 RT_BZERO(pvBitmap, cbBitmap);
3997 }
3998 /*
3999 * No bitmap. Reset the region if tracking is currently enabled.
4000 */
4001 else if ( (pFirstRegMmio->fFlags & (PGMREGMMIO2RANGE_F_MAPPED | PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
4002 == (PGMREGMMIO2RANGE_F_MAPPED | PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
4003 {
4004#ifdef VBOX_WITH_PGM_NEM_MODE
4005 if (pFirstRegMmio->pPhysHandlerR3 == NULL)
4006 {
4007 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_INTERNAL_ERROR_4);
4008 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
4009 {
4010 int rc2 = NEMR3PhysMmio2QueryAndResetDirtyBitmap(pVM, pCur->RamRange.GCPhys, pCur->RamRange.cb,
4011 pCur->RamRange.uNemRange, NULL, 0);
4012 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
4013 rc = rc2;
4014 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
4015 break;
4016 }
4017 }
4018 else
4019#endif
4020 {
4021 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
4022 {
4023 pCur->fFlags &= ~PGMREGMMIO2RANGE_F_IS_DIRTY;
4024 int rc2 = PGMHandlerPhysicalReset(pVM, pCur->RamRange.GCPhys);
4025 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
4026 rc = rc2;
4027 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
4028 break;
4029 }
4030 }
4031 }
4032
4033 return rc;
4034}
4035
4036
4037/**
4038 * Queries the dirty page bitmap and resets the monitoring.
4039 *
4040 * The PGMPHYS_MMIO2_FLAGS_TRACK_DIRTY_PAGES flag must be specified when
4041 * creating the range for this to work.
4042 *
4043 * @returns VBox status code.
4044 * @retval VERR_INVALID_FUNCTION if not created using
4045 * PGMPHYS_MMIO2_FLAGS_TRACK_DIRTY_PAGES.
4046 * @param pVM The cross context VM structure.
4047 * @param pDevIns The device owning the MMIO2 handle.
4048 * @param hMmio2 The region handle.
4049 * @param pvBitmap The output bitmap. Must be 8-byte aligned. Ignored
4050 * when @a cbBitmap is zero.
4051 * @param cbBitmap The size of the bitmap. Must be the size of the whole
4052 * MMIO2 range, rounded up to the nearest 8 bytes.
4053 * When zero only a reset is done.
4054 */
4055VMMR3_INT_DECL(int) PGMR3PhysMmio2QueryAndResetDirtyBitmap(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2,
4056 void *pvBitmap, size_t cbBitmap)
4057{
4058 /*
4059 * Do some basic validation before grapping the PGM lock and continuing.
4060 */
4061 AssertPtrReturn(pDevIns, VERR_INVALID_POINTER);
4062 AssertReturn(RT_ALIGN_Z(cbBitmap, sizeof(uint64_t)) == cbBitmap, VERR_INVALID_PARAMETER);
4063 int rc = PGM_LOCK(pVM);
4064 if (RT_SUCCESS(rc))
4065 {
4066 STAM_PROFILE_START(&pVM->pgm.s.StatMmio2QueryAndResetDirtyBitmap, a);
4067 rc = pgmR3PhysMmio2QueryAndResetDirtyBitmapLocked(pVM, pDevIns, hMmio2, pvBitmap, cbBitmap);
4068 STAM_PROFILE_STOP(&pVM->pgm.s.StatMmio2QueryAndResetDirtyBitmap, a);
4069 PGM_UNLOCK(pVM);
4070 }
4071 return rc;
4072}
4073
4074
4075/**
4076 * Worker for PGMR3PhysMmio2ControlDirtyPageTracking
4077 *
4078 * Called owning the PGM lock.
4079 */
4080static int pgmR3PhysMmio2ControlDirtyPageTrackingLocked(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, bool fEnabled)
4081{
4082 /*
4083 * Continue validation.
4084 */
4085 PPGMREGMMIO2RANGE pFirstRegMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
4086 AssertReturn(pFirstRegMmio, VERR_INVALID_HANDLE);
4087 AssertReturn( (pFirstRegMmio->fFlags & (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK))
4088 == (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK)
4089 , VERR_INVALID_FUNCTION);
4090 AssertReturn(pDevIns == pFirstRegMmio->pDevInsR3, VERR_NOT_OWNER);
4091
4092#ifdef VBOX_WITH_PGM_NEM_MODE
4093 /*
4094 * This is a nop if NEM is responsible for doing the tracking, we simply
4095 * leave the tracking on all the time there.
4096 */
4097 if (pFirstRegMmio->pPhysHandlerR3 == NULL)
4098 {
4099 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_INTERNAL_ERROR_4);
4100 return VINF_SUCCESS;
4101 }
4102#endif
4103
4104 /*
4105 * Anyting needing doing?
4106 */
4107 if (fEnabled != RT_BOOL(pFirstRegMmio->fFlags & PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
4108 {
4109 LogFlowFunc(("fEnabled=%RTbool %s\n", fEnabled, pFirstRegMmio->RamRange.pszDesc));
4110
4111 /*
4112 * Update the PGMREGMMIO2RANGE_F_TRACKING_ENABLED flag.
4113 */
4114 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio;;)
4115 {
4116 if (fEnabled)
4117 pCur->fFlags |= PGMREGMMIO2RANGE_F_TRACKING_ENABLED;
4118 else
4119 pCur->fFlags &= ~PGMREGMMIO2RANGE_F_TRACKING_ENABLED;
4120 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
4121 break;
4122 pCur = pCur->pNextR3;
4123 AssertPtrReturn(pCur, VERR_INTERNAL_ERROR_5);
4124 AssertReturn( (pCur->fFlags & (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK))
4125 == PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES
4126 , VERR_INTERNAL_ERROR_4);
4127 }
4128
4129 /*
4130 * Enable/disable handlers if currently mapped.
4131 *
4132 * We ignore status codes here as we've already changed the flags and
4133 * returning a failure status now would be confusing. Besides, the two
4134 * functions will continue past failures. As argued in the mapping code,
4135 * it's in the release log.
4136 */
4137 if (pFirstRegMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED)
4138 {
4139 if (fEnabled)
4140 pgmR3PhysMmio2EnableDirtyPageTracing(pVM, pFirstRegMmio);
4141 else
4142 pgmR3PhysMmio2DisableDirtyPageTracing(pVM, pFirstRegMmio);
4143 }
4144 }
4145 else
4146 LogFlowFunc(("fEnabled=%RTbool %s - no change\n", fEnabled, pFirstRegMmio->RamRange.pszDesc));
4147
4148 return VINF_SUCCESS;
4149}
4150
4151
4152/**
4153 * Controls the dirty page tracking for an MMIO2 range.
4154 *
4155 * @returns VBox status code.
4156 * @param pVM The cross context VM structure.
4157 * @param pDevIns The device owning the MMIO2 memory.
4158 * @param hMmio2 The handle of the region.
4159 * @param fEnabled The new tracking state.
4160 */
4161VMMR3_INT_DECL(int) PGMR3PhysMmio2ControlDirtyPageTracking(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, bool fEnabled)
4162{
4163 /*
4164 * Do some basic validation before grapping the PGM lock and continuing.
4165 */
4166 AssertPtrReturn(pDevIns, VERR_INVALID_POINTER);
4167 int rc = PGM_LOCK(pVM);
4168 if (RT_SUCCESS(rc))
4169 {
4170 rc = pgmR3PhysMmio2ControlDirtyPageTrackingLocked(pVM, pDevIns, hMmio2, fEnabled);
4171 PGM_UNLOCK(pVM);
4172 }
4173 return rc;
4174}
4175
4176
4177/**
4178 * Changes the region number of an MMIO2 region.
4179 *
4180 * This is only for dealing with save state issues, nothing else.
4181 *
4182 * @return VBox status code.
4183 *
4184 * @param pVM The cross context VM structure.
4185 * @param pDevIns The device owning the MMIO2 memory.
4186 * @param hMmio2 The handle of the region.
4187 * @param iNewRegion The new region index.
4188 *
4189 * @thread EMT(0)
4190 * @sa @bugref{9359}
4191 */
4192VMMR3_INT_DECL(int) PGMR3PhysMmio2ChangeRegionNo(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, uint32_t iNewRegion)
4193{
4194 /*
4195 * Validate input.
4196 */
4197 VM_ASSERT_EMT0_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
4198 VM_ASSERT_STATE_RETURN(pVM, VMSTATE_LOADING, VERR_VM_INVALID_VM_STATE);
4199 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
4200 AssertReturn(hMmio2 != NIL_PGMMMIO2HANDLE, VERR_INVALID_HANDLE);
4201 AssertReturn(iNewRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
4202
4203 AssertReturn(pVM->enmVMState == VMSTATE_LOADING, VERR_INVALID_STATE);
4204
4205 int rc = PGM_LOCK(pVM);
4206 AssertRCReturn(rc, rc);
4207
4208 PPGMREGMMIO2RANGE pFirstRegMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
4209 AssertReturnStmt(pFirstRegMmio, PGM_UNLOCK(pVM), VERR_NOT_FOUND);
4210 AssertReturnStmt(pgmR3PhysMmio2Find(pVM, pDevIns, pFirstRegMmio->iSubDev, iNewRegion, NIL_PGMMMIO2HANDLE) == NULL,
4211 PGM_UNLOCK(pVM), VERR_RESOURCE_IN_USE);
4212
4213 /*
4214 * Make the change.
4215 */
4216 pFirstRegMmio->iRegion = (uint8_t)iNewRegion;
4217
4218 PGM_UNLOCK(pVM);
4219 return VINF_SUCCESS;
4220}
4221
4222
4223
4224/*********************************************************************************************************************************
4225* ROM *
4226*********************************************************************************************************************************/
4227
4228/**
4229 * Worker for PGMR3PhysRomRegister.
4230 *
4231 * This is here to simplify lock management, i.e. the caller does all the
4232 * locking and we can simply return without needing to remember to unlock
4233 * anything first.
4234 *
4235 * @returns VBox status code.
4236 * @param pVM The cross context VM structure.
4237 * @param pDevIns The device instance owning the ROM.
4238 * @param GCPhys First physical address in the range.
4239 * Must be page aligned!
4240 * @param cb The size of the range (in bytes).
4241 * Must be page aligned!
4242 * @param pvBinary Pointer to the binary data backing the ROM image.
4243 * @param cbBinary The size of the binary data pvBinary points to.
4244 * This must be less or equal to @a cb.
4245 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAGS_SHADOWED
4246 * and/or PGMPHYS_ROM_FLAGS_PERMANENT_BINARY.
4247 * @param pszDesc Pointer to description string. This must not be freed.
4248 */
4249static int pgmR3PhysRomRegisterLocked(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
4250 const void *pvBinary, uint32_t cbBinary, uint8_t fFlags, const char *pszDesc)
4251{
4252 /*
4253 * Validate input.
4254 */
4255 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
4256 AssertReturn(RT_ALIGN_T(GCPhys, GUEST_PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
4257 AssertReturn(RT_ALIGN_T(cb, GUEST_PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
4258 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
4259 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
4260 AssertPtrReturn(pvBinary, VERR_INVALID_PARAMETER);
4261 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
4262 AssertReturn(!(fFlags & ~PGMPHYS_ROM_FLAGS_VALID_MASK), VERR_INVALID_PARAMETER);
4263 VM_ASSERT_STATE_RETURN(pVM, VMSTATE_CREATING, VERR_VM_INVALID_VM_STATE);
4264
4265 const uint32_t cGuestPages = cb >> GUEST_PAGE_SHIFT;
4266#ifdef VBOX_WITH_PGM_NEM_MODE
4267 const uint32_t cHostPages = RT_ALIGN_T(cb, HOST_PAGE_SIZE, RTGCPHYS) >> HOST_PAGE_SHIFT;
4268#endif
4269
4270 /*
4271 * Find the ROM location in the ROM list first.
4272 */
4273 PPGMROMRANGE pRomPrev = NULL;
4274 PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3;
4275 while (pRom && GCPhysLast >= pRom->GCPhys)
4276 {
4277 if ( GCPhys <= pRom->GCPhysLast
4278 && GCPhysLast >= pRom->GCPhys)
4279 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
4280 GCPhys, GCPhysLast, pszDesc,
4281 pRom->GCPhys, pRom->GCPhysLast, pRom->pszDesc),
4282 VERR_PGM_RAM_CONFLICT);
4283 /* next */
4284 pRomPrev = pRom;
4285 pRom = pRom->pNextR3;
4286 }
4287
4288 /*
4289 * Find the RAM location and check for conflicts.
4290 *
4291 * Conflict detection is a bit different than for RAM registration since a
4292 * ROM can be located within a RAM range. So, what we have to check for is
4293 * other memory types (other than RAM that is) and that we don't span more
4294 * than one RAM range (lazy).
4295 */
4296 bool fRamExists = false;
4297 PPGMRAMRANGE pRamPrev = NULL;
4298 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
4299 while (pRam && GCPhysLast >= pRam->GCPhys)
4300 {
4301 if ( GCPhys <= pRam->GCPhysLast
4302 && GCPhysLast >= pRam->GCPhys)
4303 {
4304 /* completely within? */
4305 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
4306 && GCPhysLast <= pRam->GCPhysLast,
4307 ("%RGp-%RGp (%s) falls partly outside %RGp-%RGp (%s)\n",
4308 GCPhys, GCPhysLast, pszDesc,
4309 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
4310 VERR_PGM_RAM_CONFLICT);
4311 fRamExists = true;
4312 break;
4313 }
4314
4315 /* next */
4316 pRamPrev = pRam;
4317 pRam = pRam->pNextR3;
4318 }
4319 if (fRamExists)
4320 {
4321 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
4322 uint32_t cPagesLeft = cGuestPages;
4323 while (cPagesLeft-- > 0)
4324 {
4325 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
4326 ("%RGp (%R[pgmpage]) isn't a RAM page - registering %RGp-%RGp (%s).\n",
4327 pRam->GCPhys + ((RTGCPHYS)(uintptr_t)(pPage - &pRam->aPages[0]) << GUEST_PAGE_SHIFT),
4328 pPage, GCPhys, GCPhysLast, pszDesc), VERR_PGM_RAM_CONFLICT);
4329 Assert(PGM_PAGE_IS_ZERO(pPage) || PGM_IS_IN_NEM_MODE(pVM));
4330 pPage++;
4331 }
4332 }
4333
4334 /*
4335 * Update the base memory reservation if necessary.
4336 */
4337 uint32_t cExtraBaseCost = fRamExists ? 0 : cGuestPages;
4338 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4339 cExtraBaseCost += cGuestPages;
4340 if (cExtraBaseCost)
4341 {
4342 int rc = MMR3IncreaseBaseReservation(pVM, cExtraBaseCost);
4343 if (RT_FAILURE(rc))
4344 return rc;
4345 }
4346
4347#ifdef VBOX_WITH_NATIVE_NEM
4348 /*
4349 * Early NEM notification before we've made any changes or anything.
4350 */
4351 uint32_t const fNemNotify = (fRamExists ? NEM_NOTIFY_PHYS_ROM_F_REPLACE : 0)
4352 | (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED ? NEM_NOTIFY_PHYS_ROM_F_SHADOW : 0);
4353 uint8_t u2NemState = UINT8_MAX;
4354 uint32_t uNemRange = 0;
4355 if (VM_IS_NEM_ENABLED(pVM))
4356 {
4357 int rc = NEMR3NotifyPhysRomRegisterEarly(pVM, GCPhys, cGuestPages << GUEST_PAGE_SHIFT,
4358 fRamExists ? PGM_RAMRANGE_CALC_PAGE_R3PTR(pRam, GCPhys) : NULL,
4359 fNemNotify, &u2NemState, fRamExists ? &pRam->uNemRange : &uNemRange);
4360 AssertLogRelRCReturn(rc, rc);
4361 }
4362#endif
4363
4364 /*
4365 * Allocate memory for the virgin copy of the RAM. In simplified memory mode,
4366 * we allocate memory for any ad-hoc RAM range and for shadow pages.
4367 */
4368 PGMMALLOCATEPAGESREQ pReq = NULL;
4369#ifdef VBOX_WITH_PGM_NEM_MODE
4370 void *pvRam = NULL;
4371 void *pvAlt = NULL;
4372 if (pVM->pgm.s.fNemMode)
4373 {
4374 if (!fRamExists)
4375 {
4376 int rc = SUPR3PageAlloc(cHostPages, 0, &pvRam);
4377 if (RT_FAILURE(rc))
4378 return rc;
4379 }
4380 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4381 {
4382 int rc = SUPR3PageAlloc(cHostPages, 0, &pvAlt);
4383 if (RT_FAILURE(rc))
4384 {
4385 if (pvRam)
4386 SUPR3PageFree(pvRam, cHostPages);
4387 return rc;
4388 }
4389 }
4390 }
4391 else
4392#endif
4393 {
4394 int rc = GMMR3AllocatePagesPrepare(pVM, &pReq, cGuestPages, GMMACCOUNT_BASE);
4395 AssertRCReturn(rc, rc);
4396
4397 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++)
4398 {
4399 pReq->aPages[iPage].HCPhysGCPhys = GCPhys + (iPage << GUEST_PAGE_SHIFT);
4400 pReq->aPages[iPage].fZeroed = false;
4401 pReq->aPages[iPage].idPage = NIL_GMM_PAGEID;
4402 pReq->aPages[iPage].idSharedPage = NIL_GMM_PAGEID;
4403 }
4404
4405 rc = GMMR3AllocatePagesPerform(pVM, pReq);
4406 if (RT_FAILURE(rc))
4407 {
4408 GMMR3AllocatePagesCleanup(pReq);
4409 return rc;
4410 }
4411 }
4412
4413 /*
4414 * Allocate the new ROM range and RAM range (if necessary).
4415 */
4416 PPGMROMRANGE pRomNew = NULL;
4417 RTR0PTR pRomNewR0 = NIL_RTR0PTR;
4418 size_t const cbRomRange = RT_ALIGN_Z(RT_UOFFSETOF_DYN(PGMROMRANGE, aPages[cGuestPages]), 128);
4419 size_t const cbRamRange = fRamExists ? 0 : RT_UOFFSETOF_DYN(PGMROMRANGE, aPages[cGuestPages]);
4420 size_t const cRangePages = RT_ALIGN_Z(cbRomRange + cbRamRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
4421 int rc = SUPR3PageAllocEx(cRangePages, 0 /*fFlags*/, (void **)&pRomNew, &pRomNewR0, NULL /*paPages*/);
4422 if (RT_SUCCESS(rc))
4423 {
4424
4425 /*
4426 * Initialize and insert the RAM range (if required).
4427 */
4428 PPGMRAMRANGE pRamNew;
4429 uint32_t const idxFirstRamPage = fRamExists ? (GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT : 0;
4430 PPGMROMPAGE pRomPage = &pRomNew->aPages[0];
4431 if (!fRamExists)
4432 {
4433 /* New RAM range. */
4434 pRamNew = (PPGMRAMRANGE)((uintptr_t)pRomNew + cbRomRange);
4435 pRamNew->pSelfR0 = !pRomNewR0 ? NIL_RTR0PTR : pRomNewR0 + cbRomRange;
4436 pRamNew->GCPhys = GCPhys;
4437 pRamNew->GCPhysLast = GCPhysLast;
4438 pRamNew->cb = cb;
4439 pRamNew->pszDesc = pszDesc;
4440 pRamNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_ROM;
4441 pRamNew->pvR3 = NULL;
4442 pRamNew->paLSPages = NULL;
4443#ifdef VBOX_WITH_NATIVE_NEM
4444 pRamNew->uNemRange = uNemRange;
4445#endif
4446
4447 PPGMPAGE pRamPage = &pRamNew->aPages[idxFirstRamPage];
4448#ifdef VBOX_WITH_PGM_NEM_MODE
4449 if (pVM->pgm.s.fNemMode)
4450 {
4451 AssertPtr(pvRam); Assert(pReq == NULL);
4452 pRamNew->pvR3 = pvRam;
4453 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4454 {
4455 PGM_PAGE_INIT(pRamPage, UINT64_C(0x0000fffffffff000), NIL_GMM_PAGEID,
4456 PGMPAGETYPE_ROM, PGM_PAGE_STATE_ALLOCATED);
4457 pRomPage->Virgin = *pRamPage;
4458 }
4459 }
4460 else
4461#endif
4462 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4463 {
4464 PGM_PAGE_INIT(pRamPage,
4465 pReq->aPages[iPage].HCPhysGCPhys,
4466 pReq->aPages[iPage].idPage,
4467 PGMPAGETYPE_ROM,
4468 PGM_PAGE_STATE_ALLOCATED);
4469
4470 pRomPage->Virgin = *pRamPage;
4471 }
4472
4473 pVM->pgm.s.cAllPages += cGuestPages;
4474 pVM->pgm.s.cPrivatePages += cGuestPages;
4475 pgmR3PhysLinkRamRange(pVM, pRamNew, pRamPrev);
4476 }
4477 else
4478 {
4479 /* Existing RAM range. */
4480 PPGMPAGE pRamPage = &pRam->aPages[idxFirstRamPage];
4481#ifdef VBOX_WITH_PGM_NEM_MODE
4482 if (pVM->pgm.s.fNemMode)
4483 {
4484 Assert(pvRam == NULL); Assert(pReq == NULL);
4485 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4486 {
4487 Assert(PGM_PAGE_GET_HCPHYS(pRamPage) == UINT64_C(0x0000fffffffff000));
4488 Assert(PGM_PAGE_GET_PAGEID(pRamPage) == NIL_GMM_PAGEID);
4489 Assert(PGM_PAGE_GET_STATE(pRamPage) == PGM_PAGE_STATE_ALLOCATED);
4490 PGM_PAGE_SET_TYPE(pVM, pRamPage, PGMPAGETYPE_ROM);
4491 PGM_PAGE_SET_STATE(pVM, pRamPage, PGM_PAGE_STATE_ALLOCATED);
4492 PGM_PAGE_SET_PDE_TYPE(pVM, pRamPage, PGM_PAGE_PDE_TYPE_DONTCARE);
4493 PGM_PAGE_SET_PTE_INDEX(pVM, pRamPage, 0);
4494 PGM_PAGE_SET_TRACKING(pVM, pRamPage, 0);
4495
4496 pRomPage->Virgin = *pRamPage;
4497 }
4498 }
4499 else
4500#endif
4501 {
4502 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4503 {
4504 PGM_PAGE_SET_TYPE(pVM, pRamPage, PGMPAGETYPE_ROM);
4505 PGM_PAGE_SET_HCPHYS(pVM, pRamPage, pReq->aPages[iPage].HCPhysGCPhys);
4506 PGM_PAGE_SET_STATE(pVM, pRamPage, PGM_PAGE_STATE_ALLOCATED);
4507 PGM_PAGE_SET_PAGEID(pVM, pRamPage, pReq->aPages[iPage].idPage);
4508 PGM_PAGE_SET_PDE_TYPE(pVM, pRamPage, PGM_PAGE_PDE_TYPE_DONTCARE);
4509 PGM_PAGE_SET_PTE_INDEX(pVM, pRamPage, 0);
4510 PGM_PAGE_SET_TRACKING(pVM, pRamPage, 0);
4511
4512 pRomPage->Virgin = *pRamPage;
4513 }
4514 pVM->pgm.s.cZeroPages -= cGuestPages;
4515 pVM->pgm.s.cPrivatePages += cGuestPages;
4516 }
4517 pRamNew = pRam;
4518 }
4519
4520#ifdef VBOX_WITH_NATIVE_NEM
4521 /* Set the NEM state of the pages if needed. */
4522 if (u2NemState != UINT8_MAX)
4523 pgmPhysSetNemStateForPages(&pRamNew->aPages[idxFirstRamPage], cGuestPages, u2NemState);
4524#endif
4525
4526 /* Flush physical page map TLB. */
4527 pgmPhysInvalidatePageMapTLB(pVM);
4528
4529 /*
4530 * Register the ROM access handler.
4531 */
4532 rc = PGMHandlerPhysicalRegister(pVM, GCPhys, GCPhysLast, pVM->pgm.s.hRomPhysHandlerType, GCPhys, pszDesc);
4533 if (RT_SUCCESS(rc))
4534 {
4535 /*
4536 * Copy the image over to the virgin pages.
4537 * This must be done after linking in the RAM range.
4538 */
4539 size_t cbBinaryLeft = cbBinary;
4540 PPGMPAGE pRamPage = &pRamNew->aPages[idxFirstRamPage];
4541 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++)
4542 {
4543 void *pvDstPage;
4544 rc = pgmPhysPageMap(pVM, pRamPage, GCPhys + (iPage << GUEST_PAGE_SHIFT), &pvDstPage);
4545 if (RT_FAILURE(rc))
4546 {
4547 VMSetError(pVM, rc, RT_SRC_POS, "Failed to map virgin ROM page at %RGp", GCPhys);
4548 break;
4549 }
4550 if (cbBinaryLeft >= GUEST_PAGE_SIZE)
4551 {
4552 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << GUEST_PAGE_SHIFT), GUEST_PAGE_SIZE);
4553 cbBinaryLeft -= GUEST_PAGE_SIZE;
4554 }
4555 else
4556 {
4557 RT_BZERO(pvDstPage, GUEST_PAGE_SIZE); /* (shouldn't be necessary, but can't hurt either) */
4558 if (cbBinaryLeft > 0)
4559 {
4560 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << GUEST_PAGE_SHIFT), cbBinaryLeft);
4561 cbBinaryLeft = 0;
4562 }
4563 }
4564 }
4565 if (RT_SUCCESS(rc))
4566 {
4567 /*
4568 * Initialize the ROM range.
4569 * Note that the Virgin member of the pages has already been initialized above.
4570 */
4571 pRomNew->pSelfR0 = pRomNewR0;
4572 pRomNew->GCPhys = GCPhys;
4573 pRomNew->GCPhysLast = GCPhysLast;
4574 pRomNew->cb = cb;
4575 pRomNew->fFlags = fFlags;
4576 pRomNew->idSavedState = UINT8_MAX;
4577 pRomNew->cbOriginal = cbBinary;
4578 pRomNew->pszDesc = pszDesc;
4579#ifdef VBOX_WITH_PGM_NEM_MODE
4580 pRomNew->pbR3Alternate = (uint8_t *)pvAlt;
4581#endif
4582 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY
4583 ? pvBinary : RTMemDup(pvBinary, cbBinary);
4584 if (pRomNew->pvOriginal)
4585 {
4586 for (unsigned iPage = 0; iPage < cGuestPages; iPage++)
4587 {
4588 PPGMROMPAGE pPage = &pRomNew->aPages[iPage];
4589 pPage->enmProt = PGMROMPROT_READ_ROM_WRITE_IGNORE;
4590#ifdef VBOX_WITH_PGM_NEM_MODE
4591 if (pVM->pgm.s.fNemMode)
4592 PGM_PAGE_INIT(&pPage->Shadow, UINT64_C(0x0000fffffffff000), NIL_GMM_PAGEID,
4593 PGMPAGETYPE_ROM_SHADOW, PGM_PAGE_STATE_ALLOCATED);
4594 else
4595#endif
4596 PGM_PAGE_INIT_ZERO(&pPage->Shadow, pVM, PGMPAGETYPE_ROM_SHADOW);
4597 }
4598
4599 /* update the page count stats for the shadow pages. */
4600 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4601 {
4602#ifdef VBOX_WITH_PGM_NEM_MODE
4603 if (pVM->pgm.s.fNemMode)
4604 pVM->pgm.s.cPrivatePages += cGuestPages;
4605 else
4606#endif
4607 pVM->pgm.s.cZeroPages += cGuestPages;
4608 pVM->pgm.s.cAllPages += cGuestPages;
4609 }
4610
4611 /*
4612 * Insert the ROM range, tell REM and return successfully.
4613 */
4614 pRomNew->pNextR3 = pRom;
4615 pRomNew->pNextR0 = pRom ? pRom->pSelfR0 : NIL_RTR0PTR;
4616
4617 if (pRomPrev)
4618 {
4619 pRomPrev->pNextR3 = pRomNew;
4620 pRomPrev->pNextR0 = pRomNew->pSelfR0;
4621 }
4622 else
4623 {
4624 pVM->pgm.s.pRomRangesR3 = pRomNew;
4625 pVM->pgm.s.pRomRangesR0 = pRomNew->pSelfR0;
4626 }
4627
4628 pgmPhysInvalidatePageMapTLB(pVM);
4629#ifdef VBOX_WITH_PGM_NEM_MODE
4630 if (!pVM->pgm.s.fNemMode)
4631#endif
4632 GMMR3AllocatePagesCleanup(pReq);
4633
4634#ifdef VBOX_WITH_NATIVE_NEM
4635 /*
4636 * Notify NEM again.
4637 */
4638 if (VM_IS_NEM_ENABLED(pVM))
4639 {
4640 u2NemState = UINT8_MAX;
4641 rc = NEMR3NotifyPhysRomRegisterLate(pVM, GCPhys, cb, PGM_RAMRANGE_CALC_PAGE_R3PTR(pRamNew, GCPhys),
4642 fNemNotify, &u2NemState,
4643 fRamExists ? &pRam->uNemRange : &pRamNew->uNemRange);
4644 if (u2NemState != UINT8_MAX)
4645 pgmPhysSetNemStateForPages(&pRamNew->aPages[idxFirstRamPage], cGuestPages, u2NemState);
4646 if (RT_SUCCESS(rc))
4647 return rc;
4648 }
4649 else
4650#endif
4651 return rc;
4652
4653 /*
4654 * bail out
4655 */
4656#ifdef VBOX_WITH_NATIVE_NEM
4657 /* unlink */
4658 if (pRomPrev)
4659 {
4660 pRomPrev->pNextR3 = pRom;
4661 pRomPrev->pNextR0 = pRom ? pRom->pSelfR0 : NIL_RTR0PTR;
4662 }
4663 else
4664 {
4665 pVM->pgm.s.pRomRangesR3 = pRom;
4666 pVM->pgm.s.pRomRangesR0 = pRom ? pRom->pSelfR0 : NIL_RTR0PTR;
4667 }
4668
4669 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4670 {
4671# ifdef VBOX_WITH_PGM_NEM_MODE
4672 if (pVM->pgm.s.fNemMode)
4673 pVM->pgm.s.cPrivatePages -= cGuestPages;
4674 else
4675# endif
4676 pVM->pgm.s.cZeroPages -= cGuestPages;
4677 pVM->pgm.s.cAllPages -= cGuestPages;
4678 }
4679#endif
4680 }
4681 else
4682 rc = VERR_NO_MEMORY;
4683 }
4684
4685 int rc2 = PGMHandlerPhysicalDeregister(pVM, GCPhys);
4686 AssertRC(rc2);
4687 }
4688
4689 if (!fRamExists)
4690 pgmR3PhysUnlinkRamRange2(pVM, pRamNew, pRamPrev);
4691 else
4692 {
4693 PPGMPAGE pRamPage = &pRam->aPages[idxFirstRamPage];
4694#ifdef VBOX_WITH_PGM_NEM_MODE
4695 if (pVM->pgm.s.fNemMode)
4696 {
4697 Assert(pvRam == NULL); Assert(pReq == NULL);
4698 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4699 {
4700 Assert(PGM_PAGE_GET_HCPHYS(pRamPage) == UINT64_C(0x0000fffffffff000));
4701 Assert(PGM_PAGE_GET_PAGEID(pRamPage) == NIL_GMM_PAGEID);
4702 Assert(PGM_PAGE_GET_STATE(pRamPage) == PGM_PAGE_STATE_ALLOCATED);
4703 PGM_PAGE_SET_TYPE(pVM, pRamPage, PGMPAGETYPE_RAM);
4704 PGM_PAGE_SET_STATE(pVM, pRamPage, PGM_PAGE_STATE_ALLOCATED);
4705 }
4706 }
4707 else
4708#endif
4709 {
4710 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++)
4711 PGM_PAGE_INIT_ZERO(pRamPage, pVM, PGMPAGETYPE_RAM);
4712 pVM->pgm.s.cZeroPages += cGuestPages;
4713 pVM->pgm.s.cPrivatePages -= cGuestPages;
4714 }
4715 }
4716
4717 SUPR3PageFreeEx(pRomNew, cRangePages);
4718 }
4719
4720 /** @todo Purge the mapping cache or something... */
4721#ifdef VBOX_WITH_PGM_NEM_MODE
4722 if (pVM->pgm.s.fNemMode)
4723 {
4724 Assert(!pReq);
4725 if (pvRam)
4726 SUPR3PageFree(pvRam, cHostPages);
4727 if (pvAlt)
4728 SUPR3PageFree(pvAlt, cHostPages);
4729 }
4730 else
4731#endif
4732 {
4733 GMMR3FreeAllocatedPages(pVM, pReq);
4734 GMMR3AllocatePagesCleanup(pReq);
4735 }
4736 return rc;
4737}
4738
4739
4740/**
4741 * Registers a ROM image.
4742 *
4743 * Shadowed ROM images requires double the amount of backing memory, so,
4744 * don't use that unless you have to. Shadowing of ROM images is process
4745 * where we can select where the reads go and where the writes go. On real
4746 * hardware the chipset provides means to configure this. We provide
4747 * PGMR3PhysProtectROM() for this purpose.
4748 *
4749 * A read-only copy of the ROM image will always be kept around while we
4750 * will allocate RAM pages for the changes on demand (unless all memory
4751 * is configured to be preallocated).
4752 *
4753 * @returns VBox status code.
4754 * @param pVM The cross context VM structure.
4755 * @param pDevIns The device instance owning the ROM.
4756 * @param GCPhys First physical address in the range.
4757 * Must be page aligned!
4758 * @param cb The size of the range (in bytes).
4759 * Must be page aligned!
4760 * @param pvBinary Pointer to the binary data backing the ROM image.
4761 * @param cbBinary The size of the binary data pvBinary points to.
4762 * This must be less or equal to @a cb.
4763 * @param fFlags Mask of flags, PGMPHYS_ROM_FLAGS_XXX.
4764 * @param pszDesc Pointer to description string. This must not be freed.
4765 *
4766 * @remark There is no way to remove the rom, automatically on device cleanup or
4767 * manually from the device yet. This isn't difficult in any way, it's
4768 * just not something we expect to be necessary for a while.
4769 */
4770VMMR3DECL(int) PGMR3PhysRomRegister(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
4771 const void *pvBinary, uint32_t cbBinary, uint8_t fFlags, const char *pszDesc)
4772{
4773 Log(("PGMR3PhysRomRegister: pDevIns=%p GCPhys=%RGp(-%RGp) cb=%RGp pvBinary=%p cbBinary=%#x fFlags=%#x pszDesc=%s\n",
4774 pDevIns, GCPhys, GCPhys + cb, cb, pvBinary, cbBinary, fFlags, pszDesc));
4775 PGM_LOCK_VOID(pVM);
4776 int rc = pgmR3PhysRomRegisterLocked(pVM, pDevIns, GCPhys, cb, pvBinary, cbBinary, fFlags, pszDesc);
4777 PGM_UNLOCK(pVM);
4778 return rc;
4779}
4780
4781
4782/**
4783 * Called by PGMR3MemSetup to reset the shadow, switch to the virgin, and verify
4784 * that the virgin part is untouched.
4785 *
4786 * This is done after the normal memory has been cleared.
4787 *
4788 * ASSUMES that the caller owns the PGM lock.
4789 *
4790 * @param pVM The cross context VM structure.
4791 */
4792int pgmR3PhysRomReset(PVM pVM)
4793{
4794 PGM_LOCK_ASSERT_OWNER(pVM);
4795 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4796 {
4797 const uint32_t cGuestPages = pRom->cb >> GUEST_PAGE_SHIFT;
4798
4799 if (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4800 {
4801 /*
4802 * Reset the physical handler.
4803 */
4804 int rc = PGMR3PhysRomProtect(pVM, pRom->GCPhys, pRom->cb, PGMROMPROT_READ_ROM_WRITE_IGNORE);
4805 AssertRCReturn(rc, rc);
4806
4807 /*
4808 * What we do with the shadow pages depends on the memory
4809 * preallocation option. If not enabled, we'll just throw
4810 * out all the dirty pages and replace them by the zero page.
4811 */
4812#ifdef VBOX_WITH_PGM_NEM_MODE
4813 if (pVM->pgm.s.fNemMode)
4814 {
4815 /* Clear all the shadow pages (currently using alternate backing). */
4816 RT_BZERO(pRom->pbR3Alternate, pRom->cb);
4817 }
4818 else
4819#endif
4820 if (!pVM->pgm.s.fRamPreAlloc)
4821 {
4822 /* Free the dirty pages. */
4823 uint32_t cPendingPages = 0;
4824 PGMMFREEPAGESREQ pReq;
4825 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
4826 AssertRCReturn(rc, rc);
4827
4828 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++)
4829 if ( !PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow)
4830 && !PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow))
4831 {
4832 Assert(PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) == PGM_PAGE_STATE_ALLOCATED);
4833 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, &pRom->aPages[iPage].Shadow,
4834 pRom->GCPhys + (iPage << GUEST_PAGE_SHIFT),
4835 (PGMPAGETYPE)PGM_PAGE_GET_TYPE(&pRom->aPages[iPage].Shadow));
4836 AssertLogRelRCReturn(rc, rc);
4837 }
4838
4839 if (cPendingPages)
4840 {
4841 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
4842 AssertLogRelRCReturn(rc, rc);
4843 }
4844 GMMR3FreePagesCleanup(pReq);
4845 }
4846 else
4847 {
4848 /* clear all the shadow pages. */
4849 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++)
4850 {
4851 if (PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow))
4852 continue;
4853 Assert(!PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow));
4854 void *pvDstPage;
4855 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << GUEST_PAGE_SHIFT);
4856 rc = pgmPhysPageMakeWritableAndMap(pVM, &pRom->aPages[iPage].Shadow, GCPhys, &pvDstPage);
4857 if (RT_FAILURE(rc))
4858 break;
4859 RT_BZERO(pvDstPage, GUEST_PAGE_SIZE);
4860 }
4861 AssertRCReturn(rc, rc);
4862 }
4863 }
4864
4865 /*
4866 * Restore the original ROM pages after a saved state load.
4867 * Also, in strict builds check that ROM pages remain unmodified.
4868 */
4869#ifndef VBOX_STRICT
4870 if (pVM->pgm.s.fRestoreRomPagesOnReset)
4871#endif
4872 {
4873 size_t cbSrcLeft = pRom->cbOriginal;
4874 uint8_t const *pbSrcPage = (uint8_t const *)pRom->pvOriginal;
4875 uint32_t cRestored = 0;
4876 for (uint32_t iPage = 0; iPage < cGuestPages && cbSrcLeft > 0; iPage++, pbSrcPage += GUEST_PAGE_SIZE)
4877 {
4878 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << GUEST_PAGE_SHIFT);
4879 PPGMPAGE const pPage = pgmPhysGetPage(pVM, GCPhys);
4880 void const *pvDstPage = NULL;
4881 int rc = pgmPhysPageMapReadOnly(pVM, pPage, GCPhys, &pvDstPage);
4882 if (RT_FAILURE(rc))
4883 break;
4884
4885 if (memcmp(pvDstPage, pbSrcPage, RT_MIN(cbSrcLeft, GUEST_PAGE_SIZE)))
4886 {
4887 if (pVM->pgm.s.fRestoreRomPagesOnReset)
4888 {
4889 void *pvDstPageW = NULL;
4890 rc = pgmPhysPageMap(pVM, pPage, GCPhys, &pvDstPageW);
4891 AssertLogRelRCReturn(rc, rc);
4892 memcpy(pvDstPageW, pbSrcPage, RT_MIN(cbSrcLeft, GUEST_PAGE_SIZE));
4893 cRestored++;
4894 }
4895 else
4896 LogRel(("pgmR3PhysRomReset: %RGp: ROM page changed (%s)\n", GCPhys, pRom->pszDesc));
4897 }
4898 cbSrcLeft -= RT_MIN(cbSrcLeft, GUEST_PAGE_SIZE);
4899 }
4900 if (cRestored > 0)
4901 LogRel(("PGM: ROM \"%s\": Reloaded %u of %u pages.\n", pRom->pszDesc, cRestored, cGuestPages));
4902 }
4903 }
4904
4905 /* Clear the ROM restore flag now as we only need to do this once after
4906 loading saved state. */
4907 pVM->pgm.s.fRestoreRomPagesOnReset = false;
4908
4909 return VINF_SUCCESS;
4910}
4911
4912
4913/**
4914 * Called by PGMR3Term to free resources.
4915 *
4916 * ASSUMES that the caller owns the PGM lock.
4917 *
4918 * @param pVM The cross context VM structure.
4919 */
4920void pgmR3PhysRomTerm(PVM pVM)
4921{
4922 /*
4923 * Free the heap copy of the original bits.
4924 */
4925 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4926 {
4927 if ( pRom->pvOriginal
4928 && !(pRom->fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY))
4929 {
4930 RTMemFree((void *)pRom->pvOriginal);
4931 pRom->pvOriginal = NULL;
4932 }
4933 }
4934}
4935
4936
4937/**
4938 * Change the shadowing of a range of ROM pages.
4939 *
4940 * This is intended for implementing chipset specific memory registers
4941 * and will not be very strict about the input. It will silently ignore
4942 * any pages that are not the part of a shadowed ROM.
4943 *
4944 * @returns VBox status code.
4945 * @retval VINF_PGM_SYNC_CR3
4946 *
4947 * @param pVM The cross context VM structure.
4948 * @param GCPhys Where to start. Page aligned.
4949 * @param cb How much to change. Page aligned.
4950 * @param enmProt The new ROM protection.
4951 */
4952VMMR3DECL(int) PGMR3PhysRomProtect(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMROMPROT enmProt)
4953{
4954 /*
4955 * Check input
4956 */
4957 if (!cb)
4958 return VINF_SUCCESS;
4959 AssertReturn(!(GCPhys & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
4960 AssertReturn(!(cb & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
4961 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
4962 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
4963 AssertReturn(enmProt >= PGMROMPROT_INVALID && enmProt <= PGMROMPROT_END, VERR_INVALID_PARAMETER);
4964
4965 /*
4966 * Process the request.
4967 */
4968 PGM_LOCK_VOID(pVM);
4969 int rc = VINF_SUCCESS;
4970 bool fFlushTLB = false;
4971 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4972 {
4973 if ( GCPhys <= pRom->GCPhysLast
4974 && GCPhysLast >= pRom->GCPhys
4975 && (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED))
4976 {
4977 /*
4978 * Iterate the relevant pages and make necessary the changes.
4979 */
4980#ifdef VBOX_WITH_NATIVE_NEM
4981 PPGMRAMRANGE const pRam = pgmPhysGetRange(pVM, GCPhys);
4982 AssertPtrReturn(pRam, VERR_INTERNAL_ERROR_3);
4983#endif
4984 bool fChanges = false;
4985 uint32_t const cPages = pRom->GCPhysLast <= GCPhysLast
4986 ? pRom->cb >> GUEST_PAGE_SHIFT
4987 : (GCPhysLast - pRom->GCPhys + 1) >> GUEST_PAGE_SHIFT;
4988 for (uint32_t iPage = (GCPhys - pRom->GCPhys) >> GUEST_PAGE_SHIFT;
4989 iPage < cPages;
4990 iPage++)
4991 {
4992 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
4993 if (PGMROMPROT_IS_ROM(pRomPage->enmProt) != PGMROMPROT_IS_ROM(enmProt))
4994 {
4995 fChanges = true;
4996
4997 /* flush references to the page. */
4998 RTGCPHYS const GCPhysPage = pRom->GCPhys + (iPage << GUEST_PAGE_SHIFT);
4999 PPGMPAGE pRamPage = pgmPhysGetPage(pVM, GCPhysPage);
5000 int rc2 = pgmPoolTrackUpdateGCPhys(pVM, GCPhysPage, pRamPage, true /*fFlushPTEs*/, &fFlushTLB);
5001 if (rc2 != VINF_SUCCESS && (rc == VINF_SUCCESS || RT_FAILURE(rc2)))
5002 rc = rc2;
5003#ifdef VBOX_WITH_NATIVE_NEM
5004 uint8_t u2State = PGM_PAGE_GET_NEM_STATE(pRamPage);
5005#endif
5006
5007 PPGMPAGE pOld = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Virgin : &pRomPage->Shadow;
5008 PPGMPAGE pNew = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Shadow : &pRomPage->Virgin;
5009
5010 *pOld = *pRamPage;
5011 *pRamPage = *pNew;
5012 /** @todo preserve the volatile flags (handlers) when these have been moved out of HCPhys! */
5013
5014#ifdef VBOX_WITH_NATIVE_NEM
5015# ifdef VBOX_WITH_PGM_NEM_MODE
5016 /* In simplified mode we have to switch the page data around too. */
5017 if (pVM->pgm.s.fNemMode)
5018 {
5019 uint8_t abPage[GUEST_PAGE_SIZE];
5020 uint8_t * const pbRamPage = PGM_RAMRANGE_CALC_PAGE_R3PTR(pRam, GCPhysPage);
5021 memcpy(abPage, &pRom->pbR3Alternate[(size_t)iPage << GUEST_PAGE_SHIFT], sizeof(abPage));
5022 memcpy(&pRom->pbR3Alternate[(size_t)iPage << GUEST_PAGE_SHIFT], pbRamPage, sizeof(abPage));
5023 memcpy(pbRamPage, abPage, sizeof(abPage));
5024 }
5025# endif
5026 /* Tell NEM about the backing and protection change. */
5027 if (VM_IS_NEM_ENABLED(pVM))
5028 {
5029 PGMPAGETYPE enmType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pNew);
5030 NEMHCNotifyPhysPageChanged(pVM, GCPhys, PGM_PAGE_GET_HCPHYS(pOld), PGM_PAGE_GET_HCPHYS(pNew),
5031 PGM_RAMRANGE_CALC_PAGE_R3PTR(pRam, GCPhysPage),
5032 pgmPhysPageCalcNemProtection(pRamPage, enmType), enmType, &u2State);
5033 PGM_PAGE_SET_NEM_STATE(pRamPage, u2State);
5034 }
5035#endif
5036 }
5037 pRomPage->enmProt = enmProt;
5038 }
5039
5040 /*
5041 * Reset the access handler if we made changes, no need
5042 * to optimize this.
5043 */
5044 if (fChanges)
5045 {
5046 int rc2 = PGMHandlerPhysicalReset(pVM, pRom->GCPhys);
5047 if (RT_FAILURE(rc2))
5048 {
5049 PGM_UNLOCK(pVM);
5050 AssertRC(rc);
5051 return rc2;
5052 }
5053 }
5054
5055 /* Advance - cb isn't updated. */
5056 GCPhys = pRom->GCPhys + (cPages << GUEST_PAGE_SHIFT);
5057 }
5058 }
5059 PGM_UNLOCK(pVM);
5060 if (fFlushTLB)
5061 PGM_INVL_ALL_VCPU_TLBS(pVM);
5062
5063 return rc;
5064}
5065
5066
5067
5068/*********************************************************************************************************************************
5069* Ballooning *
5070*********************************************************************************************************************************/
5071
5072#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
5073
5074/**
5075 * Rendezvous callback used by PGMR3ChangeMemBalloon that changes the memory balloon size
5076 *
5077 * This is only called on one of the EMTs while the other ones are waiting for
5078 * it to complete this function.
5079 *
5080 * @returns VINF_SUCCESS (VBox strict status code).
5081 * @param pVM The cross context VM structure.
5082 * @param pVCpu The cross context virtual CPU structure of the calling EMT. Unused.
5083 * @param pvUser User parameter
5084 */
5085static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysChangeMemBalloonRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
5086{
5087 uintptr_t *paUser = (uintptr_t *)pvUser;
5088 bool fInflate = !!paUser[0];
5089 unsigned cPages = paUser[1];
5090 RTGCPHYS *paPhysPage = (RTGCPHYS *)paUser[2];
5091 uint32_t cPendingPages = 0;
5092 PGMMFREEPAGESREQ pReq;
5093 int rc;
5094
5095 Log(("pgmR3PhysChangeMemBalloonRendezvous: %s %x pages\n", (fInflate) ? "inflate" : "deflate", cPages));
5096 PGM_LOCK_VOID(pVM);
5097
5098 if (fInflate)
5099 {
5100 /* Flush the PGM pool cache as we might have stale references to pages that we just freed. */
5101 pgmR3PoolClearAllRendezvous(pVM, pVCpu, NULL);
5102
5103 /* Replace pages with ZERO pages. */
5104 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
5105 if (RT_FAILURE(rc))
5106 {
5107 PGM_UNLOCK(pVM);
5108 AssertLogRelRC(rc);
5109 return rc;
5110 }
5111
5112 /* Iterate the pages. */
5113 for (unsigned i = 0; i < cPages; i++)
5114 {
5115 PPGMPAGE pPage = pgmPhysGetPage(pVM, paPhysPage[i]);
5116 if ( pPage == NULL
5117 || PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM)
5118 {
5119 Log(("pgmR3PhysChangeMemBalloonRendezvous: invalid physical page %RGp pPage->u3Type=%d\n", paPhysPage[i], pPage ? PGM_PAGE_GET_TYPE(pPage) : 0));
5120 break;
5121 }
5122
5123 LogFlow(("balloon page: %RGp\n", paPhysPage[i]));
5124
5125 /* Flush the shadow PT if this page was previously used as a guest page table. */
5126 pgmPoolFlushPageByGCPhys(pVM, paPhysPage[i]);
5127
5128 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, paPhysPage[i], (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pPage));
5129 if (RT_FAILURE(rc))
5130 {
5131 PGM_UNLOCK(pVM);
5132 AssertLogRelRC(rc);
5133 return rc;
5134 }
5135 Assert(PGM_PAGE_IS_ZERO(pPage));
5136 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_BALLOONED);
5137 }
5138
5139 if (cPendingPages)
5140 {
5141 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
5142 if (RT_FAILURE(rc))
5143 {
5144 PGM_UNLOCK(pVM);
5145 AssertLogRelRC(rc);
5146 return rc;
5147 }
5148 }
5149 GMMR3FreePagesCleanup(pReq);
5150 }
5151 else
5152 {
5153 /* Iterate the pages. */
5154 for (unsigned i = 0; i < cPages; i++)
5155 {
5156 PPGMPAGE pPage = pgmPhysGetPage(pVM, paPhysPage[i]);
5157 AssertBreak(pPage && PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM);
5158
5159 LogFlow(("Free ballooned page: %RGp\n", paPhysPage[i]));
5160
5161 Assert(PGM_PAGE_IS_BALLOONED(pPage));
5162
5163 /* Change back to zero page. (NEM does not need to be informed.) */
5164 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
5165 }
5166
5167 /* Note that we currently do not map any ballooned pages in our shadow page tables, so no need to flush the pgm pool. */
5168 }
5169
5170 /* Notify GMM about the balloon change. */
5171 rc = GMMR3BalloonedPages(pVM, (fInflate) ? GMMBALLOONACTION_INFLATE : GMMBALLOONACTION_DEFLATE, cPages);
5172 if (RT_SUCCESS(rc))
5173 {
5174 if (!fInflate)
5175 {
5176 Assert(pVM->pgm.s.cBalloonedPages >= cPages);
5177 pVM->pgm.s.cBalloonedPages -= cPages;
5178 }
5179 else
5180 pVM->pgm.s.cBalloonedPages += cPages;
5181 }
5182
5183 PGM_UNLOCK(pVM);
5184
5185 /* Flush the recompiler's TLB as well. */
5186 for (VMCPUID i = 0; i < pVM->cCpus; i++)
5187 CPUMSetChangedFlags(pVM->apCpusR3[i], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
5188
5189 AssertLogRelRC(rc);
5190 return rc;
5191}
5192
5193
5194/**
5195 * Frees a range of ram pages, replacing them with ZERO pages; helper for PGMR3PhysFreeRamPages
5196 *
5197 * @returns VBox status code.
5198 * @param pVM The cross context VM structure.
5199 * @param fInflate Inflate or deflate memory balloon
5200 * @param cPages Number of pages to free
5201 * @param paPhysPage Array of guest physical addresses
5202 */
5203static DECLCALLBACK(void) pgmR3PhysChangeMemBalloonHelper(PVM pVM, bool fInflate, unsigned cPages, RTGCPHYS *paPhysPage)
5204{
5205 uintptr_t paUser[3];
5206
5207 paUser[0] = fInflate;
5208 paUser[1] = cPages;
5209 paUser[2] = (uintptr_t)paPhysPage;
5210 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysChangeMemBalloonRendezvous, (void *)paUser);
5211 AssertRC(rc);
5212
5213 /* Made a copy in PGMR3PhysFreeRamPages; free it here. */
5214 RTMemFree(paPhysPage);
5215}
5216
5217#endif /* 64-bit host && (Windows || Solaris || Linux || FreeBSD) */
5218
5219/**
5220 * Inflate or deflate a memory balloon
5221 *
5222 * @returns VBox status code.
5223 * @param pVM The cross context VM structure.
5224 * @param fInflate Inflate or deflate memory balloon
5225 * @param cPages Number of pages to free
5226 * @param paPhysPage Array of guest physical addresses
5227 */
5228VMMR3DECL(int) PGMR3PhysChangeMemBalloon(PVM pVM, bool fInflate, unsigned cPages, RTGCPHYS *paPhysPage)
5229{
5230 /* This must match GMMR0Init; currently we only support memory ballooning on all 64-bit hosts except Mac OS X */
5231#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
5232 int rc;
5233
5234 /* Older additions (ancient non-functioning balloon code) pass wrong physical addresses. */
5235 AssertReturn(!(paPhysPage[0] & 0xfff), VERR_INVALID_PARAMETER);
5236
5237 /* We own the IOM lock here and could cause a deadlock by waiting for another VCPU that is blocking on the IOM lock.
5238 * In the SMP case we post a request packet to postpone the job.
5239 */
5240 if (pVM->cCpus > 1)
5241 {
5242 unsigned cbPhysPage = cPages * sizeof(paPhysPage[0]);
5243 RTGCPHYS *paPhysPageCopy = (RTGCPHYS *)RTMemAlloc(cbPhysPage);
5244 AssertReturn(paPhysPageCopy, VERR_NO_MEMORY);
5245
5246 memcpy(paPhysPageCopy, paPhysPage, cbPhysPage);
5247
5248 rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysChangeMemBalloonHelper, 4, pVM, fInflate, cPages, paPhysPageCopy);
5249 AssertRC(rc);
5250 }
5251 else
5252 {
5253 uintptr_t paUser[3];
5254
5255 paUser[0] = fInflate;
5256 paUser[1] = cPages;
5257 paUser[2] = (uintptr_t)paPhysPage;
5258 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysChangeMemBalloonRendezvous, (void *)paUser);
5259 AssertRC(rc);
5260 }
5261 return rc;
5262
5263#else
5264 NOREF(pVM); NOREF(fInflate); NOREF(cPages); NOREF(paPhysPage);
5265 return VERR_NOT_IMPLEMENTED;
5266#endif
5267}
5268
5269
5270/*********************************************************************************************************************************
5271* Write Monitoring *
5272*********************************************************************************************************************************/
5273
5274/**
5275 * Rendezvous callback used by PGMR3WriteProtectRAM that write protects all
5276 * physical RAM.
5277 *
5278 * This is only called on one of the EMTs while the other ones are waiting for
5279 * it to complete this function.
5280 *
5281 * @returns VINF_SUCCESS (VBox strict status code).
5282 * @param pVM The cross context VM structure.
5283 * @param pVCpu The cross context virtual CPU structure of the calling EMT. Unused.
5284 * @param pvUser User parameter, unused.
5285 */
5286static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysWriteProtectRAMRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
5287{
5288 int rc = VINF_SUCCESS;
5289 NOREF(pvUser); NOREF(pVCpu);
5290
5291 PGM_LOCK_VOID(pVM);
5292#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
5293 pgmPoolResetDirtyPages(pVM);
5294#endif
5295
5296 /** @todo pointless to write protect the physical page pointed to by RSP. */
5297
5298 for (PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRangesX);
5299 pRam;
5300 pRam = pRam->CTX_SUFF(pNext))
5301 {
5302 uint32_t cPages = pRam->cb >> GUEST_PAGE_SHIFT;
5303 for (uint32_t iPage = 0; iPage < cPages; iPage++)
5304 {
5305 PPGMPAGE pPage = &pRam->aPages[iPage];
5306 PGMPAGETYPE enmPageType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pPage);
5307
5308 if ( RT_LIKELY(enmPageType == PGMPAGETYPE_RAM)
5309 || enmPageType == PGMPAGETYPE_MMIO2)
5310 {
5311 /*
5312 * A RAM page.
5313 */
5314 switch (PGM_PAGE_GET_STATE(pPage))
5315 {
5316 case PGM_PAGE_STATE_ALLOCATED:
5317 /** @todo Optimize this: Don't always re-enable write
5318 * monitoring if the page is known to be very busy. */
5319 if (PGM_PAGE_IS_WRITTEN_TO(pPage))
5320 PGM_PAGE_CLEAR_WRITTEN_TO(pVM, pPage);
5321
5322 pgmPhysPageWriteMonitor(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT));
5323 break;
5324
5325 case PGM_PAGE_STATE_SHARED:
5326 AssertFailed();
5327 break;
5328
5329 case PGM_PAGE_STATE_WRITE_MONITORED: /* nothing to change. */
5330 default:
5331 break;
5332 }
5333 }
5334 }
5335 }
5336 pgmR3PoolWriteProtectPages(pVM);
5337 PGM_INVL_ALL_VCPU_TLBS(pVM);
5338 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
5339 CPUMSetChangedFlags(pVM->apCpusR3[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
5340
5341 PGM_UNLOCK(pVM);
5342 return rc;
5343}
5344
5345/**
5346 * Protect all physical RAM to monitor writes
5347 *
5348 * @returns VBox status code.
5349 * @param pVM The cross context VM structure.
5350 */
5351VMMR3DECL(int) PGMR3PhysWriteProtectRAM(PVM pVM)
5352{
5353 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
5354
5355 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysWriteProtectRAMRendezvous, NULL);
5356 AssertRC(rc);
5357 return rc;
5358}
5359
5360
5361/*********************************************************************************************************************************
5362* Stats. *
5363*********************************************************************************************************************************/
5364
5365/**
5366 * Query the amount of free memory inside VMMR0
5367 *
5368 * @returns VBox status code.
5369 * @param pUVM The user mode VM handle.
5370 * @param pcbAllocMem Where to return the amount of memory allocated
5371 * by VMs.
5372 * @param pcbFreeMem Where to return the amount of memory that is
5373 * allocated from the host but not currently used
5374 * by any VMs.
5375 * @param pcbBallonedMem Where to return the sum of memory that is
5376 * currently ballooned by the VMs.
5377 * @param pcbSharedMem Where to return the amount of memory that is
5378 * currently shared.
5379 */
5380VMMR3DECL(int) PGMR3QueryGlobalMemoryStats(PUVM pUVM, uint64_t *pcbAllocMem, uint64_t *pcbFreeMem,
5381 uint64_t *pcbBallonedMem, uint64_t *pcbSharedMem)
5382{
5383 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
5384 VM_ASSERT_VALID_EXT_RETURN(pUVM->pVM, VERR_INVALID_VM_HANDLE);
5385
5386 uint64_t cAllocPages = 0;
5387 uint64_t cFreePages = 0;
5388 uint64_t cBalloonPages = 0;
5389 uint64_t cSharedPages = 0;
5390 if (!SUPR3IsDriverless())
5391 {
5392 int rc = GMMR3QueryHypervisorMemoryStats(pUVM->pVM, &cAllocPages, &cFreePages, &cBalloonPages, &cSharedPages);
5393 AssertRCReturn(rc, rc);
5394 }
5395
5396 if (pcbAllocMem)
5397 *pcbAllocMem = cAllocPages * _4K;
5398
5399 if (pcbFreeMem)
5400 *pcbFreeMem = cFreePages * _4K;
5401
5402 if (pcbBallonedMem)
5403 *pcbBallonedMem = cBalloonPages * _4K;
5404
5405 if (pcbSharedMem)
5406 *pcbSharedMem = cSharedPages * _4K;
5407
5408 Log(("PGMR3QueryVMMMemoryStats: all=%llx free=%llx ballooned=%llx shared=%llx\n",
5409 cAllocPages, cFreePages, cBalloonPages, cSharedPages));
5410 return VINF_SUCCESS;
5411}
5412
5413
5414/**
5415 * Query memory stats for the VM.
5416 *
5417 * @returns VBox status code.
5418 * @param pUVM The user mode VM handle.
5419 * @param pcbTotalMem Where to return total amount memory the VM may
5420 * possibly use.
5421 * @param pcbPrivateMem Where to return the amount of private memory
5422 * currently allocated.
5423 * @param pcbSharedMem Where to return the amount of actually shared
5424 * memory currently used by the VM.
5425 * @param pcbZeroMem Where to return the amount of memory backed by
5426 * zero pages.
5427 *
5428 * @remarks The total mem is normally larger than the sum of the three
5429 * components. There are two reasons for this, first the amount of
5430 * shared memory is what we're sure is shared instead of what could
5431 * possibly be shared with someone. Secondly, because the total may
5432 * include some pure MMIO pages that doesn't go into any of the three
5433 * sub-counts.
5434 *
5435 * @todo Why do we return reused shared pages instead of anything that could
5436 * potentially be shared? Doesn't this mean the first VM gets a much
5437 * lower number of shared pages?
5438 */
5439VMMR3DECL(int) PGMR3QueryMemoryStats(PUVM pUVM, uint64_t *pcbTotalMem, uint64_t *pcbPrivateMem,
5440 uint64_t *pcbSharedMem, uint64_t *pcbZeroMem)
5441{
5442 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
5443 PVM pVM = pUVM->pVM;
5444 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
5445
5446 if (pcbTotalMem)
5447 *pcbTotalMem = (uint64_t)pVM->pgm.s.cAllPages * GUEST_PAGE_SIZE;
5448
5449 if (pcbPrivateMem)
5450 *pcbPrivateMem = (uint64_t)pVM->pgm.s.cPrivatePages * GUEST_PAGE_SIZE;
5451
5452 if (pcbSharedMem)
5453 *pcbSharedMem = (uint64_t)pVM->pgm.s.cReusedSharedPages * GUEST_PAGE_SIZE;
5454
5455 if (pcbZeroMem)
5456 *pcbZeroMem = (uint64_t)pVM->pgm.s.cZeroPages * GUEST_PAGE_SIZE;
5457
5458 Log(("PGMR3QueryMemoryStats: all=%x private=%x reused=%x zero=%x\n", pVM->pgm.s.cAllPages, pVM->pgm.s.cPrivatePages, pVM->pgm.s.cReusedSharedPages, pVM->pgm.s.cZeroPages));
5459 return VINF_SUCCESS;
5460}
5461
5462
5463
5464/*********************************************************************************************************************************
5465* Chunk Mappings and Page Allocation *
5466*********************************************************************************************************************************/
5467
5468/**
5469 * Tree enumeration callback for dealing with age rollover.
5470 * It will perform a simple compression of the current age.
5471 */
5472static DECLCALLBACK(int) pgmR3PhysChunkAgeingRolloverCallback(PAVLU32NODECORE pNode, void *pvUser)
5473{
5474 /* Age compression - ASSUMES iNow == 4. */
5475 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
5476 if (pChunk->iLastUsed >= UINT32_C(0xffffff00))
5477 pChunk->iLastUsed = 3;
5478 else if (pChunk->iLastUsed >= UINT32_C(0xfffff000))
5479 pChunk->iLastUsed = 2;
5480 else if (pChunk->iLastUsed)
5481 pChunk->iLastUsed = 1;
5482 else /* iLastUsed = 0 */
5483 pChunk->iLastUsed = 4;
5484
5485 NOREF(pvUser);
5486 return 0;
5487}
5488
5489
5490/**
5491 * The structure passed in the pvUser argument of pgmR3PhysChunkUnmapCandidateCallback().
5492 */
5493typedef struct PGMR3PHYSCHUNKUNMAPCB
5494{
5495 PVM pVM; /**< Pointer to the VM. */
5496 PPGMCHUNKR3MAP pChunk; /**< The chunk to unmap. */
5497} PGMR3PHYSCHUNKUNMAPCB, *PPGMR3PHYSCHUNKUNMAPCB;
5498
5499
5500/**
5501 * Callback used to find the mapping that's been unused for
5502 * the longest time.
5503 */
5504static DECLCALLBACK(int) pgmR3PhysChunkUnmapCandidateCallback(PAVLU32NODECORE pNode, void *pvUser)
5505{
5506 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
5507 PPGMR3PHYSCHUNKUNMAPCB pArg = (PPGMR3PHYSCHUNKUNMAPCB)pvUser;
5508
5509 /*
5510 * Check for locks and compare when last used.
5511 */
5512 if (pChunk->cRefs)
5513 return 0;
5514 if (pChunk->cPermRefs)
5515 return 0;
5516 if ( pArg->pChunk
5517 && pChunk->iLastUsed >= pArg->pChunk->iLastUsed)
5518 return 0;
5519
5520 /*
5521 * Check that it's not in any of the TLBs.
5522 */
5523 PVM pVM = pArg->pVM;
5524 if ( pVM->pgm.s.ChunkR3Map.Tlb.aEntries[PGM_CHUNKR3MAPTLB_IDX(pChunk->Core.Key)].idChunk
5525 == pChunk->Core.Key)
5526 {
5527 pChunk = NULL;
5528 return 0;
5529 }
5530#ifdef VBOX_STRICT
5531 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
5532 {
5533 Assert(pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk != pChunk);
5534 Assert(pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk != pChunk->Core.Key);
5535 }
5536#endif
5537
5538 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.PhysTlbR3.aEntries); i++)
5539 if (pVM->pgm.s.PhysTlbR3.aEntries[i].pMap == pChunk)
5540 return 0;
5541
5542 pArg->pChunk = pChunk;
5543 return 0;
5544}
5545
5546
5547/**
5548 * Finds a good candidate for unmapping when the ring-3 mapping cache is full.
5549 *
5550 * The candidate will not be part of any TLBs, so no need to flush
5551 * anything afterwards.
5552 *
5553 * @returns Chunk id.
5554 * @param pVM The cross context VM structure.
5555 */
5556static int32_t pgmR3PhysChunkFindUnmapCandidate(PVM pVM)
5557{
5558 PGM_LOCK_ASSERT_OWNER(pVM);
5559
5560 /*
5561 * Enumerate the age tree starting with the left most node.
5562 */
5563 STAM_PROFILE_START(&pVM->pgm.s.Stats.StatChunkFindCandidate, a);
5564 PGMR3PHYSCHUNKUNMAPCB Args;
5565 Args.pVM = pVM;
5566 Args.pChunk = NULL;
5567 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkUnmapCandidateCallback, &Args);
5568 Assert(Args.pChunk);
5569 if (Args.pChunk)
5570 {
5571 Assert(Args.pChunk->cRefs == 0);
5572 Assert(Args.pChunk->cPermRefs == 0);
5573 STAM_PROFILE_STOP(&pVM->pgm.s.Stats.StatChunkFindCandidate, a);
5574 return Args.pChunk->Core.Key;
5575 }
5576
5577 STAM_PROFILE_STOP(&pVM->pgm.s.Stats.StatChunkFindCandidate, a);
5578 return INT32_MAX;
5579}
5580
5581
5582/**
5583 * Rendezvous callback used by pgmR3PhysUnmapChunk that unmaps a chunk
5584 *
5585 * This is only called on one of the EMTs while the other ones are waiting for
5586 * it to complete this function.
5587 *
5588 * @returns VINF_SUCCESS (VBox strict status code).
5589 * @param pVM The cross context VM structure.
5590 * @param pVCpu The cross context virtual CPU structure of the calling EMT. Unused.
5591 * @param pvUser User pointer. Unused
5592 *
5593 */
5594static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysUnmapChunkRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
5595{
5596 int rc = VINF_SUCCESS;
5597 PGM_LOCK_VOID(pVM);
5598 NOREF(pVCpu); NOREF(pvUser);
5599
5600 if (pVM->pgm.s.ChunkR3Map.c >= pVM->pgm.s.ChunkR3Map.cMax)
5601 {
5602 /* Flush the pgm pool cache; call the internal rendezvous handler as we're already in a rendezvous handler here. */
5603 /** @todo also not really efficient to unmap a chunk that contains PD
5604 * or PT pages. */
5605 pgmR3PoolClearAllRendezvous(pVM, pVM->apCpusR3[0], NULL /* no need to flush the REM TLB as we already did that above */);
5606
5607 /*
5608 * Request the ring-0 part to unmap a chunk to make space in the mapping cache.
5609 */
5610 GMMMAPUNMAPCHUNKREQ Req;
5611 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
5612 Req.Hdr.cbReq = sizeof(Req);
5613 Req.pvR3 = NULL;
5614 Req.idChunkMap = NIL_GMM_CHUNKID;
5615 Req.idChunkUnmap = pgmR3PhysChunkFindUnmapCandidate(pVM);
5616 if (Req.idChunkUnmap != INT32_MAX)
5617 {
5618 STAM_PROFILE_START(&pVM->pgm.s.Stats.StatChunkUnmap, a);
5619 rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
5620 STAM_PROFILE_STOP(&pVM->pgm.s.Stats.StatChunkUnmap, a);
5621 if (RT_SUCCESS(rc))
5622 {
5623 /*
5624 * Remove the unmapped one.
5625 */
5626 PPGMCHUNKR3MAP pUnmappedChunk = (PPGMCHUNKR3MAP)RTAvlU32Remove(&pVM->pgm.s.ChunkR3Map.pTree, Req.idChunkUnmap);
5627 AssertRelease(pUnmappedChunk);
5628 AssertRelease(!pUnmappedChunk->cRefs);
5629 AssertRelease(!pUnmappedChunk->cPermRefs);
5630 pUnmappedChunk->pv = NULL;
5631 pUnmappedChunk->Core.Key = UINT32_MAX;
5632 MMR3HeapFree(pUnmappedChunk);
5633 pVM->pgm.s.ChunkR3Map.c--;
5634 pVM->pgm.s.cUnmappedChunks++;
5635
5636 /*
5637 * Flush dangling PGM pointers (R3 & R0 ptrs to GC physical addresses).
5638 */
5639 /** @todo We should not flush chunks which include cr3 mappings. */
5640 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
5641 {
5642 PPGMCPU pPGM = &pVM->apCpusR3[idCpu]->pgm.s;
5643
5644 pPGM->pGst32BitPdR3 = NULL;
5645 pPGM->pGstPaePdptR3 = NULL;
5646 pPGM->pGstAmd64Pml4R3 = NULL;
5647 pPGM->pGstEptPml4R3 = NULL;
5648 pPGM->pGst32BitPdR0 = NIL_RTR0PTR;
5649 pPGM->pGstPaePdptR0 = NIL_RTR0PTR;
5650 pPGM->pGstAmd64Pml4R0 = NIL_RTR0PTR;
5651 pPGM->pGstEptPml4R0 = NIL_RTR0PTR;
5652 for (unsigned i = 0; i < RT_ELEMENTS(pPGM->apGstPaePDsR3); i++)
5653 {
5654 pPGM->apGstPaePDsR3[i] = NULL;
5655 pPGM->apGstPaePDsR0[i] = NIL_RTR0PTR;
5656 }
5657
5658 /* Flush REM TLBs. */
5659 CPUMSetChangedFlags(pVM->apCpusR3[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
5660 }
5661 }
5662 }
5663 }
5664 PGM_UNLOCK(pVM);
5665 return rc;
5666}
5667
5668/**
5669 * Unmap a chunk to free up virtual address space (request packet handler for pgmR3PhysChunkMap)
5670 *
5671 * @returns VBox status code.
5672 * @param pVM The cross context VM structure.
5673 */
5674static DECLCALLBACK(void) pgmR3PhysUnmapChunk(PVM pVM)
5675{
5676 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysUnmapChunkRendezvous, NULL);
5677 AssertRC(rc);
5678}
5679
5680
5681/**
5682 * Maps the given chunk into the ring-3 mapping cache.
5683 *
5684 * This will call ring-0.
5685 *
5686 * @returns VBox status code.
5687 * @param pVM The cross context VM structure.
5688 * @param idChunk The chunk in question.
5689 * @param ppChunk Where to store the chunk tracking structure.
5690 *
5691 * @remarks Called from within the PGM critical section.
5692 * @remarks Can be called from any thread!
5693 */
5694int pgmR3PhysChunkMap(PVM pVM, uint32_t idChunk, PPPGMCHUNKR3MAP ppChunk)
5695{
5696 int rc;
5697
5698 PGM_LOCK_ASSERT_OWNER(pVM);
5699
5700 /*
5701 * Move the chunk time forward.
5702 */
5703 pVM->pgm.s.ChunkR3Map.iNow++;
5704 if (pVM->pgm.s.ChunkR3Map.iNow == 0)
5705 {
5706 pVM->pgm.s.ChunkR3Map.iNow = 4;
5707 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingRolloverCallback, NULL);
5708 }
5709
5710 /*
5711 * Allocate a new tracking structure first.
5712 */
5713 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3HeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk));
5714 AssertReturn(pChunk, VERR_NO_MEMORY);
5715 pChunk->Core.Key = idChunk;
5716 pChunk->iLastUsed = pVM->pgm.s.ChunkR3Map.iNow;
5717
5718 /*
5719 * Request the ring-0 part to map the chunk in question.
5720 */
5721 GMMMAPUNMAPCHUNKREQ Req;
5722 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
5723 Req.Hdr.cbReq = sizeof(Req);
5724 Req.pvR3 = NULL;
5725 Req.idChunkMap = idChunk;
5726 Req.idChunkUnmap = NIL_GMM_CHUNKID;
5727
5728 /* Must be callable from any thread, so can't use VMMR3CallR0. */
5729 STAM_PROFILE_START(&pVM->pgm.s.Stats.StatChunkMap, a);
5730 rc = SUPR3CallVMMR0Ex(VMCC_GET_VMR0_FOR_CALL(pVM), NIL_VMCPUID, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
5731 STAM_PROFILE_STOP(&pVM->pgm.s.Stats.StatChunkMap, a);
5732 if (RT_SUCCESS(rc))
5733 {
5734 pChunk->pv = Req.pvR3;
5735
5736 /*
5737 * If we're running out of virtual address space, then we should
5738 * unmap another chunk.
5739 *
5740 * Currently, an unmap operation requires that all other virtual CPUs
5741 * are idling and not by chance making use of the memory we're
5742 * unmapping. So, we create an async unmap operation here.
5743 *
5744 * Now, when creating or restoring a saved state this wont work very
5745 * well since we may want to restore all guest RAM + a little something.
5746 * So, we have to do the unmap synchronously. Fortunately for us
5747 * though, during these operations the other virtual CPUs are inactive
5748 * and it should be safe to do this.
5749 */
5750 /** @todo Eventually we should lock all memory when used and do
5751 * map+unmap as one kernel call without any rendezvous or
5752 * other precautions. */
5753 if (pVM->pgm.s.ChunkR3Map.c + 1 >= pVM->pgm.s.ChunkR3Map.cMax)
5754 {
5755 switch (VMR3GetState(pVM))
5756 {
5757 case VMSTATE_LOADING:
5758 case VMSTATE_SAVING:
5759 {
5760 PVMCPU pVCpu = VMMGetCpu(pVM);
5761 if ( pVCpu
5762 && pVM->pgm.s.cDeprecatedPageLocks == 0)
5763 {
5764 pgmR3PhysUnmapChunkRendezvous(pVM, pVCpu, NULL);
5765 break;
5766 }
5767 }
5768 RT_FALL_THRU();
5769 default:
5770 rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysUnmapChunk, 1, pVM);
5771 AssertRC(rc);
5772 break;
5773 }
5774 }
5775
5776 /*
5777 * Update the tree. We must do this after any unmapping to make sure
5778 * the chunk we're going to return isn't unmapped by accident.
5779 */
5780 AssertPtr(Req.pvR3);
5781 bool fRc = RTAvlU32Insert(&pVM->pgm.s.ChunkR3Map.pTree, &pChunk->Core);
5782 AssertRelease(fRc);
5783 pVM->pgm.s.ChunkR3Map.c++;
5784 pVM->pgm.s.cMappedChunks++;
5785 }
5786 else
5787 {
5788 /** @todo this may fail because of /proc/sys/vm/max_map_count, so we
5789 * should probably restrict ourselves on linux. */
5790 AssertRC(rc);
5791 MMR3HeapFree(pChunk);
5792 pChunk = NULL;
5793 }
5794
5795 *ppChunk = pChunk;
5796 return rc;
5797}
5798
5799
5800/**
5801 * Invalidates the TLB for the ring-3 mapping cache.
5802 *
5803 * @param pVM The cross context VM structure.
5804 */
5805VMMR3DECL(void) PGMR3PhysChunkInvalidateTLB(PVM pVM)
5806{
5807 PGM_LOCK_VOID(pVM);
5808 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
5809 {
5810 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk = NIL_GMM_CHUNKID;
5811 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk = NULL;
5812 }
5813 /* The page map TLB references chunks, so invalidate that one too. */
5814 pgmPhysInvalidatePageMapTLB(pVM);
5815 PGM_UNLOCK(pVM);
5816}
5817
5818
5819/**
5820 * Response to VM_FF_PGM_NEED_HANDY_PAGES and helper for pgmPhysEnsureHandyPage.
5821 *
5822 * This function will also work the VM_FF_PGM_NO_MEMORY force action flag, to
5823 * signal and clear the out of memory condition. When called, this API is used
5824 * to try clear the condition when the user wants to resume.
5825 *
5826 * @returns The following VBox status codes.
5827 * @retval VINF_SUCCESS on success. FFs cleared.
5828 * @retval VINF_EM_NO_MEMORY if we're out of memory. The FF is not cleared in
5829 * this case and it gets accompanied by VM_FF_PGM_NO_MEMORY.
5830 *
5831 * @param pVM The cross context VM structure.
5832 *
5833 * @remarks The VINF_EM_NO_MEMORY status is for the benefit of the FF processing
5834 * in EM.cpp and shouldn't be propagated outside TRPM, HM, EM and
5835 * pgmPhysEnsureHandyPage. There is one exception to this in the \#PF
5836 * handler.
5837 */
5838VMMR3DECL(int) PGMR3PhysAllocateHandyPages(PVM pVM)
5839{
5840 PGM_LOCK_VOID(pVM);
5841
5842 /*
5843 * Allocate more pages, noting down the index of the first new page.
5844 */
5845 uint32_t iClear = pVM->pgm.s.cHandyPages;
5846 AssertMsgReturn(iClear <= RT_ELEMENTS(pVM->pgm.s.aHandyPages), ("%d", iClear), VERR_PGM_HANDY_PAGE_IPE);
5847 Log(("PGMR3PhysAllocateHandyPages: %d -> %d\n", iClear, RT_ELEMENTS(pVM->pgm.s.aHandyPages)));
5848 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
5849 /** @todo we should split this up into an allocate and flush operation. sometimes you want to flush and not allocate more (which will trigger the vm account limit error) */
5850 if ( rc == VERR_GMM_HIT_VM_ACCOUNT_LIMIT
5851 && pVM->pgm.s.cHandyPages > 0)
5852 {
5853 /* Still handy pages left, so don't panic. */
5854 rc = VINF_SUCCESS;
5855 }
5856
5857 if (RT_SUCCESS(rc))
5858 {
5859 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc));
5860 Assert(pVM->pgm.s.cHandyPages > 0);
5861#ifdef VBOX_STRICT
5862 uint32_t i;
5863 for (i = iClear; i < pVM->pgm.s.cHandyPages; i++)
5864 if ( pVM->pgm.s.aHandyPages[i].idPage == NIL_GMM_PAGEID
5865 || pVM->pgm.s.aHandyPages[i].idSharedPage != NIL_GMM_PAGEID
5866 || (pVM->pgm.s.aHandyPages[i].HCPhysGCPhys & GUEST_PAGE_OFFSET_MASK))
5867 break;
5868 if (i != pVM->pgm.s.cHandyPages)
5869 {
5870 RTAssertMsg1Weak(NULL, __LINE__, __FILE__, __FUNCTION__);
5871 RTAssertMsg2Weak("i=%d iClear=%d cHandyPages=%d\n", i, iClear, pVM->pgm.s.cHandyPages);
5872 for (uint32_t j = iClear; j < pVM->pgm.s.cHandyPages; j++)
5873 RTAssertMsg2Add("%03d: idPage=%d HCPhysGCPhys=%RHp idSharedPage=%d%s\n", j,
5874 pVM->pgm.s.aHandyPages[j].idPage,
5875 pVM->pgm.s.aHandyPages[j].HCPhysGCPhys,
5876 pVM->pgm.s.aHandyPages[j].idSharedPage,
5877 j == i ? " <---" : "");
5878 RTAssertPanic();
5879 }
5880#endif
5881 }
5882 else
5883 {
5884 /*
5885 * We should never get here unless there is a genuine shortage of
5886 * memory (or some internal error). Flag the error so the VM can be
5887 * suspended ASAP and the user informed. If we're totally out of
5888 * handy pages we will return failure.
5889 */
5890 /* Report the failure. */
5891 LogRel(("PGM: Failed to procure handy pages; rc=%Rrc cHandyPages=%#x\n"
5892 " cAllPages=%#x cPrivatePages=%#x cSharedPages=%#x cZeroPages=%#x\n",
5893 rc, pVM->pgm.s.cHandyPages,
5894 pVM->pgm.s.cAllPages, pVM->pgm.s.cPrivatePages, pVM->pgm.s.cSharedPages, pVM->pgm.s.cZeroPages));
5895
5896 if ( rc != VERR_NO_MEMORY
5897 && rc != VERR_NO_PHYS_MEMORY
5898 && rc != VERR_LOCK_FAILED)
5899 for (uint32_t i = 0; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
5900 {
5901 LogRel(("PGM: aHandyPages[#%#04x] = {.HCPhysGCPhys=%RHp, .idPage=%#08x, .idSharedPage=%#08x}\n",
5902 i, pVM->pgm.s.aHandyPages[i].HCPhysGCPhys, pVM->pgm.s.aHandyPages[i].idPage,
5903 pVM->pgm.s.aHandyPages[i].idSharedPage));
5904 uint32_t const idPage = pVM->pgm.s.aHandyPages[i].idPage;
5905 if (idPage != NIL_GMM_PAGEID)
5906 {
5907 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
5908 pRam;
5909 pRam = pRam->pNextR3)
5910 {
5911 uint32_t const cPages = pRam->cb >> GUEST_PAGE_SHIFT;
5912 for (uint32_t iPage = 0; iPage < cPages; iPage++)
5913 if (PGM_PAGE_GET_PAGEID(&pRam->aPages[iPage]) == idPage)
5914 LogRel(("PGM: Used by %RGp %R[pgmpage] (%s)\n",
5915 pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), &pRam->aPages[iPage], pRam->pszDesc));
5916 }
5917 }
5918 }
5919
5920 if (rc == VERR_NO_MEMORY)
5921 {
5922 uint64_t cbHostRamAvail = 0;
5923 int rc2 = RTSystemQueryAvailableRam(&cbHostRamAvail);
5924 if (RT_SUCCESS(rc2))
5925 LogRel(("Host RAM: %RU64MB available\n", cbHostRamAvail / _1M));
5926 else
5927 LogRel(("Cannot determine the amount of available host memory\n"));
5928 }
5929
5930 /* Set the FFs and adjust rc. */
5931 VM_FF_SET(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
5932 VM_FF_SET(pVM, VM_FF_PGM_NO_MEMORY);
5933 if ( rc == VERR_NO_MEMORY
5934 || rc == VERR_NO_PHYS_MEMORY
5935 || rc == VERR_LOCK_FAILED)
5936 rc = VINF_EM_NO_MEMORY;
5937 }
5938
5939 PGM_UNLOCK(pVM);
5940 return rc;
5941}
5942
5943
5944/*********************************************************************************************************************************
5945* Other Stuff *
5946*********************************************************************************************************************************/
5947
5948/**
5949 * Sets the Address Gate 20 state.
5950 *
5951 * @param pVCpu The cross context virtual CPU structure.
5952 * @param fEnable True if the gate should be enabled.
5953 * False if the gate should be disabled.
5954 */
5955VMMDECL(void) PGMR3PhysSetA20(PVMCPU pVCpu, bool fEnable)
5956{
5957 LogFlow(("PGMR3PhysSetA20 %d (was %d)\n", fEnable, pVCpu->pgm.s.fA20Enabled));
5958 if (pVCpu->pgm.s.fA20Enabled != fEnable)
5959 {
5960#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5961 PCCPUMCTX pCtx = CPUMQueryGuestCtxPtr(pVCpu);
5962 if ( CPUMIsGuestInVmxRootMode(pCtx)
5963 && !fEnable)
5964 {
5965 Log(("Cannot enter A20M mode while in VMX root mode\n"));
5966 return;
5967 }
5968#endif
5969 pVCpu->pgm.s.fA20Enabled = fEnable;
5970 pVCpu->pgm.s.GCPhysA20Mask = ~((RTGCPHYS)!fEnable << 20);
5971 if (VM_IS_NEM_ENABLED(pVCpu->CTX_SUFF(pVM)))
5972 NEMR3NotifySetA20(pVCpu, fEnable);
5973#ifdef PGM_WITH_A20
5974 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
5975 pgmR3RefreshShadowModeAfterA20Change(pVCpu);
5976 HMFlushTlb(pVCpu);
5977#endif
5978#if 0 /* PGMGetPage will apply the A20 mask to the GCPhys it returns, so we must invalid both sides of the TLB. */
5979 IEMTlbInvalidateAllPhysical(pVCpu);
5980#else
5981 IEMTlbInvalidateAll(pVCpu);
5982#endif
5983 STAM_REL_COUNTER_INC(&pVCpu->pgm.s.cA20Changes);
5984 }
5985}
5986
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